forked from MycroftAI/skill-weather
-
Notifications
You must be signed in to change notification settings - Fork 4
/
__init__.py
1095 lines (952 loc) · 40.3 KB
/
__init__.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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021, Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Mycroft skill for communicating weather information
This skill uses the Open Weather Map One Call API to retrieve weather data
from around the globe (https://openweathermap.org/api/one-call-api). It
proxies its calls to the API through Mycroft's officially supported API,
Selene. The Selene API is also used to get geographical information about the
city name provided in the request.
"""
from datetime import datetime
from time import sleep
from typing import List
from ovos_number_parser import extract_number
from ovos_date_parser import (
nice_time,
nice_weekday,
get_date_strings
)
from ovos_bus_client.message import Message
from ovos_bus_client.session import SessionManager
from ovos_utils import classproperty
from ovos_workshop.intents import IntentBuilder
from ovos_utils.log import LOG
from ovos_utils.process_utils import RuntimeRequirements
from ovos_workshop.decorators import intent_handler, skill_api_method
from ovos_workshop.skills import OVOSSkill
from requests import HTTPError
from .weather_helpers import (
CURRENT,
DAILY,
HOURLY,
WeatherDialog,
CurrentDialog,
DailyDialog,
HourlyDialog,
Weather,
get_dialog_for_timeframe,
LocationNotFoundError,
WeatherConfig,
WeatherIntent,
WeatherReport,
WeeklyDialog,
get_report
)
TWELVE_HOUR = "half"
class WeatherSkill(OVOSSkill):
"""Main skill code for the weather skill."""
@classproperty
def runtime_requirements(self):
"""this skill needs internet"""
return RuntimeRequirements(internet_before_load=True,
network_before_load=True,
gui_before_load=False,
requires_internet=True,
requires_network=True,
requires_gui=False,
no_internet_fallback=False,
no_network_fallback=False,
no_gui_fallback=True)
def initialize(self):
# TODO - skill api
self.bus.on("skill-ovos-weather.openvoiceos.weather.request",
self.get_current_weather_homescreen)
@property
def use_24h(self) -> bool:
return self.time_format == "full"
@intent_handler(
IntentBuilder("weather")
.optionally("query")
.one_of("weather", "forecast")
.optionally("relative-time")
.optionally("relative-day")
.optionally("today")
.optionally("location")
.optionally("unit"))
def handle_weather(self, message: Message):
"""
Handle weather requests of various timeframes.
The intents gets routed accordingly
Examples:
"What's the weather like?" (current)
"How's the weather tomorrow?" (daily)
"What's the forecast for friday 9 pm?" (hourly)
"what's tomorrow's forecast in Seattle?"
Args:
message: Message Bus event information from the intent parser
"""
intent = self._get_intent_data(message)
if intent.timeframe == DAILY:
self._report_one_day_forecast(intent)
elif intent.timeframe == HOURLY:
self._report_hourly_weather(intent)
else:
self._report_current_weather(intent)
@intent_handler(
IntentBuilder("outside")
.require("query")
.require("outside")
.optionally("location")
.optionally("unit")
)
def handle_outside(self, message: Message):
"""
Handle current weather requests such as: what's it like outside?
Args:
message: Message Bus event information from the intent parser
"""
intent = self._get_intent_data(message)
self._report_current_weather(intent)
@intent_handler(
IntentBuilder("N_days_forecast")
.optionally("query")
.one_of("weather", "forecast")
.require("number-days")
.optionally("location")
.optionally("unit")
)
def handle_number_days_forecast(self, message: Message):
"""Handle multiple day forecast without specified location.
Examples:
"What is the 3 day forecast?"
"What is the weather forecast?"
Args:
message: Message Bus event information from the intent parser
"""
if self.voc_match(message.data["utterance"], "couple"):
days = 2
elif self.voc_match(message.data["utterance"], "few"):
days = 3
else:
days = int(extract_number(message.data["utterance"], lang=self.lang))
self._report_multi_day_forecast(message, days)
@intent_handler(
IntentBuilder("weekend_forecast")
.require("query")
.one_of("weather", "forecast")
.require("weekend")
.optionally("location")
.optionally("unit")
)
def handle_weekend_forecast(self, message: Message):
"""Handle requests for the weekend forecast.
Args:
message: Message Bus event information from the intent parser
"""
self._report_weekend_forecast(message)
@intent_handler(
IntentBuilder("week_weather")
.optionally("query")
.one_of("weather", "forecast")
.require("week")
.optionally("location")
.optionally("unit")
)
def handle_week_weather(self, message: Message):
"""Handle weather for week (i.e. seven days).
Args:
message: Message Bus event information from the intent parser
"""
self._report_week_summary(message)
@intent_handler(
IntentBuilder("current_temperature")
.optionally("query")
.require("temperature")
.optionally("location")
.optionally("unit")
.optionally("today")
.optionally("now")
)
def handle_current_temperature(self, message: Message):
"""Handle requests for current temperature.
Examples:
"What is the temperature in Celsius?"
"What is the temperature in Baltimore now?"
Args:
message: Message Bus event information from the intent parser
"""
self._report_temperature(message, temperature_type="current")
@intent_handler(
IntentBuilder("daily_temperature")
.optionally("query")
.require("temperature")
.require("relative-day")
.optionally("location")
.optionally("unit")
)
def handle_daily_temperature(self, message: Message):
"""Handle simple requests for current temperature.
Examples: "What is the temperature?"
Args:
message: Message Bus event information from the intent parser
"""
self._report_temperature(message)
@intent_handler(
IntentBuilder("hourly_temperature")
.optionally("query")
.require("temperature")
.require("relative-time")
.optionally("relative-day")
.optionally("location")
.optionally("unit")
)
def handle_hourly_temperature(self, message: Message):
"""Handle requests for current temperature at a relative time.
Examples:
"What is the temperature tonight?"
"What is the temperature tomorrow morning?"
Args:
message: Message Bus event information from the intent parser
"""
self._report_temperature(message)
# TODO high low teperatures really only make sense if tied to a daytime
@intent_handler(
IntentBuilder("high_temperature")
.optionally("query")
.require("high")
.require("temperature")
.optionally("location")
.optionally("unit")
.optionally("relative-day")
.optionally("now")
.optionally("today")
)
def handle_high_temperature(self, message: Message):
"""Handle a request for the high temperature.
Examples:
"What is the high temperature tomorrow?"
"What is the high temperature in London on Tuesday?"
Args:
message: Message Bus event information from the intent parser
"""
self._report_temperature(message, temperature_type="high")
@intent_handler(
IntentBuilder("low_temperature")
.optionally("query")
.require("low")
.require("temperature")
.optionally("location")
.optionally("unit")
.optionally("relative-day")
.optionally("now")
.optionally("today")
)
def handle_low_temperature(self, message: Message):
"""Handle a request for the high temperature.
Examples:
"What is the high temperature tomorrow?"
"What is the high temperature in London on Tuesday?"
Args:
message: Message Bus event information from the intent parser
"""
self._report_temperature(message, temperature_type="low")
@intent_handler(
IntentBuilder("is_hot_cold")
.require("confirm-query-current")
.one_of("hot", "cold")
.optionally("location")
.optionally("today")
)
def handle_is_it_hot_or_cold(self, message: Message):
"""Handler for temperature requests such as: is it going to be hot today?
Args:
message: Message Bus event information from the intent parser
"""
utterance = message.data["utterance"]
temperature_type = "high" if self.voc_match(utterance, "hot") else "low"
self._report_temperature(message, temperature_type)
@intent_handler(
IntentBuilder("how_hot_or_cold")
.optionally("query")
.one_of("hot", "cold")
.require("confirm-query")
.optionally("location")
.optionally("relative-day")
.optionally("today")
)
def handle_how_hot_or_cold(self, message):
"""Handler for temperature requests such as: how cold will it be today?
Args:
message: Message Bus event information from the intent parser
"""
utterance = message.data["utterance"]
temperature_type = "high" if self.voc_match(utterance, "hot") else "low"
self._report_temperature(message, temperature_type)
@intent_handler(
IntentBuilder("is_wind")
.require("confirm-query")
.require("windy")
.optionally("location")
.optionally("relative-day")
)
def handle_is_it_windy(self, message: Message):
"""Handler for weather requests such as: is it windy today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_wind(message)
@intent_handler(
IntentBuilder("current_wind")
.require("how")
.require("windy")
.optionally("confirm-query")
.optionally("relative-day")
.optionally("location")
)
def handle_windy(self, message):
"""Handler for weather requests such as: how windy is it?
Args:
message: Message Bus event information from the intent parser
"""
self._report_wind(message)
@intent_handler(
IntentBuilder("is_snow")
.require("confirm-query")
.require("snow")
.optionally("location")
)
def handle_is_it_snowing(self, message: Message):
"""Handler for weather requests such as: is it snowing today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_weather_condition(message, "snow")
@intent_handler(
IntentBuilder("is_clear")
.require("confirm-query")
.require("clear")
.optionally("location")
)
def handle_is_it_clear(self, message: Message):
"""Handler for weather requests such as: is the sky clear today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_weather_condition(message, condition="clear")
@intent_handler(
IntentBuilder("is_cloudy")
.require("confirm-query")
.require("clouds")
.optionally("location")
.optionally("relative-time")
)
def handle_is_it_cloudy(self, message: Message):
"""Handler for weather requests such as: is it cloudy today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_weather_condition(message, "clouds")
@intent_handler(
IntentBuilder("is_fog")
.require("confirm-query")
.require("fog")
.optionally("location")
)
def handle_is_it_foggy(self, message: Message):
"""Handler for weather requests such as: is it foggy today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_weather_condition(message, "fog")
@intent_handler(
IntentBuilder("is_rain")
.require("confirm-query")
.require("rain")
.optionally("location")
)
def handle_is_it_raining(self, message: Message):
"""Handler for weather requests such as: is it raining today?
Args:
message: Message Bus event information from the intent parser
0] """
self._report_weather_condition(message, "rain")
@intent_handler("do-i-need-an-umbrella.intent")
def handle_need_umbrella(self, message: Message):
"""Handler for weather requests such as: will I need an umbrella today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_weather_condition(message, "rain")
@intent_handler(
IntentBuilder("is_stormy")
.require("confirm-query")
.require("thunderstorm")
.optionally("location")
)
def handle_is_it_storming(self, message: Message):
"""Handler for weather requests such as: is it storming today?
Args:
message: Message Bus event information from the intent parser
"""
self._report_weather_condition(message, "thunderstorm")
@intent_handler(
IntentBuilder("next_rain")
.require("when")
.optionally("next")
.one_of("rain", "precipitation")
.optionally("location")
)
def handle_next_precipitation(self, message: Message):
"""Handler for weather requests such as: when will it rain next?
Args:
message: Message Bus event information from the intent parser
"""
intent_data = self._get_intent_data(message)
weather = self._get_weather(intent_data)
if weather is not None:
forecast, timeframe = weather.get_next_precipitation(intent_data)
intent_data.timeframe = timeframe
dialog = get_dialog_for_timeframe(intent_data, forecast)
dialog.build_next_precipitation_dialog()
self._speak_weather(dialog)
@intent_handler(
IntentBuilder("humidity")
.require("query")
.require("humidity")
.optionally("relative-day")
.optionally("location")
)
def handle_humidity(self, message: Message):
"""Handler for weather requests such as: how humid is it?
Args:
message: Message Bus event information from the intent parser
"""
intent_data = self._get_intent_data(message)
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog = get_dialog_for_timeframe(intent_data, intent_weather)
dialog.build_humidity_dialog()
self._speak_weather(dialog)
@intent_handler(
IntentBuilder("sunrise") # TODO - this should be in other skill
.require("when")
.optionally("location")
.require("sunrise")
.optionally("today")
.optionally("relative-day")
)
def handle_sunrise(self, message: Message):
"""Handler for weather requests such as: when is the sunrise?
Args:
message: Message Bus event information from the intent parser
"""
intent_data = self._get_intent_data(message)
intent_data.timeframe = DAILY
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog = get_dialog_for_timeframe(intent_data, intent_weather)
dialog.build_sunrise_dialog()
self._display_sunrise_sunset(intent_weather, intent_data.display_location)
self._speak_weather(dialog)
@intent_handler(
IntentBuilder("sunset") # TODO - this should be in other skill
.require("when")
.require("sunset")
.optionally("location")
.optionally("today")
.optionally("relative-day")
)
def handle_sunset(self, message: Message):
"""Handler for weather requests such as: when is the sunset?
Args:
message: Message Bus event information from the intent parser
"""
intent_data = self._get_intent_data(message)
intent_data.timeframe = DAILY
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog = get_dialog_for_timeframe(intent_data, intent_weather)
dialog.build_sunset_dialog()
self._display_sunrise_sunset(intent_weather, intent_data.display_location)
self._speak_weather(dialog)
def _display_sunrise_sunset(self, forecast: Weather, weather_location: str):
"""Display the sunrise and sunset.
Args:
forecast: daily forecasts to display
weather_location: the geographical location of the weather
"""
self.gui.clear()
self.gui["currentTimezone"] = self._format_dt(forecast.date_time)
self.gui["weatherLocation"] = weather_location
self.gui["sunrise"] = self._format_time(forecast.sunrise)
self.gui["sunset"] = self._format_time(forecast.sunset)
self.gui.show_page("SunriseSunset")
def _report_current_weather(self, intent_data: WeatherIntent):
"""Handles all requests for current weather conditions.
Args:
message: Message Bus event information from the intent parser
"""
weather = self._get_weather(intent_data)
if weather is not None:
self._display_current_conditions(weather, intent_data.display_location)
dialog = CurrentDialog(intent_data, weather.current)
dialog.build_weather_dialog()
self._speak_weather(dialog)
dialog = CurrentDialog(intent_data, weather.current)
dialog.build_humidity_dialog()
self._speak_weather(dialog)
if self.gui.connected:
sleep(7)
self._display_hourly_forecast(weather.hourly, intent_data.display_location)
sleep(7)
four_day_forecast = weather.daily[1:5]
self._display_multi_day_forecast(four_day_forecast, intent_data)
else:
sleep(5)
# reset mk1 faceplate
self.enclosure.eyes_blink("b")
self.enclosure.mouth_reset()
self.enclosure.activate_mouth_events()
def _display_current_conditions(self, weather: WeatherReport, weather_location: str):
"""Display current weather conditions on a screen.
This is the first screen that shows. Others will follow.
Args:
weather: current weather conditions from Open Weather Maps
weather_location: the geographical location of the reported weather
"""
# display in GUI
self.gui["weatherCode"] = weather.current.condition.animated_code
self.gui["currentTimezone"] = self._format_dt(weather.current.date_time.now(),
incl_time=True)
self.gui["currentTemperature"] = weather.current.temperature
self.gui["weatherCondition"] = weather.current.condition.image
self.gui["weatherLocation"] = weather_location
self.gui["highTemperature"] = weather.daily[0].temperature_high
self.gui["lowTemperature"] = weather.daily[0].temperature_low
self.gui["chanceOfPrecipitation"] = weather.current.chance_of_precipitation
self.gui["windSpeed"] = weather.current.wind_speed
self.gui["humidity"] = weather.current.humidity
self.gui.show_page("CurrentWeather", override_idle=20)
# display in mk1
self.enclosure.deactivate_mouth_events()
self.enclosure.weather_display(
weather.current.condition.code, weather.current.temperature
)
def _report_hourly_weather(self, intent_data: WeatherIntent):
"""Handles requests for a one hour forecast.
Args:
message: Message Bus event information from the intent parser
"""
weather = self._get_weather(intent_data)
if weather is not None:
try:
forecast = weather.get_forecast_for_multiple_hours(intent_data)
except IndexError:
self.speak_dialog("forty-eight-hours-available")
else:
dialog = HourlyDialog(intent_data, forecast[0])
dialog.build_weather_dialog()
self._display_hourly_forecast(forecast, intent_data.display_location)
self._speak_weather(dialog)
def _display_hourly_forecast(self, weather: List[Weather], weather_location: str):
"""Display hourly forecast on a device that supports the GUI.
On the Mark II this screen is the final for current weather. It can
also be shown when the hourly forecast is requested.
:param weather: hourly weather conditions from Open Weather Maps
"""
hourly_forecast = []
for hour_count, hourly in enumerate(weather):
if not hour_count:
continue
if hour_count > 4:
break
if self.time_format == TWELVE_HOUR:
# The datetime builtin returns hour in two character format. Convert
# to a integer and back again to remove the leading zero when present.
hour = int(hourly.date_time.strftime("%I"))
am_pm = hourly.date_time.strftime(" %p")
formatted_time = str(hour) + am_pm
else:
formatted_time = hourly.date_time.strftime("%H:00")
hourly_forecast.append(
dict(
time=formatted_time,
precipitation=hourly.chance_of_precipitation,
temperature=hourly.temperature,
weatherCondition=hourly.condition.animated_code,
)
)
self.gui["currentTimezone"] = self._format_dt(weather[0].date_time)
self.gui["weatherCode"] = weather[0].condition.animated_code
self.gui["weatherLocation"] = weather_location
self.gui["hourlyForecast"] = dict(hours=hourly_forecast)
self.gui.show_page("HourlyForecast")
def _report_one_day_forecast(self, intent_data: WeatherIntent):
"""Handles all requests for a single day forecast.
Args:
message: Message Bus event information from the intent parser
"""
weather = self._get_weather(intent_data)
if weather is not None:
forecast = weather.get_forecast_for_date(intent_data)
dialogs = self._build_forecast_dialogs([forecast], intent_data)
if self.gui.connected:
self._display_one_day(forecast, intent_data)
for dialog in dialogs:
self._speak_weather(dialog, wait=True)
def _display_one_day(self, forecast: Weather, intent_data: WeatherIntent):
"""Display the forecast for a single day
:param forecast: daily forecasts to display
"""
# display in the GUI
self.gui.clear()
self.gui["weatherLocation"] = intent_data.display_location
self.gui["weatherCode"] = forecast.condition.animated_code
self.gui["weatherDate"] = self._format_dt(forecast.date_time)
self.gui["highTemperature"] = forecast.temperature_high
self.gui["lowTemperature"] = forecast.temperature_low
self.gui["chanceOfPrecipitation"] = str(forecast.chance_of_precipitation)
self.gui["windSpeed"] = forecast.wind_speed_max
self.gui["humidity"] = forecast.humidity
self.gui.show_page("SingleDay")
# and display in the mk1 faceplate
self.enclosure.deactivate_mouth_events()
self.enclosure.weather_display(
forecast.condition.code,
(forecast.temperature_high + forecast.temperature_low) / 2
)
sleep(5)
self.enclosure.eyes_blink("b")
self.enclosure.mouth_reset()
self.enclosure.activate_mouth_events()
def _report_multi_day_forecast(self, message: Message, days: int):
"""Handles all requests for multiple day forecasts.
:param message: Message Bus event information from the intent parser
"""
weather_config = self._get_weather_config(message)
intent_data = WeatherIntent(message, weather_config)
weather = self._get_weather(intent_data)
if weather is not None:
try:
forecast = weather.get_forecast_for_multiple_days(days)
except IndexError:
self.speak_dialog("seven-days-available")
forecast = weather.get_forecast_for_multiple_days(7)
dialogs = self._build_forecast_dialogs(forecast, intent_data)
self._display_multi_day_forecast(forecast, intent_data)
for dialog in dialogs:
self._speak_weather(dialog, wait=True)
def _report_weekend_forecast(self, message: Message):
"""Handles requests for a weekend forecast.
Args:
message: Message Bus event information from the intent parser
"""
intent_data = self._get_intent_data(message)
weather = self._get_weather(intent_data)
if weather is not None:
forecast = weather.get_weekend_forecast()
dialogs = self._build_forecast_dialogs(forecast, intent_data)
self._display_multi_day_forecast(forecast, intent_data)
for dialog in dialogs:
self._speak_weather(dialog, wait=True)
def _build_forecast_dialogs(self, forecast: List[Weather], intent_data: WeatherIntent) -> List[DailyDialog]:
"""
Build the dialogs for each of the forecast days being reported to the user.
:param forecast: daily forecasts to report
:param intent_data: information about the intent that was triggered
:return: one DailyDialog instance for each day being reported.
"""
dialogs = list()
for forecast_day in forecast:
dialog = DailyDialog(intent_data, forecast_day)
dialog.build_weather_dialog()
dialogs.append(dialog)
return dialogs
def _report_week_summary(self, message: Message):
"""Summarize the week's weather rather than giving daily details.
When the user requests the weather for the week, rather than give a daily
forecast for seven days, summarize the weather conditions for the week.
Args:
message: Message Bus event information from the intent parser
"""
weather_config = self._get_weather_config(message)
intent_data = WeatherIntent(message, weather_config)
weather = self._get_weather(intent_data)
if weather is not None:
forecast = weather.get_forecast_for_multiple_days(7)
dialogs = self._build_weekly_condition_dialogs(forecast, intent_data)
dialogs.append(self._build_weekly_temperature_dialog(forecast, intent_data))
self._display_multi_day_forecast(forecast, intent_data)
for dialog in dialogs:
self._speak_weather(dialog)
def _build_weekly_condition_dialogs(self, forecast: List[Weather], intent_data: WeatherIntent) -> List[WeeklyDialog]:
"""Build the dialog communicating a weather condition on days it is forecasted.
Args:
forecast: seven day daily forecast
intent_data: Parsed intent data
Returns:
List of dialogs for each condition expected in the coming week.
"""
dialogs = list()
conditions = set([daily.condition.category for daily in forecast])
for condition in conditions:
dialog = WeeklyDialog(intent_data, forecast)
dialog.build_condition_dialog(condition=condition)
dialogs.append(dialog)
return dialogs
def _build_weekly_temperature_dialog(self, forecast: List[Weather], intent_data: WeatherIntent) -> WeeklyDialog:
"""Build the dialog communicating the forecasted range of temperatures.
Args:
forecast: seven day daily forecast
intent_data: Parsed intent data
Returns:
Dialog for the temperature ranges over the coming week.
"""
dialog = WeeklyDialog(intent_data, forecast)
dialog.build_temperature_dialog()
return dialog
def _display_multi_day_forecast(self, forecast: List[Weather], intent_data: WeatherIntent):
"""Display daily forecast data on devices that support the GUI.
Args:
forecast: daily forecasts to display
intent_data: Parsed intent data
"""
self._display_multi_day_scalable(forecast)
def _display_multi_day_scalable(self, forecast: List[Weather]):
"""Display daily forecast data on GUI devices other than the Mark II.
The generic layout supports displaying two days of a forecast at a time.
Args:
forecast: daily forecasts to display
"""
display_data = []
for day_number, day in enumerate(forecast):
if day_number == 4:
break
display_data.append(
dict(
weatherCondition=day.condition.animated_code,
highTemperature=day.temperature_high,
lowTemperature=day.temperature_low,
date=nice_weekday(day.date_time, lang=self.lang)[:3],
)
)
self.gui["forecast"] = dict(all=display_data)
self.gui.show_page("DailyForecast")
def _report_temperature(self, message: Message, temperature_type: str = None):
"""Handles all requests for a temperature.
Args:
message: Message Bus event information from the intent parser
temperature_type: current, high or low temperature
"""
intent_data = self._get_intent_data(message)
if temperature_type in ("high","low",):
intent_data.timeframe = "daily"
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog = get_dialog_for_timeframe(intent_data, intent_weather)
dialog.build_temperature_dialog(temperature_type)
self._speak_weather(dialog)
def _report_weather_condition(self, message: Message, condition: str):
"""Handles all requests for a specific weather condition.
Args:
message: Message Bus event information from the intent parser
condition: the weather condition specified by the user
"""
intent_data = self._get_intent_data(message)
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog = self._build_condition_dialog(
intent_weather, intent_data, condition
)
self._speak_weather(dialog)
def _build_condition_dialog(self, weather, intent_data: WeatherIntent, condition: str):
"""Builds a dialog for the requested weather condition.
Args:
weather: Current, hourly or daily weather forecast
intent_data: Parsed intent data
condition: weather condition requested by the user
"""
dialog = get_dialog_for_timeframe(intent_data, weather)
intent_match = self.voc_match(weather.condition.category.lower(), condition)
dialog.build_condition_dialog(intent_match)
return dialog
def _report_wind(self, message: Message):
"""Handles all requests for a wind conditions.
Args:
message: Message Bus event information from the intent parser
"""
intent_data = self._get_intent_data(message)
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog = get_dialog_for_timeframe(intent_data, intent_weather)
dialog.build_wind_dialog()
self._speak_weather(dialog)
def _get_intent_data(self, message: Message) -> WeatherIntent:
"""Parse the intent data from the message into data used in the skill.
Args:
message: Message Bus event information from the intent parser
Returns:
parsed information about the intent
"""
intent_data = None
try:
weather_config = self._get_weather_config(message)
intent_data = WeatherIntent(message, weather_config)
except ValueError:
self.speak_dialog("cant-get-forecast")
else:
unit = message.data.get("unit")
_dt = intent_data.intent_datetime
if _dt != intent_data.location_datetime: # ie current
if _dt.hour == 0 and _dt.minute == 0:
intent_data.timeframe = DAILY
else:
intent_data.timeframe = HOURLY
elif self.voc_match(intent_data.utterance, "later"):
intent_data.timeframe = HOURLY
if unit and self.voc_match(unit, "fahrenheit"):
intent_data.config.settings["units"] = "imperial"
elif unit and self.voc_match(unit, "celsius"):
intent_data.config.settings["units"] = "metric"
return intent_data
def _get_weather_config(self, message=None):
sess = SessionManager.get(message)
cfg = {"lang": sess.lang,
"system_unit": sess.system_unit,
"location": sess.location_preferences,
"date_format": sess.date_format,
"time_format": sess.time_format}
if self.settings.get("units") and self.settings.get("units") != "default":
LOG.debug(f"overriding system_unit from settings.json : {sess.system_unit} -> {self.settings['units']}")
cfg["system_unit"] = self.settings["units"]
if message and "lat_lon" in message.data:
latitude, longitude = message.data["lat_lon"]
LOG.debug(f"weather lat, lon: {latitude} , {longitude}")
cfg["location"]["coordinate"]["latitude"] = latitude
cfg["location"]["coordinate"]["longitude"] = longitude
return WeatherConfig(cfg)
def _get_weather(self, intent_data: WeatherIntent) -> WeatherReport:
"""Call the Open Weather Map One Call API to get weather information
Args:
intent_data: Parsed intent data
Returns:
An object representing the data returned by the API
"""
weather = None
if intent_data is not None:
try:
weather = get_report(intent_data.config)
except HTTPError as api_error:
LOG.exception("Weather API failure")
self._handle_api_error(api_error)
except LocationNotFoundError:
LOG.exception("City not found.")
self.speak_dialog(
"location-not-found", data=dict(location=intent_data.location)
)
except Exception:
LOG.exception("Unexpected error retrieving weather")
self.speak_dialog("cant-get-forecast")
return weather
def _handle_api_error(self, exception: HTTPError):
"""Communicate an error condition to the user.
Args:
exception: the HTTPError returned by the API call
"""