scripts

scripts to make my pc work
Index Commits Files Refs
statusbar/wthr (3845B)
   1 #!/usr/bin/python3
   2 
   3 import requests
   4 import json
   5 import pathlib
   6 from datetime import datetime
   7 
   8 # TODO: support other units
   9 
  10 icons_day = {
  11     "clear_sky": "☀️",
  12     "few_clouds": "🌤️",
  13     "scattered_clouds": "🌤",
  14     "broken_clouds": "☁",
  15     "overcast_clouds": "☁",
  16     "shower_rain": "🌧",
  17     "very_heavy_rain": "🌧",
  18     "rain": "🌧",
  19     "light_rain": "🌧️",
  20     "thunderstorm": "⛈",
  21     "snow": "❄",
  22     "mist": "🌫"
  23 }
  24 
  25 moon_phase = {
  26     (0.00, 0.124):  "🌑",
  27     (0.124, 0.249): "🌒",
  28     (0.250, 0.374): "🌓",
  29     (0.375, 0.49):  "🌔",
  30     (0.50, 0.674):  "🌕",
  31     (0.675, 0.749): "🌖",
  32     (0.750, 0.824): "🌗",
  33     (0.825, 0.99):  "🌘",
  34     (0.99, 1):      "🌑"
  35 }
  36 
  37 lat = -34.71
  38 lon = -58.27
  39 api_key = "5d30773002dbb7a5aaa846b1656965b2"
  40 units = "metric"
  41 exclude = "minutely,hourly,alert"
  42 cache_file_name = "/home/mk/.cache/wthr.json"
  43 
  44 # update time in minutes
  45 update_time = 5
  46 
  47 url = "https://api.openweathermap.org/data/2.5/onecall"
  48 params = {'lat': lat, 'lon': lon, 'appid': api_key, 'units': units, 'exclude': exclude}
  49 
  50 curr_time = datetime.now().timestamp()
  51 cache_file = pathlib.Path(cache_file_name)
  52 
  53 def cache_update():
  54     pass
  55 
  56 def cache_fetch():
  57     pass
  58 
  59 if cache_file.exists() != True:
  60     # file doesn't exist, creates one
  61     pathlib.Path(cache_file_name).touch()
  62     print("cache file created")
  63 
  64     try:
  65         res = requests.get(url, params)
  66     except (requests.ConnectionError, res):
  67         print("☠️ Service down")
  68         quit()
  69 
  70     wthr_dict = json.loads(res.text)
  71     with open(cache_file_name,'w') as cache_file:
  72         json.dump(wthr_dict, cache_file, indent=4)
  73 else:
  74     # get file modified time
  75     mtime = cache_file.stat().st_mtime
  76     if (curr_time - mtime) > (update_time * 60):
  77         try:
  78             res = requests.get(url, params)
  79         except (requests.ConnectionError, res):
  80             print("☠️ Service down")
  81             quit()
  82 
  83         wthr_dict = json.loads(res.text)
  84         with open(cache_file_name,'w') as cache_file:
  85             json.dump(wthr_dict, cache_file, indent=4)
  86     else:
  87         try:
  88             with open(cache_file_name,'r') as cache_file:
  89                 wthr_dict = json.loads(cache_file.read())
  90         except ValueError:
  91             # file not JSON
  92             try:
  93                 res = requests.get(url, params)
  94             except (requests.ConnectionError, res):
  95                 print("☠️ Service down")
  96                 quit()
  97 
  98             wthr_dict = json.loads(res.text)
  99             with open(cache_file_name,'w') as cache_file:
 100                 json.dump(wthr_dict, cache_file, indent=4)
 101 
 102 # print(json.dumps(wthr_dict, indent=4, sort_keys=True))
 103 
 104 desc = wthr_dict['current']['weather'][0]['description']
 105 main = wthr_dict['current']['weather'][0]['main']
 106 # temp = int(wthr_dict['current']['feels_like'])
 107 temp = int(wthr_dict['current']['temp'])
 108 icon = icons_day[desc.replace(' ', '_')]
 109 moon_curr = wthr_dict['daily'][0]['moon_phase']
 110 curr_time_int = int(datetime.now().strftime('%H%M'))
 111 sunrise = int(wthr_dict['current']['sunrise'])
 112 sunset = int(wthr_dict['current']['sunset'])
 113 
 114 sunrise = int(datetime.fromtimestamp(sunrise).strftime('%H%M'))
 115 sunset = int(datetime.fromtimestamp(sunset).strftime('%H%M'))
 116 
 117 for range, moon_icon in moon_phase.items():
 118     if range[0] <= moon_curr <= range[1]:
 119         moon_curr = moon_icon
 120         break
 121 
 122 night = (0000, sunrise, sunset + 100, 2359)
 123 sunset = (sunset, sunset + 50)
 124 dusk = (sunset[1], sunset[1] + 50)
 125 day = (sunrise, sunset)
 126 
 127 if (dusk[0] <= curr_time_int <= dusk[1]) and main == 'Clear':
 128     icon = "🌆"
 129 elif (sunset[0] <= curr_time_int <= sunset[1]) and (main == 'Clear'):
 130     icon = "🌇"
 131 elif ((night[0] <= curr_time_int <= night[1]) or (night[2] <= curr_time_int <= night[3])):
 132     icon = moon_curr
 133 
 134 print("{} {}° {}".format(icon, temp, main))