forked from MycroftAI/skill-weather
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1191 lines (1031 loc) · 43.5 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 pathlib import Path
from time import sleep
from typing import List, Tuple
from requests import HTTPError
from mycroft.skills import MycroftSkill, intent_handler
from mycroft.skills.intent_service import AdaptIntent
from mycroft.messagebus.message import Message
from mycroft.util.parse import extract_number
from .skill import (
CurrentDialog,
DAILY,
DailyDialog,
DailyWeather,
HOURLY,
HourlyDialog,
get_dialog_for_timeframe,
LocationNotFoundError,
OpenWeatherMapApi,
WeatherConfig,
WeatherIntent,
WeatherReport,
WeeklyDialog,
)
# TODO: VK Failures
# Locations: Washington, D.C.
#
# TODO: Intent failures
# Later weather: only the word "later" in the vocab file works all others
# invoke datetime skill
MARK_II = "mycroft_mark_2"
TWELVE_HOUR = "half"
class WeatherSkill(MycroftSkill):
"""Main skill code for the weather skill."""
def __init__(self):
super().__init__("WeatherSkill")
self.weather_api = OpenWeatherMapApi()
self.platform = self.config_core["enclosure"].get("platform", "unknown")
self.gui_image_directory = Path(self.root_dir).joinpath("ui")
self.weather_config = None
def initialize(self):
"""Do these things after the skill is loaded."""
self.weather_config = WeatherConfig(self.config_core, self.settings)
self.add_event(
"skill.weather.request-local-forecast", self.handle_get_local_forecast
)
def handle_get_local_forecast(self, _):
"""Handles a message bus command requesting current local weather information.
Such a request will typically come from a domain external to this skill that
requires weather information but should not go through the intent system
to get it.
"""
system_unit = self.config_core.get("system_unit")
try:
weather = self.weather_api.get_weather_for_coordinates(
system_unit, self.weather_config.latitude, self.weather_config.longitude, self.lang
)
except Exception:
self.log.exception("Unexpected error getting weather.")
self.bus.emit(Message("skill.weather.local-forecast-failure."))
else:
self._emit_local_weather_response(weather)
def _emit_local_weather_response(self, weather):
"""Emits an event indicating that the request for local weather was satisfied.
Responds to the command for local weather retrieval.
"""
image_path = self.gui_image_directory.joinpath(weather.current.condition.image)
weather_condition_url = "file://" + str(image_path)
event_data = dict(
temperature=weather.current.temperature,
weather_condition=weather_condition_url,
)
event = Message("skill.weather.local-forecast-obtained", data=event_data)
self.bus.emit(event)
@intent_handler(
AdaptIntent()
.optionally("query")
.one_of("weather", "forecast")
.optionally("location")
.optionally("today")
)
def handle_current_weather(self, message: Message):
"""Handle current weather requests such as: what is the weather like?
Args:
message: Message Bus event information from the intent parser
"""
self._report_current_weather(message)
@intent_handler(
AdaptIntent()
.require("query")
.require("like")
.require("outside")
.optionally("location")
.optionally("today")
)
def handle_like_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
"""
self._report_current_weather(message)
@intent_handler(
AdaptIntent()
.optionally("query")
.one_of("weather", "forecast")
.require("number-days")
.optionally("location")
)
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:
# Some STT engines hyphenate the day count (i.e. 3-day). This is not
# handled by extract_number() so remove the hyphen if it is there.
utterance = message.data["utterance"].replace("-day", " day")
days = int(extract_number(utterance))
self._report_multi_day_forecast(message, days)
@intent_handler(
AdaptIntent()
.optionally("query")
.one_of("weather", "forecast")
.require("relative-day")
.optionally("location")
)
def handle_one_day_forecast(self, message):
"""Handle forecast for a single day.
Examples:
"What is the weather forecast tomorrow?"
"What is the weather forecast on Tuesday in Baltimore?"
Args:
message: Message Bus event information from the intent parser
"""
self._report_one_day_forecast(message)
@intent_handler(
AdaptIntent()
.require("query")
.require("weather")
.require("later")
.optionally("location")
.optionally("today")
)
def handle_weather_later(self, message: Message):
"""Handle future weather requests such as: what's the weather later?
Args:
message: Message Bus event information from the intent parser
"""
self._report_one_hour_weather(message)
@intent_handler(
AdaptIntent()
.optionally("query")
.one_of("weather", "forecast")
.require("relative-time")
.optionally("relative-day")
.optionally("location")
)
def handle_weather_at_time(self, message: Message):
"""Handle future weather requests such as: what's the weather tonight?
Args:
message: Message Bus event information from the intent parser
"""
self._report_one_hour_weather(message)
@intent_handler(
AdaptIntent()
.require("query")
.one_of("weather", "forecast")
.require("weekend")
.optionally("location")
)
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(
AdaptIntent()
.optionally("query")
.one_of("weather", "forecast")
.require("week")
.optionally("location")
)
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(
AdaptIntent()
.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(
AdaptIntent()
.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, temperature_type="current")
@intent_handler(
AdaptIntent()
.optionally("query")
.require("temperature")
.require("relative-time")
.optionally("relative-day")
.optionally("location")
)
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)
@intent_handler(
AdaptIntent()
.optionally("query")
.require("high")
.optionally("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(
AdaptIntent()
.optionally("query")
.require("low")
.optionally("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(
AdaptIntent()
.require("confirm-query-current")
.one_of("hot", "cold")
.optionally("location")
.optionally("today")
)
def handle_is_it_hot(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
"""
self._report_temperature(message, "current")
@intent_handler(
AdaptIntent()
.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(
AdaptIntent()
.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(
AdaptIntent()
.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(
AdaptIntent().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(
AdaptIntent().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(
AdaptIntent()
.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(
AdaptIntent().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(
AdaptIntent().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
"""
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(
AdaptIntent()
.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(
AdaptIntent()
.require("when")
.optionally("next")
.require("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_args = intent_data, self.weather_config, forecast
dialog = get_dialog_for_timeframe(intent_data.timeframe, dialog_args)
dialog.build_next_precipitation_dialog()
spoken_percentage = self.translate(
"percentage-number", data=dict(number=dialog.data["percent"])
)
dialog.data.update(percent=spoken_percentage)
self._speak_weather(dialog)
@intent_handler(
AdaptIntent()
.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_args = intent_data, self.weather_config, intent_weather
dialog = get_dialog_for_timeframe(intent_data.timeframe, dialog_args)
dialog.build_humidity_dialog()
dialog.data.update(
percent=self.translate(
"percentage-number",
data=dict(number=dialog.data["percent"])
)
)
self._speak_weather(dialog)
@intent_handler(
AdaptIntent()
.one_of("query", "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)
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog_args = intent_data, self.weather_config, intent_weather
dialog = get_dialog_for_timeframe(intent_data.timeframe, dialog_args)
dialog.build_sunrise_dialog()
weather_location = self._build_display_location(intent_data)
self._display_sunrise_sunset(intent_weather, weather_location)
self._speak_weather(dialog)
@intent_handler(
AdaptIntent()
.one_of("query", "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)
weather = self._get_weather(intent_data)
if weather is not None:
intent_weather = weather.get_weather_for_intent(intent_data)
dialog_args = intent_data, self.weather_config, intent_weather
dialog = get_dialog_for_timeframe(intent_data.timeframe, dialog_args)
dialog.build_sunset_dialog()
weather_location = self._build_display_location(intent_data)
self._display_sunrise_sunset(intent_weather, weather_location)
self._speak_weather(dialog)
def _display_sunrise_sunset(self, forecast: DailyWeather, weather_location: str):
"""Display the sunrise and sunset.
Args:
forecast: daily forecasts to display
weather_location: the geographical location of the weather
"""
if self.platform == MARK_II:
self._display_sunrise_sunset_mark_ii(forecast, weather_location)
def _display_sunrise_sunset_mark_ii(
self, forecast: DailyWeather, weather_location: str
):
"""Display the sunrise and sunset on a Mark II device using a grid layout.
Args:
forecast: daily forecasts to display
weather_location: the geographical location of the weather
"""
self.gui.clear()
self.gui["weatherDate"] = forecast.date_time.strftime("%A %b %d")
self.gui["weatherLocation"] = weather_location
self.gui["sunrise"] = self._format_sunrise_sunset_time(forecast.sunrise)
self.gui["sunset"] = self._format_sunrise_sunset_time(forecast.sunset)
self.gui["ampm"] = self.config_core["time_format"] == TWELVE_HOUR
self.gui.show_page("sunrise_sunset_mark_ii.qml")
def _format_sunrise_sunset_time(self, date_time: datetime) -> str:
"""Format a the sunrise or sunset datetime into a string for GUI display.
The datetime builtin returns hour in two character format. Remove the
leading zero when present.
Args:
date_time: the sunrise or sunset
Returns:
the value to display on the screen
"""
if self.config_core["time_format"] == TWELVE_HOUR:
display_time = date_time.strftime("%I:%M")
if display_time.startswith("0"):
display_time = display_time[1:]
else:
display_time = date_time.strftime("%H:%M")
return display_time
def _report_current_weather(self, message: Message):
"""Handles all requests for current weather 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:
weather_location = self._build_display_location(intent_data)
self._display_current_conditions(weather, weather_location)
dialog = CurrentDialog(intent_data, self.weather_config, weather.current)
dialog.build_weather_dialog()
self._speak_weather(dialog)
if self.gui.connected and self.platform != MARK_II:
self._display_more_current_conditions(weather, weather_location)
dialog = CurrentDialog(intent_data, self.weather_config, weather.current)
dialog.build_high_low_temperature_dialog()
self._speak_weather(dialog)
if self.gui.connected:
if self.platform == MARK_II:
self._display_more_current_conditions(weather, weather_location)
sleep(5)
self._display_hourly_forecast(weather, weather_location)
else:
four_day_forecast = weather.daily[1:5]
self._display_multi_day_forecast(four_day_forecast, intent_data)
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
"""
if self.gui.connected:
page_name = "current_1_scalable.qml"
self.gui.clear()
self.gui["currentTemperature"] = weather.current.temperature
self.gui["weatherLocation"] = weather_location
self.gui["highTemperature"] = weather.current.high_temperature
self.gui["lowTemperature"] = weather.current.low_temperature
if self.platform == MARK_II:
self.gui["weatherCondition"] = weather.current.condition.image
page_name = page_name.replace("scalable", "mark_ii")
else:
self.gui["weatherCode"] = weather.current.condition.code
self.gui.show_page(page_name)
else:
self.enclosure.deactivate_mouth_events()
self.enclosure.weather_display(
weather.current.condition.code, weather.current.temperature
)
def _build_display_location(self, intent_data: WeatherIntent) -> str:
"""Build a string representing the location of the weather for display on GUI
The return value will be the device's configured location if no location is
specified in the intent. If a location is specified, and it is in the same
country as that in the device configuration, the return value will be city and
region. A specified location in a different country will result in a return
value of city and country.
Args:
intent_data: information about the intent that was triggered
Returns:
The weather location to be displayed on the GUI
"""
if intent_data.geolocation:
location = [intent_data.geolocation["city"]]
if intent_data.geolocation["country"] == self.weather_config.country:
location.append(intent_data.geolocation["region"])
else:
location.append(intent_data.geolocation["country"])
else:
location = [self.weather_config.city, self.weather_config.state]
return ", ".join(location)
def _display_more_current_conditions(
self, weather: WeatherReport, weather_location: str
):
"""Display current weather conditions on a device that supports a GUI.
This is the second screen that shows for current weather.
Args
weather: current weather conditions from Open Weather Maps
weather_location: geographical location of the reported weather
"""
page_name = "current_2_scalable.qml"
self.gui.clear()
self.gui["weatherLocation"] = weather_location
self.gui["windSpeed"] = weather.current.wind_speed
self.gui["humidity"] = weather.current.humidity
if self.platform == MARK_II:
page_name = page_name.replace("scalable", "mark_ii")
self.gui.replace_page(page_name)
else:
self.gui.show_page(page_name)
def _report_one_hour_weather(self, message: Message):
"""Handles requests for a one hour 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:
try:
forecast = weather.get_forecast_for_hour(intent_data)
except IndexError:
self.speak_dialog("forty-eight.hours.available")
else:
dialog = HourlyDialog(intent_data, self.weather_config, forecast)
dialog.build_weather_dialog()
self._speak_weather(dialog)
def _display_hourly_forecast(self, weather: WeatherReport, 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.hourly):
if not hour_count:
continue
if hour_count > 4:
break
if self.config_core["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=hourly.date_time.strftime(formatted_time),
precipitation=hourly.chance_of_precipitation,
temperature=hourly.temperature,
weatherCondition=hourly.condition.image,
)
)
self.gui["weatherLocation"] = weather_location
self.gui["hourlyForecast"] = dict(hours=hourly_forecast)
if self.gui.page is not None:
self.gui.replace_page("hourly_mark_ii.qml")
else:
self.gui.show_page("hourly_mark_ii.qml")
def _report_one_day_forecast(self, message: Message):
"""Handles all requests for a single day forecast.
Args:
message: Message Bus event information from the intent parser
"""
intent_data = WeatherIntent(message, self.lang)
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.platform == MARK_II:
self._display_one_day_mark_ii(forecast, intent_data)
for dialog in dialogs:
self._speak_weather(dialog)
def _display_one_day_mark_ii(
self, forecast: DailyWeather, intent_data: WeatherIntent
):
"""Display the forecast for a single day on a Mark II.
:param forecast: daily forecasts to display
"""
self.gui.clear()
self.gui["weatherLocation"] = self._build_display_location(intent_data)
self.gui["weatherCondition"] = forecast.condition.image
self.gui["weatherDate"] = forecast.date_time.strftime("%A %b %d")
self.gui["highTemperature"] = forecast.temperature.high
self.gui["lowTemperature"] = forecast.temperature.low
self.gui["chanceOfPrecipitation"] = str(forecast.chance_of_precipitation)
self.gui.show_page("single_day_mark_ii.qml")
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
"""
intent_data = WeatherIntent(message, self.lang)
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)
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)
def _build_forecast_dialogs(
self, forecast: List[DailyWeather], 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, self.weather_config, 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
"""
intent_data = WeatherIntent(message, self.lang)
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[DailyWeather], 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, self.weather_config, forecast)
dialog.build_condition_dialog(condition=condition)
dialogs.append(dialog)
return dialogs
def _build_weekly_temperature_dialog(
self, forecast: List[DailyWeather], 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, self.weather_config, forecast)
dialog.build_temperature_dialog()
return dialog
def _display_multi_day_forecast(
self, forecast: List[DailyWeather], intent_data: WeatherIntent
):
"""Display daily forecast data on devices that support the GUI.
Args:
forecast: daily forecasts to display
intent_data: Parsed intent data
"""
if self.platform == MARK_II:
self._display_multi_day_mark_ii(forecast, intent_data)
else:
self._display_multi_day_scalable(forecast)
def _display_multi_day_mark_ii(
self, forecast: List[DailyWeather], intent_data: WeatherIntent
):
"""Display daily forecast data on a Mark II.
The Mark II supports displaying four days of a forecast at a time.
Args:
forecast: daily forecasts to display
intent_data: Parsed intent data
"""
page_name = "daily_mark_ii.qml"
daily_forecast = []
for day in forecast:
daily_forecast.append(
dict(
weatherCondition=day.condition.image,
day=day.date_time.strftime("%a"),
highTemperature=day.temperature.high,
lowTemperature=day.temperature.low,
)
)
self.gui.clear()
self.gui["dailyForecast"] = dict(days=daily_forecast[:4])
self.gui["weatherLocation"] = self._build_display_location(intent_data)
self.gui.show_page(page_name)
if len(forecast) > 4:
sleep(15)
self.gui.clear()
self.gui["dailyForecast"] = dict(days=daily_forecast[4:])
self.gui.show_page(page_name)