-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
408 lines (307 loc) · 12.8 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import json
from GtkHelper.GtkHelper import ComboRow
from src.backend.PluginManager.ActionBase import ActionBase
from src.backend.PluginManager.PluginBase import PluginBase
from src.backend.PluginManager.ActionHolder import ActionHolder
from src.backend.DeckManagement.InputIdentifier import Input
from src.backend.PluginManager.ActionInputSupport import ActionInputSupport
# Import gtk modules
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Gtk, Adw, Gio
import sys
import os
from PIL import Image
from loguru import logger as log
import requests
from threading import Timer
# Add plugin to sys.paths
sys.path.append(os.path.dirname(__file__))
# Import globals
import globals as gl
# Import own modules
from src.backend.DeckManagement.DeckController import DeckController
from src.backend.PageManagement.Page import Page
class WindDirection(ActionBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.show_interval = 30 # minutes
self.show_timer: Timer = None
def on_ready(self):
self.show()
def get_config_rows(self) -> list:
self.units_model = Gtk.ListStore.new([str, int])
self.units_row = ComboRow(title=self.plugin_base.lm.get("actions.unit.title"), model=self.units_model)
self.lat_entry = Adw.EntryRow(title=self.plugin_base.lm.get("actions.lat-entry.title"), input_purpose=Gtk.InputPurpose.NUMBER)
self.lon_entry = Adw.EntryRow(title=self.plugin_base.lm.get("actions.long-entry.title"), input_purpose=Gtk.InputPurpose.NUMBER)
self.units_cell_renderer = Gtk.CellRendererText()
self.units_row.combo_box.pack_start(self.units_cell_renderer, True)
self.units_row.combo_box.add_attribute(self.units_cell_renderer, "text", 0)
self.load_units_model()
self.load_config_defaults()
# Connect signals
self.lat_entry.connect("notify::text", self.on_lat_changed)
self.lon_entry.connect("notify::text", self.on_lon_changed)
self.units_row.combo_box.connect("changed", self.on_units_changed)
return [self.lat_entry, self.lon_entry, self.units_row]
def load_units_model(self):
self.units_model.append([self.plugin_base.lm.get("actions.units.metric"), 1])
self.units_model.append([self.plugin_base.lm.get("actions.units.imperial"), 2])
def on_lat_changed(self, entry, text):
settings = self.get_settings()
settings["lat"] = entry.get_text()
self.set_settings(settings)
self.show()
def on_lon_changed(self, entry, *args):
settings = self.get_settings()
settings["lon"] = entry.get_text()
self.set_settings(settings)
self.show()
def on_units_changed(self, combo_box, *args):
unit = self.units_model[combo_box.get_active()][1]
settings = self.get_settings()
settings["unit"] = unit
self.set_settings(settings)
self.show()
def load_config_defaults(self):
settings = self.get_settings()
self.lat_entry.set_text(settings.get("lat", "")) # Does not accept None
self.lon_entry.set_text(settings.get("lon", "")) # Does not accept None
if settings.get("unit") == 2: #Imperial
self.units_row.combo_box.set_active(1)
else: #Celcius and none
self.units_row.combo_box.set_active(0)
def get_wind_data(self) -> list[float]:
settings = self.get_settings()
lat = settings.get("lat")
lon = settings.get("lon")
imperial = settings.get("unit") == 2
# Try to convert lat and lon to float]
try:
lat = float(lat)
lon = float(lon)
except (TypeError, ValueError):
lat = None
lon = None
if lat is None or lon is None:
return
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": lat,
"longitude": lon,
"current": ["wind_speed_10m", "wind_direction_10m"]
}
if imperial:
params["wind_speed_unit"] = "mph"
# Make request with the custom cache session
try:
resp = requests.get(url, params=params)
except Exception as e:
log.error(e)
return
# Parse response
data = resp.json()
return [
data["current"]["wind_direction_10m"],
data["current"]["wind_speed_10m"],
data["current_units"]["wind_speed_10m"]
]
def show(self):
# Stop timer if active
if self.show_timer is not None:
if self.show_timer.is_alive:
self.show_timer.cancel()
wind_data = self.get_wind_data()
if wind_data is None:
self.show_error()
return
wind_direction, wind_speed, wind_speed_unit = wind_data
self.set_bottom_label(f"{int(wind_speed)} {wind_speed_unit}", font_size=12)
with Image.open(os.path.join(self.plugin_base.PATH, "assets", "weather-icons", "wind_direction.png")) as img:
image = img.copy()
image = image.rotate(wind_direction, expand=True)
self.set_media(image=image, size=0.85, valign=-1)
# Launch timer
self.show_timer = Timer(self.show_interval*60, self.show)
self.show_timer.start()
def on_key_down(self):
# Force update
self.show()
def get_custom_config_area(self):
return Gtk.Label(label=self.plugin_base.lm.get("actions.open-meteo-thanks"))
class Weather(ActionBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.show_interval = 30 # minutes
self.show_timer: Timer = None
def on_ready(self):
self.show()
def on_key_down(self):
# Force update
self.show()
def get_config_rows(self) -> list:
self.units_model = Gtk.ListStore.new([str, int])
self.units_row = ComboRow(title=self.plugin_base.lm.get("actions.unit.title"), model=self.units_model)
self.lat_entry = Adw.EntryRow(title=self.plugin_base.lm.get("actions.lat-entry.title"), input_purpose=Gtk.InputPurpose.NUMBER)
self.lon_entry = Adw.EntryRow(title=self.plugin_base.lm.get("actions.long-entry.title"), input_purpose=Gtk.InputPurpose.NUMBER)
self.units_cell_renderer = Gtk.CellRendererText()
self.units_row.combo_box.pack_start(self.units_cell_renderer, True)
self.units_row.combo_box.add_attribute(self.units_cell_renderer, "text", 0)
self.load_units_model()
self.load_config_defaults()
# Connect signals
self.lat_entry.connect("notify::text", self.on_lat_changed)
self.lon_entry.connect("notify::text", self.on_lon_changed)
self.units_row.combo_box.connect("changed", self.on_units_changed)
return [self.lat_entry, self.lon_entry, self.units_row]
def load_units_model(self):
self.units_model.append([self.plugin_base.lm.get("actions.units.celsius"), 1])
self.units_model.append([self.plugin_base.lm.get("actions.units.fahrenheit"), 2])
def get_custom_config_area(self):
return Gtk.Label(label=self.plugin_base.lm.get("actions.open-meteo-thanks"))
def on_lat_changed(self, entry, *args):
settings = self.get_settings()
settings["lat"] = entry.get_text()
self.set_settings(settings)
self.show()
def on_lon_changed(self, entry, *args):
settings = self.get_settings()
settings["lon"] = entry.get_text()
self.set_settings(settings)
self.show()
def on_units_changed(self, combo_box, *args):
unit = self.units_model[combo_box.get_active()][1]
settings = self.get_settings()
settings["unit"] = unit
self.set_settings(settings)
self.show()
def load_config_defaults(self):
settings = self.get_settings()
self.lat_entry.set_text(settings.get("lat", "")) # Does not accept None
self.lon_entry.set_text(settings.get("lon", "")) # Does not accept Non
if settings.get("unit") == 2: #Imperial
self.units_row.combo_box.set_active(1)
else: #Celcius and none
self.units_row.combo_box.set_active(0)
def show(self):
# Stop timer if active
if self.show_timer is not None:
if self.show_timer.is_alive:
self.show_timer.cancel()
weather = self.get_weather()
if weather is None:
self.show_error()
return
weather_code, is_day, temperature, temperature_unit = weather
image_to_show = self.get_image_to_show(weather_code=weather_code, night=not is_day)
media_path = os.path.join(self.plugin_base.PATH, "assets", "weather-icons", f"{image_to_show}.png")
self.set_media(media_path=media_path, size=0.8, valign=-1)
self.set_bottom_label(f"{int(temperature)} {temperature_unit}", font_size=12)
# Launch timer
self.show_timer = Timer(self.show_interval*60, self.show)
self.show_timer.start()
def get_weather(self) -> int:
settings = self.get_settings()
lat = settings.get("lat")
lon = settings.get("lon")
imperial = settings.get("unit") == 2
# Try to convert lat and lon to float]
try:
lat = float(lat)
lon = float(lon)
except (TypeError, ValueError):
lat = None
lon = None
if lat is None or lon is None:
return
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": lat,
"longitude": lon,
"current": ["weather_code", "is_day", "temperature_2m"]
}
if imperial:
params["temperature_unit"] = "fahrenheit"
# Make request with the custom cache session
try:
resp = requests.get(url, params=params)
except Exception as e:
log.error(e)
return
# Parse response
data = resp.json()
return [data["current"]["weather_code"], data["current"]["is_day"], data["current"]["temperature_2m"], data["current_units"]["temperature_2m"]]
def get_image_to_show(self, weather_code: int, night: bool) -> str:
wc = weather_code
if wc == 0:
# Clear sky
if night:
return "clear_night"
else:
return "sunny"
elif wc in range(1, 4):
# Partly cloudy
if night:
return "cloudy_night"
else:
return "cloud"
elif wc in range(45, 49):
# Fog
return "foggy"
elif wc in range(51, 58):
# Drizzle
return "rainy_light"
elif wc in range(61, 68) or wc in range(80, 87):
# Rain
return "rainy_heavy"
elif wc in range(71, 78):
# Snow
return "snowy"
elif wc in range(95, 100):
# Thunderstorm
return "thunderstorm"
class WeatherPlugin(PluginBase):
def __init__(self):
super().__init__()
self.init_locale_manager()
self.lm = self.locale_manager
## Register actions
self.wind_direction_holder = ActionHolder(
plugin_base=self,
action_base=WindDirection,
action_id_suffix="WindDirection",
action_name=self.lm.get("actions.wind-direction.name"),
icon=Gtk.Image(icon_name="weather-windy-symbolic"),
action_support={
Input.Key: ActionInputSupport.SUPPORTED,
Input.Dial: ActionInputSupport.SUPPORTED,
Input.Touchscreen: ActionInputSupport.UNSUPPORTED
}
)
self.add_action_holder(self.wind_direction_holder)
self.weather_holder = ActionHolder(
plugin_base=self,
action_base=Weather,
action_id_suffix="Weather",
action_name=self.lm.get("actions.weather.name"),
icon=Gtk.Image(icon_name="weather-clear-symbolic"),
action_support={
Input.Key: ActionInputSupport.SUPPORTED,
Input.Dial: ActionInputSupport.SUPPORTED,
Input.Touchscreen: ActionInputSupport.UNSUPPORTED
}
)
self.add_action_holder(self.weather_holder)
# Register plugin
self.register(
plugin_name=self.lm.get("plugin.name"),
github_repo="https://github.com/StreamController/Weather",
plugin_version="1.0.0",
app_version="1.0.0-alpha"
)
def init_locale_manager(self):
self.lm = self.locale_manager
self.lm.set_to_os_default()
def get_selector_icon(self) -> Gtk.Widget:
return Gtk.Image(icon_name="weather-clear-symbolic")