-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
terrariumNotification.py
2827 lines (2585 loc) · 87.6 KB
/
terrariumNotification.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
# -*- coding: utf-8 -*-
import os
import terrariumLogging
logger = terrariumLogging.logging.getLogger(None)
import re
import datetime
import requests
import copy
# Traffic light Support
from gpiozero import LED
# Email support
import emails
# MQTT Support
import paho.mqtt.client as mqtt
import json
# Telegram
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.error import InvalidToken, TimedOut
from telegram.ext import Application, CommandHandler, MessageHandler, ConversationHandler, CallbackQueryHandler, filters
# Database
from pony import orm
from time import sleep
from operator import itemgetter
from threading import Thread, Timer
from base64 import b64encode
from pathlib import Path
from terrariumDatabase import NotificationMessage, NotificationService, Sensor, Relay, Button
from terrariumUtils import terrariumUtils, terrariumSingleton, classproperty, terrariumAsync
# Display support
from hardware.display import terrariumDisplay, terrariumDisplayLoadingException
# https://docs.python.org/3/library/gettext.html#deferred-translations
def N_(message):
return message
class terrariumNotification(terrariumSingleton):
__DEFAULT_PLACEHOLDERS = {
"date": N_("Local date"),
"date_short": N_("Local date, day and month"),
"time": N_("Local time"),
"time_short": N_("Local time, hours and minutes"),
"now": N_("Local date and time"),
}
__MAX_MESSAGES_TOTAL_PER_MINUTE = 60
__MESSAGES = {
"authentication_error": {
"name": N_("Authentication login error"),
"placeholders": {
"ip": N_("IP of the wrong login attempt"),
"username": N_("Used username"),
"password": N_("Used password"),
**__DEFAULT_PLACEHOLDERS,
},
},
"system_warning": {
"name": N_("System warning"),
"placeholders": {"message": N_("Warning message"), **__DEFAULT_PLACEHOLDERS},
},
"system_error": {
"name": N_("System error"),
"placeholders": {"message": N_("Error message"), **__DEFAULT_PLACEHOLDERS},
},
"system_summary": {
"name": N_("System summary"),
"placeholders": {
"uptime": N_("System uptime in human readable format"),
"system_load": N_("System load last minute"),
"system_load_alarm": _("True if there is an alarm"),
"cpu_temperature": N_("System CPU temperature"),
"cpu_temperature_alarm": N_("True if there is an alarm"),
"storage": N_("Storage usage"),
"memory": N_("Memory usage"),
"average_[sensor_type]": N_("Average of [sensor type] (ex. temperature)"),
"average_[sensor_type]_unit": N_("Sensor type unit value"),
"average_[sensor_type]_alarm": N_("True if there is an alarm"),
"current_watt": N_("Current power usage"),
"max_watt": N_("Max power usage"),
"current_flow": N_("Current water flow"),
"max_flow": N_("Max water flow"),
"relays_active": N_("Number of relays active"),
**__DEFAULT_PLACEHOLDERS,
},
},
"system_update_warning": {
"name": N_("System to slow with updates (warning)"),
"placeholders": {
"message": N_("Error message"),
"time_short": N_("Duration in seconds that are short"),
"update_duration": N_("The update duration in seconds"),
"loop_timeout": N_("The max update duration"),
"times_late": N_("Amount of times to late with updates"),
**__DEFAULT_PLACEHOLDERS,
},
},
"system_update_error": {
"name": N_("System to slow with updates more then 30 times"),
"placeholders": {**__DEFAULT_PLACEHOLDERS},
},
"sensor_update": {
"name": N_("Sensor update (every 30 seconds)"),
"placeholders": {
"id": N_("ID"),
"hardware": N_("Hardware type"),
"type": N_("Sensor type"),
"name": N_("Name"),
"address": N_("Address"),
"limit_min": N_("Limit min"),
"limit_max": N_("Limit max"),
"alarm_min": N_("Alarm min"),
"alarm_max": N_("Alarm max"),
"max_diff": N_("Max difference"),
"exclude_avg": N_("Exclude from average"),
"alarm": N_("True if there is an alarm"),
"value": N_("Current value"),
"error": N_("True if there is an error"),
"unit": N_("Sensor type unit value"),
**__DEFAULT_PLACEHOLDERS,
},
},
"sensor_change": {
"name": N_("Sensor change (only when value is changed)"),
"placeholders": {**__DEFAULT_PLACEHOLDERS},
},
"sensor_alarm": {"name": N_("Sensor alarm"), "placeholders": {**__DEFAULT_PLACEHOLDERS}},
"relay_update": {
"name": N_("Relay update (every 30 seconds)"),
"placeholders": {
"id": N_("ID"),
"hardware": N_("Hardware type"),
"name": N_("Name"),
"address": N_("Address"),
"wattage": N_("Max wattage"),
"flow": N_("Max water flow"),
"manual_mode": N_("True if in manual mode"),
"dimmer": N_("True if it is a dimmer"),
"value": N_("Current state"),
"error": N_("True if there is an error"),
**__DEFAULT_PLACEHOLDERS,
},
},
"relay_change": {
"name": N_("Relay change (only when value is changed)"),
"placeholders": {**__DEFAULT_PLACEHOLDERS},
},
"relay_toggle": {"name": N_("Relay toggle"), "placeholders": {**__DEFAULT_PLACEHOLDERS}},
"button_update": {
"name": N_("Button update (every 30 seconds)"),
"placeholders": {
"id": N_("ID"),
"hardware": N_("Hardware type"),
"name": N_("Name"),
"address": N_("Address"),
"value": N_("Current state"),
"error": N_("True if there is an error"),
**__DEFAULT_PLACEHOLDERS,
},
},
"button_change": {
"name": N_("Button change (only when value is changed)"),
"placeholders": {**__DEFAULT_PLACEHOLDERS},
},
"button_action": {"name": N_("Button action"), "placeholders": {**__DEFAULT_PLACEHOLDERS}},
"webcam_archive": {"name": N_("Webcam archive"), "placeholders": {**__DEFAULT_PLACEHOLDERS}},
"webcam_motion": {"name": N_("Webcam motion"), "placeholders": {**__DEFAULT_PLACEHOLDERS}},
"area_lights_incorrect": {
"name": N_("Lights area wrong state"),
"placeholders": {
"current_state": N_("Current power state"),
"sensor_state": N_("Sensor measure state"),
"name": N_("Enclosure name"),
"mode": N_("Enclosure running mode"),
**__DEFAULT_PLACEHOLDERS,
},
},
}
__MESSAGES["system_update_error"]["placeholders"] = __MESSAGES["system_update_warning"]["placeholders"]
__MESSAGES["sensor_change"]["placeholders"] = __MESSAGES["sensor_update"]["placeholders"]
__MESSAGES["sensor_alarm"]["placeholders"] = __MESSAGES["sensor_update"]["placeholders"]
__MESSAGES["relay_change"]["placeholders"] = __MESSAGES["relay_update"]["placeholders"]
__MESSAGES["relay_toggle"]["placeholders"] = __MESSAGES["relay_update"]["placeholders"]
__MESSAGES["button_change"]["placeholders"] = __MESSAGES["button_update"]["placeholders"]
__MESSAGES["button_action"]["placeholders"] = __MESSAGES["button_update"]["placeholders"]
@classproperty
def available_messages(__cls__):
data = []
for msgtype, msgdata in terrariumNotification.__MESSAGES.items():
placeholders = {}
for placeholder_id, placeholder_desc in msgdata["placeholders"].items():
placeholders[placeholder_id] = _(placeholder_desc)
data.append({"type": msgtype, "name": _(msgdata["name"]), "placeholders": placeholders})
return sorted(data, key=itemgetter("name"))
def __init__(self, engine=None):
"Initialize empty notification system with system defaults"
self.__rate_limiter_counter = {
"total": {
"rate": terrariumNotification.__MAX_MESSAGES_TOTAL_PER_MINUTE,
"allowance": terrariumNotification.__MAX_MESSAGES_TOTAL_PER_MINUTE,
"last_check": datetime.datetime.now(),
}
}
self.services = {}
self.engine = engine
def __rate_limit(self, title, rate=None):
# https://en.wikipedia.org/wiki/Token_bucket / https://stackoverflow.com/a/668327
# First the overall max rate limit
if title not in self.__rate_limiter_counter:
self.__rate_limiter_counter[title] = {
"rate": rate,
"allowance": rate,
"last_check": datetime.datetime.now(),
}
current = datetime.datetime.now()
time_passed = (current - self.__rate_limiter_counter[title]["last_check"]).total_seconds()
self.__rate_limiter_counter[title]["last_check"] = current
self.__rate_limiter_counter[title]["allowance"] += time_passed * (
self.__rate_limiter_counter[title]["rate"] / 60.0
)
if self.__rate_limiter_counter[title]["allowance"] > self.__rate_limiter_counter[title]["rate"]:
self.__rate_limiter_counter[title]["allowance"] = self.__rate_limiter_counter[title]["rate"] # throttle
if self.__rate_limiter_counter[title]["allowance"] < 1.0:
return True
else:
self.__rate_limiter_counter[title]["allowance"] -= 1.0
return False
def load_services(self):
with orm.db_session():
for service in NotificationService.select(lambda ns: ns.enabled is True):
service = service.to_dict()
if service["id"] not in self.services:
setup = copy.deepcopy(service["setup"])
# Notification states from previous run
setup["state"] = copy.deepcopy(service["state"])
if self.engine:
setup["engine"] = self.engine
setup["terrariumpi_name"] = self.engine.settings["title"]
setup["version"] = self.engine.settings["version"]
setup["profile_image"] = self.engine.settings["profile_image"]
try:
self.services[service["id"]] = terrariumNotificationService(
service["id"], service["type"], service["name"], service["enabled"], setup
)
except terrariumDisplayLoadingException as ex:
self.services[service["id"]] = None
logger.error(f'Error loading display {service["name"]}: {ex}')
def reload_service(self, service_id, new_setup):
if service_id not in self.services:
return
setup = copy.deepcopy(new_setup)
setup["terrariumpi_name"] = self.engine.settings["title"]
setup["version"] = self.engine.settings["version"]
setup["profile_image"] = self.engine.settings["profile_image"]
self.services[service_id].reload_setup(setup)
def delete_service(self, service_id):
if service_id not in self.services:
return
try:
self.services[service_id].stop()
except Exception as ex:
logger.debug(f"Service {self} has not stop action: {ex}")
del self.services[service_id]
def broadcast(self, subject, message, image):
for service in self.services.values():
if service is not None and service.enabled:
try:
service.send_message("system_broadcast", subject, message, None, [image])
except Exception as ex:
logger.exception(f"Error sending broadcast message: {ex}")
@property
def version(self):
return None if self.engine is None else self.engine.version
@property
def profile_image(self):
image = None
if self.engine is not None:
try:
Path(self.engine.settings["profile_image"]).exists()
image = self.engine.settings["profile_image"]
except FileNotFoundError:
pass
return image
def message(self, message_type, data=None, files=[]):
if message_type not in self.__MESSAGES:
return
if data is None:
data = {}
# Ignore disabled sensor, relay, button or webcam notification. Default is enabled
if data.get("notification", True) == False:
return
with orm.db_session():
for message in NotificationMessage.select(lambda nm: nm.type == message_type):
if not message.enabled:
logger.debug(f"Notification message {message} is (temporary) disabled.")
continue
if self.__rate_limit("total"):
logger.warning(
f'Hitting the total max rate limit of {self.__rate_limiter_counter["total"]["rate"]} messages per minute. Message will be ignored.'
)
continue
# Translate message variables
now = datetime.datetime.now()
data["date"] = now.strftime("%x")
data["time"] = now.strftime("%X")
data["date_short"] = now.strftime("%d-%m")
data["time_short"] = now.strftime("%H:%M")
data["now"] = now
title = None
text = None
try:
# Legacy text formatting using '$' sign
title = message.title.replace("${", "{").format(**data)
except Exception as ex:
logger.error(f"Wrong message formatting {ex}")
try:
# Legacy text formatting using '$' sign
text = message.message.replace("${", "{").format(**data)
codelist = re.findall("{.*?}", text)
for code in codelist:
result = eval(code[1:-1], {"__builtins__": {}}, {})
text = text.replace(code, result)
except Exception as ex:
logger.error(f"Wrong message formatting {ex}")
if title is None and message is None:
continue
if message.rate_limit > 0 and self.__rate_limit(title, message.rate_limit):
logger.warning(
f'Hitting the max rate limit of {self.__rate_limiter_counter[title]["rate"]} messages per minute for message {message.title}. Message will be ignored.'
)
continue
for service in message.services:
if not service.enabled:
logger.debug(f"Service {self} is (temporary) disabled.")
continue
if service.id not in self.services or self.services[service.id] is None:
logger.debug(f"Ignoring service {self} as it did not loaded correctly.")
continue
if service.rate_limit > 0 and self.__rate_limit(service.type, service.rate_limit):
logger.warning(
f'Hitting the max rate limit of {self.__rate_limiter_counter[service.type]["rate"]} messages per minute for service {service.type}. Message will be ignored.'
)
continue
if service.id not in self.services:
setup = copy.copy(service.setup)
setup["version"] = self.version
setup["profile_image"] = self.profile_image
self.services[service.id] = terrariumNotificationService(
service.id, service.type, service.name, service.enabled, setup
)
try:
message_data = data.copy()
self.services[service.id].send_message(message_type, title, text, message_data)
except Exception as ex:
logger.exception(f"Error sending notification message '{title}': {ex}")
def stop(self):
for service in self.services.values():
if service is not None:
service.stop()
class terrariumNotificationServiceException(TypeError):
"""There is a problem with loading a hardware switch. Invalid power switch action."""
def __init__(self, message, *args):
self.message = message
super().__init__(message, *args)
class terrariumNotificationService(object):
__TYPES = {
"display": {"name": _("Display"), "class": lambda: terrariumNotificationServiceDisplay},
"email": {"name": _("Email"), "class": lambda: terrariumNotificationServiceEmail},
"telegram": {"name": _("Telegram"), "class": lambda: terrariumNotificationServiceTelegram},
"traffic": {"name": _("Traffic light"), "class": lambda: terrariumNotificationServiceTrafficLight},
"webhook": {"name": _("Web-hook"), "class": lambda: terrariumNotificationServiceWebhook},
"mqtt": {"name": _("MQTT"), "class": lambda: terrariumNotificationServiceMQTT},
"pushover": {"name": _("Pushover"), "class": lambda: terrariumNotificationServicePushover},
"buzzer": {"name": _("Buzzer"), "class": lambda: terrariumNotificationServiceBuzzer},
}
@classproperty
def available_services(__cls__):
data = []
for service_type, notification in terrariumNotificationService.__TYPES.items():
data.append({"type": service_type, "name": notification["name"]})
return sorted(data, key=itemgetter("name"))
# Return polymorph service....
def __new__(cls, _, service_type, name="", enabled=True, setup=None):
if service_type not in [service["type"] for service in terrariumNotificationService.available_services]:
raise terrariumNotificationServiceException(f"Service of type {service_type} is unknown.")
return super(terrariumNotificationService, cls).__new__(
terrariumNotificationService.__TYPES[service_type]["class"]()
)
def __init__(self, service_id, service_type, name, enabled, setup):
# Hacky to fix the logging in these classes...
global logger
logger = terrariumLogging.logging.getLogger(__name__)
if service_id is None:
service_id = terrariumUtils.generate_uuid()
self.id = service_id
self.type = service_type
self.name = name
self.enabled = enabled
self.engine = setup["engine"]
self.setup = {}
self.load_setup(setup)
def __repr__(self):
return f'{terrariumNotificationService.__TYPES[self.type]["name"]} service {self.name}'
def load_setup(self, setup_data):
self.setup["terrariumpi_name"] = setup_data.get("terrariumpi_name")
self.setup["version"] = setup_data.get("version")
self.setup["profile_image"] = setup_data.get("profile_image")
def reload_setup(self, setup_data):
# Stop first
self.stop()
# Update some settings
self.name = setup_data["name"]
self.enabled = setup_data["enabled"]
# Load the new setup
setup_data.update(setup_data["setup"])
self.load_setup(setup_data)
def stop(self):
pass
class terrariumNotificationServiceDisplay(terrariumNotificationService):
def load_setup(self, setup_data):
super().load_setup(setup_data)
# Now load the actual display device
self.setup["device"] = terrariumDisplay(
None,
setup_data["hardware"],
setup_data["address"],
(
None
if not terrariumUtils.is_true(setup_data["show_title"])
else f'{setup_data["terrariumpi_name"]} {self.setup["version"]}'
),
setup_data.get("h_scroll", False),
)
# self.show_picture(setup_data["profile_image"])
def send_message(self, msg_type, subject, message, data=None, attachments=[]):
self.setup["device"].message(message)
def show_picture(self, picture):
try:
self.setup["device"].write_image(picture)
except Exception:
pass
def stop(self):
try:
self.setup["device"].stop()
self.setup["device"] = None
except Exception as ex:
logger.error(f"Error stopping display: {ex}")
class terrariumNotificationServiceEmail(terrariumNotificationService):
def load_setup(self, setup_data):
self.setup = {
"address": setup_data.get("address"),
"port": int(setup_data.get("port", 25)),
"username": setup_data.get("username"),
"password": setup_data.get("password"),
"sender": setup_data.get("sender"),
"receiver": setup_data.get("receiver", "").split(","),
}
if self.setup["sender"] is None:
self.setup["sender"] = re.sub(
r"(.*)@(.*)", "\\1+terrariumpi@\\2", self.setup["receiver"][0], 0, re.MULTILINE
)
super().load_setup(setup_data)
def send_message(self, msg_type, subject, message, data=None, attachments=[]):
if self.setup is None or len(self.setup.get("receiver", [])) == 0:
# Configuration is not loaded, or no receivers, ignore sending emails
return
html_body = '<html><head><title>{}</title></head><body><img src="cid:{}" alt="Profile image" title="Profile image" align="right" style="max-width:300px;border-radius:25%;">{}</body></html>'
email_message = emails.Message(
headers={"X-Mailer": "TerrariumPI version {}".format(self.setup["version"])},
html=html_body.format(
subject, os.path.basename(self.setup["profile_image"]), message.replace("\n", "<br />")
),
text=message,
subject=subject,
mail_from=("TerrariumPI", self.setup["sender"]),
)
profile_image_path = ("public/" if self.setup["profile_image"].startswith("img/") else "") + self.setup[
"profile_image"
]
try:
with open(profile_image_path, "rb") as fp:
profile_image = fp.read()
email_message.attach(
filename=os.path.basename(self.setup["profile_image"]),
content_disposition="inline",
data=profile_image,
)
except FileNotFoundError:
logger.warning(f"Profile image at location {profile_image_path} does not exists.")
for attachment in attachments:
try:
with open(attachment, "rb") as fp:
attachment_data = fp.read()
email_message.attach(filename=os.path.basename(attachment), data=attachment_data)
except FileNotFoundError:
pass
mail_tls_ssl = ["tls", "ssl", None]
while not len(mail_tls_ssl) == 0:
smtp_settings = {"host": self.setup["address"], "port": self.setup["port"]}
smtp_security = mail_tls_ssl.pop(0)
if smtp_security is not None:
smtp_settings[smtp_security] = True
if "" != self.setup["username"]:
smtp_settings["user"] = self.setup["username"]
smtp_settings["password"] = self.setup["password"]
for receiver in self.setup["receiver"]:
response = email_message.send(to=(receiver, receiver), smtp=smtp_settings)
if response.status_code == 250:
# Mail sent, clear remaining connection types
mail_tls_ssl = []
class terrariumNotificationServiceWebhook(terrariumNotificationService):
def load_setup(self, setup_data):
self.setup = {
"address": setup_data.get("url"),
}
super().load_setup(setup_data)
def send_message(self, msg_type, subject, message, data=None, attachments=[]):
if data is None:
data = {}
data["message"] = message
data["subject"] = subject
# Add a unique ID to make clients able to filter duplicate messages
data["uuid"] = terrariumUtils.generate_uuid()
data["type"] = msg_type
if "now" in data:
data["now"] = data["now"].strftime("%c")
if len(attachments) > 0:
data["files"] = []
for attachment in attachments:
try:
with open(attachment, "rb") as fp:
attachment_data = fp.read()
data["files"].append(
{"name": os.path.basename(attachment), "data": b64encode(attachment_data).decode("utf-8")}
)
except FileNotFoundError:
pass
r = requests.post(self.setup["address"], json=data)
if r.status_code != 200:
logger.error(f'Error sending webhook to url \'{self.setup["address"]}\' with status code: {r.status_code}')
class terrariumNotificationServiceTrafficLight(terrariumNotificationService):
__YELLOW_TIMEOUT = 5 * 60
__RED_TIMEOUT = 15 * 60
def load_setup(self, setup_data):
self.setup = {
"red": (
None if setup_data.get("red") is None else LED(terrariumUtils.to_BCM_port_number(setup_data.get("red")))
),
"yellow": (
None
if setup_data.get("yellow") is None
else LED(terrariumUtils.to_BCM_port_number(setup_data.get("yellow")))
),
"green": (
None
if setup_data.get("green") is None
else LED(terrariumUtils.to_BCM_port_number(setup_data.get("green")))
),
"red_timer": None,
"yellow_timer": None,
}
# Animate once, leave green on
for led in ["red", "yellow", "green"]:
if self.setup[led] is not None:
self.setup[led].on()
if led != "green":
sleep(1)
self.setup[led].off()
super().load_setup(setup_data)
def send_message(self, msg_type, subject, message, data=None, attachments=[]):
led = None
if "system_warning" == msg_type:
led = "yellow"
timeout = self.__YELLOW_TIMEOUT
elif "system_error" == msg_type:
led = "yellow"
timeout = self.__RED_TIMEOUT
else:
return
if led is not None and self.setup[led] is not None:
self.setup[led].on()
if self.setup[f"{led}_timer"] is not None:
try:
self.setup[f"{led}_timer"].cancel()
except Exception as ex:
print(f"Traffic {led} exception")
print(ex)
self.setup[f"{led}_timer"] = Timer(timeout, lambda: self.setup[f"{led}"].off())
def stop(self):
for led in ["red", "yellow", "green"]:
if self.setup[led] is not None:
self.setup[led].off()
if self.setup.get(f"{led}_timer"):
try:
self.setup[f"{led}_timer"].cancel()
except Exception as ex:
logger.error(f"Error stopping traffic light led {led}: {ex}")
class terrariumNotificationServiceBuzzer(terrariumNotificationService):
# Original code from https://github.com/gumslone/raspi_buzzer_player
__NOTES = {
"B0": 31,
"C1": 33,
"CS1": 35,
"D1": 37,
"DS1": 39,
"EB1": 39,
"E1": 41,
"F1": 44,
"FS1": 46,
"G1": 49,
"GS1": 52,
"A1": 55,
"AS1": 58,
"BB1": 58,
"B1": 62,
"C2": 65,
"CS2": 69,
"D2": 73,
"DS2": 78,
"EB2": 78,
"E2": 82,
"F2": 87,
"FS2": 93,
"G2": 98,
"GS2": 104,
"A2": 110,
"AS2": 117,
"BB2": 123,
"B2": 123,
"C3": 131,
"CS3": 139,
"D3": 147,
"DS3": 156,
"EB3": 156,
"E3": 165,
"F3": 175,
"FS3": 185,
"G3": 196,
"GS3": 208,
"A3": 220,
"AS3": 233,
"BB3": 233,
"B3": 247,
"C4": 262,
"CS4": 277,
"D4": 294,
"DS4": 311,
"EB4": 311,
"E4": 330,
"F4": 349,
"FS4": 370,
"G4": 392,
"GS4": 415,
"A4": 440,
"AS4": 466,
"BB4": 466,
"B4": 494,
"C5": 523,
"CS5": 554,
"D5": 587,
"DS5": 622,
"EB5": 622,
"E5": 659,
"F5": 698,
"FS5": 740,
"G5": 784,
"GS5": 831,
"A5": 880,
"AS5": 932,
"BB5": 932,
"B5": 988,
"C6": 1047,
"CS6": 1109,
"D6": 1175,
"DS6": 1245,
"EB6": 1245,
"E6": 1319,
"F6": 1397,
"FS6": 1480,
"G6": 1568,
"GS6": 1661,
"A6": 1760,
"AS6": 1865,
"BB6": 1865,
"B6": 1976,
"C7": 2093,
"CS7": 2217,
"D7": 2349,
"DS7": 2489,
"EB7": 2489,
"E7": 2637,
"F7": 2794,
"FS7": 2960,
"G7": 3136,
"GS7": 3322,
"A7": 3520,
"AS7": 3729,
"BB7": 3729,
"B7": 3951,
"C8": 4186,
"CS8": 4435,
"D8": 4699,
"DS8": 4978,
}
__SONGS = {
"SOS": {
"melody": [
__NOTES["BB2"],
__NOTES["BB2"],
__NOTES["BB2"],
0,
__NOTES["BB2"],
__NOTES["BB2"],
__NOTES["BB2"],
0,
__NOTES["BB2"],
__NOTES["BB2"],
__NOTES["BB2"],
],
"tempo": [8, 8, 8, 2, 2, 2, 2, 2, 8, 8, 8],
"pause": 0.30,
"pace": 1.0,
},
"The Final Countdown": {
"melody": [
__NOTES["A3"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["E5"],
__NOTES["A4"],
__NOTES["F3"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["D3"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["F5"],
__NOTES["A4"],
__NOTES["G3"],
0,
__NOTES["D5"],
__NOTES["C5"],
__NOTES["D5"],
__NOTES["C5"],
__NOTES["B4"],
__NOTES["D5"],
__NOTES["C5"],
__NOTES["A3"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["E5"],
__NOTES["A4"],
__NOTES["F3"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["D3"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["F5"],
__NOTES["A4"],
__NOTES["G3"],
0,
__NOTES["D5"],
__NOTES["C5"],
__NOTES["D5"],
__NOTES["C5"],
__NOTES["B4"],
__NOTES["D5"],
__NOTES["C5"],
__NOTES["B4"],
__NOTES["C5"],
__NOTES["D5"],
__NOTES["C5"],
__NOTES["D5"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["C5"],
__NOTES["B4"],
__NOTES["A4"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["E5"],
__NOTES["F5"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["E5"],
],
"tempo": [
1,
16,
16,
4,
4,
1,
16,
16,
8,
8,
4,
1,
16,
16,
4,
4,
2,
4,
16,
16,
8,
8,
8,
8,
4,
4,
16,
16,
4,
4,
1,
16,
16,
8,
8,
4,
1,
16,
16,
4,
4,
2,
4,
16,
16,
8,
8,
8,
8,
4,
16,
16,
4,
16,
16,
8,
8,
8,
8,
4,
4,
2,
8,
4,
16,
16,
1,
],
"pause": 0.30,
"pace": 1.2000,
},
"Old MacDonald Had A Farm": {
"melody": [
__NOTES["C5"],
__NOTES["C5"],
__NOTES["C5"],
__NOTES["G4"],
__NOTES["A4"],
__NOTES["A4"],
__NOTES["G4"],
__NOTES["E5"],
__NOTES["E5"],
__NOTES["D5"],
__NOTES["D5"],
__NOTES["C5"],