-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SkywarnPlus.py
2151 lines (1859 loc) · 83.4 KB
/
SkywarnPlus.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
#!/usr/bin/python3
"""
SkywarnPlus.py v0.8.0 by Mason Nelson
===============================================================================
SkywarnPlus is a utility that retrieves severe weather alerts from the National
Weather Service and integrates these alerts with an Asterisk/app_rpt based
radio repeater controller.
This utility is designed to be highly configurable, allowing users to specify
particular counties for which to check for alerts, the types of alerts to include
or block, and how these alerts are integrated into their radio repeater system.
This includes features such as automatic voice alerts and a tail message feature
for constant updates. All alerts are sorted by severity and cover a broad range
of weather conditions such as hurricane warnings, thunderstorms, heat waves, etc.
Configurable through a .yaml file, SkywarnPlus serves as a comprehensive and
flexible tool for those who need to stay informed about weather conditions
and disseminate this information through their radio repeater system.
This file is part of SkywarnPlus.
SkywarnPlus is free software: you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version. SkywarnPlus is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with SkywarnPlus. If not, see <https://www.gnu.org/licenses/>.
"""
import os
import json
import logging
import requests
import shutil
import fnmatch
import subprocess
import time
import wave
import contextlib
import math
import sys
import itertools
from datetime import datetime, timezone, timedelta
from dateutil import parser
from pydub import AudioSegment
from ruamel.yaml import YAML
from collections import OrderedDict
# Use ruamel.yaml instead of PyYAML
yaml = YAML()
# Directories and Paths
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
CONFIG_PATH = os.path.join(BASE_DIR, "config.yaml")
COUNTY_CODES_PATH = os.path.join(BASE_DIR, "CountyCodes.md")
# Open and read configuration file
with open(CONFIG_PATH, "r") as config_file:
config = yaml.load(config_file)
config = json.loads(json.dumps(config)) # Convert config to a normal dictionary
# Define whether SkywarnPlus is enabled in config.yaml
MASTER_ENABLE = config.get("SKYWARNPLUS", {}).get("Enable", False)
# Define tmp_dir and sounds_path
TMP_DIR = config.get("DEV", {}).get("TmpDir", "/tmp/SkywarnPlus")
SOUNDS_PATH = config.get("Alerting", {}).get(
"SoundsPath", os.path.join(BASE_DIR, "SOUNDS")
)
# Create tmp_dir if it doesn't exist
if TMP_DIR:
os.makedirs(TMP_DIR, exist_ok=True)
else:
print("Error: tmp_dir is not set.")
# Define Blocked events
GLOBAL_BLOCKED_EVENTS = config.get("Blocking", {}).get("GlobalBlockedEvents", [])
if GLOBAL_BLOCKED_EVENTS is None:
GLOBAL_BLOCKED_EVENTS = []
SAYALERT_BLOCKED_EVENTS = config.get("Blocking", {}).get("SayAlertBlockedEvents", [])
if SAYALERT_BLOCKED_EVENTS is None:
SAYALERT_BLOCKED_EVENTS = []
TAILMESSAGE_BLOCKED_EVENTS = config.get("Blocking", {}).get(
"TailmessageBlockedEvents", []
)
if TAILMESSAGE_BLOCKED_EVENTS is None:
TAILMESSAGE_BLOCKED_EVENTS = []
# Define Max Alerts
MAX_ALERTS = config.get("Alerting", {}).get("MaxAlerts", 99)
# Define audio_delay
AUDIO_DELAY = config.get("Asterisk", {}).get("AudioDelay", 0)
# Define Tailmessage configuration
TAILMESSAGE_CONFIG = config.get("Tailmessage", {})
ENABLE_TAILMESSAGE = TAILMESSAGE_CONFIG.get("Enable", False)
TAILMESSAGE_FILE = TAILMESSAGE_CONFIG.get(
"TailmessagePath", os.path.join(TMP_DIR, "wx-tail.wav")
)
# Define IDChange configuration
IDCHANGE_CONFIG = config.get("IDChange", {})
ENABLE_IDCHANGE = IDCHANGE_CONFIG.get("Enable", False)
# Data file path
DATA_FILE = os.path.join(TMP_DIR, "data.json")
# Tones directory
TONE_DIR = config["CourtesyTones"].get("ToneDir", os.path.join(SOUNDS_PATH, "TONES"))
# Define possible alert strings
ALERT_STRINGS = [
"911 Telephone Outage Emergency",
"Administrative Message",
"Air Quality Alert",
"Air Stagnation Advisory",
"Arroyo And Small Stream Flood Advisory",
"Ashfall Advisory",
"Ashfall Warning",
"Avalanche Advisory",
"Avalanche Warning",
"Avalanche Watch",
"Beach Hazards Statement",
"Blizzard Warning",
"Blizzard Watch",
"Blowing Dust Advisory",
"Blowing Dust Warning",
"Brisk Wind Advisory",
"Child Abduction Emergency",
"Civil Danger Warning",
"Civil Emergency Message",
"Coastal Flood Advisory",
"Coastal Flood Statement",
"Coastal Flood Warning",
"Coastal Flood Watch",
"Dense Fog Advisory",
"Dense Smoke Advisory",
"Dust Advisory",
"Dust Storm Warning",
"Earthquake Warning",
"Evacuation - Immediate",
"Excessive Heat Warning",
"Excessive Heat Watch",
"Extreme Cold Warning",
"Extreme Cold Watch",
"Extreme Fire Danger",
"Extreme Wind Warning",
"Fire Warning",
"Fire Weather Watch",
"Flash Flood Statement",
"Flash Flood Warning",
"Flash Flood Watch",
"Flood Advisory",
"Flood Statement",
"Flood Warning",
"Flood Watch",
"Freeze Warning",
"Freeze Watch",
"Freezing Fog Advisory",
"Freezing Rain Advisory",
"Freezing Spray Advisory",
"Frost Advisory",
"Gale Warning",
"Gale Watch",
"Hard Freeze Warning",
"Hard Freeze Watch",
"Hazardous Materials Warning",
"Hazardous Seas Warning",
"Hazardous Seas Watch",
"Hazardous Weather Outlook",
"Heat Advisory",
"Heavy Freezing Spray Warning",
"Heavy Freezing Spray Watch",
"High Surf Advisory",
"High Surf Warning",
"High Wind Warning",
"High Wind Watch",
"Hurricane Force Wind Warning",
"Hurricane Force Wind Watch",
"Hurricane Local Statement",
"Hurricane Warning",
"Hurricane Watch",
"Hydrologic Advisory",
"Hydrologic Outlook",
"Ice Storm Warning",
"Lake Effect Snow Advisory",
"Lake Effect Snow Warning",
"Lake Effect Snow Watch",
"Lake Wind Advisory",
"Lakeshore Flood Advisory",
"Lakeshore Flood Statement",
"Lakeshore Flood Warning",
"Lakeshore Flood Watch",
"Law Enforcement Warning",
"Local Area Emergency",
"Low Water Advisory",
"Marine Weather Statement",
"Nuclear Power Plant Warning",
"Radiological Hazard Warning",
"Red Flag Warning",
"Rip Current Statement",
"Severe Thunderstorm Warning",
"Severe Thunderstorm Watch",
"Severe Weather Statement",
"Shelter In Place Warning",
"Short Term Forecast",
"Small Craft Advisory",
"Small Craft Advisory For Hazardous Seas",
"Small Craft Advisory For Rough Bar",
"Small Craft Advisory For Winds",
"Small Stream Flood Advisory",
"Snow Squall Warning",
"Special Marine Warning",
"Special Weather Statement",
"Storm Surge Warning",
"Storm Surge Watch",
"Storm Warning",
"Storm Watch",
"Test",
"Tornado Warning",
"Tornado Watch",
"Tropical Depression Local Statement",
"Tropical Storm Local Statement",
"Tropical Storm Warning",
"Tropical Storm Watch",
"Tsunami Advisory",
"Tsunami Warning",
"Tsunami Watch",
"Typhoon Local Statement",
"Typhoon Warning",
"Typhoon Watch",
"Urban And Small Stream Flood Advisory",
"Volcano Warning",
"Wind Advisory",
"Wind Chill Advisory",
"Wind Chill Warning",
"Wind Chill Watch",
"Winter Storm Warning",
"Winter Storm Watch",
"Winter Weather Advisory",
]
# Generate the WA list based on the length of WS
ALERT_INDEXES = [str(i + 1) for i in range(len(ALERT_STRINGS))]
# Test if the script needs to start from a clean slate
CLEANSLATE = config.get("DEV", {}).get("CLEANSLATE", False)
if CLEANSLATE:
shutil.rmtree(TMP_DIR)
os.mkdir(TMP_DIR)
# Logging setup
LOG_CONFIG = config.get("Logging", {})
ENABLE_DEBUG = LOG_CONFIG.get("Debug", False)
LOG_FILE = LOG_CONFIG.get("LogPath", os.path.join(TMP_DIR, "SkywarnPlus.log"))
# Set up logging
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG if ENABLE_DEBUG else logging.INFO)
# Set up log message formatting
LOG_FORMATTER = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
# Set up console log handler
C_HANDLER = logging.StreamHandler()
C_HANDLER.setFormatter(LOG_FORMATTER)
LOGGER.addHandler(C_HANDLER)
# Set up file log handler
F_HANDLER = logging.FileHandler(LOG_FILE)
F_HANDLER.setFormatter(LOG_FORMATTER)
LOGGER.addHandler(F_HANDLER)
# Get the "CountyCodes" from the config
COUNTY_CODES_CONFIG = config.get("Alerting", {}).get("CountyCodes", [])
# Initialize COUNTY_CODES and COUNTY_WAVS
COUNTY_CODES = []
COUNTY_WAVS = []
# Check the type of "CountyCodes" config to handle both list and dictionary
if isinstance(COUNTY_CODES_CONFIG, list):
# If it's a list, check if it's a list of strings or dictionaries
if all(isinstance(i, str) for i in COUNTY_CODES_CONFIG):
# It's the old format and we can use it directly
COUNTY_CODES = COUNTY_CODES_CONFIG
elif all(isinstance(i, dict) for i in COUNTY_CODES_CONFIG):
# It's a list of dictionaries with WAV files
# We need to separate the county codes and the WAVs
for dic in COUNTY_CODES_CONFIG:
for key, value in dic.items():
COUNTY_CODES.append(key)
COUNTY_WAVS.append(value)
elif isinstance(COUNTY_CODES_CONFIG, dict):
# If it's a dictionary, it's got WAV files
# We need to separate the county codes and the WAVs
COUNTY_CODES = list(COUNTY_CODES_CONFIG.keys())
COUNTY_WAVS = list(COUNTY_CODES_CONFIG.values())
else:
# Invalid format, set it to an empty list
COUNTY_CODES = []
COUNTY_WAVS = []
# Log some debugging information
LOGGER.debug("Base directory: %s", BASE_DIR)
LOGGER.debug("Temporary directory: %s", TMP_DIR)
LOGGER.debug("Sounds path: %s", SOUNDS_PATH)
LOGGER.debug("Tailmessage path: %s", TAILMESSAGE_FILE)
LOGGER.debug("Global Blocked events: %s", GLOBAL_BLOCKED_EVENTS)
LOGGER.debug("SayAlert Blocked events: %s", SAYALERT_BLOCKED_EVENTS)
LOGGER.debug("Tailmessage Blocked events: %s", TAILMESSAGE_BLOCKED_EVENTS)
def load_state():
"""
Load the state from the state file if it exists, else return an initial state.
The state file is expected to be a JSON file. If certain keys are missing in the
loaded state, this function will provide default values for those keys.
"""
# Check if the state data file exists
if os.path.exists(DATA_FILE):
with open(DATA_FILE, "r") as file:
state = json.load(file)
# Ensure 'alertscript_alerts' key is present in the state, default to an empty list
state["alertscript_alerts"] = state.get("alertscript_alerts", [])
# Process 'last_alerts' key to maintain the order of alerts using OrderedDict
# This step is necessary because JSON does not preserve order by default
last_alerts = state.get("last_alerts", [])
state["last_alerts"] = OrderedDict((x[0], x[1]) for x in last_alerts)
# Ensure 'last_sayalert' and 'active_alerts' keys are present in the state
state["last_sayalert"] = state.get("last_sayalert", [])
state["active_alerts"] = state.get("active_alerts", [])
return state
# If the state data file does not exist, return a default state
else:
return {
"ct": None,
"id": None,
"alertscript_alerts": [],
"last_alerts": OrderedDict(),
"last_sayalert": [],
"active_alerts": [],
}
def save_state(state):
"""
Save the state to the state file.
The state is saved as a JSON file. The function ensures certain keys in the state
are converted to lists before saving, ensuring consistency and ease of processing
when the state is later loaded.
"""
# Convert 'alertscript_alerts', 'last_sayalert', and 'active_alerts' keys to lists
# This ensures consistency in data format, especially useful when loading the state later
state["alertscript_alerts"] = list(state["alertscript_alerts"])
state["last_sayalert"] = list(state["last_sayalert"])
state["active_alerts"] = list(state["active_alerts"])
# Convert 'last_alerts' from OrderedDict to list of items
# This step is necessary because JSON does not natively support OrderedDict
state["last_alerts"] = list(state["last_alerts"].items())
# Save the state to the data file in a formatted manner
with open(DATA_FILE, "w") as file:
json.dump(state, file, ensure_ascii=False, indent=4)
def get_alerts(countyCodes):
"""
Retrieves severe weather alerts for specified county codes and processes them.
"""
# Define mappings to convert severity levels from various terminologies to a numeric scale
severity_mapping_api = {
"Extreme": 4,
"Severe": 3,
"Moderate": 2,
"Minor": 1,
"Unknown": 0,
}
severity_mapping_words = {"Warning": 4, "Watch": 3, "Advisory": 2, "Statement": 1}
# Initialize storage for the alerts and a set to keep track of processed alerts
alerts = OrderedDict()
seen_alerts = set()
# Log current time for reference
current_time = datetime.now(timezone.utc)
LOGGER.debug("getAlerts: Current time: %s", current_time)
# Handle alert injection for development/testing purposes
if config.get("DEV", {}).get("INJECT", False):
LOGGER.debug("getAlerts: DEV Alert Injection Enabled")
injected_alerts = config["DEV"].get("INJECTALERTS", [])
LOGGER.debug("getAlerts: Injecting alerts: %s", injected_alerts)
max_counties = len(countyCodes) # Assuming countyCodes is a list of counties
county_codes_cycle = itertools.cycle(countyCodes)
county_assignment_counter = 1
for alert_info in injected_alerts:
if isinstance(alert_info, dict):
alert_title = alert_info.get("Title", "")
specified_counties = alert_info.get("CountyCodes", [])
else:
continue # Ignore if not a dictionary
last_word = alert_title.split()[-1]
severity = severity_mapping_words.get(last_word, 0)
description = "This alert was manually injected as a test."
end_time_str = alert_info.get("EndTime")
county_data = []
# If no counties are specified, use the ones provided to the function in an increasing manner
if not specified_counties:
# Limit the number of counties assigned to not exceed max_counties
counties_to_assign = min(county_assignment_counter, max_counties)
specified_counties = [
next(county_codes_cycle) for _ in range(counties_to_assign)
]
county_assignment_counter += 1 # Increment for the next injected alert
for county in specified_counties:
if county not in countyCodes:
LOGGER.error(
"Specified county code '%s' is not defined in the config. Using next available county code from the config.",
county,
)
county = next(county_codes_cycle)
end_time = (
datetime.strptime(end_time_str, "%Y-%m-%dT%H:%M:%SZ")
if end_time_str
else current_time + timedelta(hours=1)
)
county_data.append(
{
"county_code": county,
"severity": severity,
"description": description,
"end_time_utc": end_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
}
)
alerts[alert_title] = (
county_data # Add the list of dictionaries to the alert
)
# If injected alerts are used, we return them here and don't proceed with the function.
return sort_alerts(alerts)
# Configuration specifies whether to use 'effective' or 'onset' time for alerts.
# Depending on the configuration, we set the appropriate keys for start and end time.
timetype_mode = config.get("Alerting", {}).get("TimeType", "onset")
if timetype_mode == "effective":
LOGGER.debug("getAlerts: Using effective time for alerting")
time_type_start = "effective"
time_type_end = "expires"
elif timetype_mode == "onset":
LOGGER.debug("getAlerts: Using onset time for alerting")
time_type_start = "onset"
time_type_end = "ends"
else:
LOGGER.error(
"getAlerts: Invalid TimeType specified in config.yaml. Using onset time instead."
)
time_type_start = "onset"
time_type_end = "ends"
# Loop over each county code and retrieve alerts from the API.
for countyCode in countyCodes:
url = "https://api.weather.gov/alerts/active?zone={}".format(countyCode)
#
# WARNING: ONLY USE THIS FOR DEVELOPMENT PURPOSES
# THIS URL WILL RETURN ALL ACTIVE ALERTS IN THE UNITED STATES
# url = "https://api.weather.gov/alerts/active"
try:
# If we can get a successful response from the API, we process the alerts from the response.
response = requests.get(url)
response.raise_for_status()
LOGGER.debug(
"getAlerts: Checking for alerts in %s at URL: %s", countyCode, url
)
alert_data = response.json()
for feature in alert_data["features"]:
# Extract start and end times. If end time is missing, use 'expires' time.
start = feature["properties"].get(time_type_start)
end = feature["properties"].get(time_type_end)
if not end:
end = feature["properties"].get("expires")
LOGGER.debug(
'getAlerts: %s has no "%s" time, using "expires" time instead: %s',
feature["properties"]["event"],
time_type_end,
end,
)
if start and end:
# If both start and end times are available, convert them to datetime objects.
start_time = parser.isoparse(start)
end_time = parser.isoparse(end)
# Convert alert times to UTC.
start_time_utc = start_time.astimezone(timezone.utc)
end_time_utc = end_time.astimezone(timezone.utc)
event = feature["properties"]["event"]
# If the current time is within the alert's active period, we process it further.
if start_time_utc <= current_time < end_time_utc:
description = feature["properties"].get("description", "")
severity = feature["properties"].get("severity", None)
# Check if the event is globally blocked as per the configuration. If it is, skip this event.
is_blocked = False
for global_blocked_event in GLOBAL_BLOCKED_EVENTS:
if fnmatch.fnmatch(event, global_blocked_event):
LOGGER.debug(
"getAlerts: Globally Blocking %s as per configuration",
event,
)
is_blocked = True
break
# If the event is globally blocked, we skip the remaining code in this loop iteration and move to the next one.
if is_blocked:
continue
# Determine severity from event name or API's severity value.
if severity is None:
last_word = event.split()[-1]
severity = severity_mapping_words.get(last_word, 0)
else:
severity = severity_mapping_api.get(severity, 0)
# Log the alerts and their severity level for debugging purposes.
LOGGER.debug(
"getAlerts: %s - %s - Severity: %s",
countyCode,
event,
severity,
)
# Check if the event has already been processed (seen).
# If it has been seen, we add a new dictionary to its list of alerts. This dictionary contains details about the alert.
if event in seen_alerts:
alerts[event].append(
{
"county_code": countyCode, # the county code the alert is for
"severity": severity, # the severity level of the alert
"description": description, # a description of the alert
"end_time_utc": end_time_utc.strftime(
"%Y-%m-%dT%H:%M:%S.%fZ"
), # the time the alert ends in UTC
}
)
# If the event hasn't been seen before, we create a new list entry in the 'alerts' dictionary for this event.
else:
alerts[event] = [
{
"county_code": countyCode, # the county code the alert is for
"severity": severity, # the severity level of the alert
"description": description, # a description of the alert
"end_time_utc": end_time_utc.strftime(
"%Y-%m-%dT%H:%M:%S.%fZ"
), # the time the alert ends in UTC
}
]
# Add the event to the set of seen alerts.
seen_alerts.add(event)
# If the current time is not within the alert's active period, we skip it.
else:
time_difference = time_until(start_time_utc, current_time)
LOGGER.debug(
"getAlerts: Skipping %s, not active for another %s.",
event,
time_difference,
)
LOGGER.debug(
"Current time: %s | Alert start: %s | Alert end %s",
current_time,
start_time_utc,
end_time_utc,
)
else:
LOGGER.debug(
"getAlerts: Skipping %s, missing start or end time.",
feature["properties"]["event"],
)
except requests.exceptions.RequestException as e:
LOGGER.debug("Failed to retrieve alerts for %s. Reason: %s", countyCode, e)
LOGGER.debug("API unreachable. Using stored data instead.")
# Load alerts from data.json
if os.path.isfile(DATA_FILE):
with open(DATA_FILE) as f:
data = json.load(f)
stored_alerts = data.get("last_alerts", [])
# Filter alerts by end_time_utc
current_time_str = datetime.now(timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%S.%fZ"
)
LOGGER.debug("Current time: %s", current_time_str)
alerts = {}
for stored_alert in stored_alerts:
event = stored_alert[0]
alert_list = stored_alert[1]
alerts[event] = []
for alert in alert_list:
end_time_str = alert["end_time_utc"]
if parser.parse(end_time_str) >= parser.parse(
current_time_str
):
LOGGER.debug(
"getAlerts: Keeping %s because it does not expire until %s",
event,
end_time_str,
)
alerts[event].append(alert)
else:
LOGGER.debug(
"getAlerts: Removing %s because it expired at %s",
event,
end_time_str,
)
else:
LOGGER.error("No stored data available.")
break
alerts = OrderedDict(
sorted(
alerts.items(),
key=lambda item: (
max([x["severity"] for x in item[1]]), # Max Severity
severity_mapping_words.get(item[0].split()[-1], 0), # Words severity
),
reverse=True,
)
)
# If the number of alerts exceeds the maximum defined constant, we truncate the alerts.
alerts = OrderedDict(list(alerts.items())[:MAX_ALERTS])
return alerts
def sort_alerts(alerts):
"""
Sorts and limits the alerts based on their severity and word severity.
"""
# Define mapping for converting common alert terminologies to a numeric severity scale
severity_mapping_words = {"Warning": 4, "Watch": 3, "Advisory": 2, "Statement": 1}
# Sort the alerts first by their maximum severity, and then by their word severity
sorted_alerts = OrderedDict(
sorted(
alerts.items(),
key=lambda item: (
max([x["severity"] for x in item[1]]), # Max Severity for the alert
severity_mapping_words.get(
item[0].split()[-1], 0
), # Severity based on last word in the alert title
),
reverse=True, # Sort in descending order
)
)
# Truncate the list of alerts to the maximum allowed number (MAX_ALERTS)
limited_alerts = OrderedDict(list(sorted_alerts.items())[:MAX_ALERTS])
return limited_alerts
def time_until(start_time_utc, current_time):
"""
Calculate the time difference between two datetime objects and returns it
as a formatted string.
"""
# Calculate the time difference between the two datetime objects
delta = start_time_utc - current_time
# Determine the sign (used for formatting)
sign = "-" if delta < timedelta(0) else ""
# Decompose the time difference into days, hours, and minutes
days, remainder = divmod(abs(delta.total_seconds()), 86400)
hours, remainder = divmod(remainder, 3600)
minutes, _ = divmod(remainder, 60)
# Return the time difference as a formatted string
return "{}{} days, {} hours, {} minutes".format(
sign, int(days), int(hours), int(minutes)
)
def say_alerts(alerts):
"""
Generate and broadcast severe weather alert sounds on Asterisk.
"""
# Load the current state
state = load_state()
# Extract only the alert names and associated counties
alert_names_and_counties = {
alert: [county["county_code"] for county in counties]
for alert, counties in alerts.items()
}
# Filter out alerts that are blocked based on configuration
filtered_alerts_and_counties = {}
for alert, county_codes in alert_names_and_counties.items():
if any(
fnmatch.fnmatch(alert, blocked_event)
for blocked_event in SAYALERT_BLOCKED_EVENTS
):
LOGGER.debug("sayAlert: blocking %s as per configuration", alert)
continue
filtered_alerts_and_counties[alert] = county_codes
# Check if the filtered alerts are the same as the last run
if filtered_alerts_and_counties == state.get("last_sayalert", {}):
LOGGER.debug(
"sayAlert: alerts and counties are the same as the last broadcast - skipping."
)
return
# Update the state with the current alerts
state["last_sayalert"] = filtered_alerts_and_counties
save_state(state)
# Initialize the audio segments and paths
alert_file = "{}/alert.wav".format(TMP_DIR)
word_space = AudioSegment.silent(duration=600)
sound_effect = AudioSegment.from_wav(
os.path.join(
SOUNDS_PATH,
"ALERTS",
"EFFECTS",
config.get("Alerting", {}).get("AlertSeperator", "Woodblock.wav"),
)
)
intro_effect = AudioSegment.from_wav(
os.path.join(
SOUNDS_PATH,
"ALERTS",
"EFFECTS",
config.get("Alerting", {}).get("AlertSound", "Duncecap.wav.wav"),
)
)
combined_sound = (
intro_effect
+ word_space
+ AudioSegment.from_wav(os.path.join(SOUNDS_PATH, "ALERTS", "SWP_148.wav"))
)
# Build the combined sound with alerts and county names
alert_count = 0
for alert, counties in alerts.items():
if alert in filtered_alerts_and_counties:
try:
descriptions = [county["description"] for county in counties]
end_times = [county["end_time_utc"] for county in counties]
index = ALERT_STRINGS.index(alert)
audio_file = AudioSegment.from_wav(
os.path.join(
SOUNDS_PATH, "ALERTS", "SWP_{}.wav".format(ALERT_INDEXES[index])
)
)
combined_sound += sound_effect + audio_file
LOGGER.debug(
"sayAlert: Added %s (SWP_%s.wav) to alert sound",
alert,
ALERT_INDEXES[index],
)
if config["Alerting"]["WithMultiples"]:
if len(set(descriptions)) > 1 or len(set(end_times)) > 1:
LOGGER.debug(
"sayAlert: Found multiple unique instances of the alert %s",
alert,
)
multiples_sound = AudioSegment.from_wav(
os.path.join(SOUNDS_PATH, "ALERTS", "SWP_149.wav")
)
combined_sound += (
AudioSegment.silent(duration=200) + multiples_sound
)
alert_count += 1
added_county_codes = set()
for county in counties:
if counties.index(county) == 0:
word_space = AudioSegment.silent(duration=600)
else:
word_space = AudioSegment.silent(duration=400)
county_code = county["county_code"]
if (
COUNTY_WAVS
and county_code in COUNTY_CODES
and county_code not in added_county_codes
):
index = COUNTY_CODES.index(county_code)
county_name_file = COUNTY_WAVS[index]
LOGGER.debug(
"sayAlert: Adding %s ID %s to %s",
county_code,
county_name_file,
alert,
)
try:
combined_sound += word_space + AudioSegment.from_wav(
os.path.join(SOUNDS_PATH, county_name_file)
)
except FileNotFoundError:
LOGGER.error(
"sayAlert: County audio file not found: %s",
os.path.join(SOUNDS_PATH, county_name_file),
)
added_county_codes.add(county_code)
if counties.index(county) == len(counties) - 1:
combined_sound += AudioSegment.silent(duration=600)
except ValueError:
LOGGER.error("sayAlert: Alert not found: %s", alert)
except FileNotFoundError:
LOGGER.error(
"sayAlert: Alert audio file not found: %s/ALERTS/SWP_%s.wav",
SOUNDS_PATH,
ALERT_INDEXES[index],
)
if alert_count == 0:
LOGGER.debug("sayAlert: All alerts were blocked, not broadcasting any alerts.")
return
alert_suffix = config.get("Alerting", {}).get("SayAlertSuffix", None)
if alert_suffix is not None:
suffix_silence = AudioSegment.silent(duration=600)
LOGGER.debug("sayAlert: Adding alert suffix %s", alert_suffix)
suffix_file = os.path.join(SOUNDS_PATH, alert_suffix)
suffix_sound = AudioSegment.from_wav(suffix_file)
combined_sound += suffix_silence + suffix_sound
if AUDIO_DELAY > 0:
LOGGER.debug("sayAlert: Prepending audio with %sms of silence", AUDIO_DELAY)
silence = AudioSegment.silent(duration=AUDIO_DELAY)
combined_sound = silence + combined_sound
LOGGER.debug("sayAlert: Exporting alert sound to %s", alert_file)
converted_combined_sound = convert_audio(combined_sound)
converted_combined_sound.export(alert_file, format="wav")
LOGGER.debug("sayAlert: Replacing tailmessage with silence")
silence = AudioSegment.silent(duration=100)
converted_silence = convert_audio(silence)
converted_silence.export(TAILMESSAGE_FILE, format="wav")
node_numbers = config.get("Asterisk", {}).get("Nodes", [])
for node_number in node_numbers:
LOGGER.info("Broadcasting alert on node %s", node_number)
command = '/usr/sbin/asterisk -rx "rpt localplay {} {}"'.format(
node_number, os.path.splitext(os.path.abspath(alert_file))[0]
)
subprocess.run(command, shell=True)
# Get the duration of the alert_file
with contextlib.closing(wave.open(alert_file, "r")) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = math.ceil(frames / float(rate))
wait_time = duration + 10
LOGGER.debug(
"Waiting %s seconds for Asterisk to make announcement to avoid doubling alerts with tailmessage...",
wait_time,
)
time.sleep(wait_time)
def say_allclear():
"""
Generate and broadcast 'all clear' message on Asterisk.
"""
# Load current state and clear the last_sayalert list
state = load_state()
state["last_sayalert"] = []
save_state(state)
# Define file paths for the sounds
all_clear_sound_file = os.path.join(
config.get("Alerting", {}).get("SoundsPath"),
"ALERTS",
"EFFECTS",
config.get("Alerting", {}).get("AllClearSound"),
)
swp_147_file = os.path.join(SOUNDS_PATH, "ALERTS", "SWP_147.wav")
# Load sound files into AudioSegment objects
all_clear_sound = AudioSegment.from_wav(all_clear_sound_file)
swp_147_sound = AudioSegment.from_wav(swp_147_file)
# Generate silence for spacing between sounds
silence = AudioSegment.silent(duration=600) # 600 ms of silence
# Combine the "all clear" sound and SWP_147 sound with the configured silence between them
combined_sound = all_clear_sound + silence + swp_147_sound
# Add a delay before the sound if configured
if AUDIO_DELAY > 0:
LOGGER.debug("sayAllClear: Prepending audio with %sms of silence", AUDIO_DELAY)
delay_silence = AudioSegment.silent(duration=AUDIO_DELAY)
combined_sound = delay_silence + combined_sound
# Append a suffix to the sound if configured
if config.get("Alerting", {}).get("SayAllClearSuffix", None) is not None:
suffix_silence = AudioSegment.silent(
duration=600
) # 600ms silence before the suffix
suffix_file = os.path.join(
SOUNDS_PATH, config.get("Alerting", {}).get("SayAllClearSuffix")
)
LOGGER.debug("sayAllClear: Adding all clear suffix %s", suffix_file)
suffix_sound = AudioSegment.from_wav(suffix_file)
combined_sound += (
suffix_silence + suffix_sound
) # Append the silence and then the suffix to the combined sound
# Now, convert the final combined sound
converted_combined_sound = convert_audio(combined_sound)
# Export the final converted sound to a file
all_clear_file = os.path.join(TMP_DIR, "allclear.wav")
converted_combined_sound.export(all_clear_file, format="wav")
# Play the "all clear" sound on the configured Asterisk nodes
node_numbers = config.get("Asterisk", {}).get("Nodes", [])
for node_number in node_numbers:
LOGGER.info("Broadcasting all clear message on node %s", node_number)
command = '/usr/sbin/asterisk -rx "rpt localplay {} {}"'.format(
node_number, os.path.splitext(os.path.abspath(all_clear_file))[0]
)
subprocess.run(command, shell=True)
def build_tailmessage(alerts):
"""
Build a tailmessage, which is a short message appended to the end of a
transmission to update on the weather conditions.
"""
# Determine whether the user has enabled county identifiers
county_identifiers = config.get("Tailmessage", {}).get("TailmessageCounties", False)
# Extract only the alert names from the OrderedDict keys
alert_names = [alert for alert in alerts.keys()]
# Get the suffix config
tailmessage_suffix = config.get("Tailmessage", {}).get("TailmessageSuffix", None)
# If alerts is empty
if not alerts:
LOGGER.debug("buildTailMessage: No alerts, creating silent tailmessage")
silence = AudioSegment.silent(duration=100)
converted_silence = convert_audio(silence)
converted_silence.export(TAILMESSAGE_FILE, format="wav")
return
combined_sound = AudioSegment.empty()
sound_effect = AudioSegment.from_wav(
os.path.join(
SOUNDS_PATH,
"ALERTS",
"EFFECTS",
config.get("Alerting", {}).get("AlertSeperator", "Woodblock.wav"),
)
)
for (