forked from Tertiush/ParadoxIP150v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IP150-MQTTv2.py
1150 lines (896 loc) · 49.8 KB
/
IP150-MQTTv2.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 hashlib
import socket
import time
import lib.client as mqtt
import sys
import array
import random
import ConfigParser
import struct
import importlib
import logging
import logging.handlers
# Alarm controls can be given in payload, e.g. Paradox/C/P1, payl = Disarm
################################################################################################
# Paradox IP Modile
################################################################################################
# Change History
################################################################################################
# 2017-03-11
# - Longer delay on errors.
#
# 2017-03-02
# - Added logging around connection retries
# - Added time.sleep(5) on each failure
#
# 2017-02-26
# - Changed print statementst to logging statement to generate a proper log file
# - Added new config key words Topic_Publish_ZoneState and Topic_Publish_Partition
# - Topic_Publish_ZoneState - that is called from TestEventMessages when a zone event is found,
# froamt Paradox/Zone/<zone name> - where zone name is extracted from the event packet (chars 15 - 30)
# - Topic_Publish_Partition - that is called from TestEventMessages when a partition
# arm/disarm event is found
###############################################################################################
# Do not edit these variables here, use the config.ini file instead.
Zone_Amount = 32
passw = "abcd"
user = "1234"
IP150_IP = "10.0.0.120"
IP150_Port = 10000
Poll_Speed = 30.5 # Seconds (float)
MQTT_IP = "10.0.0.130"
MQTT_Port = 1883
MQTT_KeepAlive = 60 # Seconds
mqtt_username = None
mqtt_password = None
# Options are Arm, Disarm, Stay, Sleep (case sensitive!)
Topic_Publish_Events = "Paradox/Events"
Events_Payload_Numeric = "False"
Topic_Subscribe_Control = "Paradox/C/" # e.g. To arm partition 1: Paradox/C/P1/Arm
Startup_Publish_All_Info = "True"
Startup_Update_All_Labels = "True"
Topic_Publish_Labels = "Paradox/Labels"
Topic_Publish_AppState = "Paradox/State"
Topic_Publish_ZoneState = "Paradox/Zone"
Topic_Publish_ArmState = "Paradox/Partition"
Publish_Static_Topic = 0
Alarm_Model = "ParadoxMG5050"
Alarm_Registry_Map = "ParadoxMG5050"
Alarm_Event_Map = "ParadoxMG5050"
# Global variables
Alarm_Control_Action = 0
Alarm_Control_Partition = 0
Alarm_Control_NewState = ""
Output_FControl_Action = 0
Output_FControl_Number = 0
Output_FControl_NewState = ""
Output_PControl_Action = 0
Output_PControl_Number = 0
Output_PControl_NewState = ""
State_Machine = 0
Polling_Enabled = 1
Debug_Mode = 0
Error_Delay = 30
#Logging
LOG_LEVEL = logging.INFO
LOG_FILE = "/var/log/paradoxip.log"
LOG_FORMAT = "%(asctime)s %(levelname)s %(message)s"
#logging.basicConfig(filename=LOG_FILE, format=LOG_FORMAT, level=LOG_LEVEL)
logger = logging.getLogger()
def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
try:
dict1[option] = Config.get(section, option)
if dict1[option] == -1:
logging.info("skip: %s" % option)
except:
logging.error("exception on %s!" % option)
dict1[option] = None
return dict1
def on_connect(client, userdata, flags, rc):
logging.info("Connected to MQTT broker with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# client.subscribe("$SYS/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
global Alarm_Control_Partition
global Alarm_Control_NewState
global Alarm_Control_Action
global Output_FControl_Number
global Output_FControl_NewState
global Output_FControl_Action
global Output_PControl_Number
global Output_PControl_NewState
global Output_PControl_Action
global Polling_Enabled
valid_states = ['Arm', 'Disarm', 'Sleep', 'Stay']
logging.info("MQTT Message: " + msg.topic + " " + str(msg.payload))
topic = msg.topic
if Topic_Subscribe_Control in msg.topic:
if "Polling" in msg.topic:
if "Enable" in msg.topic:
logging.info("Enable polling message received...")
client.publish(Topic_Publish_AppState, "Polling: Enabling...", 1, True)
Polling_Enabled = 1
if "Disable" in msg.topic:
logging.info("Disable polling message received...")
Polling_Enabled = 0
elif "/FO/" in msg.topic:
try:
Output_FControl_Number = int((topic.split(Topic_Subscribe_Control + 'FO/'))[1].split('/')[0])
logging.info("Output force control number: %s " % Output_FControl_Number)
try:
Output_FControl_NewState = (topic.split('/FO/' + str(Output_FControl_Number) + '/'))[1]
except Exception, e:
Output_FControl_NewState = msg.payload
if len(Output_FControl_NewState) < 1:
logging.info('No payload given for control number: e.g. On')
logging.info("Output force control state: %s " % Output_FControl_NewState)
client.publish(Topic_Publish_AppState,
"Output: Forcing PGM " + str(Output_FControl_Number) + " to state: " + Output_FControl_NewState, 1, True)
Output_FControl_Action = 1
except:
logging.error("MQTT message received with incorrect structure")
elif "/PO/" in msg.topic:
try:
Output_PControl_Number = int((topic.split(Topic_Subscribe_Control + 'PO/'))[1].split('/')[0])
logging.info("Output pulse control number: %s " % Output_PControl_Number)
try:
Output_PControl_NewState = (topic.split('/PO/' + str(Output_PControl_Number) + '/'))[1]
except Exception, e:
Output_PControl_NewState = msg.payload
if len(Output_PControl_NewState) < 1:
logging.error('No payload given for control number: e.g. On')
logging.info("Output pulse control state: %s" % Output_PControl_NewState)
client.publish(Topic_Publish_AppState,
"Output: Pulsing PGM " + str(Output_PControl_Number) + " to state: " + Output_PControl_NewState,
1, True)
Output_PControl_Action = 1
except:
logging.error("MQTT message received with incorrect structure")
elif "/P" in msg.topic:
try:
Alarm_Control_Partition = int((topic.split(Topic_Subscribe_Control + 'P'))[1].split('/')[0])
logging.info("Alarm control partition: %s" % Alarm_Control_Partition)
try:
Alarm_Control_NewState = (topic.split('/P' + str(Alarm_Control_Partition) + '/'))[1]
except Exception:
Alarm_Control_NewState = msg.payload
if len(Alarm_Control_NewState) < 1:
logging.error('No payload given for alarm control: e.g. Disarm')
logging.info("Alarm control state: %s" % Alarm_Control_NewState)
client.publish(Topic_Publish_AppState,
"Alarm: Control partition " + str(Alarm_Control_Partition) + " to state: " + Alarm_Control_NewState,
1, True)
Alarm_Control_Action = 1
except:
logging.error("MQTT message received with incorrect structure")
def connect_ip150socket(address, port):
try:
print "trying to connect %s" % address
logging.info("Connecting to %s" % address)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect((address, port))
print "connected"
except Exception, e:
logging.error( "Error connecting to IP module (exiting): " + repr(e))
print "error connecting"
client.publish(Topic_Publish_AppState,
"Error connecting to IP module (exiting): " + repr(e),
1, True)
sys.exit()
return s
class paradox:
loggedin = 0
aliveSeq = 0
alarmName = None
zoneTotal = 0
zoneStatus = ['']
zoneNames = {}
zonePartition = None
partitionStatus = None
partitionName = None
Skip_Update_Labels = 0
def __init__(self, _transport, _encrypted=0, _retries=10, _alarmeventmap="ParadoxMG5050",
_alarmregmap="ParadoxMG5050"):
self.comms = _transport # instance variable unique to each instance
self.retries = _retries
self.encrypted = _encrypted
self.alarmeventmap = _alarmeventmap
self.alarmregmap = _alarmregmap
# MyClass = getattr(importlib.import_module("." + self.alarmmodel + "EventMap", __name__))
try:
mod = __import__("ParadoxMap", fromlist=[self.alarmeventmap + "EventMap"])
self.eventmap = getattr(mod, self.alarmeventmap + "EventMap")
except Exception, e:
logging.error("Failed to load Event Map: %s " % repr(e))
logging.error("Defaulting to MG5050 Event Map...")
try:
mod = __import__("ParadoxMap", fromlist=["ParadoxMG5050EventMap"])
self.eventmap = getattr(mod, "ParadoxMG5050EventMap")
except Exception, e:
logging.error("Failed to load Event Map (exiting): %s" % repr(e))
sys.exit()
try:
mod = __import__("ParadoxMap", fromlist=[self.alarmregmap + "Registers"])
self.registermap = getattr(mod, self.alarmregmap + "Registers")
except Exception, e:
logging.error("Failed to load Register Map (defaulting to not update labels from alarm): %s" % repr(e))
self.Skip_Update_Labels = 1
# self.eventmap = ParadoxMG5050EventMap # Need to check panel type here and assign correct dictionary!
# self.registermap = ParadoxMG5050Registers # Need to check panel type here and assign correct dictionary!
def skipLabelUpdate(self):
return self.Skip_Update_Labels
def saveState(self):
self.eventmap.save()
def loadState(self):
logging.info("Loading previous event states and labels from file")
self.eventmap.load()
def login(self, password, Debug_Mode=0): # Construct the login message, 16 byte header +
# 16byte [or multiple] payloading being the password
logging.info("Logging into alarm system...")
header = "\xaa" # First construct the 16 byte header, starting with 0xaa
header += bytes(bytearray([len(password)])) # Add the length of the password which is appended after the header
header += "\x00\x03" # No idea what this is
if self.encrypted == 0: # Encryption flag
header += "\x08" # Encryption off [default for now]
else:
header += "\x09" # Encryption on
header += "\xf0\x00\x0a" # No idea what this is, although the fist byte seems like a sequence number
# header += "\xf0\x00\x0e\x00\x01" # iParadox initial request
header = header.ljust(16, '\xee') # The remained of the 16B header is filled with 0xee
message = password # Add the password as the start of the payload
# FIXME: Add support for passwords longer than 16 characters
message = message.ljust(16, '\xee') # The remainder of the 16B payload is filled with 0xee
reply = self.readDataRaw(header + message, Debug_Mode) # Send message to the alarm panel and read the reply
if reply[4] == '\x38':
logging.info("Login to alarm panel successful")
loggedin = 1
else:
loggedin = 0
logging.info("Login request unsuccessful, panel returned: " + " ".join(hex(ord(reply[4]))))
header = list(header)
header[1] = '\x00'
header[5] = '\xf2'
header2 = "".join(header)
self.readDataRaw(header2, Debug_Mode)
header[5] = '\xf3'
header2 = "".join(header)
reply = self.readDataRaw(header2, Debug_Mode)
reply = list(reply) # Send "waiting" header until reply is at least 48 bytes in length indicating ready state
header[1] = '\x25'
header[3] = '\x04'
header[5] = '\x00'
header2 = "".join(header)
message = '\x72\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
message = self.format37ByteMessage(message)
reply = self.readDataRaw(header2 + message, Debug_Mode)
# A - no sending after this
header[1] = '\x26'
header[3] = '\x03'
header[5] = '\xf8'
header2 = "".join(header)
message = '\x50\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
message = self.format37ByteMessage(message)
reply = self.readDataRaw(header2 + message, Debug_Mode)
header[1] = '\x25'
header[3] = '\x04'
header[5] = '\x00'
header2 = "".join(header)
message = '\x5f\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
message = self.format37ByteMessage(message)
reply = self.readDataRaw(header2 + message, Debug_Mode)
header[1] = '\x25'
header[3] = '\x04'
header[5] = '\x00'
header[7] = '\x14'
header2 = "".join(header)
# reply = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x10\x11\x12\x13\x14\x15\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09'
message = reply[16:26]
message += reply[24:26]
message += '\x19\x00\x00'
message += reply[31:39]
message += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00'
message = self.format37ByteMessage(message)
reply = self.readDataRaw(header2 + message, Debug_Mode)
header[1] = '\x25'
header[3] = '\x04'
header[5] = '\x00'
header[7] = '\x14'
header2 = "".join(header)
message = '\x50\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
message = self.format37ByteMessage(message)
reply = self.readDataRaw(header2 + message, Debug_Mode)
header[1] = '\x25'
header[3] = '\x04'
header[5] = '\x00'
header[7] = '\x14'
header2 = "".join(header)
message = '\x50\x00\x0e\x52\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
message = self.format37ByteMessage(message)
reply = self.readDataRaw(header2 + message, Debug_Mode)
return loggedin
def format37ByteMessage(self, message):
checksum = 0
if len(message) % 37 != 0:
for val in message: # Calculate checksum
checksum += ord(val)
# print "CS: " + str(checksum)
while checksum > 255:
checksum = checksum - (checksum / 256) * 256
# print "CS: " + str(checksum)
message += bytes(bytearray([checksum])) # Add check to end of message
msgLen = len(message) # Pad with 0xee till end of last 16 byte message
if (msgLen % 16) != 0:
message = message.ljust((msgLen / 16 + 1) * 16, '\xee')
# print " ".join(hex(ord(i)) for i in message)
return message
# Implementation inspired by https://github.com/bioego/Paradox-UWP
def updateZoneAndAlarmStatus(self, Startup_Publish_All_Info="True", Debug_Mode=0):
header = "\xaa\x25\x00\x04\x08\x00\x00\x14\xee\xee\xee\xee\xee\xee\xee\xee"
message = "\x50\x00\x80"
message += "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
message += "\x00\xd0\xee\xee\xee\xee\xee\xee\xee\xee\xee\xee\xee"
reply = self.readDataRaw(header + self.format37ByteMessage(message), Debug_Mode)
if len(reply) < 39:
print "Response without zone status"
return
# Skip to zone status
reply = reply[25:]
reply = reply[10:] # skip date, time and voltages
for x in range(4):
data = ord(reply[x])
for y in range(8):
bit = data & 1
data = data / 2
itemNo = x * 8 + y + 1
if itemNo in self.zoneNames.keys():
location = self.zoneNames[itemNo]
if len(location) > 0:
zoneState = "ON" if bit else "OFF"
print "Publishing initial zone state (state:" + zoneState + ", zone:" + location + ")"
client.publish_with_timestamp(Topic_Publish_ZoneState + "/" + location, "ON" if bit else "OFF", qos=1, retain=True)
time.sleep(0.3)
message = "\x50\x00\x80\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
message += "\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd1\xee\xee\xee\xee\xee\xee\xee\xee\xee\xee\xee"
reply = self.readDataRaw(header + self.format37ByteMessage(message), Debug_Mode)
if len(reply) < 34:
print "Response without zone status"
return
# Skip to alarm status
reply = reply[33:]
alarmState = ord(reply[0])
alarmState = "ON" if (alarmState & 1) else "OFF"
print "Publishing initial alarm state (state:" + alarmState + ")"
client.publish_with_timestamp(Topic_Publish_ArmState, alarmState, qos=1, retain=True)
time.sleep(0.3)
return
def updateAllLabels(self, Startup_Publish_All_Info="True", Topic_Publish_Labels="True", Debug_Mode=0):
for func in self.registermap.getsupportedItems():
if Debug_Mode >= 2:
logging.debug("updateAllLabels: Reading from alarm: " + func)
try:
register_dict = getattr(self.registermap, "get" + func + "Register")()
mapping_dict = getattr(self.eventmap, "set" + func)
total = sum(1 for x in register_dict if isinstance(x, int))
if Debug_Mode >= 2:
logging.debug("updateAllLabels: Amount of numeric items in dictionary to read: " + str(total))
header = register_dict["Header"]
skip_next = 0
for x in range(1, total + 1):
if skip_next == 1:
skip_next = 0
continue
# print "Update generic registers step: " + str(x)
message = register_dict[x]["Send"]
try:
next_message = register_dict[x + 1]["Send"]
except KeyError:
skip_next = 1
# print "no next key"
# print "Current msg " + " ".join(hex(ord(i)) for i in message)
# print "Next msg " + " ".join(hex(ord(i)) for i in next_message)
assert isinstance(message, basestring), "Message to be sent is not a string: %r" % message
message = message.ljust(36, '\x00')
# print " ".join(hex(ord(i)) for i in message)
reply = self.readDataRaw(header + self.format37ByteMessage(message), Debug_Mode)
start = register_dict[x]["Receive"]["Start"]
finish = register_dict[x]["Receive"]["Finish"]
# self.zoneNames.append(reply[start:finish].rstrip()) FIXME: remove all internal zoneNames references and only use the dict
mapping_dict(x, reply[start:finish].rstrip().translate(None, '\x00'))
if (skip_next == 0) and (message[0:len(next_message)] == next_message):
# print "Same"
start = register_dict[x + 1]["Receive"]["Start"]
finish = register_dict[x + 1]["Receive"]["Finish"]
mapping_dict(x + 1, reply[start:finish].rstrip().translate(None, '\x00'))
skip_next = 1
try:
completed_dict = getattr(self.eventmap, "getAll" + func)()
if Debug_Mode >= 1:
logging.info("Labels detected for " + func + ":")
logging.info(completed_dict)
except Exception, e:
logging.error("Failed to load supported function's completed mappings after updating: %s" % repr(e))
if Startup_Publish_All_Info == "True":
topic = func.split("Label")[0]
if topic[0].upper() + topic[1:] + "s" == "Zones":
self.zoneNames = completed_dict
logging.info("updateAllLabels: Topic being published " + Topic_Publish_Labels + "/" + topic[0].upper() + topic[1:] + "s" + ';'.join('{}{}'.format(key, ":" + val) for key, val in completed_dict.items()))
client.publish(Topic_Publish_Labels + "/" + topic[0].upper() + topic[1:] + "s",
';'.join('{}{}'.format(key, ":" + val) for key, val in completed_dict.items()), 1, True)
except Exception, e:
logging.error("Failed to load supported function's mapping: %s" % repr(e))
return
def testForEvents(self, Events_Payload_Numeric=0, Publish_Static_Topic=0, Debug_Mode=0):
reply_amount, headers, messages = self.splitMessage(self.readDataRaw('', Debug_Mode))
interrupt = 0 # Signal 3rd party connection interrupt
#if Debug_Mode >= 1:
# logging.debug('.')
reply = '.'
if Debug_Mode >= 1 and reply_amount > 1:
logging.debug("Multiple data: " + repr(messages))
if reply_amount > 0:
if self.retries < 10:
logging.info("Setting retries back to 3 after a couple of errors")
self.retries = 10
for message in messages:
if Debug_Mode >= 2:
logging.debug("Event data: " + " ".join(hex(ord(i)) for i in message))
if len(message) > 0:
if message[0] == '\xe2' or message[0] == '\xe0':
try:
location = ""
if Events_Payload_Numeric == 0:
event, subevent = self.eventmap.getEventDescription(ord(message[7]), ord(message[8]))
location = message[15:30].strip().translate(None, '\x00')
if location:
logging.debug("Event: \"%s\"" % location)
print "Event: \"%s\"" % location
reply = "Event:" + event + ";SubEvent:" + subevent
print str(ord(message[7]))
# zone status messages Paradox/Zone/ZoneName 0 for close, 1 for open
if ord(message[7]) == 0:
logging.info("Publishing event \"%s\" for %s = %s" % (Topic_Publish_ZoneState, location, "OFF"))
client.publish_with_timestamp(Topic_Publish_ZoneState + "/" + location,"OFF", qos=1, retain=True)
elif ord(message[7]) == 1:
logging.info("Publishing event \"%s\" for %s = %s" % (Topic_Publish_ZoneState, location, "ON"))
client.publish_with_timestamp(Topic_Publish_ZoneState + "/" + location,"ON", qos=1, retain=True)
elif ord(message[7]) == 2 and ord(message[8]) == 11: #Disarm
logging.info("Publishing event \"%s\" = %s" % (Topic_Publish_ArmState, "disarm"))
client.publish_with_timestamp(Topic_Publish_ArmState ,"OFF", qos=1, retain=True)
elif ord(message[7]) == 2 and ord(message[8]) == 12: #arm
logging.info("Publishing event \"%s\" = %s" % (Topic_Publish_ZoneState, "arm"))
client.publish_with_timestamp(Topic_Publish_ArmState ,"ON", qos=1, retain=True)
if Events_Payload_Numeric == 1:
reply = "E:" + str(ord(message[7])) + ";SE:" + str(ord(message[8]))
logging.info("Publishing event E\"%s\" for :SE %s " % (str(ord(message[7])), str(ord(message[8])) ) )
if Publish_Static_Topic == "1":
client.publish_with_timestamp(Topic_Publish_Events + "/" + str(ord(message[7])) + "/" + str(ord(message[8])), qos=1, retain=False)
client.publish(Topic_Publish_Events, reply, qos=0, retain=False)
if Debug_Mode >= 1:
logging.debug(reply)
except ValueError:
reply = "No register entry for Event: " + str(ord(message[7])) + ", Sub-Event: " + str(
ord(message[8]))
elif message[0] == '\x75' and message[1] == '\x49':
interrupt = 1;
else:
reply = "Unknown event: " + " ".join(hex(ord(i)) for i in message)
return interrupt
def splitMessage(self, request=''): # FIXME: Make msg a list to handle multiple 37byte replies
if len(request) > 0:
requests = request.split('\xaa')
del requests[0]
for i, val in enumerate(requests):
requests[i] = '\xaa' + val
# print "Request seq " + str(i) + ": " + " ".join(hex(ord(i)) for i in requests[i])
# print "Request(s): ", requests
replyAmount = len(requests)
x = replyAmount
headers = [] * replyAmount
messages = [] * replyAmount
# print "Reply amount: ", x
x -= 1
# print "Going into while with first element: " + requests[0]
while x >= 0:
# print "Working on number " + str(x) + ": " + " ".join(hex(ord(i)) for i in requests[i])
if len(requests[x]) > 16:
headers.append(requests[x][:16])
messages.append(requests[x][16:])
elif len(requests[x]) == 16:
headers.append(requests[x][:16])
messages.append([])
# return headers, ''
x -= 1
return replyAmount, headers, messages
else:
return 0, [], []
def sendData(self, request=''):
if len(request) > 0:
self.comms.send(request)
time.sleep(0.25)
def readDataRaw(self, request='', Debug_Mode=2):
# self.testForEvents() # First check for any pending events received
tries = self.retries
while tries > 0:
try:
if Debug_Mode >= 2:
logging.debug(str(len(request)) + "-> " + " ".join(hex(ord(i)) for i in request))
self.sendData(request)
inc_data = self.comms.recv(1024)
if Debug_Mode >= 2:
logging.debug( str(len(inc_data)) + "<- " + " ".join(hex(ord(i)) for i in inc_data))
tries = 0
except socket.timeout, e:
err = e.args[0]
if err == 'timed out':
#logging.error("Timed out error, no retry -<-- could fix this" + repr(e))
#this seems to be where it goes normally while waiting for traffic.
tries = 0
sys.exc_clear()
return ''
# sleep(1)
# print 'Receive timed out, ret'
# continue
else:
logging.error("Error reading data from IP module, retrying again... (" + str(tries) + "): " + repr(e))
tries -= 1
time.sleep(Error_Delay)
sys.exc_clear()
pass
except socket.error, e:
logging.error("Unknown error on socket connection, retrying (%d) ... %s " % (tries, repr(e)))
tries -= 1
time.sleep(Error_Delay)
if tries == 0:
logging.info("Failure, disconnected.")
sys.exit(1)
else:
logging.error("After error, continuing %d attempts left" % tries)
sys.exc_clear()
return ''
continue
else:
if len(inc_data) == 0:
tries -= 1
logging.info('Socket connection closed by remote host: %d' % tries)
time.sleep(Error_Delay)
if tries == 0:
logging.error('Failure, disconnecting')
sys.exit(0)
else:
return inc_data
def readDataStruct37(self, inputData='', Debug_Mode=0): # Sends data, read input data and return the Header and Message
rawdata = self.readDataRaw(inputData, Debug_Mode)
# Extract the header and message
if len(rawdata) > 16:
header = rawdata[:16]
message = rawdata[17:]
return header, message
def controlGenericOutput(self, mapping_dict, output, state, Debug_Mode=0):
registers = mapping_dict
header = registers["Header"]
if Debug_Mode >= 1:
logging.debug( "Sending generic Output Control: Output: " + str(output) + ", State: " + state)
message = registers[output][state]
assert isinstance(message, basestring), "Message to be sent is not a string: %r" % message
message = message.ljust(36, '\x00')
# print " ".join(hex(ord(i)) for i in message)
reply = self.readDataRaw(header + self.format37ByteMessage(message), Debug_Mode)
return
def controlPGM(self, pgm, state="OFF", Debug_Mode=0):
# print state.upper()
assert (isinstance(pgm, int) and pgm >= 0 and pgm <= 16), "Problem with PGM number: %r" % str(pgm)
assert (isinstance(pgm, int) and pgm >= 0 and pgm <= 16), "Problem with PGM number: %r" % str(pgm)
assert isinstance(state, basestring), "State given is not a string: %r" % str(state)
assert (state.upper() == "ON" or state.upper() == "OFF"), "State is not given correctly: %r" % str(state)
self.controlGenericOutput(self.registermap.getcontrolOutputRegister(), pgm, state.upper(), Debug_Mode)
return
def controlGenericAlarm(self, mapping_dict, partition, state, Debug_Mode):
registers = mapping_dict
header = registers["Header"]
logging.info("Sending generic Alarm Control: Partition: " + str(partition) + ", State: " + state)
message = registers[partition][state]
assert isinstance(message, basestring), "Message to be sent is not a string: %r" % message
message = message.ljust(36, '\x00')
# print " ".join(hex(ord(i)) for i in message)
reply = self.readDataRaw(header + self.format37ByteMessage(message), Debug_Mode)
return
def controlAlarm(self, partition=1, state="Disarm", Debug_Mode=0):
assert (
isinstance(partition,
int) and partition >= 0 and partition <= 16), "Problem with partition number: %r" % str(
partition)
assert isinstance(state, basestring), "State given is not a string: %r" % str(state)
assert (state.upper() in self.registermap.getcontrolAlarmRegister()[
partition]), "State is not given correctly: %r" % str(state)
self.controlGenericAlarm(self.registermap.getcontrolAlarmRegister(), partition, state.upper(), Debug_Mode)
return
def disconnect(self, Debug_Mode=2):
# header = "\xaa\x00\x00\x03\x51\xff\x00\x0e\x00\x01\xee\xee\xee\xee\xee\xee"
header = "\xaa\x25\x00\x04\x08\x00\x00\x14\xee\xee\xee\xee\xee\xee\xee\xee"
message = "\x70\x00\x05"
self.readDataRaw(header + self.format37ByteMessage(message), Debug_Mode)
def keepAlive(self, Debug_Mode=0):
header = "\xaa\x25\x00\x04\x08\x00\x00\x14\xee\xee\xee\xee\xee\xee\xee\xee"
message = "\x50\x00\x80"
message += bytes(bytearray([self.aliveSeq]))
message += "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
self.sendData(header + message)
self.aliveSeq += 1
if self.aliveSeq > 6:
self.aliveSeq = 0
def walker(self, ):
self.zoneTotal = Zone_Amount
logging.info("Reading (" + str(Zone_Amount) + ") zone names...")
header = "\xaa\x25\x00\x04\x08\x00\x00\x14\xee\xee\xee\xee\xee\xee\xee\xee"
for x in range(16, 65535, 32):
message = "\xe2\x00"
zone = x
zone = list(struct.pack("H", zone))
swop = zone[0]
zone[0] = zone[1]
zone[1] = swop
temp = "".join(zone)
# print " ".join(hex(ord(i)) for i in temp)
message += temp
message += "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
# print " ".join(hex(ord(i)) for i in message)
reply = self.readDataRaw(header + self.format37ByteMessage(message))
logging.info(reply)
# print " ".join(hex(ord(i)) for i in reply)
time.sleep(0.3)
return
if __name__ == '__main__':
State_Machine = 0
attempts = 3
print "logging to file %s" % LOG_FILE
speciallogging = False
interruptCountdown = 0
interrupt = 0
while True:
if speciallogging:
print "Special logging after errorsstate %d" % State_Machine
logging.info("Special logging after errors state %d" % State_Machine)
# -------------- Read Config file ----------------
if State_Machine <= 0:
print "reading config"
logging.info("Reading config.ini file...")
logger.info("Reading config.ini file...")
try:
Config = ConfigParser.ConfigParser()
Config.read("config.ini")
LOG_FILE = Config.get("Application","Log_File")
log_handler = logging.handlers.WatchedFileHandler(LOG_FILE)
formatter = logging.Formatter(LOG_FORMAT)
log_handler.setLevel(logging.DEBUG)
log_handler.setFormatter(formatter)
logging.info("logging complete")
logging.debug("logging complete")
#logger = logging.getLogger()
log_handler2 = logging.StreamHandler()
log_handler2.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
log_handler2.setFormatter(formatter)
logger.addHandler(log_handler2)
logger.addHandler(log_handler)
logger.info("logging complete")
logger.error("test")
Alarm_Model = Config.get("Alarm", "Alarm_Model")
Alarm_Registry_Map = Config.get("Alarm", "Alarm_Registry_Map")
Alarm_Event_Map = Config.get("Alarm", "Alarm_Event_Map")
Zone_Amount = int(Config.get("Alarm", "Zone_Amount"))
if Zone_Amount % 2 != 0:
Zone_Amount += 1
passw = Config.get("IP150", "Password")
user = Config.get("IP150", "Pincode")
IP150_IP = Config.get("IP150", "IP")
IP150_Port = int(Config.get("IP150", "IP_Software_Port"))
MQTT_IP = Config.get("MQTT Broker", "IP")
MQTT_Port = int(Config.get("MQTT Broker", "Port"))
mqtt_username = Config.get("MQTT Broker", "Mqtt_Username")
mqtt_password = Config.get("MQTT Broker", "Mqtt_Password")
Topic_Publish_Events = Config.get("MQTT Topics", "Topic_Publish_Events")
Events_Payload_Numeric = int(Config.get("MQTT Topics", "Events_Payload_Numeric"))
Topic_Subscribe_Control = Config.get("MQTT Topics", "Topic_Subscribe_Control")
Startup_Publish_All_Info = Config.get("MQTT Topics", "Startup_Publish_All_Info")
Topic_Publish_Labels = Config.get("MQTT Topics", "Topic_Publish_Labels")
Topic_Publish_AppState = Config.get("MQTT Topics", "Topic_Publish_AppState")
Startup_Update_All_Labels = Config.get("Application", "Startup_Update_All_Labels")
Topic_Publish_ZoneState = Config.get("MQTT Topics", "Topic_Publish_ZoneState")
Topic_Publish_ArmState = Config.get("MQTT Topics", "Topic_Publish_ArmState")
Publish_Static_Topic = Config.get("MQTT Topics", "Publish_Static_Topic")
Debug_Mode = int(Config.get("Application", "Debug_Mode"))
Auto_Logoff = Config.get("Application", "Auto_Logoff")
Logoff_Delay = int(Config.get("Application", "Logoff_Delay"))
if Debug_Mode > 0:
logging.info("Setting loglevel to debug")
logging.debug("Logging Set to debug")
logging.info("logging set to debug")
logging.info("config.ini file read successfully: %d" % Debug_Mode)
print "config read"
State_Machine += 1
except Exception, e:
logging.error("******************* Error reading config.ini file (will use defaults): %s" % e)
State_Machine = 1
attempts = 3
# -------------- MQTT ----------------
elif State_Machine == 1:
try:
if speciallogging:
logging.info("State machine 1: starting client again")
logging.info("State01:Attempting connection to MQTT Broker: " + MQTT_IP + ":" + str(MQTT_Port))
client = mqtt.Client()
if mqtt_password == '':
mqtt_password = None
if mqtt_username != '':
client.username_pw_set(mqtt_username, mqtt_password)
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_IP, MQTT_Port, MQTT_KeepAlive)
client.loop_start()
client.subscribe(Topic_Subscribe_Control + "#")
logging.info("State01:MQTT client subscribed to control messages on topic: " + Topic_Subscribe_Control + "#")
client.publish(Topic_Publish_AppState,"State Machine 1, Connected to MQTT Broker",1,True)
State_Machine += 1
except Exception, e:
logging.error( "MQTT connection error (" + str(attempts) + ": " + e.strerror)
time.sleep(Poll_Speed * 5)
attempts -= 1
if attempts < 1:
logging.error( "State01:Error within State_Machine: {0}: {1}".format(State_Machine,e.strerror))
State_Machine -= 1
logging.error( "State01:Going to State_Machine: " + str(State_Machine))
attempts = 3
# -------------- Login to IP Module ----------------
elif State_Machine == 2 and Polling_Enabled == 1:
try:
if speciallogging:
logging.info("State machine 2 + polling: starting calarm communication again")
logging.info("State02:Connecting to IP Module")
client.publish(Topic_Publish_AppState, "State Machine 2, Connecting to IP Module...", 1, True)
comms = connect_ip150socket(IP150_IP, IP150_Port)
client.publish(Topic_Publish_AppState,
"State Machine 2, Connected to IP Module, unlocking...",
1, True)
myAlarm = paradox(comms, 0, 3, Alarm_Event_Map, Alarm_Registry_Map)
if not myAlarm.login(passw, Debug_Mode):
logging.info("State02:Failed to login & unlock to IP module, check if another app is using the port. Retrying... ")
client.publish(Topic_Publish_AppState,
"State Machine 2, Failed to login & unlock to IP module, check if another app is using the port. Retrying... ",
1, True)
comms.close()
time.sleep(Poll_Speed * 20)
else:
client.publish(Topic_Publish_AppState, "State Machine 2, Logged into IP Module successfully", 1, True)
logging.info("State02: Logged into IP modeule successfully")
State_Machine += 1
speciallogging = False
except Exception, e:
logging.error( "State02:Error attempting connection to IP module ({0}): {1}".format(attempts, e))
client.publish(Topic_Publish_AppState,
"State Machine 2, Exception, retrying... ({0}): {1}".format(attempts, e),1, True)
time.sleep(Poll_Speed * 5)