forked from futzle/MiOS-CaddxNX584
-
Notifications
You must be signed in to change notification settings - Fork 0
/
L_CaddxNX584Security.lua
2035 lines (1868 loc) · 70.7 KB
/
L_CaddxNX584Security.lua
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
--
-- GE Caddx Network NX-584/NX-8E Alarm Plugin
-- Copyright (C) 2009-2011 Deborah Pickett
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
-- Version 0.2 2011-04-27 by Deborah Pickett
-- * Panic modes (medical, fire, police)
-- * Uses Partition API 2
--
-- Version 0.1 2010-08-07 by Deborah Pickett
-- * Probes interface for valid partitions
-- * Sets interface clock
-- * Creates luup child devices for partitions and zones
-- * Tracks partitions' armed state (away/stay/disarmed/breached)
-- * Tracks zones' tripped state
-- * Tracks zones' bypass state
-- * Actions supported:
-- - bypass zone
-- - quick (one-touch) arm
-- - arm with PIN
-- - quick (one-touch) partial (away) arm
-- - partial (away) arm with PIN
-- - disarm with PIN
--
-- Contributors:
-- * X10 interface supplied by brandonharville
module ("L_CaddxNX584Security", package.seeall)
ALARM_SERVICEID = "urn:futzle-com:serviceId:CaddxNX584Security1"
ALARM_PARTITION_SERVICEID = "urn:micasaverde-com:serviceId:AlarmPartition2"
ALARM_ZONE_SERVICEID = "urn:micasaverde-com:serviceId:SecuritySensor1"
INCOMING_EXPECTING_START = 0 -- Between messages
INCOMING_EXPECTING_LENGTH = 1 -- Received start byte 0x7e
INCOMING_EXPECTING_TYPE = 2 -- Received length byte
INCOMING_EXPECTING_CHECKSUM1 = 3 -- Received all bytes, now need first checksum byte
INCOMING_EXPECTING_CHECKSUM2 = 4 -- Received first checksum byte
INCOMING_EXPECTING_MESSAGE = 5 -- Receiving message body bytes
LOG_DEBUG = false -- Debug I/O with interface.
MAX_RETRIES = 3 -- This many failures indicates the system has failed.
LOG_MESSAGE_ZONE = {
[0] = "Alarm (Zone %d Partition %d)",
[1] = "Alarm restore (Zone %d Partition %d)",
[2] = "Bypass (Zone %d Partition %d)",
[3] = "Bypass restore (Zone %d Partition %d)",
[4] = "Tamper (Zone %d Partition %d)",
[5] = "Tamper restore (Zone %d Partition %d)",
[6] = "Trouble (Zone %d Partition %d)",
[7] = "Trouble restore (Zone %d Partition %d)",
[8] = "TX low battery (Zone %d Partition %d)",
[9] = "TX low battery restore (Zone %d Partition %d)",
[10] = "Zone lost (Zone %d Partition %d)",
[11] = "Zone lost restore (Zone %d Partition %d)",
[12] = "Start of cross time (Zone %d Partition %d)",
}
LOG_MESSAGE_PANEL = {
[17] = "Special expansion event",
[18] = "Duress (Partition %d)",
[19] = "Manual fire (Partition %d)",
[20] = "Auxiliary 2 Panic (Partition %d)",
[22] = "Panic (Partition %d)",
[23] = "Keypad tamper (Partition %d)",
[34] = "Telephone fault",
[35] = "Telephone fault restore",
[38] = "Fail to communicate",
[39] = "Log full",
[44] = "Auto test",
[45] = "Start program",
[46] = "End program",
[47] = "Start download",
[48] = "End download",
[50] = "Ground fault",
[51] = "Ground fault restore",
[52] = "Manual test",
[54] = "Start of listen in",
[55] = "Technician on site",
[56] = "Technician left",
[57] = "Control power up",
[123] = "Begin walk-test",
[124] = "End walk-test",
[125] = "Re-exit (Partition %d)",
[127] = "Data lost",
}
LOG_MESSAGE_DEVICE = {
[24] = "Control box tamper (Device %d)",
[25] = "Control box tamper Restore (Device %d)",
[26] = "AC fail (Device %d)",
[27] = "AC fail restore (Device %d)",
[28] = "Low battery (Device %d)",
[29] = "Low battery restore (Device %d)",
[30] = "Over-current (Device %d)",
[31] = "Over-current restore (Device %d)",
[32] = "Siren tamper (Device %d)",
[33] = "Siren tamper restore (Device %d)",
[36] = "Expander trouble (Device %d)",
[37] = "Expander trouble restore (Device %d)",
}
LOG_MESSAGE_USER = {
[40] = "Opening (User %d Partition %d)",
[41] = "Closing (User %d Partition %d)",
[42] = "Exit error (User %d Partition %d)",
[43] = "Recent closing (User %d Partition %d)",
[49] = "Cancel (User %d Partition %d)",
[53] = "Closed with zones bypassed (User %d Partition %d)",
[120] = "First to open (User %d Partition %d)",
[121] = "Last to close (User %d Partition %d)",
[122] = "PIN entered with bit 7 set (User %d Partition %d)",
[123] = "Output trip (User %d)",
}
--
-- Map Partition and Zone numbers to device Ids
--
-- Thanks to guessed for this snippet.
function findChild(deviceId, label)
for k, v in pairs(luup.devices) do
if (v.device_num_parent == deviceId and v.id == label) then
return k
end
end
end
function partitionName(p)
return "Partition-" .. p .. "bis"
end
function findPartition(parent, p)
return findChild(parent, partitionName(p))
end
function zoneName(z)
return "Zone-" .. z
end
function findZone(parent, z)
return findChild(parent, zoneName(z))
end
--
-- Utility functions for bitwise operations.
--
-- bitMask(val, pos)
-- Poor man's bitwise operation: return true if a bit is set, false if clear.
-- val: number from 0 to 255
-- pos: power of two, value of bit being tested
function bitMask(val, pos)
return (val % (pos*2) >= pos)
end
-- bitAnd(a, b)
-- poor man's bitwise operation: AND of two bytes.
-- a, b: numbers 0-255 to compute the bitwise AND of
function bitAnd(a, b)
local result = 0
local pos = 1
repeat
if (bitMask(a, pos) and bitMask(b,pos)) then
result = result + pos
end
pos = pos * 2
until pos == 256
end
-- debug(s)
-- Print a message to the Luup log, only if debugging is enabled.
function debug(s)
if (LOG_DEBUG) then
luup.log(s)
end
end
--
-- Initial setup
--
-- caddxInitialize(deviceId)
-- Initialize the interface:
-- - Check that the interface is configured to handle all the requests we may send.
-- - Get status of the alarm system.
-- - Get a list of valid partitions.
function caddxInitialize(deviceId)
luup.log("Initializing Caddx NX-584")
-- Remember parent device ID.
ROOT_DEVICE = deviceId
if (luup.variable_get(ALARM_SERVICEID, "Debug", ROOT_DEVICE) == "1") then
LOG_DEBUG = true
end
-- Run from serial device (including IPSerial) or open a socket?
local ioDevice = luup.variable_get("urn:micasaverde-com:serviceId:HaDevice1", "IODevice", ROOT_DEVICE)
local useSocket = false
if (ioDevice == nil or ioDevice == "") then useSocket = true end
if (useSocket) then
local ip = luup.devices[ROOT_DEVICE].ip
local ipv4, tcpport = ip:match("(%d+%.%d+%.%d+%.%d+):(%d+)")
if (ipv4 ~= nil and tcpport ~= nil) then
luup.log(string.format("Opening socket to %s port %s", ipv4, tcpport))
luup.io.open(ROOT_DEVICE, ipv4, tcpport)
else
luup.log("No serial device specified; exiting")
luup.set_failure(1, ROOT_DEVICE)
return false, "No serial device specified. Visit the Connect tab and choose how the device is attached.", string.format("%s[%d]", luup.devices[ROOT_DEVICE].description, ROOT_DEVICE)
end
else
luup.log("Opening serial port")
end
luup.set_failure(0, ROOT_DEVICE)
-- Help prevent race condition
luup.io.intercept()
-- Incoming byte state machine initialization.
RECEIVE_STATE = INCOMING_EXPECTING_START
INCOMING_ESCAPED = 0x0
CHECKSUM1 = 0
CHECKSUM2 = 0
LENGTH = 0
-- Ask the alarm system if it's configured to be
-- able to respond to the requests we'll give it.
if (not setUpInterface(ROOT_DEVICE)) then
luup.set_failure(true, ROOT_DEVICE)
return false, "Failed to set up interface", string.format("%s[%d]", luup.devices[ROOT_DEVICE].description, ROOT_DEVICE)
end
-- Set the clock on the interface.
if (CAPABILITY_SET_CLOCK) then
setInterfaceClock(ROOT_DEVICE)
end
-- Ask the alarm system about the global status.
-- Includes: faults; 4- or 6-digit PIN; list of valid partitions.
if (not getSystemStatus(ROOT_DEVICE)) then
luup.set_failure(true, ROOT_DEVICE)
return false, "Failed to get initial status", string.format("%s[%d]", luup.devices[ROOT_DEVICE].description, ROOT_DEVICE)
end
-- Set the device category. 22 is "alarm panel".
luup.attr_set("category_num", 22, k)
-- Start enumerating child devices.
local childDevices = luup.chdev.start(ROOT_DEVICE)
-- Get information about each partition.
PARTITION_STATUS = {}
PARTITION_CONFIGURED = {}
for partition, _ in pairs(PARTITION_VALID) do
-- Do this until we are satisfied that we are done.
-- This is complicated by the fact that the alarm system
-- may send asynchronous events while we are learning its
-- configuration. Perversely, we may get an asynchronous
-- message about partition x when we just asked about partition y.
debug("Setting up partition " .. partition)
PARTITION_STATUS[partition] = {}
local done = false
repeat
if (setUpPartition(ROOT_DEVICE, childDevices, partition)) then
done = true
PARTITION_CONFIGURED[partition] = true
end
until done == true
end
-- Get information about each zone.
ZONE_STATUS = {}
ZONE_VALID = {}
zoneCount = 0
for zone = 1,128 do
if (setUpZone(ROOT_DEVICE, childDevices, zone)) then
zoneCount = zoneCount + 1
ZONE_VALID[zone] = true
ZONE_STATUS[zone] = { }
end
end
-- Commit child devices.
luup.chdev.sync(ROOT_DEVICE, childDevices)
-- Set the initial states for each partition based on the
-- information we've collected.
for partition, _ in pairs(PARTITION_VALID) do
-- Set the device category. 23 is "alarm partition".
luup.attr_set("category_num", 23, findPartition(ROOT_DEVICE, partition))
updatePartitionDevice(ROOT_DEVICE, partition)
end
-- Set the initial states for each zone based on the
-- information we've collected.
for zone, _ in pairs(ZONE_VALID) do
-- Set the device category. 4 is "security sensor".
local zoneDevice = findZone(ROOT_DEVICE, zone)
luup.attr_set("category_num", 4, zoneDevice)
if (ZONE_STATUS[zone]["isFaulted"] == nil) then
-- No knowledge of the current state.
-- Use child state as best guess.
local tripped = luup.variable_get(ALARM_ZONE_SERVICEID, "Tripped", zoneDevice)
ZONE_STATUS[zone]["isFaulted"] = (tripped == "1")
end
if (ZONE_STATUS[zone]["isBypassed"] == nil) then
-- No knowledge of the current state.
-- Use child state as best guess.
local armed = luup.variable_get(ALARM_ZONE_SERVICEID, "Armed", zoneDevice)
ZONE_STATUS[zone]["isBypassed"] = (armed == "0")
end
updateZoneDevice(ROOT_DEVICE, zone)
end
-- Scan result callbacks.
ZONE_SCAN = {}
USER_SCAN = {}
LOGEVENT_SCAN = {}
luup.register_handler("callbackHandler", "GetConfiguration")
luup.register_handler("callbackHandler", "ZoneScan")
luup.register_handler("callbackHandler", "ZoneNameScan")
luup.register_handler("callbackHandler", "UserScan")
luup.register_handler("callbackHandler", "LogEventScan")
-- Setup is complete. Prepare to finish initialization.
debug("Finished initialization")
-- These are the messages that we expect to get from the alarm system
-- during normal operation.
PERMANENT_HANDLERS = {
[4] = handleZoneStatusMessage,
[5] = handleZonesSnapshotMessage,
[6] = handlePartitionStatusMessage,
[7] = handlePartitionsSnapshotMessage,
[8] = handleSystemStatusMessage,
[10] = handleLogEventMessage,
}
TEMPORARY_HANDLERS = {}
JOBS = {}
JOBS_PENDING_SEND = {}
JOBS_PENDING_SEND_HEAD = 1
JOBS_PENDING_SEND_TAIL = 0
-- No zones? Warn the user.
if (zoneCount == 0) then
-- Bug in MiOS prevents this from displaying.
luup.task("No zones defined. Visit the Zones tab to add them.", 1, string.format("%s[%d]", luup.devices[ROOT_DEVICE].description, ROOT_DEVICE))
end
-- Initializtion complete.
return true
end
-- sendMessageAndHandleResponse(deviceId, message, handlers)
-- Send a message (message type + body encoded in a string)
-- to the alarm system, and wait for a message in response.
function sendMessageAndHandleResponse(deviceId, message, handlers)
luup.io.intercept()
local retries = 0
repeat
sendMessage(message)
-- Get a full message.
local a, b, c
repeat
local status
status, a, b, c = readByte(luup.io.read(3, ROOT_DEVICE))
if (status == 2) then
-- Bad checksum. Send a negative acknowledgment message.
sendNegativeAcknowledgeMessage()
retries = retries + 1
end
until (status == 4)
if (handlers[a] ~= nil) then
-- This is the message I am looking for.
return handleMessage(ROOT_DEVICE, handlers, a, b, c)
elseif (a == "timeout") then
-- Timed out waiting for a response (e.g., during setup)
debug("Timed out waiting for response, retrying")
retries = retries + 1
else
-- This is a message I don't want.
debug(string.format("Received inconvenient message 0x%02x", a))
if (LOG_DEBUG) then logMessage("Unsolicited message body:", b) end
-- Implementation note: documentation says we should send
-- sendMessageRejectedMessage() but that doesn't seem to placate
-- the alarm system.
if (c) then sendPositiveAcknowledgeMessage() end -- Yes, dear.
end
until (retries == MAX_RETRIES)
luup.set_failure(true)
return false
end
-- setUpInterface(deviceId)
-- Get the configuration information about the alarm system.
-- Send an Interface Configuration Request 0x21,
-- and wait for the reply 0x01. Reject any other messages
-- that may come in (e.g., zone status messages)
function setUpInterface(deviceId)
debug("Sending message and waiting for response: 0x21 Interface Configuration Request")
return sendMessageAndHandleResponse(ROOT_DEVICE, "\033",
{
[1] = function (deviceId, message)
debug("Handling message: 0x01 Interface Configuration")
-- Firmware version.
debug(string.format("Firmware version %s", string.sub(message, 1, 4)))
-- Check that the interface can respond to the message requests
-- that we need.
if (bitMask(string.byte(string.sub(message,5)), 2) -- 0x01
and bitMask(string.byte(string.sub(message,5)), 16) -- 0x04
and bitMask(string.byte(string.sub(message,5)), 32) -- 0x05
and bitMask(string.byte(string.sub(message,5)), 64) -- 0x06
and bitMask(string.byte(string.sub(message,5)), 128) -- 0x07
and bitMask(string.byte(string.sub(message,6)), 1) -- 0x08
and bitMask(string.byte(string.sub(message,7)), 2) -- 0x21
and bitMask(string.byte(string.sub(message,7)), 16) -- 0x24
and bitMask(string.byte(string.sub(message,7)), 32) -- 0x25
and bitMask(string.byte(string.sub(message,7)), 64) -- 0x26
and bitMask(string.byte(string.sub(message,7)), 128) -- 0x27
and bitMask(string.byte(string.sub(message,8)), 1) -- 0x28
) then
luup.log("All message codes are supported.")
else
-- An essential message has been disabled.
-- To do: signal failure.
end
-- Not all alarm systems know how to name zones; it depends
-- on the keypads attached to the system.
if (bitMask(string.byte(string.sub(message,7)), 8)) then
luup.log("Zone Name enabled")
CAPABILITY_ZONE_NAME = true
end
-- Get historical event log entries
if (bitMask(string.byte(string.sub(message,8)), 4)) then
luup.log("Log Event enabled")
CAPABILITY_LOG_EVENT = true
end
-- User Information Request with PIN
-- Get a user's authorization and PIN
if (bitMask(string.byte(string.sub(message,9)), 4)) then
luup.log("Get User Information with PIN enabled")
CAPABILITY_GET_USER_INFORMATION_WITH_PIN = true
end
-- Set User Code with PIN
if (bitMask(string.byte(string.sub(message,9)), 16)) then
luup.log("Set User Code with PIN enabled")
CAPABILITY_SET_USER_CODE_WITH_PIN = true
end
-- Set User Authorization with PIN
if (bitMask(string.byte(string.sub(message,9)), 64)) then
luup.log("Set User Authorization with PIN enabled")
CAPABILITY_SET_USER_AUTHORIZATION_WITH_PIN = true
end
-- Set Clock can be optionally disabled.
if (bitMask(string.byte(string.sub(message,10)), 8)) then
luup.log("Set Clock enabled")
CAPABILITY_SET_CLOCK = true
end
-- Primary Keypad Function with PIN can be optionally disabled.
if (bitMask(string.byte(string.sub(message,10)), 16)) then
luup.log("Primary Keypad Function with PIN enabled")
CAPABILITY_PRIMARY_KEYPAD_WITH_PIN = true
end
-- Secondary Keypad Function can be optionally disabled.
if (bitMask(string.byte(string.sub(message,10)), 64)) then
luup.log("Secondary Keypad Function enabled")
CAPABILITY_SECONDARY_KEYPAD = true
end
-- Zone bypass can be optionally disabled.
if (bitMask(string.byte(string.sub(message,10)), 128)) then
luup.log("Zone bypass enabled")
CAPABILITY_ZONE_BYPASS = true
end
return 0
end
}
)
end
-- setInterfaceClock()
-- Tell the alarm system the current time. It uses this when
-- it communicates with the back-to-base monitoring service
-- and it may display it on alphanumeric keypads.
function setInterfaceClock(deviceId)
debug("Sending message and waiting for response: 0x3b Set Interface Clock")
local timeTable = os.date("*t")
return sendMessageAndHandleResponse(ROOT_DEVICE, string.char(0x3b + 128) .. string.format("%c%c%c%c%c%c",
timeTable["year"] % 100,
timeTable["month"],
timeTable["day"],
timeTable["hour"],
timeTable["min"],
timeTable["wday"]),
{
[29] = function (deviceId, message)
return 0
end,
[31] = function (deviceId, message)
debug("Failed to set clock on interface")
return 0
end,
["timeout"] = function (deviceId, message)
-- Not the end of the world.
debug("Timeout while setting clock on interface")
return 0
end,
}
)
end
-- getSystemStatus(deviceId)
-- Request the state of the alarm system:
-- - List of valid partitions.
-- - 4- or 6-digit PIN codes.
function getSystemStatus(deviceId)
debug("Sending message and waiting for response: 0x28 System Status Request")
PARTITION_VALID = {}
-- Callbacks to handle System Status request.
return sendMessageAndHandleResponse(ROOT_DEVICE, "\040",
{
[8] = function (deviceId, message)
debug("Handling message: 0x08 System Status")
-- Byte 10 of the response contains a list of valid partitions.
VALID_PARTITIONS_BITMASK = string.byte(string.sub(message,10))
for partition = 1, 8 do
if (bitMask(VALID_PARTITIONS_BITMASK, 2^(partition-1))) then
luup.log(string.format("Valid partition %d", partition))
PARTITION_VALID[partition] = true
end
end
-- Byte 5 contains 4- or 6-digit PINs
if (bitMask(string.byte(string.sub(message,5)), 1)) then
CONFIGURATION_PIN_LENGTH = 6
else
CONFIGURATION_PIN_LENGTH = 4
end
luup.log(string.format("PIN length is %d", CONFIGURATION_PIN_LENGTH))
-- Set device variables that are encoded in this message.
handleSystemStatusMessage(deviceId, message)
return 0
end
}
)
end
-- setUpPartition(deviceId, childDevices, p)
-- p: number, partition (1 origin)
-- Returns true if the received reply was for the requested partition,
-- otherwise false (and the caller should try again).
function setUpPartition(deviceId, childDevices, p)
debug("Sending message and waiting for response: 0x26 Partition Status Request")
local partitionConfigured = false
sendMessageAndHandleResponse(ROOT_DEVICE, "\038" .. string.char(p - 1),
{
[6] = function (deviceId, message)
debug("Handling message: 0x06 Partition Status")
if (string.byte(string.sub(message,1)) == p - 1) then
-- This is the partition we were asking about.
-- Partitions aren't named, so invent a suitable name.
PARTITION_STATUS[p]["name"] = "Partition " .. p
luup.chdev.append(
ROOT_DEVICE, childDevices,
partitionName(p), PARTITION_STATUS[p]["name"],
"urn:schemas-futzle-com:device:CaddxNX584Partition:2", "D_CaddxNX584Partition2.xml",
"", "", true
)
processPartitionStatusMessage(message)
partitionConfigured = true
else
-- This partition may have been configured already.
-- May as well note the changed state.
processPartitionStatusMessage(message)
end
return 0
end,
[7] = function (deviceId, message)
debug("Handling message: 0x07 Partitions Snapshot")
-- This isn't a response to our request, but we should
-- note the status changes for the paritions that we've
-- already processed.
processPartitionsSnapshotMessage(message)
return 0
end
}
)
return partitionConfigured
end
-- setUpZone(deviceId, childDevices, z)
-- Get information about a zone and create a child device for it.
-- z: Zone number (1 origin)
-- Returns true if the zone is known, otherwise returns false.
function setUpZone(deviceId, childDevices, z)
debug("Searching for zone " .. z)
local deviceFile = luup.variable_get(ALARM_SERVICEID, "Zone" .. z .. "Type", ROOT_DEVICE)
local deviceName = luup.variable_get(ALARM_SERVICEID, "Zone" .. z .. "Name", ROOT_DEVICE)
if (deviceFile ~= nil and deviceFile ~= "") then
debug(string.format("Zone %d (%s): %s", z, deviceName, deviceFile))
luup.chdev.append(
ROOT_DEVICE, childDevices,
zoneName(z), deviceName,
"", deviceFile,
"I_CaddxNX584Security.xml", "", false
)
return true
end
return false
end
--
-- Shared code for processing messages during setup and normal operation.
--
-- processPartitionStatusMessage(message)
-- Update the state of a child device upon receipt of a 0x06 Partition Status message.
-- message: The body of the message.
function processPartitionStatusMessage(message)
local partition = string.byte(string.sub(message,1)) + 1
if (not PARTITION_VALID[partition]) then
debug(string.format("Ignoring invalid partition %d", partition))
return nil
end
PARTITION_STATUS[partition]["isArmed"] = bitMask(string.byte(string.sub(message,2)), 64)
PARTITION_STATUS[partition]["isPartial"] = bitMask(string.byte(string.sub(message,4)), 4)
PARTITION_STATUS[partition]["isSiren"] = bitMask(string.byte(string.sub(message,3)), 2)
PARTITION_STATUS[partition]["wasSiren"] = bitMask(string.byte(string.sub(message,3)), 1)
PARTITION_STATUS[partition]["isReady"] = bitMask(string.byte(string.sub(message,7)), 4)
PARTITION_STATUS[partition]["isChime"] = bitMask(string.byte(string.sub(message,4)), 8)
PARTITION_STATUS[partition]["isExitDelay"] = bitMask(string.byte(string.sub(message,4)), 192)
PARTITION_STATUS[partition]["isEntryDelay"] = bitMask(string.byte(string.sub(message,4)), 16) or
bitMask(string.byte(string.sub(message,8)), 1)
PARTITION_STATUS[partition]["lastUser"] = string.byte(string.sub(message,6))
return partition
end
-- processPartitionsSnapshotMessage(message)
-- Update the state of all child partition devices that are configured.
function processPartitionsSnapshotMessage(message)
for partition = 1,8 do
if (PARTITION_VALID[parition] and PARTITION_CONFIGURED[partition]) then
PARTITION_STATUS[partition]["isArmed"] = bitMask(string.byte(string.sub(message,partition+1)), 4)
PARTITION_STATUS[partition]["isPartial"] = bitMask(string.byte(string.sub(message,partition+1)), 8)
PARTITION_STATUS[partition]["isReady"] = bitMask(string.byte(string.sub(message,partition+1)), 2)
PARTITION_STATUS[partition]["isChime"] = bitMask(string.byte(string.sub(message,partition+1)), 16)
PARTITION_STATUS[partition]["isExitDelay"] = bitMask(string.byte(string.sub(message,partition+1)), 64)
PARTITION_STATUS[partition]["isEntryDelay"] = bitMask(string.byte(string.sub(message,partition+1)), 32)
PARTITION_STATUS[partition]["wasSiren"] = bitMask(string.byte(string.sub(message,partition+1)), 128)
end
end
end
-- processZoneStatusMessage(message)
-- Update the state of a child device upon receipt of a 0x04 Zone Status message.
-- message: The body of the message. The zone must already be configured.
function processZoneStatusMessage(message)
local zone = string.byte(string.sub(message,1)) + 1
local partitions = bitAnd(string.byte(string.sub(message,2)), VALID_PARTITIONS_BITMASK)
if (partitions ~= 0) then
if (ZONE_VALID[zone]) then
debug(string.format("Valid zone %d", zone))
ZONE_STATUS[zone]["isFaulted"] = bitMask(string.byte(string.sub(message,6)), 1)
ZONE_STATUS[zone]["isBypassed"] = bitMask(string.byte(string.sub(message,6)), 8)
else
debug(string.format("Ignoring invalid zone %d", zone))
end
end
return zone
end
-- processZonesSnapshotMessage(message)
-- Update the state of all child partition devices that are configured.
function processZonesSnapshotMessage(message)
-- First byte is the set of 16 zones in this snapshot.
local z16 = string.byte(string.sub(message,1)) * 16
for zone2 = 1,8 do
-- Two zones per byte.
if (ZONE_VALID[z16+zone2*2-1]) then
ZONE_STATUS[z16+zone2*2-1]["isFaulted"] = bitMask(string.byte(string.sub(message,zone2+1)), 1)
ZONE_STATUS[z16+zone2*2-1]["isBypassed"] = bitMask(string.byte(string.sub(message,zone2+1)), 2)
end
if (ZONE_VALID[z16+zone2*2]) then
ZONE_STATUS[z16+zone2*2]["isFaulted"] = bitMask(string.byte(string.sub(message,zone2+1)), 16)
ZONE_STATUS[z16+zone2*2]["isBypassed"] = bitMask(string.byte(string.sub(message,zone2+1)), 32)
end
end
return z16
end
-- processLogEventMessage(message)
-- Extract log event information from a log message.
function processLogEventMessage(message)
local logSize = string.byte(string.sub(message, 2))
local messageNumber = string.byte(string.sub(message, 3)) % 127
local variableNumber = string.byte(string.sub(message, 4))
local partitionNumber = string.byte(string.sub(message, 5)) + 1
local month = string.byte(string.sub(message, 6))
local date = string.byte(string.sub(message, 7))
local hour = string.byte(string.sub(message, 8))
local minute = string.byte(string.sub(message, 9))
local messageText = "Unknown message"
local messageType
if (LOG_MESSAGE_ZONE[messageNumber]) then
messageType = "Zone"
variableNumber = variableNumber + 1
messageText = string.format(LOG_MESSAGE_ZONE[messageNumber], variableNumber, partitionNumber)
elseif (LOG_MESSAGE_PANEL[messageNumber]) then
messageType = "Panel"
messageText = string.format(LOG_MESSAGE_PANEL[messageNumber], partitionNumber)
elseif (LOG_MESSAGE_DEVICE[messageNumber]) then
messageType = "Device"
messageText = string.format(LOG_MESSAGE_DEVICE[messageNumber], variableNumber, partitionNumber)
elseif (LOG_MESSAGE_USER[messageNumber]) then
messageType = "User"
variableNumber = variableNumber + 1
messageText = string.format(LOG_MESSAGE_USER[messageNumber], variableNumber, partitionNumber)
end
return messageNumber, messageType, variableNumber, partitionNumber,
month, date, hour, minute, messageText, logSize
end
-- updatePartitionDevice(deviceId, partition)
-- Update the Luup child device corresponding to the partition
-- with information previously set in the PARTITION_STATUS variable.
function updatePartitionDevice(deviceId, partition)
if (partition ~= nil) then
debug("Setting state for partition " .. partition)
local partitionDevice = findPartition(ROOT_DEVICE, partition)
if (partitionDevice == nil) then return end
-- Create a variable on the alarm interface matching the user who
-- last changed the partition, if there isn't already.
local lastUser = luup.variable_get(ALARM_SERVICEID, "User" .. PARTITION_STATUS[partition]["lastUser"], ROOT_DEVICE)
if (lastUser == nil) then
lastUser = "User " .. PARTITION_STATUS[partition]["lastUser"]
luup.variable_set(ALARM_SERVICEID, "User" .. PARTITION_STATUS[partition]["lastUser"], lastUser, ROOT_DEVICE)
end
-- This is the user who last modified the partition.
luup.variable_set(ALARM_PARTITION_SERVICEID, "LastUser", lastUser, partitionDevice)
-- Chime mode.
local chime = PARTITION_STATUS[partition]["isChime"] and "1" or "0"
debug("ChimeEnabled: " .. chime)
luup.variable_set(ALARM_PARTITION_SERVICEID, "ChimeEnabled", chime, partitionDevice)
-- Past alarm (which has since cleared).
local pastAlarm = PARTITION_STATUS[partition]["wasSiren"] and "1" or "0"
debug("AlarmMemory: " .. pastAlarm)
luup.variable_set(ALARM_PARTITION_SERVICEID, "AlarmMemory", pastAlarm, partitionDevice)
-- Current alarm.
local breached = PARTITION_STATUS[partition]["isSiren"] and "Active" or "None"
debug("Alarm: " .. breached)
luup.variable_set(ALARM_PARTITION_SERVICEID, "Alarm", breached, partitionDevice)
-- Detailed armed state.
-- Listed in increasing order of importance.
local detailArmed = "Disarmed"
detailArmed = PARTITION_STATUS[partition]["isReady"] and "Ready" or detailArmed
detailArmed = PARTITION_STATUS[partition]["isArmed"] and "Armed" or detailArmed
detailArmed = PARTITION_STATUS[partition]["isPartial"] and "Stay" or detailArmed
detailArmed = PARTITION_STATUS[partition]["isExitDelay"] and "ExitDelay" or detailArmed
detailArmed = PARTITION_STATUS[partition]["isEntryDelay"] and "EntryDelay" or detailArmed
debug("DetailedArmMode: " .. detailArmed)
luup.variable_set(ALARM_PARTITION_SERVICEID, "DetailedArmMode", detailArmed, partitionDevice)
-- Simple armed state (armed or not).
local armed = PARTITION_STATUS[partition]["isArmed"] and "Armed" or "Disarmed"
debug("ArmMode: " .. armed)
luup.variable_set(ALARM_PARTITION_SERVICEID, "ArmMode", armed, partitionDevice)
end
end
-- updateZoneDevice(deviceId, zone)
-- Update the Luup child device corresponding to the zone
-- with information previously set in the ZONE_STATUS variable.
function updateZoneDevice(deviceId, zone)
if (zone ~= nil) then
debug("Setting state for zone " .. zone)
local zoneDevice = findZone(ROOT_DEVICE, zone)
if (zoneDevice == nil) then return end
if (ZONE_STATUS[zone]["isFaulted"] ~= nil) then
local tripped = ZONE_STATUS[zone]["isFaulted"] and "1" or "0"
debug("Tripped: " .. tripped)
luup.variable_set(ALARM_ZONE_SERVICEID, "Tripped", tripped, zoneDevice)
if (tripped == "1") then
luup.variable_set(ALARM_ZONE_SERVICEID, "LastTrip", os.time(), zoneDevice)
end
end
-- If bypass control is disabled by interface, don't change it.
if (CAPABILITY_ZONE_BYPASS and ZONE_STATUS[zone]["isBypassed"] ~= nil) then
-- Invert logic because alarm panel speaks of "is bypassed".
local armed = ZONE_STATUS[zone]["isBypassed"] and "0" or "1"
debug("Armed: " .. armed)
luup.variable_set(ALARM_ZONE_SERVICEID, "Armed", armed, zoneDevice)
end
end
end
--
-- Handlers for asynchronous messages from the alarm system.
--
-- handleZoneStatusMessage(deviceId, message)
-- We received a zone status message.
-- Use the information in it to update the zone device.
function handleZoneStatusMessage(deviceId, message)
debug("Handling message: 0x04 Zone Status")
local zone = processZoneStatusMessage(message)
updateZoneDevice(ROOT_DEVICE, zone)
return 0
end
-- handleZonesSnapshotMessage(deviceId, message)
-- We received a zones snapshot message for a bank of 16 zones.
-- Use the information in it to update the zone devices.
function handleZonesSnapshotMessage(deviceId, message)
debug("Handling message: 0x05 Zones Snapshot")
local z16 = processZonesSnapshotMessage(message)
for zone = z16*16+1,z16*16+16 do
if (ZONE_VALID[zone]) then
updateZoneDevice(ROOT_DEVICE, zone)
end
end
return 0
end
-- handlePartitionStatusMessage(deviceId, message)
-- We received a partition status message.
-- Use the information in it to update the partition device.
function handlePartitionStatusMessage(deviceId, message)
debug("Handling message: 0x06 Partition Status")
local partition = processPartitionStatusMessage(message)
updatePartitionDevice(ROOT_DEVICE, partition)
return 0
end
-- handlePartitionsSnapshotMessage(deviceId, message)
-- We received a partitions snapshot message for all eight partitions.
-- Use the information in it to update the partition devices.
function handlePartitionsSnapshotMessage(deviceId, message)
debug("Handling message: 0x07 Partitions Snapshot")
processPartitionsSnapshotMessage(message)
for parition = 1,8 do
if (PARTITION_VALID[partition]) then
updatePartitionDevice(ROOT_DEVICE, partition)
end
end
return 0
end
function handleSystemStatusMessage(deviceId, message)
debug("Handling message: 0x08 System Status")
-- Battery level is only binary. Fake a continuum.
luup.variable_set("urn:micasaverde-com:serviceId:HaDevice1", "BatteryLevel", bitMask(string.byte(string.sub(message,3)), 64) and 10 or 100, deviceId)
-- Communication stack pointer.
luup.variable_set(ALARM_SERVICEID, "StackPointer", string.byte(string.sub(message,11)), deviceId)
return 0
end
-- handleLogEventMessage(deviceId, message)
-- Note the most recent log event sent by the panel.
function handleLogEventMessage(deviceId, message)
debug("Handling message: 0x0a Log Event")
local messageNumber, messageType, variableNumber, partitionNumber,
month, date, hour, minute, messageText, logSize =
processLogEventMessage(message)
if (messageType == "Zone") then
luup.variable_set(ALARM_SERVICEID, "LastLogEventZone", variableNumber, deviceId)
elseif (messageType == "Device") then
luup.variable_set(ALARM_SERVICEID, "LastLogEventDevice", variableNumber, deviceId)
elseif (messageType == "User") then
luup.variable_set(ALARM_SERVICEID, "LastLogEventUser", variableNumber, deviceId)
end
luup.variable_set(ALARM_SERVICEID, "LastLogEventPartition", partitionNumber, deviceId)
if (minute < 10) then minute = "0" + minute end
luup.variable_set(ALARM_SERVICEID, "LastLogEventTime", string.format("%d-%d %d:%d", month, date, hour, minute), deviceId)
luup.variable_set(ALARM_SERVICEID, "LastLogEvent", messageText, deviceId)
debug(string.format("Log message: %d %s", messageNumber, messageText))
luup.variable_set(ALARM_SERVICEID, "LastLogEventID", messageNumber, deviceId)
return 0
end
--
-- Utility functions for communicating with the interface.
--
-- sendCommandFailedMessage()
-- Send Command Failed if plugin was unable to do something
-- asked of it by the alarm system.
function sendCommandFailedMessage()
debug("Sending message: 0x1C Command Failed")
sendMessage("\028") -- 28 == 0x1C
end
-- sendPositiveAcknowledgeMessage()
-- Send Positive Acknowledgment if plugin was asked to
-- acknowledge something by the alarm system.
function sendPositiveAcknowledgeMessage()
debug("Sending message: 0x1D Positive Acknowledge")
sendMessage("\029") -- 29 == 0x1D
end
-- sendNegativeAcknowledgeMessage()
-- Send Negative Acknowledgment if plugin received a garbled
-- message or if the alarm system tries to send a second
-- message before the first is acknowledged.
function sendNegativeAcknowledgeMessage()
debug("Sending message: 0x1E Negative Acknowledge")
sendMessage("\030") -- 30 == 0x1E
end
-- sendMessageRejectedMessage()
-- Send Message Rejection if plugin received a message,
-- it is valid, but the interface doesn't know what to
-- do with it.
-- Experience suggests the interface doesn't expect to
-- receive this message, but only to send it.
function sendMessageRejectedMessage()
debug("Sending message: 0x1F Message Reject")
sendMessage("\031") -- 31 == 0x1F
end
-- packByte(b)
-- Escape bytes 0x7e and 0x7d to ensure that the start byte (0x7e)
-- is never seen in the middle of a message.
function packByte(b)
if (b == 0x7e) then
return "\125\094" -- 0x7d 0x5e
elseif (b == 0x7d) then
return "\125\093" -- 0x7d 0x5d
else
return string.char(b)
end
end
-- sendMessage(message)
-- Byte-stuff the message, prepend the start byte 0x7e and the length,
-- append the checksum, and send it.
function sendMessage(message)
local packedMessage = string.char(0x7e)
resetChecksum()
-- Length should be always short enough to avoid byte-stuffing issues.
packedMessage = packedMessage .. string.char(string.len(message))
updateChecksum(string.len(message))
for i = 1, string.len(message) do
local b = string.byte(message,i)
updateChecksum(b)
packedMessage = packedMessage .. packByte(b)
end
local c1, c2 = getChecksum()
packedMessage = packedMessage .. packByte(c1) .. packByte(c2)
if (LOG_DEBUG) then logMessage("Outgoing:", packedMessage) end
luup.io.write(packedMessage)
end
function resetChecksum()