-
Notifications
You must be signed in to change notification settings - Fork 1
/
alarm.py
1569 lines (1263 loc) · 52.7 KB
/
alarm.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
import time
import json
import threading
import logging
import logging.handlers
import datetime
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import configparser
import argparse
import atexit
import os
import math
import random
from itertools import chain
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Optional
from pushover import Pushover
import hass_discovery as hass
from healthchecks import HealthChecks
from arduino import Arduino
from battery import Battery
GPIO.setmode(GPIO.BCM) # set board mode to Broadcom
GPIO.setwarnings(False) # don't show warnings
config = configparser.ConfigParser()
config.read('config.ini')
parser = argparse.ArgumentParser()
parser.add_argument('--silent', dest='silent', action='store_true',
help="suppress siren outputs")
parser.add_argument('--siren-block', dest='siren_block_relay', action='store_true',
help="activate siren block relay")
parser.add_argument('--payload', dest='print_payload', action='store_true',
help="print payload on publish")
parser.add_argument('--status', dest='print_status', action='store_true',
help="print status object on publish")
parser.add_argument('--serial', dest='print_serial', action='store_true',
help="print serial data on receive")
parser.add_argument('--timers', dest='print_timers', action='store_true',
help="print timers debug")
parser.add_argument('--log', dest='log_level', action='store', choices=["DEBUG", "INFO", "WARNING"],
help="set log level")
# parser.set_defaults(feature=True)
args = parser.parse_args()
class ArmMode(Enum):
Home = auto()
Away = auto()
AwayDelayed = auto()
Water = auto()
Direct = auto()
Fire = auto()
Notify = auto()
class AlarmState(Enum):
Disarmed = "disarmed"
ArmedHome = "armed_home"
ArmedAway = "armed_away"
Triggered = "triggered"
Pending = "pending"
Arming = "arming"
class AlarmPanelAction(Enum):
Disarm = auto()
ArmHome = auto()
ArmAway = auto()
InvalidCode = auto()
NotReady = auto()
AlreadyDisarmed = auto()
class SensorValue(Enum):
Truthy = True
Falsy = False
On = "on"
# Panic = "panic"
Emergency = "emergency"
class DevClass(Enum):
Generic = None
Tamper = "tamper"
Motion = "motion"
Door = "door"
Moisture = "moisture"
class ZoneAttribute(Enum):
Chime = auto()
OpenWarning = auto()
def __repr__(self):
return self.name
class Zone:
def __init__(self, key: str, label: str, dev_class: DevClass,
arm_modes: list[ArmMode], attributes: list[ZoneAttribute] = None):
self.key = key
self.label = label
self.dev_class = dev_class
self.arm_modes = arm_modes
self.attributes = attributes if attributes is not None else []
class Input(Zone):
def __init__(self, key: str, gpio: int, label: str, dev_class: DevClass,
arm_modes: list[ArmMode], attributes: list[ZoneAttribute] = None):
super().__init__(key, label, dev_class, arm_modes, attributes)
self.gpio = gpio
def __str__(self):
return self.label
def __repr__(self):
return f"i{self.gpio}:{self.label} {self.attributes}"
def get(self):
return GPIO.input(self.gpio) == 1
@property
def is_true(self):
return self.get()
class Output:
def __init__(self, gpio: int, label: str, debug: bool = False):
self.gpio = gpio
self.label = label
self.debug = debug
def __str__(self):
return self.label
def set(self, value):
if self.get() != value:
if self in [outputs["siren1"], outputs["siren2"]] and args.silent and value:
logging.debug("Suppressing %s, because silent", self)
return
GPIO.output(self.gpio, value)
if self.debug:
logging.debug("Output: %s set to %s", self, value)
def get(self):
return GPIO.input(self.gpio) == 1
@property
def is_true(self):
return self.get()
class Sensor(Zone):
def __init__(self, key: str, topic: str, field: str, value: SensorValue, label: str, dev_class: DevClass,
arm_modes: list[ArmMode], timeout: int = 0, attributes: list[ZoneAttribute] = None):
super().__init__(key, label, dev_class, arm_modes, attributes)
self.topic = topic
self.field = field
self.value = value
self.timeout = timeout
self.timestamp = time.time()
self.linkquality = []
def __str__(self):
return self.label
def __repr__(self):
return f"s:{self.label} {self.attributes}"
def get(self):
return state.data["zones"][self.key]
@property
def is_true(self):
return self.get()
# @dataclass
# class Zones:
# inputs: dict[str, Input]
# sensors: dict[str, Sensor]
#
# @property
# def all(self) -> dict[str, Zone]:
# return self.inputs | self.sensors
#
# def get(self, zone_key):
# return next((zone for key, zone in self.all if key == zone_key), None)
class ZoneTimer:
def __init__(self, key: str, zones: list[str], label: str, blocked_state: list[str]):
self.key = key
self.zones = zones
self.zone_value = True
self.label = label
self.blocked_state = blocked_state
self.timestamp = time.time()
def __str__(self):
return self.label
@property
def seconds(self):
return config.getint("zone_timers", self.key, fallback=300)
def cancel(self):
self.timestamp = time.time() - self.seconds
class AlarmPanel:
def __init__(self, topic: str, fields: dict[str, str], actions: dict[AlarmPanelAction, str], label: str,
set_states: dict[AlarmState, str] = None, timeout: int = 0):
self.topic = topic
self.fields = fields
self.actions = actions
self.label = label
self.set_states = set_states or {}
self.timeout = timeout
self.timestamp = time.time()
self.linkquality = []
def __str__(self):
return self.label
def __repr__(self):
return f"p:{self.label}"
def set(self, alarm_state: AlarmState):
if alarm_state not in self.set_states:
return
logging.debug("Sending state: %s to alarm panel %s", self.set_states[alarm_state], self.label)
data = {"arm_mode": {"mode": self.set_states[alarm_state]}}
mqtt_client.publish(f"{self.topic}/set", json.dumps(data), retain=False)
def validate(self, transaction: str, alarm_action: AlarmPanelAction):
if transaction is None or alarm_action not in self.actions:
return
logging.debug("Sending verification: %s to alarm panel %s", self.actions[alarm_action], self.label)
data = {"arm_mode": {"transaction": int(transaction), "mode": self.actions[alarm_action]}}
mqtt_client.publish(f"{self.topic}/set", json.dumps(data), retain=False)
inputs = {
"ext_tamper": Input(
key="ext_tamper",
gpio=2,
label="External tamper",
dev_class=DevClass.Tamper,
arm_modes=[ArmMode.Home, ArmMode.Away]
),
"zone01": Input(
key="zone01",
gpio=3,
label="1st floor hallway motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.Away],
),
# "zone02": Input(4),
# "zone03": Input(17),
# "zone04": Input(27),
# "zone05": Input(14),
# "zone06": Input(15),
# "zone07": Input(18),
# "zone08": Input(22),
# "zone09": Input(23),
# "1st_floor_tamper": Input(
# gpio=24,
# label="1st floor tamper",
# dev_class="tamper",
# arm_modes=[]
# ),
# "zone11": None,
# "zone12": None,
}
outputs = {
"led_red": Output(
gpio=5,
label="Red LED"
),
"led_green": Output(
gpio=6,
label="Green LED"
),
"buzzer": Output(
gpio=16,
label="Buzzer"
),
"siren1": Output(
gpio=19,
label="Siren indoor",
debug=True
),
"siren2": Output(
gpio=26,
label="Siren outdoor",
debug=True
),
"door_chime": Output(
gpio=13,
label="Door chime"
),
# "aux1": Output(20),
# "aux2": Output(21)
}
sensors = {
"door1": Sensor(
key="door1",
topic="zigbee2mqtt/Door front",
field="contact",
value=SensorValue.Falsy,
label="Front door",
dev_class=DevClass.Door,
arm_modes=[ArmMode.Home, ArmMode.AwayDelayed],
attributes=[ZoneAttribute.Chime, ZoneAttribute.OpenWarning],
timeout=3900
),
"door2": Sensor(
key="door2",
topic="zigbee2mqtt/Door back",
field="contact",
value=SensorValue.Falsy,
label="Back door",
dev_class=DevClass.Door,
arm_modes=[ArmMode.Home, ArmMode.Away],
attributes=[ZoneAttribute.Chime],
timeout=3900
),
"door3": Sensor(
key="door3",
topic="zigbee2mqtt/Door 2nd floor",
field="contact",
value=SensorValue.Falsy,
label="2nd floor door",
dev_class=DevClass.Door,
arm_modes=[ArmMode.Home, ArmMode.Away],
attributes=[ZoneAttribute.Chime],
timeout=3900
),
"motion1": Sensor(
key="motion1",
topic="zigbee2mqtt/Motion kitchen",
field="occupancy",
value=SensorValue.Truthy,
label="Kitchen motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.Away],
timeout=3900
),
"motion2": Sensor(
key="motion2",
topic="zigbee2mqtt/Motion living room",
field="occupancy",
value=SensorValue.Truthy,
label="Living room motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.Away],
timeout=3900
),
"motion3": Sensor(
key="motion3",
topic="hass2mqtt/binary_sensor/entreen_motion/state",
field="value",
value=SensorValue.On,
label="Entrance motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.AwayDelayed]
),
"motion4": Sensor(
key="motion4",
topic="zigbee2mqtt/Motion 2nd floor hallway",
field="occupancy",
value=SensorValue.Truthy,
label="2nd floor hallway motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.Away],
timeout=3900
),
"motion5": Sensor(
key="motion5",
topic="hass2mqtt/binary_sensor/hue_motion_sensor_1_motion/state",
field="value",
value=SensorValue.On,
label="Bathroom motion",
dev_class=DevClass.Motion,
arm_modes=[]
),
"motion6": Sensor(
key="motion6",
topic="zigbee2mqtt/Motion master bedroom",
field="occupancy",
value=SensorValue.Truthy,
label="Master bedroom motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.Away],
timeout=3900
),
"garage_motion1": Sensor(
key="garage_motion1",
topic="hass2mqtt/binary_sensor/garasjen_motion/state",
field="value",
value=SensorValue.On,
label="Garage motion",
dev_class=DevClass.Motion,
arm_modes=[ArmMode.Notify]
),
"garage_door1": Sensor(
key="garage_door1",
topic="zigbee2mqtt/Door garage side",
field="contact",
value=SensorValue.Falsy,
label="Garage side door",
dev_class=DevClass.Door,
arm_modes=[ArmMode.Notify],
timeout=3900
),
"water_leak1": Sensor(
key="water_leak1",
topic="zigbee2mqtt/Water kitchen dishwasher",
field="water_leak",
value=SensorValue.Truthy,
label="Kitchen dishwasher leak",
dev_class=DevClass.Moisture,
arm_modes=[ArmMode.Water],
timeout=3600
),
"water_leak2": Sensor(
key="water_leak2",
topic="zigbee2mqtt/Water kitchen sink",
field="water_leak",
value=SensorValue.Truthy,
label="Kitchen sink leak",
dev_class=DevClass.Moisture,
arm_modes=[ArmMode.Water],
timeout=3600
),
"water_leak3": Sensor(
key="water_leak3",
topic="zigbee2mqtt/Water tap hatch",
field="water_leak",
value=SensorValue.Truthy,
label="Outdoor tap hatch leak",
dev_class=DevClass.Moisture,
arm_modes=[ArmMode.Water],
timeout=3600
),
"emergency1": Sensor(
key="emergency1",
topic="zigbee2mqtt/Panel entrance",
field="action",
value=SensorValue.Emergency,
label="Emergency button entrance",
dev_class=DevClass.Generic,
arm_modes=[ArmMode.Direct]
),
"emergency2": Sensor(
key="emergency2",
topic="zigbee2mqtt/Panel master bedroom",
field="action",
value=SensorValue.Emergency,
label="Emergency button bedroom",
dev_class=DevClass.Generic,
arm_modes=[ArmMode.Direct]
),
"fire_test": Sensor(
key="fire_test",
topic="home/alarm_test/test/fire",
field="value",
value=SensorValue.On,
label="Fire test",
dev_class=DevClass.Generic,
arm_modes=[ArmMode.Fire]
)
}
zones = inputs | sensors
# zones = Zones(inputs, sensors)
home_zones = [v for k, v in zones.items() if ArmMode.Home in v.arm_modes]
away_zones = [v for k, v in zones.items() if ArmMode.Away in v.arm_modes or ArmMode.AwayDelayed in v.arm_modes]
water_zones = [v for k, v in zones.items() if ArmMode.Water in v.arm_modes]
direct_zones = [v for k, v in zones.items() if ArmMode.Direct in v.arm_modes]
fire_zones = [v for k, v in zones.items() if ArmMode.Fire in v.arm_modes]
notify_zones = [v for k, v in zones.items() if ArmMode.Notify in v.arm_modes]
codes = dict(config.items("codes"))
zone_timers = {
"hallway_motion": ZoneTimer(
key="hallway_motion",
zones=["zone01", "motion4"],
# zone_value=True,
label="Hallway motion",
blocked_state=["armed_away"]
),
"kitchen_motion": ZoneTimer(
key="kitchen_motion",
zones=["motion1"],
# zone_value=True,
label="Kitchen motion",
blocked_state=["armed_away", "armed_home"]
)
}
alarm_panels = {
"home_assistant": AlarmPanel(
topic="home/alarm_test/set",
fields={"action": "action", "code": "code"},
actions={
AlarmPanelAction.Disarm: "DISARM",
AlarmPanelAction.ArmAway: "ARM_AWAY",
AlarmPanelAction.ArmHome: "ARM_HOME"
},
label="Home Assistant"
),
"develco1": AlarmPanel(
topic="zigbee2mqtt/Panel entrance",
fields={"action": "action", "code": "action_code"},
actions={
AlarmPanelAction.Disarm: "disarm",
AlarmPanelAction.ArmAway: "arm_all_zones",
AlarmPanelAction.ArmHome: "arm_day_zones",
AlarmPanelAction.InvalidCode: "invalid_code",
AlarmPanelAction.NotReady: "not_ready",
AlarmPanelAction.AlreadyDisarmed: "not_ready"
},
label="Entrance alarm panel",
set_states={
AlarmState.Disarmed: "disarm",
AlarmState.ArmedHome: "arm_day_zones",
AlarmState.ArmedAway: "arm_all_zones",
AlarmState.Triggered: "in_alarm",
AlarmState.Pending: "entry_delay",
AlarmState.Arming: "exit_delay"
},
timeout=900
),
"develco2": AlarmPanel(
topic="zigbee2mqtt/Panel master bedroom",
fields={"action": "action", "code": "action_code"},
actions={
AlarmPanelAction.Disarm: "disarm",
AlarmPanelAction.ArmAway: "arm_all_zones",
AlarmPanelAction.ArmHome: "arm_day_zones",
AlarmPanelAction.InvalidCode: "invalid_code",
AlarmPanelAction.NotReady: "not_ready",
AlarmPanelAction.AlreadyDisarmed: "not_ready"
},
label="Master bedroom alarm panel",
set_states={
AlarmState.Disarmed: "disarm",
AlarmState.ArmedHome: "arm_day_zones",
AlarmState.ArmedAway: "arm_all_zones",
AlarmState.Triggered: "in_alarm",
AlarmState.Pending: "entry_delay",
AlarmState.Arming: "exit_delay"
},
timeout=900
)
}
logging_format = "%(asctime)s - %(levelname)s: %(message)s"
logging.basicConfig(format=logging_format, level=logging.DEBUG, datefmt="%H:%M:%S")
battery_log = logging.getLogger("battery")
battery_log_handler = logging.FileHandler('logs/battery.log')
battery_log_handler.setFormatter(logging.Formatter(logging_format))
battery_log.addHandler(battery_log_handler)
# rpi_gpio_log = logging.getLogger("rpi_gpio")
# rpi_gpio_log_file_handler = logging.handlers.RotatingFileHandler('logs/rpi_gpio.log',
# maxBytes=200*1000, backupCount=5)
# rpi_gpio_log_file_handler.setFormatter(logging.Formatter(logging_format))
# rpi_gpio_log_mem_handler = logging.handlers.MemoryHandler(50, target=rpi_gpio_log_file_handler)
# rpi_gpio_log_mem_handler.setFormatter(logging.Formatter(logging_format))
# rpi_gpio_log.addHandler(rpi_gpio_log_mem_handler)
if args.log_level:
logging.getLogger().setLevel(args.log_level)
logging.info("Log level set to %s", args.log_level)
for gpio_input in inputs.values():
GPIO.setup(gpio_input.gpio, GPIO.IN)
for gpio_output in outputs.values():
GPIO.setup(gpio_output.gpio, GPIO.OUT)
gpio_output.set(False)
def wrapping_up() -> None:
for output in outputs.values():
output.set(False)
logging.info("All outputs set to False")
atexit.register(wrapping_up)
@dataclass
class StateData:
arm_not_ready: bool = None
auxiliary_voltage: float = None
battery_charging: bool = None
battery_level: int = None
battery_low: bool = None
battery_test_running: bool = None
battery_voltage: float = None
system_voltage: float = None
config: dict[str, bool] = field(default_factory=dict)
fault: bool = None
reboot_required: bool = None
state: str = None
tamper: bool = None
temperature: float = None
triggered: Optional[str] = None
water_valve: bool = None
zigbee_bridge: bool = None
zone_timers: dict[str, dict] = field(default_factory=dict)
zones: dict[str, Optional[bool]] = field(default_factory=dict)
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
if not hasattr(self, item):
logging.warning("Setting undefined attribute on state data object: %s", item)
setattr(self, item, value)
class State:
def __init__(self):
self.data: StateData = StateData(
state=config.get("system", "state"),
config={
"walk_test": config.getboolean("config", "walk_test", fallback=False),
"door_open_warning": config.getboolean("config", "door_open_warning", fallback=True),
"door_chime": config.getboolean("config", "door_chime", fallback=False),
"aux_output1": config.getboolean("config", "aux_output1", fallback=False),
"aux_output2": config.getboolean("config", "aux_output2", fallback=False)
},
zones={k: None for k, v in zones.items()},
zone_timers={k: {"value": None, "attributes": {"seconds": v.seconds}} for k, v in zone_timers.items()},
)
self._lock: threading.Lock = threading.Lock()
self._faults: list[str] = ["mqtt_connected"]
self.blocked: set[Zone] = set()
self.status: dict[str, bool] = {}
self.code_attempts: int = 0
self.zones_open: set[Zone] = set()
self.notify_timestamps: dict[Zone, time] = {v: time.time() for v in notify_zones}
def json(self) -> str:
return json.dumps(self.data.__dict__)
def publish(self) -> None:
mqtt_client.publish("home/alarm_test/availability", "online", retain=True)
mqtt_client.publish('home/alarm_test', self.json(), retain=True)
if args.print_payload:
print(json.dumps(self.data.__dict__, indent=2, sort_keys=True))
if args.print_status:
print(json.dumps(self.status, indent=2, sort_keys=True))
@property
def system(self) -> str:
return self.data["state"]
@system.setter
def system(self, alarm_state: str) -> None:
if alarm_state not in [e.value for e in AlarmState]:
raise ValueError(f"State: {alarm_state} is not valid")
with self._lock:
logging.warning("System state changed to: %s", alarm_state)
# if (state == "armed_away" and self.data["state"] == "triggered") or state == "disarmed":
if alarm_state in ["disarmed", "armed_home", "armed_away"]:
self.code_attempts = 0
self.data["triggered"] = None
if len(self.zones_open) > 0:
logging.info("Clearing open zones: %s", self.zones_open)
self.zones_open.clear()
self.data["state"] = alarm_state
self.publish()
if alarm_state in ["disarmed", "armed_home", "armed_away"]:
with open('config.ini', 'w') as configfile:
config.set("system", "state", alarm_state)
config.write(configfile)
for panel in [v for k, v in alarm_panels.items() if v.set_states]:
panel.set(AlarmState(alarm_state))
def zone(self, zone_key: str, value: bool) -> None:
zone = zones[zone_key]
if self.data["zones"][zone_key] != value:
self.data["zones"][zone_key] = value
logging.info("Zone: %s changed to %s", zone, value)
for timer_key, timer in zone_timers.items():
if zone_key in timer.zones:
# logging.debug("Zone: %s found in timer %s", zone, timer_key)
self.zone_timer(timer_key)
if value and state.data["config"]["walk_test"]:
threading.Thread(target=buzzer_signal, args=(2, [0.2, 0.2])).start()
if (value and state.data["config"]["door_chime"] and ZoneAttribute.Chime in zone.attributes
and not state.data["config"]["walk_test"] and self.system == "disarmed"
and not door_chime_lock.locked()):
threading.Thread(target=door_chime, args=()).start()
if value and self.system in ["triggered", "armed_home", "armed_away"]:
if zone in notify_zones and (time.time() - self.notify_timestamps[zone] > 180):
pushover.push(f"Notify zone is open: {zone}", 1)
self.notify_timestamps[zone] = time.time()
tamper_zones = {k: v.get() for k, v in zones.items() if v.dev_class == DevClass.Tamper}
state.data["tamper"] = any(tamper_zones.values())
for tamper_key, tamper_status in tamper_zones.items():
state.status[f"{tamper_key}"] = not tamper_status
clear = not any([o.get() for o in away_zones])
self.data["arm_not_ready"] = not clear
self.publish()
if zone in self.blocked and value is False:
self.blocked.remove(zone)
logging.debug("Blocked zones: %s", self.blocked)
def fault(self) -> None:
faults = [k for k, v in self.status.items() if not v]
if self._faults != faults:
self.data["fault"] = bool(faults)
self._faults = faults
self.publish()
if faults:
faulted_status = ", ".join(faults).upper()
logging.error("System check(s) failed: %s", faulted_status)
pushover.push(f"System check(s) failed: {faulted_status}")
else:
logging.info("System status restored")
pushover.push("System status restored")
def zone_timer(self, timer_key: str) -> None:
timer = zone_timers[timer_key]
timer_zones = [v for k, v in self.data["zones"].items() if k in timer.zones]
# print(json.dumps(timer_zones, indent=2, sort_keys=True))
# if timer.zone_value:
# zone_state = any(timer_zones)
# else:
# zone_state = not any(timer_zones)
zone_state = any(timer_zones)
if zone_state:
timer.timestamp = time.time()
if state.system in timer.blocked_state:
timer.cancel()
last_msg_s = round(time.time() - timer.timestamp)
value = last_msg_s < timer.seconds
# if not timer.zone_value:
# value = not value
if self.data["zone_timers"][timer_key]["value"] != value:
self.data["zone_timers"][timer_key]["value"] = value
logging.info("Zone timer: %s changed to %s", timer, value)
self.publish()
if args.print_timers and value:
print(f"{timer}: {datetime.timedelta(seconds=timer.seconds-last_msg_s)}")
def buzzer(seconds: int, current_state: str) -> bool:
logging.info("Buzzer loop started (%d seconds)", seconds)
start_time = time.time()
while (start_time + seconds) > time.time():
if current_state == "arming":
if any([o.get() for o in home_zones]):
buzzer_signal(1, [0.2, 0.8])
else:
buzzer_signal(1, [0.05, 0.95])
if current_state == "pending":
if (start_time + (seconds/2)) > time.time():
buzzer_signal(1, [0.05, 0.95])
else:
buzzer_signal(2, [0.05, 0.45])
if state.system != current_state:
logging.info("Buzzer loop aborted")
return False
logging.info("Buzzer loop completed")
return True
def buzzer_signal(repeat: int, duration: list[float]) -> None:
with buzzer_lock:
if len(duration) > 2:
time.sleep(duration[2])
for _ in range(repeat):
outputs["buzzer"].set(True)
time.sleep(duration[0])
outputs["buzzer"].set(False)
time.sleep(duration[1])
def siren(seconds: int, zone: Zone, current_state: str) -> bool:
logging.info("Siren loop started (%d seconds, %s, %s)",
seconds, zone, current_state)
start_time = time.time()
# zones_open = len(state.zones_open)
while (start_time + seconds) > time.time():
# ANSI S3.41-1990; Temporal Three or T3 pattern
# Indoor siren uses about 0.2 seconds to react
if zone in fire_zones:
for _ in range(3):
outputs["siren1"].set(True)
time.sleep(0.7)
outputs["siren1"].set(False)
time.sleep(0.3)
time.sleep(1)
elif zone in water_zones:
outputs["siren1"].set(True)
time.sleep(0.5)
outputs["siren1"].set(False)
time.sleep(10)
else:
outputs["siren1"].set(True)
# outputs["beacon"].set(True)
if ((time.time()-start_time) > (seconds/3) and len(state.zones_open) > 1) or zone in direct_zones:
outputs["siren2"].set(True)
time.sleep(1)
if state.system != current_state:
outputs["siren1"].set(False)
outputs["siren2"].set(False)
# outputs["beacon"].set(False)
logging.info("Siren loop aborted")
return False
# if len(state.zones_open) > zones_open:
# logging.warning("Open triggered zones increased, extending trigger time")
# logging.debug("Trigger time increased by: %d seconds", time.time() - start_time)
# start_time = time.time()
# zones_open = len(state.zones_open)
outputs["siren1"].set(False)
outputs["siren2"].set(False)
# outputs["beacon"].set(False)
logging.info("Siren loop completed")
return True
def arming(user: str) -> None:
state.system = "arming"
arming_time = config.getint("times", "arming")
if args.silent:
arming_time = 10
if buzzer(arming_time, "arming") is True:
active_away_zones = [o.label for o in away_zones if o.get()]
if not active_away_zones:
state.system = "armed_away"
pushover.push(f"System armed away, by {user}")
else:
logging.error("Arm away failed, not clear: %s", active_away_zones)
state.system = "disarmed"
active_away_zones_str = ", ".join(active_away_zones)
pushover.push(f"Arm away failed, not clear: {active_away_zones_str}", 1, {"sound": "siren"})
buzzer_signal(1, [1, 0])
def pending(current_state: str, zone: Zone) -> None:
delay_time = config.getint("times", "delay")
if args.silent:
delay_time = 10
with pending_lock:
state.system = "pending"
logging.info("Pending because of zone: %s", zone)
if buzzer(delay_time, "pending") is True:
triggered(current_state, zone)
def triggered(current_state: str, zone: Zone) -> None:
trigger_time = config.getint("times", "trigger")
if args.silent:
trigger_time = 30
with triggered_lock:
if zone in fire_zones:
state.data["triggered"] = "Fire"
elif zone in water_zones:
state.data["triggered"] = "Water leak"
elif zone in direct_zones:
state.data["triggered"] = "Emergency"
else:
state.data["triggered"] = "Intrusion"
state.system = "triggered"
logging.warning("Triggered because of %s, zone: %s", state.data.triggered, zone)
pushover.push(f"{state.data.triggered}, zone: {zone}", 2)
state.blocked.add(zone)
logging.debug("Blocked zones: %s", state.blocked)
if siren(trigger_time, zone, "triggered") is True:
state.system = current_state
def disarmed(user: str) -> None:
state.system = "disarmed"
pushover.push(f"System disarmed, by {user}")
buzzer_signal(2, [0.05, 0.15])
def armed_home(user: str) -> None:
active_home_zones = [o.label for o in home_zones if o.get()]
if not active_home_zones:
state.system = "armed_home"
pushover.push(f"System armed home, by {user}")
buzzer_signal(1, [0.05, 0.05])
else:
logging.error("Arm home failed, not clear: %s", active_home_zones)
state.system = "disarmed"
active_home_zones_str = ", ".join(active_home_zones)
pushover.push(f"Arm home failed, not clear: {active_home_zones_str}", 1, {"sound": "siren"})
buzzer_signal(1, [1, 0])
def water_alarm() -> None:
with water_alarm_lock:
water_alarm_time = time.time()
logging.warning("Entered water alarm lock!")
arduino.commands.put([3, True]) # Water valve relay
arduino.commands.put([4, True]) # Dishwasher relay (NC)
# Keep in loop until manually reset
while not arduino.data.inputs[4]:
if math.floor(time.time() - water_alarm_time) % 30 == 0:
buzzer_signal(1, [0.5, 0.5])
buzzer_signal(2, [0.1, 0.2])
else:
time.sleep(1)
logging.info("Leaving water alarm lock.")
# Turn water back on if manual switch enabled
if arduino.data.inputs[3]:
arduino.commands.put([3, False]) # Water valve relay
arduino.commands.put([4, False]) # Dishwasher relay (NC)
def run_led() -> None:
while True:
run_led_output = "led_red" if state.data["fault"] else "led_green"
if state.system == "disarmed":