-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathnabweatherd.py
More file actions
627 lines (552 loc) · 22.9 KB
/
Copy pathnabweatherd.py
File metadata and controls
627 lines (552 loc) · 22.9 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import datetime
import logging
import random
import sys
from asgiref.sync import sync_to_async
from dateutil import tz
from meteofrance_api.client import MeteoFranceClient, Place
from nabcommon.nabservice import NabInfoService
from nabcommon.typing import NabdPacket
from . import rfid_data
class NabWeatherd(NabInfoService):
class meteoError(Exception):
"""Raise when errors occur while parsing data"""
UNIT_CELSIUS = 1
UNIT_FARENHEIT = 2
# [25 {3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 0 0 0 0 0 0 0 0 0}] // soleil
SUNNY_INFO_ANIMATION = (
'{"tempo":25,"colors":['
'{"left":"ffff00","center":"ffff00","right":"ffff00"},'
'{"left":"ffff00","center":"ffff00","right":"ffff00"},'
'{"left":"ffff00","center":"ffff00","right":"ffff00"},'
'{"left":"ffff00","center":"ffff00","right":"ffff00"},'
'{"left":"ffff00","center":"ffff00","right":"ffff00"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"}]}'
)
RAIN_ONE_HOUR = (
'{"tempo":16,"colors":['
'{"left":"00000","center":"003399","right":"000000"},'
'{"left":"003399","center":"000000","right":"003399"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"003399","right":"000000"},'
'{"left":"003399","center":"000000","right":"003399"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"003399","right":"000000"},'
'{"left":"003399","center":"000000","right":"003399"},'
'{"left":"00000","center":"00000","right":"000000"},'
'{"left":"00000","center":"003399","right":"000000"},'
'{"left":"003399","center":"000000","right":"003399"},'
'{"left":"000000","center":"000000","right":"000000"}]}'
)
# [125 {0 3 0 4 0 4}] // nuages
CLOUDY_INFO_ANIMATION = (
'{"tempo":125,"colors":['
'{"left":"000000","center":"ffff00","right":"000000"},'
'{"left":"0000ff","center":"000000","right":"0000ff"}]}'
)
WHITE_INFO_ANIMATION = (
'{"tempo":125,"colors":['
'{"left":"ffffff","center":"ffffff","right":"ffffff"},'
'{"left":"000000","center":"000000","right":"000000"}]}'
)
# [25 {4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 0 0 0}] // brouillard
FOGGY_INFO_ANIMATION = (
'{"tempo":25,"colors":['
'{"left":"0000ff","center":"0000ff","right":"0000ff"},'
'{"left":"0000ff","center":"0000ff","right":"0000ff"},'
'{"left":"0000ff","center":"0000ff","right":"0000ff"},'
'{"left":"0000ff","center":"0000ff","right":"0000ff"},'
'{"left":"0000ff","center":"0000ff","right":"0000ff"},'
'{"left":"000000","center":"000000","right":"000000"}]}'
)
# [20 {0 0 0 0 4 0 4 0 4 0 0 0 0 0 4 4 0 0 0 0 0 0 4 0 0 0 4}] // pluie
RAINY_INFO_ANIMATION = (
'{"tempo":20,"colors":['
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"0000ff","right":"000000"},'
'{"left":"0000ff","center":"000000","right":"0000ff"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"0000ff"},'
'{"left":"0000ff","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"0000ff"},'
'{"left":"000000","center":"0000ff","right":"000000"},'
'{"left":"000000","center":"000000","right":"0000ff"}]}'
)
# [40 {4 0 0 0 0 0 0 0 4 0 0 0 0 4 0 0 0 0 0 0 4 0 0 0 0 4 0
# 0 0 0 4 0 0 0 0 0}] // neige
SNOWY_INFO_ANIMATION = (
'{"tempo":40,"colors":['
'{"left":"0000ff","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"0000ff"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"0000ff","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"0000ff"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"0000ff","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"0000ff","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"}]}'
)
# [25 {0 4 3 0 0 0 0 0 0 0 0 0 0 0 0 4 3 0 0 4 3 0 0 0 0 0 0
# 0 3 4 3 4 0}] // orage
STORMY_INFO_ANIMATION = (
'{"tempo":25,"colors":['
'{"left":"000000","center":"0000ff","right":"ffff00"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"0000ff","center":"ffff00","right":"000000"},'
'{"left":"000000","center":"0000ff","right":"ffff00"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"000000","right":"000000"},'
'{"left":"000000","center":"ffff00","right":"0000ff"},'
'{"left":"ffff00","center":"0000ff","right":"000000"}]}'
)
# Météo France weather classes
WEATHER_CLASSES = {
"Eclaircies": ("sunny", SUNNY_INFO_ANIMATION),
"Peu nuageux": ("sunny", SUNNY_INFO_ANIMATION),
"Ensoleillé": ("sunny", SUNNY_INFO_ANIMATION),
"Ciel clair": ("sunny", SUNNY_INFO_ANIMATION),
"Ciel voilé": ("cloudy", CLOUDY_INFO_ANIMATION),
"Ciel voilé nuit": ("cloudy", CLOUDY_INFO_ANIMATION),
"Très nuageux": ("cloudy", CLOUDY_INFO_ANIMATION),
"Couvert": ("cloudy", CLOUDY_INFO_ANIMATION),
"Variable": ("cloudy", CLOUDY_INFO_ANIMATION),
"Rares averses": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Averses faibles": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Averses": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Pluies éparses": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Pluie": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Pluie modérée": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Pluie faible": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Pluie forte": (
"rainy",
RAINY_INFO_ANIMATION,
),
"Risque de grêle": ("rainy", RAINY_INFO_ANIMATION),
"Risque de grèle": ("rainy", RAINY_INFO_ANIMATION),
"Bruine / Pluie faible": ("rainy", RAINY_INFO_ANIMATION),
"Bruine": ("rainy", RAINY_INFO_ANIMATION),
"Pluies éparses / Rares averses": ("rainy", RAINY_INFO_ANIMATION),
"Pluie / Averses": ("rainy", RAINY_INFO_ANIMATION),
"Pluie et neige mêlées": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Neige / Averses de neige": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Neige": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Averses de neige": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Averses de neige faible": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Neige faible": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Neige forte": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Quelques flocons": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Pluie et neige": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Pluie verglaçante": (
"snowy",
SNOWY_INFO_ANIMATION,
),
"Brume ou bancs de brouillard": (
"foggy",
FOGGY_INFO_ANIMATION,
),
"Bancs de Brouillard": (
"foggy",
FOGGY_INFO_ANIMATION,
),
"Brouillard": (
"foggy",
FOGGY_INFO_ANIMATION,
),
"Brouillard dense": (
"foggy",
FOGGY_INFO_ANIMATION,
),
"Brouillard givrant": (
"foggy",
FOGGY_INFO_ANIMATION,
),
"Brume": (
"foggy",
FOGGY_INFO_ANIMATION,
),
"Pluies orageuses": ("stormy", STORMY_INFO_ANIMATION),
"Pluie orageuses": ("stormy", STORMY_INFO_ANIMATION),
"Orages": ("stormy", STORMY_INFO_ANIMATION),
"Averses orageuses": ("stormy", STORMY_INFO_ANIMATION),
"Orage avec grêle": ("stormy", STORMY_INFO_ANIMATION),
"Risque d'orages": ("stormy", STORMY_INFO_ANIMATION),
}
weather_bedtime_done = False
weather_wakeup_done = False
async def perform(self, expiration, args, config):
weather_forecast = "today"
await NabInfoService.perform(self, expiration, args, config)
(
location,
unit,
weather_animation_type,
weather_frequency,
next_performance_weather_vocal_date,
next_performance_weather_vocal_flag,
) = config
current_tz = self.get_system_tz()
now = datetime.datetime.now(tz=tz.gettz(current_tz))
if (
next_performance_weather_vocal_flag
and next_performance_weather_vocal_date < now
):
logging.debug("performing random weather forecast")
if now.hour > 18:
weather_forecast = "tomorrow"
else:
weather_forecast = "today"
await self._do_perform_additional(config, weather_forecast)
from . import models
config_t = await models.Config.load_async()
config_t.next_performance_weather_vocal_flag = False
await config_t.save_async()
if weather_frequency == 3:
from nabclockd import models as clock_models
clock_config = await clock_models.Config.load_async()
bedtime = datetime.datetime(
now.year,
now.month,
now.day,
clock_config.sleep_hour,
clock_config.sleep_min,
tzinfo=tz.gettz(current_tz),
)
wakeup = datetime.datetime(
now.year,
now.month,
now.day,
clock_config.wakeup_hour,
clock_config.wakeup_min,
tzinfo=tz.gettz(current_tz),
)
just_before_bedtime = bedtime + datetime.timedelta(minutes=-5)
just_after_wakeup = wakeup + datetime.timedelta(minutes=5)
if now < just_after_wakeup and now > wakeup:
weather_forecast = "today"
if not self.weather_wakeup_done:
await self._do_perform_additional(config, weather_forecast)
self.weather_wakeup_done = True
from . import models
config_t = await models.Config.load_async()
config_t.next_performance_weather_vocal_flag = False
await config_t.save_async()
else:
self.weather_wakeup_done = False
if now > just_before_bedtime and now < bedtime:
weather_forecast = "tomorrow"
if not self.weather_bedtime_done:
await self._do_perform_additional(config, weather_forecast)
self.weather_bedtime_done = True
from . import models
config_t = await models.Config.load_async()
config_t.next_performance_weather_vocal_flag = False
await config_t.save_async()
else:
self.weather_bedtime_done = False
async def get_config(self):
from . import models
config = await models.Config.load_async()
return (
config.next_performance_date,
config.next_performance_type,
(
config.location,
config.unit,
config.weather_animation_type,
config.weather_frequency,
config.next_performance_weather_vocal_date,
config.next_performance_weather_vocal_flag,
),
)
async def update_next(self, next_date, next_args):
from . import models
config = await models.Config.load_async()
config.next_performance_date = next_date
config.next_performance_type = next_args
current_tz = self.get_system_tz()
now = datetime.datetime.now(tz=tz.gettz(current_tz))
if not config.next_performance_weather_vocal_flag:
# every hour approx
if config.weather_frequency == 1:
minutes = random.randint(40, 70) # nosec B311
config.next_performance_weather_vocal_date = (
now + datetime.timedelta(minutes=minutes)
)
logging.debug(
"update_next / next_performance_weather_vocal"
f"={config.next_performance_weather_vocal_date}"
)
config.next_performance_weather_vocal_flag = True
elif config.weather_frequency == 2:
minutes = random.randint(100, 190) # nosec B311
config.next_performance_weather_vocal_date = (
now + datetime.timedelta(minutes=minutes)
)
logging.debug(
"update_next / next_performance_weather_vocal"
f"={config.next_performance_weather_vocal_date}"
)
config.next_performance_weather_vocal_flag = True
elif config.weather_frequency == 3:
config.next_performance_weather_vocal_date = None
config.next_performance_weather_vocal_flag = False
await config.save_async()
def get_system_tz(self):
with open("/etc/timezone") as w:
return w.read().strip()
def next_info_update(self, config):
if config is None:
return None
now = datetime.datetime.now(datetime.timezone.utc)
next_5mn = now + datetime.timedelta(seconds=300)
return next_5mn
async def fetch_info_data(self, config_t):
from . import models # noqa
(
location,
unit,
weather_animation_type,
weather_frequency,
next_performance_weather_vocal_date,
next_performance_weather_vocal_flag,
) = config_t
if location is None:
return None
place = Place(location)
client = await sync_to_async(MeteoFranceClient)()
try:
my_place_weather_forecast = client.get_forecast_for_place(place)
data = my_place_weather_forecast.daily_forecast
logging.debug(f"data: {data}")
except Exception as err:
logging.error(f"{err}")
return None
# Rain info
next_rain = False
try:
raininfo = client.get_rain(place.latitude, place.longitude)
logging.debug(f"rain forecast: {raininfo.forecast}")
for five_min_slots in raininfo.forecast:
if five_min_slots["rain"] != 1:
next_rain = True
break
except Exception as err:
logging.error(f"{err}")
next_rain = False
# todo : prevenir que les infos de rain ne sont pas dispo
current_weather_class = self.normalize_weather_class(
data[0]["weather12H"]["desc"]
)
today_forecast_weather_class = self.normalize_weather_class(
data[0]["weather12H"]["desc"]
)
today_forecast_max_temp = int(data[0]["T"]["max"])
tomorrow_forecast_weather_class = self.normalize_weather_class(
data[1]["weather12H"]["desc"]
)
tomorrow_forecast_max_temp = int(data[0]["T"]["max"])
return {
"weather_animation_type": weather_animation_type,
"current_weather_class": current_weather_class,
"next_rain": next_rain,
"today_forecast_weather_class": today_forecast_weather_class,
"today_forecast_max_temp": today_forecast_max_temp,
"tomorrow_forecast_weather_class": tomorrow_forecast_weather_class,
"tomorrow_forecast_max_temp": tomorrow_forecast_max_temp,
}
def normalize_weather_class(self, weather_class):
if weather_class in NabWeatherd.WEATHER_CLASSES:
return weather_class
logging.warning(f"unexpected weather class: {weather_class}")
return None
def get_animation(self, info_data):
if info_data is None:
return
logging.debug(f"get_animation: {info_data['weather_animation_type']}")
# Rain
if (info_data["weather_animation_type"] == "weather_and_rain") or (
info_data["weather_animation_type"] == "rain_only"
):
if info_data["next_rain"] is True:
packet = (
'{"type":"info",'
'"info_id":"nabweatherd_rain",'
'"animation":' + self.RAIN_ONE_HOUR + "}\r\n"
)
else:
packet = '{"type":"info",' '"info_id":"nabweatherd_rain"}\r\n'
self.writer.write(packet.encode("utf8"))
# Weather
if (info_data["weather_animation_type"] == "weather_and_rain") or (
(info_data["weather_animation_type"] == "weather_only")
):
# si weather on supprime l'animation rain
if info_data["weather_animation_type"] == "weather_only":
packet = '{"type":"info",' '"info_id":"nabweatherd_rain"}\r\n'
self.writer.write(packet.encode("utf8"))
(weather_class, info_animation) = NabWeatherd.WEATHER_CLASSES[
info_data["today_forecast_weather_class"]
]
return info_animation
if info_data["weather_animation_type"] == "nothing":
# Return mais avant on supprime l'animation rain
packet = '{"type":"info",' '"info_id":"nabweatherd_rain"}\r\n'
self.writer.write(packet.encode("utf8"))
logging.debug("get_animation: no visual information")
return None
async def perform_additional(self, expiration, type, info_data, config_t):
(
location,
unit,
weather_animation_type,
weather_frequency,
next_performance_weather_vocal_date,
next_performance_weather_vocal_local,
) = config_t
if location is None:
logging.debug("No location (service is unconfigured)")
packet = (
'{"type":"message",'
'"signature":{"audio":['
'"nabweatherd/signature.mp3"]},'
'"body":[{"audio":["nabweatherd/no-location-error.mp3"]}],'
'"expiration":"' + expiration.isoformat() + '"}\r\n'
)
self.writer.write(packet.encode("utf8"))
elif info_data is None:
logging.debug("No data available")
packet = (
'{"type":"message",'
'"signature":{"audio":['
'"nabweatherd/signature.mp3"]},'
'"body":[{"audio":["nabweatherd/no-data-error.mp3"]}],'
'"expiration":"' + expiration.isoformat() + '"}\r\n'
)
self.writer.write(packet.encode("utf8"))
else:
if type == "today":
(weather_class, info_animation) = NabWeatherd.WEATHER_CLASSES[
info_data["today_forecast_weather_class"]
]
max_temp = info_data["today_forecast_max_temp"]
elif type == "tomorrow":
(weather_class, info_animation) = NabWeatherd.WEATHER_CLASSES[
info_data["tomorrow_forecast_weather_class"]
]
max_temp = info_data["tomorrow_forecast_max_temp"]
else:
logging.debug(f"Unknown type {type}")
return
unit_sound_file = "degree.mp3"
if unit == NabWeatherd.UNIT_FARENHEIT:
max_temp = round(max_temp * 1.8 + 32.0)
unit_sound_file = "degree_f.mp3"
packet = (
'{"type":"message",'
'"signature":{"audio":["nabweatherd/signature.mp3"]},'
'"body":[{"audio":["nabweatherd/' + type + '.mp3",'
'"nabweatherd/sky/' + weather_class + '.mp3",'
'"nabweatherd/temp/' + str(max_temp) + '.mp3",'
'"nabweatherd/' + unit_sound_file + '"]}],'
'"expiration":"' + expiration.isoformat() + '"}\r\n'
)
self.writer.write(packet.encode("utf8"))
await self.writer.drain()
async def _do_perform(self, type):
next_date, next_args, config_t = await self.get_config()
now = datetime.datetime.now(datetime.timezone.utc)
expiration = now + datetime.timedelta(minutes=1)
await self.perform(expiration, type, config_t)
async def _do_perform_additional(self, config, type):
info_data = await self.fetch_info_data(config)
now = datetime.datetime.now(datetime.timezone.utc)
expiration = now + datetime.timedelta(minutes=1)
await self.perform_additional(expiration, type, info_data, config)
async def process_nabd_packet(self, packet: NabdPacket):
if (
packet["type"] == "asr_event"
and packet["nlu"]["intent"] == "nabweatherd/forecast"
):
if "date" in packet["nlu"] and packet["nlu"]["date"][
:10
] != datetime.datetime.now().strftime("%Y-%m-%d"):
type = "tomorrow"
else:
type = "today"
logging.debug(f"ASR triggered forecast for {type}")
await self._do_perform(type)
elif (
packet["type"] == "rfid_event"
and packet["app"] == "nabweatherd"
and packet["event"] == "detected"
):
if "data" in packet:
type = rfid_data.unserialize(packet["data"].encode("utf8"))
else:
type = "today"
logging.debug(f"RFID triggered forecast for {type}")
await self._do_perform(type)
if __name__ == "__main__":
NabWeatherd.main(sys.argv[1:])