-
Notifications
You must be signed in to change notification settings - Fork 6
/
asmara.py
2751 lines (2689 loc) · 122 KB
/
asmara.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
"""
Note: Please do absolute imports, it allows me to clean up shit we don't use, and doesn't import extra code. It should be more efficient anyways.
"""
# Standard Library
from datetime import datetime as DT
from datetime import timezone as TZ
from datetime import timedelta as timedelta
from json import dump, load
from multiprocessing import Process, active_children
from os import getcwd, path, remove, walk
from random import choice, shuffle
from subprocess import PIPE, Popen
from sys import exit
from threading import Thread, Barrier, enumerate, current_thread
from time import mktime, sleep
from warnings import filterwarnings
from argparse import ArgumentParser
# Third-Party
from EAS2Text.EAS2Text import EAS2Text
from EASGen.EASGen import EASGen
from numpy import (
append,
blackman,
empty,
fft,
frombuffer,
int16,
log,
log10,
)
from pydub import AudioSegment
from pydub.effects import normalize
from pydub.generators import Sine
from pydub.utils import make_chunks, mediainfo
from requests import get, exceptions
from calendar import isleap
# First-Party
from utilities import utilities, severity
filterwarnings("ignore")
currentAlert = []
liveAlert = {}
class AS_MON(Process):
global currentAlert
global liveAlert
__monitors__ = {}
__receivedAlerts__ = {}
__receivedAlertsIndex__ = []
__pendingAlerts__ = {}
__run__ = True
__liveAlertLock__ = False
__useATTNDT__ = True
def __init__(self, URL: str = "") -> None:
self.__monitorName__ = None
self.__monitor__ = {
"Type": "Stream",
"URL": URL,
"State": True,
"Online": True,
"Alert": False,
"AttentionTone": False,
"Live": False,
}
if isinstance(URL, dict):
if "AUD" in URL:
self.__monitor__["Type"] = "Audio"
self.__monitor__["URL"] = URL["AUD"]
elif "SDR" in URL:
self.__monitor__["Type"] = "Radio"
self.__monitor__["URL"] = URL["SDR"]
num = 1
while self.__monitorName__ == None:
if str(num) in self.__monitors__:
num = num + 1
else:
self.__monitorName__ = str(num)
self.__updateMon__(self.__monitorName__, self.__monitor__)
self.__decode__ = None
self.__stream__ = None
self.__alertData__ = {}
self.__decThread__ = Thread(
target=self.__decoder__,
name=f"DECODER-{self.__monitorName__}",
daemon=True,
)
self.__monThread__ = Thread(
target=self.__recorder__,
name=f"MONITOR-{self.__monitorName__}",
daemon=True,
)
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Created.",
classType="MAIN",
sev=severity.debug,
)
self.__decodeLock__ = Barrier(2)
self.__monThread__.start()
self.__decThread__.start()
def killMon(self):
self.__monitor__["State"] = False
while self.__decode__.poll() == None:
self.__decode__.terminate()
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Decoder Terminated.",
classType="DECODER",
sev=severity.trace,
)
while self.__stream__.poll() == None:
self.__stream__.terminate()
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Recorder Terminated.",
classType="MONITOR",
sev=severity.trace,
)
try:
del self.__monitors__[self.__monitorName__]
except ValueError:
pass
return
@classmethod
def __updateMon__(cls, monName, mon):
cls.__monitors__[monName] = mon
@classmethod
def __liveLock__(cls):
cls.__liveAlertLock__ = True
@classmethod
def __LiveUnlock__(cls):
cls.__liveAlertLock__ = False
@classmethod
def __liveStatus__(cls):
return cls.__liveAlertLock__
def __MonState__(self, update: bool = False):
if update:
self.__updateMon__(self.__monitorName__, self.__monitor__)
else:
return (
"Online"
if self.__monitor__["Online"]
else "Offline"
if self.__monitor__["State"]
else "Disabled"
)
def __ATTNDetection__(self, pkt, bufferSize, sampleRate, window):
dBDect = 10
fin = []
bandPasses = [
(
float((800 / (sampleRate / bufferSize)) + 1),
float((900 / (sampleRate / bufferSize)) - 1),
[851, 852, 853, 854, 855],
),
(
float((900 / (sampleRate / bufferSize)) + 1),
float((1000 / (sampleRate / bufferSize)) - 1),
[958, 959, 960, 961, 962],
),
(
float((1000 / (sampleRate / bufferSize)) + 1),
float((2000 / (sampleRate / bufferSize)) - 1),
[1048, 1049, 1050, 1051, 1052],
),
]
try:
for bandPass in bandPasses:
if len(pkt) == bufferSize:
indata = pkt * window
bp = fft.rfft(indata)
minFilterBin = bandPass[0]
maxFilterBin = bandPass[1]
for i in range(len(bp)):
if i < minFilterBin:
bp[i] = 0
if i > maxFilterBin:
bp[i] = 0
fftData = abs(bp) ** 2
which = fftData[1:].argmax() + 1
dB = 10 * log10(1e-20 + abs(bp[which]))
if round(dB) >= dBDect:
if which != len(fftData) - 1:
y0, y1, y2 = log(fftData[which - 1 : which + 2 :])
x1 = (y2 - y0) * 0.5 / (2 * y1 - y2 - y0)
thefreq = (which + x1) * sampleRate / bufferSize
else:
thefreq = which * sampleRate / bufferSize
if round(thefreq) in bandPass[2]:
fin.append(True)
else:
fin.append(False)
else:
fin.append(False)
else:
fin.append(False)
if (fin[0] and fin[1]) or fin[2] or (fin[0] and fin[1] and fin[2]):
return True
else:
return False
except:
return False
@classmethod
def __alertToOld__(cls, ZCZC, alert):
if ZCZC in cls.__receivedAlertsIndex__:
cls.__receivedAlerts__[ZCZC] = alert
else:
cls.__receivedAlerts__[ZCZC] = alert
cls.__receivedAlertsIndex__.append(ZCZC)
@classmethod
def __alertFromOld__(cls, index: int = 0) -> dict:
try:
alert = cls.__receivedAlertsIndex__.pop(index)
prevAlert = cls.__receivedAlerts__.pop(alert)
except Exception as E:
utilities.autoPrint(
text=f"{type(E).__name__}, {E}",
classType="MAIN",
sev=severity.error,
)
tb = E.__traceback__
while tb is not None:
utilities.autoPrint(
text=f"File: {tb.tb_frame.f_code.co_filename}\nFunc: {tb.tb_frame.f_code.co_name}\nLine: {tb.tb_lineno}",
classType="MAIN",
sev=severity.error,
)
tb = tb.tb_next
return {alert: prevAlert}
def __decoder__(self):
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Opening Decoder Thread.",
classType="DECODER",
sev=severity.trace,
)
try:
samedec_version = Popen(["samedec", "-V"], stdout=PIPE).communicate()[0].decode("UTF-8").strip()
if not samedec_version.startswith("samedec 0.1."):
self.__decode__ = Popen(
["samedec", "-r", "24000"],
stdout=PIPE,
stdin=PIPE,
stderr=PIPE,
bufsize=1,
)
else:
utilities.autoPrint(
text=f"SAMEDEC is not version 0.2 or higher! Recommended version is 0.2.3.",
classType="DECODER",
sev=severity.fatal,
)
AS_MAN.killAsmara()
exit(1)
except FileNotFoundError:
utilities.autoPrint(
text=f"Samedec is not installed on the computer. Please install SAMEDEC 0.2.3 or higher.",
classType="DECODER",
sev=severity.fatal,
)
AS_MAN.killAsmara()
exit(1)
utilities.autoPrint(
text=f"{self.__monitorName__}: Ready.",
classType="DECODER",
sev=severity.trace,
)
self.__decodeLock__.wait()
utilities.autoPrint(
text=f"{self.__monitorName__}: Running.",
classType="DECODER",
sev=severity.trace,
)
while self.__run__:
if not self.__monitor__["State"]:
sleep(1)
else:
try:
decode = (
self.__decode__.stdout.readline()
.decode("utf-8")
.strip("\n")
)
if "ZCZC" in decode:
noCall = "-".join(decode.split("-")[:-2]) + "-"
headerTranslation = EAS2Text(decode)
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Receiving Alert:\n{headerTranslation.EASText}\n{decode}",
classType="DECODER",
sev=severity.alert,
)
if headerTranslation.evnt == "EAN":
utilities.autoPrint(
text=f"EAN RECIEVED ON MONITOR {self.__monitorName__}.",
classType="DECODER",
sev=severity.warning,
)
elif headerTranslation.evnt == "EAT":
utilities.autoPrint(
text=f"EAT RECIEVED ON MONITOR {self.__monitorName__}.",
classType="DECODER",
sev=severity.warning,
)
try:
if noCall in self.__receivedAlerts__:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert already processed.",
classType="DECODER",
sev=severity.alert,
)
self.__monitor__["Alert"] = False
else:
x = DT.strptime(
decode.split("-")[-3], "%j%H%M"
)
expiryOffset = 0
timeStamp = decode.split("-")[-4].split("+")[1]
currDate = DT.now(TZ.utc)
currYear = currDate.today().year
leapDate = f"2/29/{currYear}"
if isleap(currYear):
if DT.now(TZ.utc).strftime('%Y-%m-%d') > DT.strptime(leapDate,"%m/%d/%Y").strftime('%Y-%m-%d'):
expiryOffset = 86400
elif DT.now(TZ.utc).strftime('%Y-%m-%d') == DT.strptime(leapDate,"%m/%d/%Y").strftime('%Y-%m-%d'):
midnight = (DT.now(TZ.utc) + timedelta(days=1)).replace(hour=0, minute=0, microsecond=0, second=0)
expiryOffset = 86400 - (DT.now(TZ.utc) - midnight).seconds
print(expiryOffset)
else:
expiryOffset = 0
startTime = mktime(
DT(
DT.utcnow().year,
x.month,
x.day,
x.hour,
x.minute,
).timetuple()
)
endTime = startTime + (
(int(timeStamp[:2]) * 60) * 60
+ int(timeStamp[2:]) * 60
)
now = mktime(DT.utcnow().timetuple()) + expiryOffset
filt = self.__FilterManager__(
headerTranslation.org,
headerTranslation.evnt,
headerTranslation.FIPS,
headerTranslation.callsign,
)
utilities.autoPrint(
text=f"now: {now}\nstartTime: {startTime}\n endTime: {endTime}\nnow - S.T: {now - startTime}\nnow - E.T: {now - endTime}",
classType="DECODER",
sev=severity.trace,
)
if now >= endTime:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert is Expired.",
classType="DECODER",
sev=severity.alert,
)
self.__monitor__["Alert"] = False
elif (now - startTime) < 0 and int(
now - startTime
) < -300:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert is *Very* Expired.",
classType="DECODER",
sev=severity.alert,
)
self.__monitor__["Alert"] = False
else:
if filt["Matched"]:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert is New and Valid.",
classType="DECODER",
sev=severity.alert,
)
if (now - startTime) < 0 and int(
now - startTime
) < -300:
wait_time = int(
round(
(
int(
0
- (now - startTime)
)
/ 60
),
0,
)
)
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert is approx {wait_time} minutes early, waiting for effect...",
classType="DECODER",
sev=severity.debug,
)
filt[
"Actions"
] = f"Relay:{wait_time}"
self.__alertData__ = {
"Monitor": f"Monitor {self.__monitorName__}",
"Time": now,
"Event": " ".join(
headerTranslation.evntText.split(
" "
)[
1:
]
),
"Protocol": noCall,
"From": headerTranslation.callsign,
"Filter": filt,
"Length": 0,
}
if (
"Live" in filt["Actions"]
and not self.__liveStatus__()
):
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert will relay Live.",
classType="DECODER",
sev=severity.alert,
)
self.__monitor__["Alert"] = True
self.__monitor__["Live"] = True
self.__liveLock__()
self.__alertToOld__(
noCall, self.__alertData__
)
if AS_MAN.__logger__:
self.__log__ = utilities.log(
AS_MAN.__callsign__,
AS_MAN.__webhooks__,
"Patching Alert Live",
decode,
filt["Name"],
self.__monitorName__,
False,
"",
self.__monitor__["URL"],
AS_MAN.version,
email=AS_MAN.__email__,
)
elif (
"Live" in filt["Actions"]
and self.__liveStatus__()
):
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Live alert active, recording new alert in background.",
classType="DECODER",
sev=severity.alert,
)
self.__alertToOld__(
noCall, self.__alertData__
)
if AS_MAN.__logger__:
self.__log__ = utilities.log(
AS_MAN.__callsign__,
AS_MAN.__webhooks__,
"Recieving alert",
decode,
filt["Name"],
self.__monitorName__,
False,
"",
self.__monitor__["URL"],
AS_MAN.version,
email=AS_MAN.__email__,
)
self.__monitor__["Alert"] = True
elif "Relay" in filt["Actions"]:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert will be relayed ASAP.",
classType="DECODER",
sev=severity.alert,
)
self.__alertToOld__(
noCall, self.__alertData__
)
if AS_MAN.__logger__:
self.__log__ = utilities.log(
AS_MAN.__callsign__,
AS_MAN.__webhooks__,
"Recieving alert",
decode,
filt["Name"],
self.__monitorName__,
False,
"",
self.__monitor__["URL"],
AS_MAN.version,
email=AS_MAN.__email__,
)
self.__monitor__["Alert"] = True
else:
if not "Now" in filt["Actions"]:
self.__alertToOld__(
noCall, self.__alertData__
)
if AS_MAN.__logger__:
self.__log__ = utilities.log(
AS_MAN.__callsign__,
AS_MAN.__webhooks__,
"Recieving alert",
decode,
filt["Name"],
self.__monitorName__,
False,
"",
self.__monitor__[
"URL"
],
AS_MAN.version,
email=AS_MAN.__email__,
)
self.__monitor__[
"Alert"
] = True
else:
self.__monitor__[
"Alert"
] = False
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert Filter is Ignore.",
classType="DECODER",
sev=severity.alert,
)
self.__alertToOld__(
noCall, self.__alertData__
)
if AS_MAN.__logger__:
utilities.log(
AS_MAN.__callsign__,
AS_MAN.__webhooks__,
"Alert Ignored",
decode,
filt["Name"],
self.__monitorName__,
False,
"",
self.__monitor__[
"URL"
],
AS_MAN.version,
email=AS_MAN.__email__,
)
else:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert is Not in Filter.",
classType="DECODER",
sev=severity.alert,
)
self.__monitor__["Alert"] = False
except ValueError:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: EAS Data is INVALID: {decode}",
classType="DECODER",
sev=severity.debug,
)
self.__monitor__["Alert"] = False
elif "NNNN" and self.__monitor__["Alert"]:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: EOMs Recieved.",
classType="DECODER",
sev=severity.info,
)
self.__monitor__["Alert"] = False
except Exception as E:
sleep(0.1)
if self.__run__:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: {type(E).__name__}, {E}",
classType="DECODER",
sev=severity.error,
)
tb = E.__traceback__
while tb is not None:
utilities.autoPrint(
text=f"File: {tb.tb_frame.f_code.co_filename}\nFunc: {tb.tb_frame.f_code.co_name}\nLine: {tb.tb_lineno}",
classType="DECODER",
sev=severity.error,
)
tb = tb.tb_next
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Closing Decoder Thread.",
classType="DECODER",
sev=severity.trace,
)
self.__decode__.kill()
self.__decode__.poll()
return
def __FilterManager__(self, ORG: str, EVNT: str, FIPS: str, CALL: str):
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Checking Filters...",
classType="FILTER",
sev=severity.debug,
)
nat = {
"Name": "National Alert",
"Originators": ["PEP"],
"EventCodes": ["EAN", "EAT"],
"SameCodes": ["*"],
"CallSigns": ["*"],
"Action": "Live:Now",
}
try:
filters = AS_MAN.__filters__
if filters[0] != nat:
filters.insert(
0,
nat,
)
for filter in filters:
OOO, EEE, SSS, CCC = False, False, False, False
name, originators, eventCodes, sameCodes, callsigns, action = (
filter["Name"],
filter["Originators"],
filter["EventCodes"],
filter["SameCodes"],
filter["CallSigns"],
filter["Action"],
)
if ("*" in originators) or (ORG in originators):
OOO = True
if ("*" in eventCodes) or (EVNT in eventCodes):
EEE = True
if ("*" in callsigns) or (CALL.strip() in callsigns):
CCC = True
if "LOCAL" in sameCodes or "LOC" in sameCodes:
sameCodes[:] = (
same
for same in sameCodes
if same.upper() != "LOCAL" or same.upper() != "LOC"
)
sameCodes += AS_MAN.__localFIPS__
for sameCode in sameCodes:
if sameCode == "*":
SSS = True
break
elif (
len(sameCode) == 6
and sameCode.startswith("*")
and sameCode.endswith("***")
):
for FIP in FIPS:
if FIP[1:3] == sameCode[1:3]:
SSS = True
break
elif len(sameCode) == 6 and sameCode.startswith("*"):
for FIP in FIPS:
if FIP[-5:] == sameCode[-5:]:
SSS = True
break
elif len(sameCode) == 6 and sameCode.endswith("***"):
for FIP in FIPS:
if FIP[:3] == sameCode[:3]:
SSS = True
break
elif len(sameCode) == 6:
for FIP in FIPS:
if FIP == sameCode:
SSS = True
break
if OOO and EEE and SSS and CCC:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Matched Filter {name}: {action}",
classType="FILTER",
sev=severity.debug,
)
return {"Matched": True, "Name": name, "Actions": action}
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: No Matching Filters.",
classType="FILTER",
sev=severity.debug,
)
return {"Matched": False}
except Exception as E:
sleep(0.1)
if self.__run__:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: {type(E).__name__}, {E}",
classType="FILTER",
sev=severity.error,
)
tb = E.__traceback__
while tb is not None:
utilities.autoPrint(
text=f"File: {tb.tb_frame.f_code.co_filename}\nFunc: {tb.tb_frame.f_code.co_name}\nLine: {tb.tb_lineno}",
classType="FILTER",
sev=severity.error,
)
tb = tb.tb_next
def __recorder__(self):
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Opening Monitor Thread.",
classType="MONITOR",
sev=severity.trace,
)
if self.__monitor__["Type"] == "Audio":
## URI STYLE:
## <TYPE>|<DEV>|<SAMP>|<CHAN>
## alsa|hw:0|44.1k|2 (Alsa Device hw:0, 44.1k Samplerate, 2 Channels)
## pulse|alsa_input.pci-0000_00_1f.3.3.analog-stereo|24k|1 (Pulse Device alsa_input.pci-0000_00_1f.3.3.analog-stereo, 24k Samplerate, 1 Channels)
## jack|mon1|32k|2 (Jack Device mon1, 2 Channels (SR Controlled by Jack))
## Config style: {"AUD": "<URI>"}
cmd = [
"ffmpeg",
"-hide_banner",
"-nostdin",
"-loglevel",
"quiet",
"-nostats",
"-sample_rate",
self.__monitor__["URL"].split("|")[2],
"-channels",
self.__monitor__["URL"].split("|")[3],
"-f",
self.__monitor__["URL"].split("|")[0],
"-i",
self.__monitor__["URL"].split("|")[1],
"-f",
"s16le",
"-c:a",
"pcm_s16le",
"-ar",
"24000",
"-ac",
"1",
"-af",
"alimiter=level=true:attack=1,volume=-6dB",
"-",
]
elif self.__monitor__["Type"] == "Radio":
## URI STYLE:
## <DEV>|<FREQ>|<TYPE>
## 0|162.4M|fm (NWR on SDR 0)
## 1|93.3M|wfm (93.3 FM on SDR 1)
## 2|710k|am (710 AM on SDR 2)
## Config style: {"SDR": "<URI>"}
cmd = [
"rtl_fm",
"-d",
self.__monitor__["URL"].split("|")[0],
"-f",
self.__monitor__["URL"].split("|")[1],
"-M",
self.__monitor__["URL"].split("|")[2],
"-A",
"fast",
"-r",
"24k",
]
if self.__monitor__["URL"].split("|")[2] == "wfm":
cmd.insert(len(cmd) - 4, "-s")
cmd.insert(len(cmd) - 4, "170k")
cmd.insert(len(cmd) - 2, "-E")
cmd.insert(len(cmd) - 2, "deemp")
else:
cmd = [
"ffmpeg",
"-hide_banner",
"-nostdin",
"-loglevel",
"quiet",
"-nostats",
"-reconnect",
"1",
"-reconnect_at_eof",
"1",
"-reconnect_streamed",
"1",
"-reconnect_on_network_error",
"1",
"-reconnect_delay_max",
"5",
"-i",
self.__monitor__["URL"],
"-f",
"s16le",
"-c:a",
"pcm_s16le",
"-map",
"0",
"-map",
"-0:v",
"-map",
"-0:s",
"-ar",
"24000",
"-ac",
"1",
"-af",
"alimiter=level=true:attack=1,volume=-6dB",
"-",
]
self.__stream__ = Popen(
cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=1
)
alertAudio = empty(0, dtype=int16)
testStatus = False
## TODO: Make this a config option
setLevel = 5 # Number of decodes before we count it.
## TODO: Make this a config option
hold = 3 # Number of samples to hold for
threshLevelATTN = setLevel
threshLenATTN = hold
detectedATTN = False
activeATTN = False
window = blackman(4800)
audioBork = 0
removedATTN = False
buffTemp = 0
alertGenerated = False
liveBuff = AudioSegment.empty()
alertSegment = {
"headers": AudioSegment.empty(),
"attnTone": AudioSegment.empty(),
"message": AudioSegment.empty(),
"eoms": AudioSegment.empty(),
}
utilities.autoPrint(
text=f"{self.__monitorName__}: Ready.",
classType="MONITOR",
sev=severity.trace,
)
self.__decodeLock__.wait()
utilities.autoPrint(
text=f"{self.__monitorName__}: Running.",
classType="MONITOR",
sev=severity.trace,
)
while self.__run__:
try:
if not self.__monitor__["State"]:
sleep(1)
elif not self.__monitor__["Online"]:
self.__stream__ = Popen(
cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=1
)
## TODO: Replace Subprocess with ASYNC, allow for kill if too long.
## See: https://stackoverflow.com/questions/10756383/timeout-on-subprocess-readline-in-python
data = self.__stream__.stdout.read(
24000
) # Try to read 1 second of audio from the stream
audioSamples = frombuffer(data, dtype=int16)
if len(audioSamples) > 0:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: has been restored (Down for {(audioBork-24000)*10} seconds).",
classType="MONITOR",
sev=severity.info,
)
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: {self.__monitor__['URL']} Restored.",
classType="MONITOR",
sev=severity.trace,
)
audioBork = 0
self.__monitor__["Online"] = True
else:
self.__stream__.kill()
self.__stream__.poll()
audioBork += 1
for i in range(10):
if self.__run__:
sleep(1)
else:
break
else:
data = self.__stream__.stdout.read(2400 * 4)
audioSamples = frombuffer(data, dtype=int16)
self.__decode__.stdin.write(audioSamples)
if (
self.__monitor__["Live"] == True
and self.__monitor__["Alert"] == True
):
if not alertGenerated:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Generating Live Alert Headers.",
classType="MONITOR",
sev=severity.debug,
)
header = f"{self.__alertData__['Protocol']}{AS_MAN.__callsign__}-"
headerTranslation = EAS2Text(header)
alertName = f"EAS_LIVE_{headerTranslation.org}-{headerTranslation.evnt}-{headerTranslation.timeStamp}-{headerTranslation.callsign.replace('/', '-').strip().replace(' ', '-')}"
alert = EASGen.genHeader(
header_data=header,
mode=AS_MAN.__config__["Emulation"],
)
tone = EASGen.genATTN(
mode=AS_MAN.__config__["Emulation"]
)
buffTemp = (
round((len(alert) + len(tone)) / 1000, 0)
* 3.125
)
self.__alertData__["Length"] = 0.00
event = self.__alertData__["Event"]
call = self.__alertData__["From"]
data = {
"Audio": alertName,
"Type": "Live",
"Event": event,
"Callsign": call,
"Protocol": header,
}
self.__alertToOld__(
self.__alertData__["Protocol"],
self.__alertData__,
)
liveAlert[alertName] = ["HEADER_HEADER_HEADER"]
liveAlert[alertName].append(alert)
liveAlert[alertName].append("TONE_TONE_TONE")
liveAlert[alertName].append(tone)
liveBuff += alert + tone
currentAlert.append(data)
alertGenerated = True
oof = True
if oof:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Alert Audio LIVE in {buffTemp/3.125} Seconds.",
classType="MONITOR",
sev=severity.debug,
)
liveAlert[alertName].append("AUDIO_AUDIO_AUDIO")
oof = False
liveAudio = AudioSegment(
audioSamples.tobytes(),
frame_rate=24000,
sample_width=2,
channels=1,
)
if buffTemp > 0:
buffTemp -= 1
else:
liveBuff += liveAudio
liveAlert[alertName].append(liveAudio)
elif self.__monitor__["Live"] == True:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Generating Live Alert EOMs.",
classType="MONITOR",
sev=severity.debug,
)
EOM = EASGen.genEOM(
mode=AS_MAN.__config__["Emulation"],
) + AudioSegment.silent(500)
liveAlert[alertName].append("EOM_EOM_EOM")
liveAlert[alertName].append(EOM)
liveBuff += EOM
self.__monitor__["Live"] = False
alertGenerated = False
self.__LiveUnlock__()
alertName = (
f"{AS_MAN.__exportFolder__}/{alertName}.wav"
)
if AS_MAN.__logger__ and AS_MAN.__export__:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Logging Alert.",
classType="MONITOR",
sev=severity.trace,
)
liveBuff.export(
out_f=alertName,
format="wav",
codec="pcm_s16le",
)
self.__log__ = utilities.log(
AS_MAN.__callsign__,
AS_MAN.__webhooks__,
"Live Alert Patched",
f"{self.__alertData__['Protocol']}{self.__alertData__['From']}-",
self.__alertData__["Filter"]["Name"],
self.__monitorName__,
True,
alertName,
self.__monitor__["URL"],
AS_MAN.version,
self.__log__,
email=AS_MAN.__email__,
)
elif AS_MAN.__logger__:
utilities.autoPrint(
text=f"Monitor {self.__monitorName__}: Logging Alert.",
classType="MONITOR",
sev=severity.trace,
)
audFlag = False