forked from IndigoDomotics/DSC-Alarm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdsc.py
1599 lines (1351 loc) · 66.1 KB
/
dsc.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
#######################################################################
# DSC Alarm interface
# Originally developed by Travis Cook
# www.frightideas.com
#
# Redesign to replace Indigo with Fibaro Home Center 2 by Ove Nystås
#######################################################################
from datetime import datetime
import re
import serial # installed with sudo apt-get install python3-serial
import time
ZONE_STATE_OPEN = 'open'
ZONE_STATE_CLOSED = 'closed'
ZONE_STATE_TRIPPED = 'tripped'
ZONE_GROUP_STATE_OPEN = 'zoneOpen'
ZONE_GROUP_STATE_CLOSED = 'allZonesClosed'
ZONE_GROUP_STATE_TRIPPED = 'zoneTripped'
ALARM_STATE_DISARMED = 'disarmed'
ALARM_STATE_EXIT_DELAY = 'exitDelay'
ALARM_STATE_FAILED_TO_ARM = 'FailedToArm'
ALARM_STATE_ARMED = 'armed'
ALARM_STATE_ENTRY_DELAY = 'entryDelay'
ALARM_STATE_TRIPPED = 'tripped'
KEYPAD_STATE_CHIME_ENABLED = 'enabled'
KEYPAD_STATE_CHIME_DISABLED = 'disabled'
ALARM_ARMED_STATE_DISARMED = 'disarmed'
ALARM_ARMED_STATE_STAY = 'stay'
ALARM_ARMED_STATE_AWAY = 'away'
LED_INDEX_LIST = ['None', 'Ready', 'Armed', 'Memory', 'Bypass', 'Trouble',
'Program', 'Fire', 'Backlight', 'AC']
LED_STATE_LIST = ['off', 'on', 'flashing']
ARMED_MODE_LIST = ['Away', 'Stay', 'Away, No Delay', 'Stay, No Delay']
PANIC_TYPE_LIST = ['None', 'Fire', 'Ambulance', 'Panic']
MONTH_LIST = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
CMD_NORMAL = 0
CMD_THERMO_SET = 1
PING_INTERVAL = 301
HOLD_RETRY_TIME_MINUTES = 3
# Note the "indigo" module is automatically imported and made available inside
# our global name space by the host process.
###############################################################################
class Plugin(indigo.PluginBase):
########################################
def __init__(self, pluginId, pluginDisplayName,
pluginVersion, pluginPrefs):
self.States = self.enum(STARTUP=1, HOLD=2, HOLD_RETRY=3,
HOLD_RETRY_LOOP=4, BOTH_INIT=5,
ENABLE_TIME_BROADCAST=7,
BOTH_PING=8, BOTH_POLL=9)
self.state = self.States.STARTUP
self.logLevel = 1
self.shutdown = False
self.configRead = False
self.interfaceState = 0
self.zoneList = {}
self.tempList = {}
self.zoneGroupList = {}
self.trippedZoneList = []
self.triggerList = []
self.keypadList = {}
self.createVariables = False
self.port = None
self.repeatAlarmTripped = False
self.isPortOpen = False
self.txCmdList = []
self.closeTheseZonesList = []
self.currentHoldRetryTime = HOLD_RETRY_TIME_MINUTES
self.ourVariableFolder = None
self.configEmailUrgent = ""
self.configEmailNotice = ""
self.configEmailUrgentSubject = ""
self.configEmailNoticeSubject = ""
self.configSpeakVariable = None
self.configKeepTimeSynced = True
self.troubleCode = 0
self.troubleClearedTimer = 0
def enum(self, **enums):
return type('Enum', (), enums)
def __del__(self):
indigo.PluginBase.__del__(self)
########################################
def startup(self):
self.logger.log(4, "startup called")
self.configRead = self.getConfiguration(self.pluginPrefs)
self.updater.checkVersionPoll()
def shutdown(self):
self.logger.log(4, "shutdown called")
###########################################################################
# Indigo Device Start/Stop
###########################################################################
def deviceStartComm(self, dev):
self.logger.log(4, "<<-- entering deviceStartComm: %s (%d - %s)" %
(dev.name, dev.id, dev.deviceTypeId))
props = dev.pluginProps
if dev.deviceTypeId == 'alarmZoneGroup':
if dev.id not in self.zoneGroupList:
self.zoneGroupList[dev.id] = props['devList']
if dev.states['state'] == 0:
dev.updateStateOnServer(key="state",
value=ZONE_GROUP_STATE_CLOSED)
elif dev.deviceTypeId == 'alarmZone':
if 'zoneNumber' not in props:
return
zone = int(props['zoneNumber'])
if zone not in list(self.zoneList.keys()):
self.zoneList[zone] = dev.id
else:
self.logger.logError("Zone %s is already assigned "
"to another device." % zone)
# Check for new version zone states.
# If they're not present tell Indigo to reread the Devices.xml file
if 'LastChangedShort' not in dev.states:
dev.stateListOrDisplayStateIdChanged()
# If state is invalid or not there, set to closed
if dev.states['state'] == 0:
dev.updateStateOnServer(key='state',
value=ZONE_STATE_CLOSED)
dev.updateStateOnServer(key="LastChangedShort",
value=self.
getShortTime(dev.
states["LastChangedTimer"]))
# Check for new version properties to see if we need to refresh
# the device
if 'occupancyGroup' not in props:
self.logger.log(3, "Adding occupancyGroup to "
"device %s properties." % dev.name)
props.update({"occupancyGroup": 0})
dev.replacePluginPropsOnServer(props)
# If the variable we used no longer exists then remove the varID
if "var" in props:
if props["var"] not in indigo.variables:
props["var"] = None
dev.replacePluginPropsOnServer(props)
else:
props["var"] = None
dev.replacePluginPropsOnServer(props)
elif dev.deviceTypeId == 'alarmKeypad':
self.keypadList[int(dev.pluginProps['partitionNumber'])] = dev.id
# self.logger.log(3, u"Adding keypad: %s" % self.keypadList)
dev.updateStateOnServer(key='state',
value=ALARM_STATE_DISARMED)
# Check for new keypad states.
# If they're not present tell Indigo to reread the Devices.xml file
if 'ArmedState' not in dev.states:
dev.stateListOrDisplayStateIdChanged()
elif dev.deviceTypeId == 'alarmTemp':
sensor = int(dev.pluginProps['sensorNumber'])
if sensor not in list(self.tempList.keys()):
self.tempList[sensor] = dev
self.logger.log(4, "exiting deviceStartComm -->>")
def deviceStopComm(self, dev):
self.logger.log(4, "<<-- entering deviceStopComm: %s (%d - %s)" %
(dev.name, dev.id, dev.deviceTypeId))
if dev.deviceTypeId == 'alarmZoneGroup':
if dev.id in self.zoneGroupList:
del self.zoneGroupList[dev.id]
elif dev.deviceTypeId == 'alarmZone':
if 'zoneNumber' in dev.pluginProps:
zone = int(dev.pluginProps['zoneNumber'])
if zone in list(self.zoneList.keys()):
del self.zoneList[zone]
# self.logger.log(3, "ZoneList is now: %s" % self.zoneList)
elif dev.deviceTypeId == 'alarmKeypad':
if 'partitionNumber' in dev.pluginProps:
keyp = int(dev.pluginProps['partitionNumber'])
if keyp in self.keypadList:
del self.keypadList[keyp]
elif dev.deviceTypeId == 'alarmTemp':
if 'sensorNumber' in dev.pluginProps:
tmp = int(dev.pluginProps['sensorNumber'])
if tmp in self.tempList:
del self.tempList[int(dev.pluginProps['sensorNumber'])]
self.logger.log(4, "exiting deviceStopComm -->>")
# def deviceUpdated(self, origDev, newDev):
# self.logger.log(4, "<<-- entering deviceUpdated: %s" % origDev.name)
# origDev.name = newDev.name
# self.logger.log(4, "OrigDev now: %s" % origDev.name)
# self.DigiTemp.deviceStop(origDev)
# self.DigiTemp.deviceStart(newDev)
###########################################################################
# Indigo Trigger Start/Stop
###########################################################################
def triggerStartProcessing(self, trigger):
self.logger.log(4, "<<-- entering triggerStartProcessing: %s (%d)" %
(trigger.name, trigger.id))
self.triggerList.append(trigger.id)
self.logger.log(4, "exiting triggerStartProcessing -->>")
def triggerStopProcessing(self, trigger):
self.logger.log(4, "<<-- entering triggerStopProcessing: %s (%d)" %
(trigger.name, trigger.id))
if trigger.id in self.triggerList:
self.logger.log(4, "TRIGGER FOUND")
self.triggerList.remove(trigger.id)
self.logger.log(4, "exiting triggerStopProcessing -->>")
# def triggerUpdated(self, origDev, newDev):
# self.logger.log(4, "<<-- entering triggerUpdated: %s" % origDev.name)
# self.triggerStopProcessing(origDev)
# self.triggerStartProcessing(newDev)
###########################################################################
# Indigo Trigger Firing
###########################################################################
def triggerEvent(self, eventId):
self.logger.log(4, "<<-- entering triggerEvent: %s " % eventId)
for trigId in self.triggerList:
trigger = indigo.triggers[trigId]
if trigger.pluginTypeId == eventId:
indigo.trigger.execute(trigger)
return
###########################################################################
# Indigo Menu Action Methods
###########################################################################
def checkForUpdates(self):
self.logger.log(1, "Manually checking for updates")
self.updater.checkVersionNow()
###########################################################################
# Indigo Action Methods
###########################################################################
def methodDisarmAlarm(self, action):
self.logger.log(1, "Disarming alarm")
tx = "".join(["0401", self.pluginPrefs['code'],
"0" * (6 - len(self.pluginPrefs['code']))])
self.txCmdList.append((CMD_NORMAL, tx))
def methodArmStay(self, action):
self.logger.log(1, "Arming alarm in stay mode.")
self.txCmdList.append((CMD_NORMAL, '0311'))
def methodArmAway(self, action):
self.logger.log(1, "Arming alarm in away mode.")
self.txCmdList.append((CMD_NORMAL, '0301'))
def methodPanicAlarm(self, action):
panicType = action.props['panicAlarmType']
self.logger.log(1, "Activating Panic Alarm! (%s)" %
PANIC_TYPE_LIST[int(panicType)])
self.txCmdList.append((CMD_NORMAL, '060' + panicType))
def methodSendKeypress(self, action):
self.logger.log(3, "Received Send Keypress Action")
keys = action.props['keys']
firstChar = True
sendBreak = False
for char in keys:
if char == 'L':
time.sleep(2)
sendBreak = False
if (firstChar is False):
self.txCmdList.append((CMD_NORMAL, '070^'))
if char != 'L':
self.txCmdList.append((CMD_NORMAL, '070' + char))
sendBreak = True
firstChar = False
if (sendBreak is True):
self.txCmdList.append((CMD_NORMAL, '070^'))
# Queue a command to set DSC Thermostat Setpoints
def methodAdjustThermostat(self, action):
self.logger.log(3, "Device %s:" % action)
self.txCmdList.append((CMD_THERMO_SET, action))
# The command queued above calls this routine to create the packet
def setThermostat(self, action):
# find this thermostat in our list to get the number
for sensorNum in list(self.tempList.keys()):
if self.tempList[sensorNum].id == action.deviceId:
break
self.logger.log(3, "SensorNum = %s" % sensorNum)
# send 095 for thermostat in question, wait for 563 response
# self.logger.log(3, '095' + str(sensorNum))
rx = self.sendPacket('095' + str(sensorNum), waitFor='563')
if len(rx) == 0:
self.logger.logError('Error getting current thermostat setpoints, '
'aborting adjustment.')
return
if action.props['thermoAdjustmentType'] == '+' or \
action.props['thermoAdjustmentType'] == '-':
sp = 0
else:
sp = int(action.props['thermoSetPoint'])
# then 096TC+000 to inc cool,
# 096Th-000 to dec heat
# 096Th=### to set setpoint
# wait for 563 response
# self.logger.log(3, '096%u%c%c%03u' %
# (sensorNum, action.props['thermoAdjustWhich'],
# action.props['thermoAdjustmentType'], sp))
rx = self.sendPacket('096%u%c%c%03u' %
(sensorNum, action.props['thermoAdjustWhich'],
action.props['thermoAdjustmentType'], sp),
waitFor='563')
if len(rx) == 0:
self.logger.logError('Error changing thermostat setpoints, '
'aborting adjustment.')
return
# send 097T
# send 097 for thermostat in question to save setting,
# wait for 563 response
rx = self.sendPacket('097' + str(sensorNum), waitFor='563')
if len(rx) == 0:
self.logger.logError('Error saving thermostat setpoints, '
'aborting adjustment.')
return
# Reset an Alarm Zone Group's timers to 0
#
def methodResetZoneGroupTimer(self, action):
if action.deviceId in indigo.devices:
zoneGrp = indigo.devices[action.deviceId]
self.logger.log(3, "Manual timer reset for "
"alarm zone group \"%s\"" % zoneGrp.name)
zoneGrp.updateStateOnServer(key="AnyMemberLastChangedTimer",
value=0)
zoneGrp.updateStateOnServer(key="EntireGroupLastChangedTimer",
value=0)
###########################################################################
# Indigo Pref UI Methods
###########################################################################
# Validate the pluginConfig window after user hits OK
# Returns False on failure, True on success
def validatePrefsConfigUi(self, valuesDict):
self.logger.log(3, "validating Prefs called")
errorMsgDict = indigo.Dict()
wasError = False
if len(valuesDict['serialPort']) == 0:
errorMsgDict['serialPort'] = "Select a valid serial port."
wasError = True
if len(valuesDict['code']) > 6:
errorMsgDict['code'] = "The code must be 6 digits or less."
wasError = True
if len(valuesDict['code']) == 0:
errorMsgDict[
'code'] = "You must enter the alarm's arm/disarm code."
wasError = True
if len(valuesDict['emailUrgent']) > 0:
if not re.match(r"[^@]+@[^@]+\.[^@]+", valuesDict['emailUrgent']):
errorMsgDict[
'emailUrgent'] = "Please enter a valid email address."
wasError = True
if wasError is True:
return (False, valuesDict, errorMsgDict)
# Tell DSC module to reread it's config
self.configRead = False
# User choices look good, so return True
# (client will then close the dialog window).
return (True, valuesDict)
def validateActionConfigUi(self, valuesDict, typeId, actionId):
self.logger.log(3, "validating Action Config called")
if typeId == 'actionSendKeypress':
keys = valuesDict['keys']
cleanKeys = re.sub(r'[^a-e0-9LFAP<>=*#]+', '', keys)
if len(keys) != len(cleanKeys):
errorMsgDict = indigo.Dict()
errorMsgDict['keys'] = \
"There are invalid keys in your keystring."
return (False, valuesDict, errorMsgDict)
return (True, valuesDict)
def validateEventConfigUi(self, valuesDict, typeId, eventId):
self.logger.log(3, "validating Event Config called")
# self.logger.log(3, "Type: %s, Id: %s, Dict: %s" %
# (typeId, eventId, valuesDict))
if typeId == 'userArmed' or typeId == 'userDisarmed':
code = valuesDict['userCode']
if len(code) != 4:
errorMsgDict = indigo.Dict()
errorMsgDict['userCode'] = \
"The user code must be 4 digits in length."
return (False, valuesDict, errorMsgDict)
cleanCode = re.sub(r'[^0-9]+', '', code)
if len(code) != len(cleanCode):
errorMsgDict = indigo.Dict()
errorMsgDict['userCode'] = \
"The code can only contain digits 0-9."
return (False, valuesDict, errorMsgDict)
return (True, valuesDict)
def validateDeviceConfigUi(self, valuesDict, typeId, devId):
self.logger.log(3, "validating Device Config called")
# self.logger.log(3, "Type: %s, Id: %s, Dict: %s" %
# (typeId, devId, valuesDict))
if typeId == 'alarmZone':
zoneNum = int(valuesDict['zoneNumber'])
if zoneNum in list(self.zoneList.keys()) and \
devId != indigo.devices[self.zoneList[zoneNum]].id:
self.logger.log(3, "ZONEID: %s" %
self.DSC.zoneList[zoneNum].id)
errorMsgDict = indigo.Dict()
errorMsgDict['zoneNumber'] = "This zone has already been " \
"assigned to a different device."
return (False, valuesDict, errorMsgDict)
return (True, valuesDict)
def getZoneList(self, filter_="", valuesDict=None,
typeId="", targetId=0):
myArray = []
for i in range(1, 65):
zoneName = str(i)
if i in list(self.zoneList.keys()):
zoneDev = indigo.devices[self.zoneList[i]]
zoneName = ''.join([str(i), ' - ', zoneDev.name])
myArray.append((str(i), zoneName))
return myArray
def getZoneDevices(self, filter_="", valuesDict=None,
typeId="", targetId=0):
myArray = []
for dev in indigo.devices:
try:
if dev.deviceTypeId == 'alarmZone':
myArray.append((dev.id, dev.name))
except:
pass
return myArray
###########################################################################
# Configuration Routines
###########################################################################
# Reads the plugins config file into our own variables
def getConfiguration(self, valuesDict):
# Tell our logging class to reread the config for level changes
self.logger.readConfig()
self.logger.log(3, "getConfiguration start")
try:
# Get setting of Create Variables checkbox
if valuesDict['createVariables'] is True:
self.createVariables = True
else:
self.createVariables = False
# If the variable folder doesn't exist disable variables,
# we're done!
if valuesDict['variableFolder'] not in indigo.variables.folders:
self.createVariables = False
self.configKeepTimeSynced = valuesDict.get('syncTime', True)
self.configSpeakVariable = None
if 'speakToVariableEnabled' in valuesDict:
if valuesDict['speakToVariableEnabled'] is True:
self.configSpeakVariable = \
int(valuesDict['speakToVariableId'])
if self.configSpeakVariable not in indigo.variables:
self.logger.logError('Speak variable not found in '
'variable list')
self.configSpeakVariable = None
self.configEmailUrgent = valuesDict.get('emailUrgent', '')
self.configEmailNotice = valuesDict.get('updaterEmail', '')
self.configEmailUrgentSubject = \
valuesDict.get('emailUrgentSubject', 'Alarm Tripped')
self.configEmailNoticeSubject = \
valuesDict.get('updaterEmailSubject', 'Alarm Trouble')
self.logger.log(3, "Configuration read successfully")
return True
except:
self.logger.log(2, "Error reading plugin configuration. "
"(happens on very first launch)")
return False
###########################################################################
# Communication Routines
###########################################################################
def calcChecksum(self, s):
calcSum = 0
for c in s:
calcSum += ord(c)
calcSum %= 256
return calcSum
def closePort(self):
if self.port is None:
return
if self.port.isOpen() is True:
self.port.close()
self.port = None
def openPort(self):
self.closePort()
self.logger.log(1, "Initializing communication on port %s" %
self.pluginPrefs['serialPort'])
try:
self.port = serial.Serial(self.pluginPrefs['serialPort'],
9600,
writeTimeout=1)
except Exception as err:
self.logger.logError('Error opening serial port: %s' %
(str(err)))
return False
if self.port.isOpen() is True:
self.port.flushInput()
self.port.timeout = 1
return True
return False
def readPort(self):
if self.port.isOpen() is False:
self.state = self.States.BOTH_INIT
return ""
data = ""
try:
data = self.port.readline()
except Exception as err:
self.logger.logError('Connection RX Error: %s' % (str(err)))
# Return with '-' signaling calling subs to abort
# so we can re-init.
data = '-'
# exit()
except:
self.logger.logError('Connection RX Problem, plugin quitting')
exit()
return data
def writePort(self, data):
self.port.write(data)
def sendPacketOnly(self, data):
pkt = "%s%02X\r\n" % (data, self.calcChecksum(data))
self.logger.log(4, "TX: %s" % pkt)
try:
self.writePort(pkt)
except Exception as err:
self.logger.logError('Connection TX Error: %s' % (str(err)))
exit()
except:
self.logger.logError('Connection TX Problem, plugin quitting')
exit()
def sendPacket(self, tx, waitFor='500', rxTimeout=3, txRetries=3):
retries = txRetries
txCmd = tx[:3]
while txRetries > 0:
self.sendPacketOnly(tx)
ourTimeout = time.time() + rxTimeout
txRetries -= 1
while time.time() < ourTimeout:
if self.shutdown is True:
return ''
(rxCmd, rxData) = self.readPacket()
# If rxCmd == - then the socket closed, return for re-init
if rxCmd == '-':
return '-'
if rxCmd == '502':
self.logger.logError('Received system error after '
'sending command, aborting.')
return ''
# If rxCmd is not 0 length then we received a response
if len(rxCmd) > 0:
if waitFor == '500':
if (rxCmd == '500') and (rxData == txCmd):
return rxData
elif (rxCmd == waitFor):
return rxData
if txCmd != '000':
self.logger.logError('Timed out after waiting for response to '
'command %s for %u seconds, retrying.' %
(tx, rxTimeout))
self.logger.logError('Resent command %s %u times with no success, '
'aborting.' % (tx, retries))
return ''
def readPacket(self):
data = self.readPort()
if len(data) == 0:
return ('', '')
elif data == '-':
# socket has closed, return with signal to re-initialize
return ('-', '')
data = data.strip()
m = re.search(r'^(...)(.*)(..)$', data)
if not m:
return ('', '')
# Put this try in to try to catch exceptions when non-ascii characters
# were received, not sure why they are being received.
try:
self.logger.log(4, "RX: %s" % data)
(cmd, dat, sum_) = (m.group(1), m.group(2), int(m.group(3), 16))
except:
self.logger.logError('IT-100 Error: '
'Received a response with invalid characters')
return ('', '')
if sum_ != self.calcChecksum("".join([cmd, dat])):
self.logger.logError("Checksum did not match "
"on a received packet.")
return ('', '')
# Parse responses based on cmd value
if cmd == '500': # Command Acknowledge
self.logger.log(3, "ACK for cmd %s." % dat)
self.cmdAck = dat
elif cmd == '501': # Command Error
self.logger.logError('IT-100: '
'Received a command with a bad checksum')
elif cmd == '502': # System Error
errText = 'Unknown'
if dat == '017':
errText = 'Keybus Busy – Installer Mode'
elif dat == '021':
errText = 'Requested Partition is out of Range'
elif dat == '023':
errText = 'Partition is Not Armed'
elif dat == '024':
errText = 'Partition is Not Ready to Arm'
self.triggerEvent('eventFailToArm')
self.speak('speakTextFailedToArm')
elif dat == '026':
errText = 'User Code Not Required'
elif dat == '027':
errText = 'Virtual Keypad is Disabled'
elif dat == '029':
errText = 'Not Valid Parameter'
elif dat == '030':
errText = 'Keypad Does Not Come Out of Blank Mode'
elif dat == '031':
errText = 'IT-100 is already in Thermostat menu'
elif dat == '032':
errText = 'IT-100 is Not in Thermostat menu'
elif dat == '033':
errText = 'No Response from Thermostat (or Escort Module)'
self.logger.logError("IT-100 Error (%s): %s" % (dat, errText))
elif cmd == '550': # Time/Date Broadcast
m = re.search(r'^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$', dat)
if m:
tHour = int(m.group(1))
tMinute = int(m.group(2))
tMonth = int(m.group(3)) - 1
tDay = int(m.group(4))
tYear = int(m.group(5))
# Check if we should sync time
if self.configKeepTimeSynced is True:
d = datetime.now()
if (d.year != tYear) or (d.month != tMonth) or \
(d.day != tDay) or (d.hour != tHour) or \
(d.minute != tMinute):
self.logger.log(1, "Setting alarm panel time and "
"date.")
self.txCmdList.append((CMD_NORMAL, "010%s" %
d.strftime("%H%M%m%d%y")))
else:
self.logger.log(3, "Alarm time is within 1 minute of "
"actual time, no update necessary.")
elif cmd == '560': # Ring Detected
# NOTE: ESCORTTM5580TC module is required to receive this command.
# Not implemented
self.logger.log(1, "Ring Detected. Not implemented!")
elif cmd == '561': # Indoor Temperature Broadcast
m = re.search(r'^(.)(...)$', dat)
if m:
(sensor, temp) = (int(m.group(1)), int(m.group(2)))
self.updateSensorTemp(sensor, 'inside', temp)
elif cmd == '562': # Outdoor Temperature Broadcast
m = re.search(r'^(.)(...)$', dat)
if m:
(sensor, temp) = (int(m.group(1)), int(m.group(2)))
self.updateSensorTemp(sensor, 'outside', temp)
elif cmd == '563': # Thermostat Set Points
m = re.search(r'^(.)(...)(...)$', dat)
if m:
(sensor, cool, heat) = (int(m.group(1)),
int(m.group(2)),
int(m.group(3)))
self.updateSensorTemp(sensor, 'cool', cool)
self.updateSensorTemp(sensor, 'heat', heat)
elif cmd == '570': # Broadcast Labels
# NOTE: This function is only available with the
# PowerSeries PC1616/1832/1864 Panels
# Not implemented
self.logger.log(1, "Broadcast Labels. Not implemented!")
elif cmd == '580': # Baud Rate Set
# The IT-100 sends the command in response to
# the following command sent by the application.
# Baud Change Rate ........................................ (080)
# Val:
# 0 (30h) = 9600
# 1 (31h) = 19200
# 2 (32h) = 38400
# 3 (33h) = 57600
# 4 (34h) = 115200
# Not implemented
self.logger.log(1, "Baud Rate Set. Not implemented!")
elif cmd == '601': # Zone Alarm
m = re.search(r'^(.)(...)$', dat)
if m:
(partition, zone) = (int(m.group(1)), int(m.group(2)))
self.updateZoneState(zone, ZONE_STATE_TRIPPED)
if zone not in self.trippedZoneList:
self.trippedZoneList.append(zone)
self.sendZoneTrippedEmail()
elif cmd == '602': # Zone Alarm Restore
m = re.search(r'^(.)(...)$', dat)
if m:
(partition, zone) = (int(m.group(1)), int(m.group(2)))
self.logger.log(1, "Zone %d Restored. (Partition %d)" %
(zone, partition))
elif cmd == '603': # Zone Tamper
# Zone Tamper | 603 (36, 30, 33h) | 4 (Part. 1-8, Zn 1-64)
# This IT-100 command indicates that a zone and associated
# partition has a tamper condition.
# Partition 1(31h)-8(38h), Zn 1(30, 30, 31h)-Zone 64(30, 36, 34h)
# Not implemented
self.logger.log(1, "Zone Tamper. Not implemented!")
elif cmd == '604': # Zone Tamper Restore
# Not implemented
self.logger.log(1, "Zone Tamper Restore. Not implemented!")
elif cmd == '605': # Zone Fault
# Not implemented
self.logger.log(1, "Zone Fault. Not implemented!")
elif cmd == '606': # Zone Fault Restore
# Not implemented
self.logger.log(1, "Zone Fault Restore. Not implemented!")
elif cmd == '609': # Zone Open
zone = int(dat)
self.logger.log(3, "Zone number %d Open." % zone)
self.updateZoneState(zone, ZONE_STATE_OPEN)
if self.repeatAlarmTripped is True:
if zone in self.closeTheseZonesList:
self.closeTheseZonesList.remove(zone)
elif cmd == '610': # Zone Restored
zone = int(dat)
self.logger.log(3, "Zone number %d Closed." % zone)
# Update the zone to closed ONLY if the alarm is not tripped
# We want the tripped states to be preserved so someone looking
# at their control page will see all the zones that have been
# opened since the break in.
if self.repeatAlarmTripped is False:
self.updateZoneState(zone, ZONE_STATE_CLOSED)
else:
self.closeTheseZonesList.append(zone)
elif cmd == '620': # Duress Alarm
self.logger.log(1, "Duress Alarm Detected")
elif cmd == '621': # [F] Key Alarm
self.logger.log(1, "Fire Key Alarm Detected")
elif cmd == '622': # [F] Key Restoral
self.logger.log(1, "Fire Key Alarm Restored")
elif cmd == '623': # [A] Key Alarm
self.logger.log(1, "Auxiliary Key Alarm Detected")
elif cmd == '624': # [A] Key Restoral
self.logger.log(1, "Auxiliary Key Alarm Restored")
elif cmd == '625': # [P] Key Alarm
self.logger.log(1, "Panic Key Alarm Detected")
elif cmd == '626': # [P] Key Restoral
self.logger.log(1, "Panic Key Alarm Restored")
elif cmd == '631': # Auxiliary Input Alarm
self.logger.log(1, "Auxiliary Input Alarm Detected")
elif cmd == '632': # Auxiliary Input Alarm Restored
self.logger.log(1, "Auxiliary Input Alarm Restored")
elif cmd == '650': # Partition Ready
self.logger.log(3, "Partition %d Ready" % int(dat))
elif cmd == '651': # Partition Not Ready
self.logger.log(3, "Partition %d Not Ready" % int(dat))
elif cmd == '652': # Partition Armed - Descriptive Mode
if len(dat) == 1:
partition = int(dat)
self.logger.log(3, "Alarm Armed. (Partition %d)" % partition)
self.updateKeypad(partition, 'state', ALARM_STATE_ARMED)
# TODO: This response does not tell us armed type trigger.
# Stay, Away, etc. :(
elif len(dat) == 2:
m = re.search(r'^(.)(.)$', dat)
if m:
(partition, mode) = (int(m.group(1)), int(m.group(2)))
self.logger.log(1,
"Alarm Armed in %s mode. (Partition %d)" %
(ARMED_MODE_LIST[mode], partition))
if (mode == 0) or (mode == 2):
armedEvent = 'armedAway'
self.updateKeypad(partition,
'ArmedState',
ALARM_ARMED_STATE_AWAY)
else:
armedEvent = 'armedStay'
self.updateKeypad(partition,
'ArmedState',
ALARM_ARMED_STATE_STAY)
self.triggerEvent(armedEvent)
self.updateKeypad(partition,
'state',
ALARM_STATE_ARMED)
elif cmd == '653': # Partition in Ready to Force Arm
# Partition Ready - Forced Arming Enabled
# We don't do anything with this now.
# Not implemented
self.logger.log(1, "Partition in Ready to Force Arm. "
"Not implemented!")
elif cmd == '654': # Partition In Alarm
self.logger.log(1, "Alarm TRIPPED! (Partition %d)" % int(dat))
self.updateKeypad(int(dat),
'state',
ALARM_STATE_TRIPPED)
self.triggerEvent('eventAlarmTripped')
self.repeatAlarmTrippedNext = time.time()
self.repeatAlarmTripped = True
elif cmd == '655': # Partition Disarmed
# If the alarm has been disarmed while it was tripped,
# update any zone state that were closed during the break in.
# We don't update them during the event so that Indigo's zone
# states will represent a zone as tripped during the entire event.
if self.repeatAlarmTripped is True:
self.repeatAlarmTripped = False
for zone in self.closeTheseZonesList:
self.updateZoneState(zone, ZONE_STATE_CLOSED)
self.closeTheseZonesList = []
partition = int(dat)
self.logger.log(1, "Alarm Disarmed. (Partition %d)" % partition)
self.trippedZoneList = []
self.updateKeypad(partition,
'state',
ALARM_STATE_DISARMED)
self.updateKeypad(partition,
'ArmedState', ALARM_ARMED_STATE_DISARMED)
self.triggerEvent('eventAlarmDisarmed')
self.speak('speakTextDisarmed')
elif cmd == '656': # Exit Delay in Progress
self.logger.log(1, "Exit Delay. (Partition %d)" % int(dat))
self.updateKeypad(int(dat), 'state', ALARM_STATE_EXIT_DELAY)
self.speak('speakTextArming')
elif cmd == '657': # Entry Delay in Progress
self.logger.log(1, "Entry Delay. (Partition %d)" % int(dat))
self.updateKeypad(int(dat), 'state', ALARM_STATE_ENTRY_DELAY)
self.speak('speakTextEntryDelay')
elif cmd == '658': # Keypad Lock-out
# Not implemented
self.logger.log(1, "Keypad Lock-out. Not implemented!")
elif cmd == '659': # Keypad Blanking
# Not implemented
self.logger.log(1, "Keypad Blanking. Not implemented!")
elif cmd == '660': # Command Output In Progress
# Not implemented
self.logger.log(1, "Command Output In Progress. Not implemented!")
elif cmd == '670': # Invalid Access Code
# Not implemented
self.logger.log(1, "Invalid Access Code. Not implemented!")
elif cmd == '671': # Function Not Available
# Not implemented
self.logger.log(1, "Function Not Available. Not implemented!")
elif cmd == '672': # Fail to Arm
self.logger.log(1, "Alarm Failed to Arm. (Partition %d)" %
int(dat))
self.triggerEvent('eventFailToArm')
self.speak('speakTextFailedToArm')
elif cmd == '673': # Partition Busy
self.logger.log(3, "Partition %d Busy." % int(dat))
elif cmd == '700': # User Closing
m = re.search(r'^(.)(....)$', dat)
if m:
(partition, user) = (int(m.group(1)), m.group(2))
self.logger.log(1, "Alarm armed by user %s. (Partition %d)" %
(user, partition))
for trig in self.triggerList:
trigger = indigo.triggers[trig]
if trigger.pluginTypeId == 'userArmed':
if trigger.pluginProps['userCode'] == user:
indigo.trigger.execute(trigger.id)
elif cmd == '701': # Special Closing
partition = int(dat)
self.logger.log(1, "Alarm armed by one of the following methods: "
"Quick Arm, Auto Arm, Keyswitch, DLS software, "
"Wireless Key. (Partition %d)" % partition)
elif cmd == '702': # Partial Closing
partition = int(dat)
self.logger.log(1, "Alarm armed but one or more zones have been "
"bypassed. (Partition %d)" % partition)
elif cmd == '750': # User Opening
m = re.search(r'^(.)(....)$', dat)
if m:
(partition, user) = (int(m.group(1)), m.group(2))
self.logger.log(1,
"Alarm disarmed by user %s. (Partition %d)" %
(user, partition))
for trig in self.triggerList:
trigger = indigo.triggers[trig]
if trigger.pluginTypeId == 'userDisarmed':
if trigger.pluginProps['userCode'] == user:
indigo.trigger.execute(trigger.id)
elif cmd == '751': # Special Opening