forked from ElephantEight/GenGenSceneController
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL_GenGenSceneControllerShared.lua
More file actions
executable file
·1639 lines (1548 loc) · 57.3 KB
/
L_GenGenSceneControllerShared.lua
File metadata and controls
executable file
·1639 lines (1548 loc) · 57.3 KB
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
-- GenGeneric Scene Controller shared code Version 1.23d
-- Supports Evolve LCD1, Cooper RFWC5 and Nexia One Touch Controllers
--
-- Copyright (C) 2017, 2018 Gustavo A Fernandez
-- Thanks to Ron Luna and Ctrlable for contributing for RFWC5 support
--
-- 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 can access the terms of this license at
-- https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
--
bit = require "bit"
nixio = require "nixio"
nixFs = require "nixio.fs"
--
-- Debugging functions
--
ANSI_BLACK = "\027[30m"
ANSI_RED = "\027[31m"
ANSI_GREEN = "\027[32m"
ANSI_YELLOW = "\027[33m"
ANSI_BLUE = "\027[34m"
ANSI_MAGENTA = "\027[35m"
ANSI_CYAN = "\027[36m"
ANSI_WHITE = "\027[37m"
ANSI_BRIGHT_BLACK = "\027[1;30m"
ANSI_BRIGHT_RED = "\027[1;31m"
ANSI_BRIGHT_GREEN = "\027[1;32m"
ANSI_BRIGHT_YELLOW = "\027[1;33m"
ANSI_BRIGHT_BLUE = "\027[1;34m"
ANSI_BRIGHT_MAGENTA = "\027[1;35m"
ANSI_BRIGHT_CYAN = "\027[1;36m"
ANSI_BRIGHT_WHITE = "\027[1;37m"
ANSI_RESET = "\027[0m"
local function stackDepthIndent()
local str = ""
local level = 4
while debug.getinfo (level, "n") do
str = str .. " "
level = level + 1
end
return str
end
local function getFunctionInfo(level,name)
local info = debug.getinfo(level, "n")
if not name then
if info and info.name then
name = info.name
else
info = debug.getinfo(level)
if info then
name = "unknown [line " .. tostring(info.currentline-1).."]"
local s2 = string.gsub(info.source,"[^\n]*\n", "", info.currentline-2)
if s2 then
local s3 = string.match(s2, "[^\n]*")
if s3 then
local s4 = string.match(s3, "function%s*([%w_]+)")
if s4 then
name = s4
else
name = s3
end
end
end
else
name = "unknown"
end
end
end
local str = name.."("
local ix = 1
while true do
local name, value = debug.getlocal(level, ix)
if not name then
break
end
if ix > 1 then
str = str .. ", "
end
local v = "..."
if name ~= "SCObj" then -- Hack. SCObj is big and useless in DEntry/VEntry
v = tableToString(value)
end
str = str .. tostring(name) .. "=" .. v
ix = ix + 1
end
str = str .. ")"
return str
end
local function logList(...)
local s = ""
for i = 1, select ("#", ...) do
local x = select(i, ...)
if type(x) == "string" then
s = s .. x
else
s = s .. tableToString(x)
end
end
return s
end
function luup_device_message(device, error, message, timeout, source)
VEntry()
if luup.device_message then
luup.device_message(device, error, message, timeout, source)
end
end
function ELog(...)
if VerboseLogging > 0 then
luup.log(ANSI_BRIGHT_RED .. GetDeviceName() .." Error: " .. ANSI_RESET .. stackDepthIndent() .. logList(...) .. debug.traceback(ANSI_CYAN, 2) .. ANSI_RESET)
else
luup.log(ANSI_BRIGHT_RED .. GetDeviceName() .." Error: " .. ANSI_RESET .. stackDepthIndent() .. logList(...))
end
luup_device_message(luup.device,
2, -- job_Error
logList(...), -- message
0, -- No timeout
GetDeviceName()) -- source
end
function log(...)
luup.log(GetDeviceName() ..": " .. stackDepthIndent() .. logList(...))
end
function ILog(...)
if VerboseLogging >= 1 then
luup.log(ANSI_BRIGHT_YELLOW .. GetDeviceName() .. " info: " .. stackDepthIndent() .. logList(...) .. ANSI_RESET)
end
end
function DLog(...)
if VerboseLogging >= 2 then
luup.log(GetDeviceName() .. " debug: " .. stackDepthIndent() .. logList(...))
end
end
function DEntry(name)
if VerboseLogging >= 2 then
luup.log(GetDeviceName() .. " debug: " .. stackDepthIndent() .. getFunctionInfo(3,name))
end
end
-- VerboseLogging == 3 shows extended Z-Wave queue but not VLog/VEntry
function VLog(...)
if VerboseLogging >= 4 then
luup.log(GetDeviceName() .. " verbose: " .. stackDepthIndent() .. logList(...))
end
end
function VEntry(name)
if VerboseLogging >= 4 then
luup.log(GetDeviceName() .. " verbose: " .. stackDepthIndent() .. getFunctionInfo(3,name))
end
end
function printTable(tab,prefix,hash)
local k,v,s,i, top, pref, p, q, r
if prefix == nil then
prefix = ""
end
if hash == nil then
top = true
hash = {}
else
top = false
end
if hash[tab] ~= nil then
log(prefix .. "recursive " .. hash[tab])
return
end
if type(tab) == "string" then
log(prefix .. " (" .. type(tab) .. ") = " .. string.format("%q", tab))
elseif type(tab) ~= "table" then
log(prefix .. " (" .. type(tab) .. ") = " .. tostring(tab))
else
hash[tab] = prefix
r = {}
if top then
log(prefix .. "{")
pref = prefix
prefix = prefix .. " "
end
for k,v in pairs(tab) do
table.insert(r,{k=k, v=v})
end
table.sort(r,function(x,y) return tostring(x.k):lower() < tostring(y.k):lower(); end)
for p,q in ipairs(r) do
k = q.k;
v = q.v;
if type(k) == "table" then
log(prefix .. "key-{")
printTable(k,prefix .. " ", hash);
s = " }: "
else
s = tostring(k) .. ": "
end
if type(v) == "table" then
log(prefix .. s .. "{")
printTable(v,prefix .. string.rep(" ",#s) .. " ", hash)
log(prefix .. string.rep(" ",#s) .. "}")
elseif type(v) == "string" then
log(prefix .. s .. "(" .. type(v) .. ") " .. string.format("%q",v))
else
log(prefix .. s .. "(" .. type(v) .. ") " .. tostring(v))
end
end
if top then
log(pref .. "}")
end
hash[tab] = nil;
end
end
function tableToString(tab, hash)
if type(tab) == "string" then
return string.format("%q",tab)
elseif type(tab) ~= "table" then
return tostring(tab)
end
if hash == nil then
hash = {}
elseif hash[tab] then
return "recursive"
end
hash[tab] = true
local k,v,s
s = "{"
for k,v in pairs(tab) do
if s ~= "{" then
s = s .. ", "
end
if type(k) == "table" then
s = s .. tableToString(k, hash)
elseif type(k) == "number" then
s = s .. "[" .. k .. "]"
else
s = s .. tostring(k)
end
s = s .. "="
if type(v) == "string" then
s = s .. string.format("%q",v)
elseif type(v) == "table" then
s = s .. tableToString(v, hash)
else
s = s .. tostring(v)
end
end
s = s .. "}"
hash[tab] = nil
return s
end
--
-- Global lock
--
local global_lock_name = "/tmp/gengen_lock"
-- creat and excl flags are crucial here. open will fail if the file already exists.
local global_lock_flags = nixio.open_flags("creat", "excl")
function take_global_lock()
local lockFile = nixio.open(global_lock_name, global_lock_flags, 666)
if lockFile then
lockFile:close()
ILog("Global lock taken")
return true
end
ILog("Waiting for global lock")
return false
end
function give_global_lock()
nixFs.unlink(global_lock_name)
ILog("Global lock given")
end
--
-- Z-Wave Queue and job handling
--
zwint = require "zwint"
SID_ZWAVEMONITOR = "urn:gengen_mcv-org:serviceId:ZWaveMonitor1"
SID_ZWN = "urn:micasaverde-com:serviceId:ZWaveNetwork1"
SID_SCENECONTROLLER = "urn:gengen_mcv-org:serviceId:SceneController1"
GENGENINSTALLER_SID = "urn:gengen_mcv-org:serviceId:SceneControllerInstaller1"
GENGENINSTALLER_DEVTYPE = "urn:schemas-gengen_mcv-org:device:SceneControllerInstaller:1"
local ZWaveQueue = {}
local ActiveZWaveJob = nil
local DelayingJob = false
local ZWaveQueueNext = nil
local ZWaveQueueNodes = 0
local TaskHandleList = {}
local OtherJobPending = false
local ZWaveQueuePendingTime = 0
local MinOtherJobDelay = 400
local ZQ_MaxQueueDepth = 3 -- Actually only 2 pending. at least 1 slot always unused.
MonitorContextNum = 0
MonitorContextList = {}
local DeviceAwakeList = {}
local DeviceAwakeStates = {}
local DeviceAwakeNextState = 1
local NoMoreInformationContexts = {}
local function EnqueueActionOrMessage(SCObj, queueNode)
VEntry()
local peer_dev_num = GetPeerDevNum(luup.device)
local description = ""
if peer_dev_num then
description = queueNode.description or luup.devices[peer_dev_num].description
if not queueNode.responseDevice then
queueNode.responseDevice = peer_dev_num
end
if queueNode.hasBattery == nil then
queueNode.hasBattery = SCObj.HasBattery
end
end
queueNode.description = description
VLog("EnqueueActionOrMessage-External: ", queueNode)
table.insert(ExternalZWaveQueue, queueNode)
end
-- Enqueue a local Z-Wave controller message.
function EnqueueZWaveControllerMessage(SCObj, name, node_id, data, dev_num, delay)
VEntry()
EnqueueActionOrMessage(SCObj, {
type=0,
name=name,
description=luup.devices[dev_num].description,
device=dev_num,
node_id=node_id,
data=data,
delay=delay})
end
-- Enqueue a Z-Wave message. No response is expected. Wait <delay> milliseconds
-- before sending a Z-Wave command to the same device
function EnqueueZWaveMessage(SCObj, name, node_id, data, dev_num, delay)
VEntry()
EnqueueActionOrMessage(SCObj, {
type=1,
name=name,
description=luup.devices[dev_num].description,
device=dev_num,
node_id=node_id,
data=data,
delay=delay})
end
-- Enqueue a Z-Wave message to a target device.
-- No response is expected. Wait <delay> milliseconds
-- before sending a Z-Wave command to the same device
function EnqueueTargetZWaveMessage(SCObj, name, node_id, data, dev_num, delay)
VEntry()
EnqueueActionOrMessage(SCObj, {
type=1,
name=name,
description=luup.devices[dev_num].description,
device=dev_num,
node_id=node_id,
data=data,
delay=delay,
hasBattery=false})
end
-- Enqueue a Lua action within the Z-Wave queue
-- Name must be the name of the job as returned by the job watch callback. e.g. ZWJob_PollNode
-- Parameters 2-5 are the same as luup_action.
function EnqueueLuupAction(SCObj, name, node_id, service, action, arguments, device, delay)
VEntry()
EnqueueActionOrMessage(SCObj, {
type=2,
name=name,
device=device,
node_id=node_id,
service=service,
description=service..": "..action,
action=action,
arguments=arguments,
hasBattery=false,
delay=delay})
end
-- Enqueue a Z-Wave message, expecting a response.
-- name, node_id, data, delay - as in EnqueueZWaveMessage
-- controller: true if a message to the local controller, false if a message to a remote device
-- pattern is a Linux externed refular expression which will be matched against the hexified incoming Z-Wave data.
-- Callback is a function which is passed the peer device number and any captures from the regex.
-- The capture array is nil if a timeout occurred.
-- If callback is nil, then this can be used to wait until the response is receviced, without regard to its value,
-- before sending any other commands to that specific device.
-- Oneshot is true if the monitor should be canceled as soon as it matches.
-- Timeout and delay are in milliseconds.
-- If timeeout is 0 or nil then the monitor will be active until canceled with CancelZWaveMonitor
-- If armPattern is not nil then the given pattern must be sent first to arm the monitor.
-- If autoResponse is not nil then the received data is not received by LuaUPnP and the given autoResponse is sent to the device instead.
-- Delay is applied after the response is received but ignored in case of a timeout.
-- Returns a context which can be passed to CancelZWaveMonitor if callback is not nil.
function EnqueueZWaveMessageWithResponse(SCObj, name, node_id, data, delay, controller, pattern, callback, oneshot, dev_num, timeout, armPattern, autoResponse)
VEntry()
local context
if callback then
MonitorContextNum = MonitorContextNum + 1
context = "R_" .. name .. "_" .. node_id .. "_" .. MonitorContextNum
MonitorContextList[context] = {incoming=true, callback=callback, oneshot=oneshot, releaseNodeId=node_id}
end
local messageType = 1
if controller then
messageType = 0
end
EnqueueActionOrMessage(SCObj, {
type=messageType,
name=name,
description=luup.devices[dev_num].description,
node_id=node_id,
device=dev_num,
data=data,
delay=delay,
pattern=pattern,
context=context,
oneshot=oneshot,
timeout=timeout,
armPattern=armPattern,
autoResponse=autoResponse})
return context
end
local function EnqueueInternalActionOrMessage(queueNode)
VEntry()
local node_id = queueNode.node_id
if not node_id then
node_id = 0
end
if queueNode.type == 4 then
InitWakeUpNotificationMonitor(queueNode.responseDevice, queueNode.node_id, true)
return
end
if queueNode.pattern then
-- Handle cases where callback was passed as nil.
-- Also handles cases where a non-first-peer relays the response to
-- the installert to release the waitingForResponse flag.
if not queueNode.context then
MonitorContextNum = MonitorContextNum + 1
queueNode.context = "W" .. queueNode.node_id .. "_" .. MonitorContextNum
end
if not MonitorContextList[queueNode.context] then
MonitorContextList[queueNode.context] = {incoming=true, oneshot=queueNode.oneshot, releaseNodeId=queueNode.node_id}
end
end
local newDev = ZWaveQueue[node_id]
if not newDev then
if queueNode.type == 1 then
luup_device_message(queueNode.device,
0, -- job_WaitingToStart
"Waiting to configure", -- message
5, -- Timeout
GetDeviceName()) -- source
end
newDev = {node_id=node_id}
ZWaveQueue[node_id] = newDev
ZWaveQueueNodes = ZWaveQueueNodes + 1
if not ZWaveQueueNext then
newDev.next = newDev
newDev.prev = newDev
ZWaveQueueNext = newDev
else
newDev.next = ZWaveQueueNext
newDev.prev = ZWaveQueueNext.prev
ZWaveQueueNext.prev.next = newDev
ZWaveQueueNext.prev = newDev
end
end
if #newDev > 0 and newDev[#newDev].final then
if not queueNode.final then -- Ignore final over final
table.insert(newDev, #newDev, queueNode) -- Insert non-final before existing final
end
else
-- Here we apply the "*" hack which indicates that a command can replace another command further ahead in the queue.
-- This is useful when an "all on" or "all off"-type scene can change the indicator several times.
if string.sub(queueNode.name,1,1) == "*" then
queueNode.matchString = string.match(queueNode.name, "[^(]+", 2) -- Skip the initial *. Ignore anything after (
if queueNode.matchString then
for i, v in ipairs(newDev) do
if ZWaveQueueNext ~= v and v.matchString == queueNode.matchString and v.node_id == queueNode.node_id then
newDev[i] = queueNode
return
end
end
end
end
table.insert(newDev, queueNode) -- Normal case. Insert at end.
if queueNode.hasBattery then
InitWakeUpNotificationMonitor(queueNode.responseDevice, queueNode.node_id, false)
if #newDev == 1 and DeviceAwakeList[queueNode.node_id] ~= 1 then
log(ANSI_YELLOW, queueNode.description, " is now on battery wait", ANSI_RESET)
local handle = TaskHandleList[queueNode.responseDevice]
if not handle then
handle = -1
end
TaskHandleList[queueNode.responseDevice] = luup.task("Waiting for device to wake up", 1, queueNode.description, handle)
if queueNode.type == 1 then
luup_device_message(queueNode.device,
5, -- job_WaitingForCallback
"Waiting for device to wake up", -- message
0, -- No timeout
GetDeviceName()) -- source
end
end
end
end
end
-- Enqueues a special message called as part of the "configured" trigger.
-- which initializes the wake-up monitor in "already awake" state if it
-- has not already been initialized
function EnqueueInitWakeupMonitorMessage(name, node_id, peer_dev_num)
VEntry("EnqueueInitWakeupMonitorMessage")
local queueNode = {
type=4,
name=name,
node_id=node_id,
responseDevice = peer_dev_num,
description = luup.devices[peer_dev_num].description,
hasBattery = true}
table.insert(ExternalZWaveQueue, queueNode)
end
-- Enqueue the last Z-Wave message in a group.
-- This is used for the "no more information" message for battery devices.
-- It may be deleted if other items are queued behind it.
local function EnqueueFinalZWaveMessage(name, node_id, data, peer_dev_num)
VEntry("EnqueueFinalZWaveMessage")
local queueNode = {
type=1,
name=name,
node_id=node_id,
data=data,
delay=0,
responseDevice = peer_dev_num,
description = luup.devices[peer_dev_num].description,
hasBattery = true,
final=true}
EnqueueInternalActionOrMessage(queueNode)
end
-- Monitors a Z-Wave message sent by the controller or intercpets a message sent by LuaUPnP
-- and optionally removes the message and sends an expected autoResponse back to to the sender
-- Outgoing is false for monitoring incoming data or true for intercepting outgoing data.
-- Arm_regex is an optional Linux extended regular expression which will be matched
-- against the hexified data in the opposite direction. A match will arm the monitor/intercept.
-- If arm_pattern is nil then the monitor/intercept is always armed.
-- Main_regex is a Linux extended regular expression which will be matched
-- against the hexified outgoing Z-Wave data from LuaUPnP (intercept) or incoming data
-- from the controller (monitor). A match will trigger the monitor/incercept if it is armed.
-- Response (if not nil) is a hex string which will be returned to the sender (after converting into
-- binary) when monitor/intercept is triggered. The data that caused the trigger is not passed through.
-- If autoResponse is nil then the data is passed through.
-- The autoResponse string can also include \1 ... \9 captures from the intercept regex (but not the
-- arm regex) and can also include XX to calculate the Z-Wave checksum.
-- Callback is a function which is passed the peer device number and any captures from
-- the main regex. The capture array is nil if a timeout occurred.
-- Callback can also be a string as a function name in which case the callback will be executed
-- by the installer device which actually dispatches most Z-Wave commands
-- Callback can be nil if not needed.
-- Oneshot is true if the intercept should be canceled as soon as it matches.
-- If OneShot is false and arm_regex is not nil, then the intercept is disarmed when it triggers.
-- Timeout and delay are in milliseconds.
-- If timeout is 0 then the monitor will be active until canceled with CancelZWaveMonitor
-- Label - A label used in creating the unique key for this monitor. Should be descriptive and helps with debugging.
-- Forward is true if the response should be forwarded to the opposite party rather than returned back to the sender.
-- Only used if AutoResponse is non-nil
-- Returns a context which can be passed to CancelZWaveMonitor or nil if error.
function MonitorZWaveData(outgoing, peer_dev_num, arm_regex, intercept_regex, autoResponse, callback, owneshot, timeout, label, forward)
VEntry()
if not zwint or not zwint.monitor then
DLog("MonitorZWaveData returning nil because zwint is not yet installer")
return nil
end
local context
MonitorContextNum = MonitorContextNum + 1
local prefix = "M_"
if outgoing then
prefix = "I_"
end
if not forward then
forward = false
end
context = prefix .. label .. "_" .. peer_dev_num.."_"..MonitorContextNum
if not callback then
context = "*" .. context
end
MonitorContextList[context] = {outgoing=outgoing, callback=callback, oneshot=oneshot}
local result, errcode, errmessage
if outgoing then
result, errcode, errmessage = zwint.intercept(peer_dev_num, context, intercept_regex, owneshot, timeout, arm_regex, autoResponse, forward)
else
result, errcode, errmessage = zwint.monitor(peer_dev_num, context, intercept_regex, owneshot, timeout, arm_regex, autoResponse, forward)
end
if not result then
ELog("MonitorZWaveData: zwint failed. error code=", errcode, " error message=", errmessage)
MonitorContextList[context] = nil;
return nil;
end
return context;
end
-- Remove the current job from the Z-Wave queue.
-- Return true if there are more jobs in the queue
local function RemoveHeadFromZWaveQueue(job)
VEntry()
local queue = ZWaveQueueNext
if job then
queue = ZWaveQueue[job.node_id]
if not queue then
ELog("Job not in queue:", ZWaveQueue)
return false
end
end
if not queue then
return false
end
local removed = queue[1]
table.remove(queue,1)
if #queue == 0 then
if removed and removed.type == 1 then
luup_device_message(removed.device,
4, -- job_Completed
"Done", -- message
1, -- Timeout
GetDeviceName()) -- source
end
ZWaveQueue[queue.node_id] = nil
ZWaveQueueNodes = ZWaveQueueNodes - 1
if queue.next == queue then
ZWaveQueueNext = nil
return false
else
queue.next.prev = queue.prev
queue.prev.next = queue.next
if queue == ZWaveQueueNext then
ZWaveQueueNext = queue.next
end
end
end
return true;
end
-- Remove the current job and and other jobs for that node (if it is non-zero)
-- from the queue. Return true if there are jobs remaining in the queue for
-- other nodes.
local function RemoveNodeFromZWaveQueue(job)
if job.node_id == 0 then
return RemoveHeadFromZWaveQueue(job)
end
local result = true
local queue = ZWaveQueueNext
if job then
queue = ZWaveQueue[job.node_id]
end
if not queue then
return false
end
ZWaveQueue[queue.node_id] = nil
ZWaveQueueNodes = ZWaveQueueNodes - 1
if queue.next == queue then
ZWaveQueueNext = nil
result = false
else
queue.next.prev = queue.prev
queue.prev.next = queue.next
if queue == ZWaveQueueNext then
ZWaveQueueNext = queue.next
end
end
while #queue > 0 do
local j2 = table.remove(queue, 1)
if j2 ~= job and j2.responseDevice and j2.responseDevice > 0 and j2.timeout and j2.timeout > 0 then
VLog("RemoveNodeFromZWaveQueue: sending fake timeout for job which was never started due to previously failed job:", j2)
while not take_global_lock() do
luup.sleep(100) -- Will this work and not cause LuaUPnP crashes? Using luup.call_delay here is difficult
end
luup.call_action(SID_ZWAVEMONITOR, "Timeout", {key=j2.context}, j2.responseDevice)
give_global_lock()
end
end
return result;
end
function SceneController_InitWakeupMonitor(device, settings)
DEntry()
InitWakeUpNotificationMonitor(settings.Peer_Dev_Num, settings.ZWave_Node)
end
function CheckUI5ZWaveQueueHeadStatus2(data)
local j = ActiveZWaveJob
if not j then
return
end
j.err_num, j.err_msg = luup.job.status(j.job_num, 1)
if not j.err_msg then
j.err_msg = ""
end
if j.err_num == 0 then
j.err_msg = j.err_msg .. "Waiting to start"
end
if j.err_num ~= j.last_err_num or j.err_msg ~= j.last_err_msg then
j.last_err_num = j.err_num
j.last_err_msg = j.err_msg
local lul_job = {}
if j.type == 0 then
lul_job.type = "ZWJob_GenericSendFrame"
lul_job.name = "send_code"
else
lul_job.type = "ZWJob_SendData"
lul_job.name = "childcmd node "..j.node_id
end
lul_job.status = j.err_num
lul_job.notes = j.err_msg
SceneController_JobWatchCallBack(lul_job)
if j.err_num >= 2 and j.err_num <= 4 then
return
end
end
CheckUI5ZWaveQueueHeadStatus("")
end
local function ChangeBatteryNoMoreInformationMonitor(peer_dev_num, zwave_node, enable)
VEntry("ChangeBatteryNoMoreInformationMonitor")
local BatteryNoMoreInformationCallback = function(installer, captures)
local deviceAwakeCount = DeviceAwakeList[zwave_node]
VEntry("BatteryNoMoreInformationCallback")
if not deviceAwakeCount == nil or deviceAwakeCount == 0 then
ELog("Received a No More Information message for device ", peer_dev_num, " Z-Wave node ", zwave_node, " without a corresponing wake-up event.")
return
end
deviceAwakeCount = deviceAwakeCount - 1;
DeviceAwakeList[zwave_node] = deviceAwakeCount;
if deviceAwakeCount == 1 then
local list = ZWaveQueue[zwave_node]
if list and list[1] then
local device = luup.devices[peer_dev_num]
log(ANSI_YELLOW, "Battery wait released for ", device.description, ANSI_RESET)
local handle = TaskHandleList[peer_dev_num]
if not handle then
handle = -1
end
TaskHandleList[peer_dev_num] = luup.task("", 4, device.description, handle)
end
EnqueueFinalZWaveMessage("BatteryNoMoreInformation", zwave_node, "0x84 0x8", peer_dev_num);
else
VLog("BatteryNoMoreInformationCallback: Battery wait not released because deviceAwakeCount=",deviceAwakeCount)
end
end
if enable then
if not NoMoreInformationContexts[peer_dev_num] then
NoMoreInformationContexts[peer_dev_num] = MonitorZWaveData(
true, -- outgoing
luup.device, -- peer_dev_num
nil, -- armRegEx
--[==[
C1 C2 C3
41 12/04/16 20:05:27.515 0x1 0xd 0x0 0x19 0x9 0x2 0x84 0x8 0x5 0x0 0x0 0x0 0x0 0x4 0x6d (#\r############m)
SOF - Start Of Frame --+ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ +-------------+ ¦ ¦
length = 13 ------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
Request ----------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
FUNC_ID_ZW_SEND_DATA_GENERIC ---------------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
Device 12=Nexia One Touch Scene Controller Z-Wave -+ ¦ ¦ ¦ ¦ ¦ ¦ ¦
Data length = 2 -----------------------+ ¦ ¦ ¦ ¦ ¦ ¦
COMMAND_CLASS_WAKE_UP ----------------------------+ ¦ ¦ ¦ ¦ ¦
WAKE_UP_NO_MORE_INFORMATION --------------------------------+ ¦ ¦ ¦ ¦
Xmit options = ACK | AUTO_ROUTE ------------------------------------+ ¦ ¦ ¦
Routing data ignored ---------------------------------------------+ ¦ ¦
Callback = 4 --------------------------------------------------------+ ¦
Checksum OK -------------------------------------------------------------+
--]==]
"^01 .. 00 (..) (" .. string.format("%02X", zwave_node) .. ") .. 84 08 .+ (..) ..$",
--[==[
42 12/04/16 20:05:27.538 0x6 0x1 0x4 0x1 0x19 0x1 0xe2 (#######)
ACK - Acknowledge --+ ¦ ¦ ¦ ¦ ¦ ¦
SOF - Start Of Frame ------+ ¦ ¦ ¦ ¦ ¦
length = 4 ----------+ ¦ ¦ ¦ ¦
Response --------------+ ¦ ¦ ¦
FUNC_ID_ZW_SEND_DATA_GENERIC -------------------+ ¦ ¦
RetVal: OK -----------------------+ ¦
Checksum OK ----------------------------+
42 12/04/16 20:05:27.539 got expected ACK -- removed
ACK: 0x6 (#)
42 12/04/16 20:05:27.778 0x1 0x5 0x0 0x19 0x4 0x0 0xe7 (#######)
SOF - Start Of Frame --+ ¦ ¦ ¦ ¦ ¦ ¦
length = 5 ------+ ¦ ¦ ¦ ¦ ¦
Request ----------+ ¦ ¦ ¦ ¦
FUNC_ID_ZW_SEND_DATA_GENERIC ---------------+ ¦ ¦ ¦
Callback = 4 -------------------+ ¦ ¦
TRANSMIT_COMPLETE_OK -----------------------+ ¦
Checksum OK ----------------------------+
41 12/04/16 20:05:27.779 ACK: 0x6 (#) -- removed
--]==]
"06 01 04 01 \\1 01 XX 01 05 00 \\1 \\3 00 XX",
BatteryNoMoreInformationCallback,
false, -- oneShot
0, -- no timeout
"BatteryNoMoreInfo")
end
VLog(" Created no more information context: ", NoMoreInformationContexts[peer_dev_num])
else
local context = NoMoreInformationContexts[peer_dev_num]
if context then
VLog(" Deleting no more information context: ", context)
zwint.cancel(luup.device, context)
MonitorContextList[context] = nil
NoMoreInformationContexts[peer_dev_num] = nil
end -- if context
end -- else not enable
end -- function ChangeBatteryNoMoreInformationMonitor
function InitWakeUpNotificationMonitor(peer_dev_num, zwave_node, alreadyAwake)
VEntry()
if DeviceAwakeList[zwave_node] ~= nil then
return
end
DeviceAwakeList[zwave_node] = 0
local WakeUpNotificationCallback = function(installer, captures)
local deviceAwake = DeviceAwakeList[zwave_node]
VEntry("WakeUpNotificationCallback")
if deviceAwake > 0 then
DeviceAwakeList[zwave_node] = deviceAwake + 1
else
DeviceAwakeList[zwave_node] = 2
end
if DeviceAwakeList[zwave_node] == 2 then
ChangeBatteryNoMoreInformationMonitor(peer_dev_num, zwave_node, true)
end
DeviceAwakeStates[zwave_node] = DeviceAwakeNextState
luup.call_delay("SceneController_NoMoreInformationTimeout", 10, peer_dev_num .. "_" .. zwave_node .. "_" .. DeviceAwakeNextState, true)
DeviceAwakeNextState = DeviceAwakeNextState+1
end
MonitorZWaveData(
false, -- outgoing
luup.device, -- peer_dev_num
nil, -- arm_regex
--[==[
42 12/04/16 20:05:26.449 0x1 0x8 0x0 0x4 0x4 0x9 0x2 0x84 0x7 0x7f (##########)
SOF - Start Of Frame --+ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
length = 8 ------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
Request ----------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦
FUNC_ID_APPLICATION_COMMAND_HANDLER ----------+ ¦ ¦ ¦ ¦ ¦ ¦
Receive Status BROAD ------------------+ ¦ ¦ ¦ ¦ ¦
Device 12=Nexia One Touch Scene Controller Z-Wave ----+ ¦ ¦ ¦ ¦
Data length = 2 --------------------------+ ¦ ¦ ¦
COMMAND_CLASS_WAKE_UP -------------------------------+ ¦ ¦
WAKE_UP_NOTIFICATION -----------------------------------+ ¦
Checksum OK ----------------------------------------+
--]==]
"^01 .. 00 04 .. " .. string.format("%02X", zwave_node) .. " .. 84 07",
nil, -- autoResponse
WakeUpNotificationCallback,
false, -- not oneShot
0, -- no timeout
"WakeUpNotification")
if alreadyAwake then
WakeUpNotificationCallback(nil, nil)
end
end
-- Always run the Z-Wave queue in a delay task to avoid any deadlocks.
function RunInternalZWaveQueue(fromWhere, delay_ms)
DEntry()
local t1 = socket.gettime()
local delayTime = t1 + delay_ms/1000
if delayTime > ZWaveQueuePendingTime then
ZWaveQueuePendingTime = delayTime
end
if OtherJobPending then
DLog("OtherJobPending. Quitting")
return
end
if ActiveZWaveJob then
DLog("ActiveZWaveJob. Quitting")
return
end
if DelayingJob then
DLog("DelayingJob. Quitting")
return
end
if not ZWaveQueueNext then
DLog("Not ZWaveQueueNext. Quitting")
return
end
DelayingJob = true;
delay_ms = (ZWaveQueuePendingTime - t1) * 1000
local delay_sec
if delay_ms <= 0 then
delay_sec = 0
else
delay_sec = math.floor(delay_ms / 1000)
local sleep_ms = math.floor(delay_ms - delay_sec*1000)
if sleep_ms > 0 then
VLog("RunInternalZWaveQueue: luup.sleep for ",delay_sec," seconds and ", sleep_ms," ms");
luup.sleep(sleem_ms)
local t2 = socket.gettime()
if (t2 - t1) * 1000 < sleep_ms then
delay_sec = delay_sec + 1
VLog("luup.sleep too short. Delaying by an extra second: ", delay_sec)
else
VLog("luup.sleep done")
end
end
end
luup.call_delay("SceneController_RunInternalZWaveQueue", delay_sec, fromWhere, true)
end
function SceneController_RunInternalZWaveQueue(fromWhere)
VEntry("SceneController_RunInternalZWaveQueue")
DelayingJob = false
if OtherJobPending then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") An outside job is still active")
return
end
if not ZWaveQueueNext then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") queue is empty")
return
end
if ActiveZWaveJob then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") Job still active: job=", ActiveZWaveJob)
return
end
local now = socket.gettime()
local delay = math.floor((ZWaveQueuePendingTime - now) * 1000)
if delay > 0 then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") called too soon. Delaying ", delay, "ms")
RunInternalZWaveQueue("ZWaveQueuePendingDelay", delay)
return
end
-- If the head of the queue is in a time delay or otherwise blocked.
-- look around the queue array for another queue who's first job we can perform now
-- or else has the shortest delay.
local nextTime = nil
local nextQueue = nil
local biggestDelay = -1
local longestQueue = 0
local bestCandidate = nil
local candidate = ZWaveQueueNext
repeat
if candidate[1].waitingForResponse then
if candidate[1].type == 0 then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") Stopping seach because waitingForResponse from local controller:", candidate[1])
bestCandidate = nil
nextQueue = nil
break;
else
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") Skipping candidate due to waitingForResponse:", candidate[1])
end
elseif candidate[1].hasBattery and DeviceAwakeList[candidate[1].node_id] ~= 1 then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") Skipping candidate due to batteryWait:", candidate[1])
else
if candidate[1].waitUntil then
if candidate[1].waitUntil > now then
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") time wait queue entry still waiting for ", (candidate[1].waitUntil - now), " seconds from now: ", candidate[1])
if not nextTime or nextTime > candidate[1].waitUntil then
nextTime = candidate[1].waitUntil
nextQueue = candidate
if candidate.type == 0 then -- We cannot start jobs for other nodes until any local job has had time to complete.
bestCandidate = nil
break;
end
end
else
VLog("SceneController_RunInternalZWaveQueue(", fromWhere, ") Removing time wait queue entry which already passed ", (now - candidate[1].waitUntil), " seconds ago: ", candidate[1])
ZWaveQueueNext = candidate
if RemoveHeadFromZWaveQueue() then
RunInternalZWaveQueue(fromWhere.." after timeout", 0)
end
return
end