forked from akbooer/Z-Way
-
Notifications
You must be signed in to change notification settings - Fork 0
/
L_ZWay2.lua
1981 lines (1647 loc) · 64.9 KB
/
L_ZWay2.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
module (..., package.seeall)
ABOUT = {
NAME = "L_ZWay2",
VERSION = "2021.07.24",
DESCRIPTION = "Z-Way interface for openLuup",
AUTHOR = "@akbooer",
COPYRIGHT = "(c) 2013-2021 AKBooer",
DOCUMENTATION = "https://community.getvera.com/t/openluup-zway-plugin-for-zwave-me-hardware/193746",
DEBUG = false,
LICENSE = [[
Copyright 2013-2021 AK Booer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
}
-- 2017.10.03 added test_from_file function
-- 2018.03.15 remove command class 113 from being Security sensor CC 48 equivalent
-- see: http://forum.micasaverde.com/index.php/topic,62975.0.html
-- 2018.07.16 name = dv.metrics.title, for @DesT
-- 2018.08.25 check for missing device file in parameter_list() (thanks @ramwal)
-- 2020.02.10 fixed meter variable names, thanks @rafale77
-- ditto, CurrentSetpoint in command class 67
-- see: https://community.getvera.com/t/zway-plugin/212312/40
-----------------
-- 2020.02.12 L_ZWay2 -- rethink of device presentation and numbering
-- 2020.02.25 add intermediate instance nodes
-- 2020.02.26 change node numbering scheme
-- 2020.03.02 significant improvements to dimmer handling thanks to @rafale77
-- ... sundry iterations on GitHub
-- 2020.03.11 add SendData action (thanks @DesT), fix nil setpoint serviceId
-- 2020.03.12 complete restructure in progress...
-- 2020.03.16 continued refactoring ... including asynchronous HTTP requests
-- 2020.03.23 improve thermostat recognition (thanks @ronluna)
-- 2020.03.29 fix handling of missing class #67 in thermostats (thanks @ronluna)
-- 2020.03.30 @rafale77, pull request#24, fix Window Covering Service
-- 2020.03.31 fix x_or_y() functions to work with 1 or 0 as well as '1' or '0' (thanks @DesT)
-- 2020.04.05 @rafale77, pull request #27, scene controller LED handling (Leviton 4-button)
-- 2020.05.11 don't disable devices in Room101 (because they weren't enabled when restored. Thanks @kfxo)
-- see: https://smarthome.community/topic/111/all-z-way-devices-disabled-attribute-is-set-to-1
-- 2020.05.12 add command class 1 updater for ZWave.me battery switch, thanks @ArcherS
-- see: https://smarthome.community/topic/113/changing-device-type-for-wall-controller
-- 2020.07.12 add CC 91, Central Scene for Remotec ZRC90 (and others?)
-- see: https://smarthome.community/topic/171/remotec-zrc90
-- 2020.11.24 add category_num, if not set already, when checking devices
-- 2021.01.19 flag authorisation failure during synchronous or asynchronous requests (thanks @PerH)
-- 2021.02.09 add support for GetConfig
-- 2021.07.24 add support for Fibaro TRV
local json = require "rapidjson"
local chdev = require "openLuup.chdev" -- NOT the same as the luup.chdev module! (special create fct)
local async = require "openLuup.http_async"
local loader = require "openLuup.loader"
local http = require "socket.http"
local ltn12 = require "ltn12"
local empty = setmetatable ({}, {__newindex = function() error ("read-only", 2) end})
local function _log(text, level)
luup.log(("%s: %s"): format ("ZWay", text), (level or 50))
end
local function debug (info)
if ABOUT.DEBUG then
print (info)
_log(info, "DEBUG")
end
end
-----------------------------------------
--
-- Z-WayVDev() API
--
local function ZWayAPI (ip, sid)
local cookie = "ZWAYSession=" .. (sid or '')
local function build_request (url, body, response_body)
return {
method = body and "POST" or "GET",
url = url,
headers = {
["Content-Length"] = body and #body,
["Cookie"] = cookie,
},
source = body and ltn12.source.string(body),
sink = ltn12.sink.table(response_body)
}
end
local function build_response (url, status, response_body)
local json_response = table.concat (response_body)
if status ~= 200 then
_log (url)
_log (json_response)
end
return status, json_response
end
local function HTTP_request (url, body)
local response_body = {}
local _, status = http.request (build_request (url, body, response_body))
return build_response (url, status, response_body)
end
local function HTTP_async_request (url, body_or_callback, callback)
local response_body = {}
local body = callback and body_or_callback or nil
callback = callback or body_or_callback
return async.request (build_request (url, body, response_body), -- return request status, not result
function (_, status)
callback (build_response (url, status, response_body))
end)
end
local function HTTP_request_json (url, body)
local status, json_response = HTTP_request (url, body)
return status, json.decode (json_response)
end
local function authenticate (user, password)
cookie = nil -- invalidate old one, whatever
local url = "http://%s:8083/ZAutomation/api/v1/login"
local data = json.encode {login=user, password = password}
local _, j = HTTP_request_json (url: format (ip), data)
local sid = j and j.data and j.data.sid
cookie = sid and "ZWAYSession=" .. sid or nil
return sid, j
end
local function devices ()
local url = "http://%s:8083/ZAutomation/api/v1/devices"
local status, d = HTTP_request_json (url: format (ip))
return d and d.data and d.data.devices or empty, status
end
-- send a command
local function command (id, cmd)
local url = "http://%s:8083/ZAutomation/api/v1/devices/ZWayVDev_zway_%s/command/%s"
local request = url: format (ip, id, cmd)
return HTTP_request_json (request)
end
-- send a zwave command
local function zwcommand (id, inst, cc, cmd)
local url = "http://%s:8083/ZWaveAPI/Run/devices[%s].instances[%s].commandClasses[%s].%s"
local request = url: format (ip, id, inst, cc, cmd)
return HTTP_request_json (request)
end
-- send a data packet
local function zwsend (id, data)
local url = "http://%s:8083/ZWaveAPI/Run/SendData(%s,%s)"
local request = url: format (ip, id, data)
return HTTP_request_json (request)
end
-- send a generic request
local function request (req)
local url = "http://%s:8083%s"
local request = url: format (ip, req)
return HTTP_request (request)
end
-- send a generic ASYNC request
local function async_request (req, callback)
local url = "http://%s:8083%s"
local request = url: format (ip, req)
return HTTP_async_request (request, callback)
end
-- return status
local function status ()
local url = "http://%s:8083/ZAutomation/api/v1/status"
local _, d = HTTP_request_json (url: format (ip))
return d
end
return {
request = request, -- for low-level access
status = status,
command = command,
zwcommand = zwcommand,
zwsend = zwsend,
devices = devices,
authenticate = authenticate,
async_request = async_request, -- ditto, asynchronous
-- Z-Wave Device API
zDevAPI = {
controller = function ()
local status, response = request "/ZWaveAPI/Run/zway.controller"
return status, json.decode (response)
end,
command = zwcommand,
send = zwsend,
},
-- Virtual Device API
vDevAPI = {
command = command,
status = status,
},
-- JavaScript API
JSAPI = {},
}
end
-----------------------------------------
--
-- DUMMY Z-WayVDev() API, for testing from file
--
local function ZWayDummyAPI (filename)
local function noop() end
local f = assert (io.open (filename), "TEST filename not found")
local J = f: read "*a"
f: close()
local D = json.decode (J)
if D then
return {
request = noop,
command = noop,
devices = function () return D end,
status = function () return {data = "OK"} end,
zwcommand = noop,
zwsend = noop,
}
end
end
local Z -- the Zway API object
local cclass_update -- table of command_class updaters indexed by altid
local devNo -- our device number
local OFFSET -- bridge offset for child devices
local ASYNCPOLL -- asynch polling if true
local POLLRATE -- poll rate for Zway devices
local CLONEROOMS --
local NAMEDEVICES --
local ZERODIMMER --
local DEV = setmetatable ({
--
dimmer = "D_DimmableLight1.xml",
thermos = "D_HVAC_ZoneThermostat1.xml",
motion = "D_MotionSensor1.xml",
-- these preset devices don't correspond to any ZWay vDev
controller = "D_SceneController1.xml",
combo = "D_ComboDevice1.xml",
rgb = "D_DimmableRGBLight1.xml",
-- D_Siren1.xml
-- D_SmokeSensor1.xml
},{
__index = function (_,n) _log ("ERROR: Unknown DEV: "..(n or '?')) end})
local KnownSID = { -- list of all implemented serviceIds
"urn:akbooer-com:serviceId:ZWay1",
"urn:micasaverde-com:serviceId:Camera1",
"urn:micasaverde-com:serviceId:Color1",
"urn:micasaverde-com:serviceId:ComboDevice1",
"urn:micasaverde-com:serviceId:DoorLock1",
"urn:micasaverde-com:serviceId:EnergyMetering1",
"urn:micasaverde-com:serviceId:GenericSensor1",
"urn:micasaverde-com:serviceId:HVAC_OperatingState1",
"urn:micasaverde-com:serviceId:HaDevice1",
"urn:micasaverde-com:serviceId:HumiditySensor1",
"urn:micasaverde-com:serviceId:LightSensor1",
"urn:micasaverde-com:serviceId:SceneController1",
"urn:micasaverde-com:serviceId:SceneControllerLED1",
"urn:micasaverde-com:serviceId:SecuritySensor1",
"urn:micasaverde-com:serviceId:ZWaveNetwork1",
"urn:upnp-org:serviceId:Dimming1",
"urn:upnp-org:serviceId:WindowCovering1",
"urn:upnp-org:serviceId:FanSpeed1",
"urn:upnp-org:serviceId:HVAC_FanOperatingMode1",
"urn:upnp-org:serviceId:HVAC_UserOperatingMode1",
"urn:upnp-org:serviceId:SwitchPower1",
"urn:upnp-org:serviceId:TemperatureSensor1",
"urn:upnp-org:serviceId:TemperatureSetpoint1",
"urn:upnp-org:serviceId:TemperatureSetpoint1_Cool",
"urn:upnp-org:serviceId:TemperatureSetpoint1_Heat",
}
-- build list of shorthand names for known serviceId
local SID = setmetatable ({
AltUI = "urn:upnp-org:serviceId:altui1",
bridge = luup.openLuup.bridge.SID, -- for Remote_ID variable
},{
__index = function (_,n) _log ("ERROR: Unknown SID: "..(n or '?')) end})
for _,name in ipairs (KnownSID) do
local short_name = name: match "[^:]+$" :gsub ("%d*$",'')
SID[short_name] = name
SID[name] = short_name
end
--[[
ZWayVDev [Node ID]:[Instance ID]:[Command Class ID]:[Scale ID]
The Node Id is the node id of the physical device,
the Instance ID is the instance id of the device or ’0’ if there is only one instance.
The command class ID refers to the command class the function is embedded in.
The scale id is usually ’0’ unless the virtual device is generated from a Z-Wave device
that supports multiple sensors with different scales in one single command class.
--]]
-- given vDev structure, return altid, vtype, etc...
-- ... node, instance, command_class, scale, sub_class, sub_scale, tail
local NICS_pattern = "^(%d+)%-(%d+)%-?(%d*)%-?(%d*)%-?(%d*)%-?(%d*)%-?(.-)$"
local function NICS_etc (vDev)
local vtype, altid = vDev.id: match "^ZWayVDev_(zway_%D*)(.+)"
if altid then
return altid, vtype, altid: match (NICS_pattern)
end
end
local NIaltid = "^(%d+)%-(%d+)$" -- altid of just node-instance format (ie. not child vDev)
-- NB: for thermostats, see @rigpapa's useful post:
-- old: http://forum.micasaverde.com/index.php/topic,79510.0.html
-- new: https://community.getvera.com/t/need-help-getting-started-trying-to-get-themostat-with-heat-cool-setpoints/198983/2
-- LUUP utility functions
local function getVar (name, service, device)
service = service or SID.ZWay
device = device or devNo
-- this needs to be fast because it is called for every vDev each update cycle.
-- use openLuup objects, rather than slower luup.variable_get() function call
-- local x = luup.variable_get (service, name, device)
local dev, srv, var, x
dev = luup.devices[tonumber(device)]
srv = dev.services[service]
if srv then var = srv.variables[name] end
if var then x = var.value end
return x
end
local function setVar (name, value, service, device)
service = service or SID.ZWay
device = device or devNo
-- use getVar(), above, rather than slower luup.variable_get () function call
-- local old = luup.variable_get (service, name, device)
local old = getVar (name, service, device)
if tostring(value) ~= old then
luup.variable_set (service, name, value, device) -- no option here, because of logging, etc.
end
end
-- get and check UI variables
local function uiVar (name, default, lower, upper)
local value = getVar (name)
local oldvalue = value
if value and (value ~= "") then -- bounds check if required
if lower and (tonumber (value) < lower) then value = lower end
if upper and (tonumber (value) > upper) then value = upper end
else
value = default
end
value = tostring (value)
if value ~= oldvalue then setVar (name, value) end -- default or limits may have modified value
return value
end
-- given "on" or "off" or "1" or "0"
-- return "1" or "0" or "on" or "off"
local function on_or_off (x)
local y = {
["on"] = "1", ["off"] = "0",
["1"] = "on", ["0"] = "off",
[1] = "on", [0] = "off",
[true] = "on"}
local z = tonumber (x)
local on = z and z > 0
return y[on or x] or x
end
local function open_or_close (x)
local y = {
["open"] = "0", ["close"] = "1",
["0"] = "open", ["1"] = "close",
[0] = "open", [1] = "close"}
return y[x] or x
end
local function rev_open_or_close (x)
local y = {
["open"] = "1", ["close"] = "0",
["1"] = "open", ["0"] = "close",
[1] = "open", [0] = "close"}
return y[x] or x
end
-- make either "1" or "true" or true work the same way
local function is_true (flag)
local y = {["true"] = true, ["1"] = true, [1] = true, [true] = true}
return y [flag]
end
-- 2021.01.19 flag authorisation failure
local function authentication_failure()
luup.set_failure (2)
setVar ("DisplayLine1", 'Login required', SID.AltUI)
end
----------------------------------------------------
--
-- SERVICE SCHEMAS - virtual services
-- openLuup => Zway
--
local SRV = setmetatable ({}, {__index = function (t,n) return t[SID[n]] end}) -- auto name alias
--[[
vDev commands:
1. ’update’: updates a sensor value
2. ’on’: turns a device on
3. ’off’: turns a device off
4. ’exact’: sets the device to an exact value. This will be a temperature for thermostats or a percentage value of motor controls or dimmers
--]]
SRV.SwitchPower = {
---------------
-- 2020.03.02 thanks to @rafale77 for extensive testing and code changes
--
SetTarget = function (d, args)
local level = tostring(args.newTargetValue or 0)
local off = level == '0'
local class ="-37"
luup.variable_set (SID.SwitchPower, "Target", off and '0' or '1', d)
local dimmer = luup.variable_get(SID.Dimming, "OnEffectLevel",d) -- check for dimmer
if dimmer then
class = "-38"
if ZERODIMMER then
luup.variable_set (SID.Dimming, "LoadLevelTarget", off and '0' or dimmer, d)
end
end
local value = on_or_off (level)
local gdo = luup.variable_get(SID.DoorLock, "Status",d) -- check garage door
if gdo then
class = "-102"
value = rev_open_or_close(level)
end
local altid = luup.devices[d].id
altid = altid: match (NIaltid) and altid..class or altid
Z.command (altid, value)
end,
}
SRV.Dimming = {
---------------
-- 2020.03.02 thanks to @rafale77 for extensive testing and code changes
--
SetLoadLevelTarget = function (d, args)
local level = tostring (args.newLoadlevelTarget or 0)
local off = level == '0'
local class = "-38"
luup.variable_set (SID.SwitchPower, "Target", off and '0' or '1', d)
luup.variable_set (SID.Dimming, "OnEffectLevel", level, d)
luup.variable_set (SID.Dimming, "LoadLevelTarget", level, d)
local altid = luup.devices[d].id
altid = altid: match (NIaltid) and altid..class or altid
local value = "exact?level=" .. level
Z.command (altid, value)
end,
}
SRV.HaDevice = {
ToggleState = function (d)
local toggle = {['0'] = '1', ['1']= '0'}
local status = getVar ("Status", SID.SwitchPower, d)
if status then
SRV.SwitchPower.SetTarget (d, {newTargetValue = toggle [status] or '0'})
end
end,
Poll = function (d)
local cc = 32
local cmd = "Get()"
local altid = luup.devices[d].id
local id, inst = altid: match (NIaltid)
Z.zwcommand(id, inst, cc, cmd)
end,
GetConfig = {
run = function (d,args)
local cc = 112
local par = args.parameter
local data = "Get(%s)"
local data2 = "data[%s].val.value"
local altid = luup.devices[d].id
local id, inst = altid: match (NIaltid)
data = data: format(par)
data2 = data2: format(par)
Z.zwcommand(id, inst, cc, data)
ret, conf = Z.zwcommand(id, inst, cc, data2)
end,
extra_returns = {Config = function () return conf end}
},
SendConfig = function (d,args)
local cc = 112
local par,cmd,sz = args.parameter, args.command, args.size or 0
local data = "Set(%s,%s,%s)"
data = data: format(par,cmd,sz)
local altid = luup.devices[d].id
local id, inst = altid: match (NIaltid)
Z.zwcommand(id, inst, cc, data)
end,
}
SRV.TemperatureSensor = {
GetCurrentTemperature = {returns = {CurrentTemp = "CurrentTemperature"}},
}
--
SRV.SecuritySensor = {
SetArmed = function (d, args)
luup.variable_set (SID.SecuritySensor, "Armed", args.newArmedValue or '0', d)
end,
}
SRV.Color = {
-- args.newColorRGBTarget = "61,163,69"
SetColorRGB = function (d, args)
local rgb = { (args.newColorRGBTarget or ''): match "^(%d+),(%d+),(%d+)" }
if #rgb ~= 3 then return end
-- find our child devices...
local c = {}
for i,dev in pairs (luup.devices) do
if dev.device_num_parent == d then
c[#c+1] = {devNo = i, altid = dev.id}
end
end
table.sort (c, function (a,b) return a.altid < b.altid end)
if #c < 5 then return end
-- assume the order M0 M1 R G B (w)
for i = 1,3 do
_log ("setting: " .. rgb[i])
local level = math.floor ((rgb[i]/256)^2 * 100) -- map 0-255 to 0-100, with a bit of gamma
SRV.Dimming.SetLoadLevelTarget (c[i+2].devNo, {newLoadlevelTarget = level})
end
end,
}
SRV.DoorLock = {
SetTarget = function (d, args)
local value = open_or_close (args.newTargetValue)
local altid = luup.devices[d].id
altid = altid: match (NIaltid) and altid.."-98" or altid
Z.command (altid, value)
end,
}
SRV.EnergyMetering = {
ResetKWH = function (d)
local altid = luup.devices[d].id
local id, inst = altid: match (NIaltid)
local cc = 50 --command class
local cmd = "Reset()"
Z.zwcommand(id, inst, cc, cmd)
end,
}
SRV.GenericSensor = { }
SRV.HumiditySensor = { }
SRV.LightSensor = { }
-- returns the first n bits of the binary representation of x
local function num2bits (x, n)
local b = {}
for i = 1,n do b[i] = x % 2; x = (x - b[i]) / 2 end
return b
end
-- assemble number from binary array representation
local function bits2num (b)
local d = 0
for i = #b,1,-1 do d = d + d + b[i] end
return d
end
-- see: https://community.getvera.com/t/leviton-scene-controller-questions/172155
-- also: http://wiki.micasaverde.com/index.php/Leviton_LED_Debugging
SRV.SceneControllerLED = {
-- newValue = 0,1,2 or 3 where 0=off, 1=green, 2=red, 3=orange (red and green)
-- Indicator = 1-4, or 5 to set all to same colour
-- LightSettings bits are arranged as: MSB RRRRGGGG LSB
-- 43214321 corresponding button number
-- 2020.04.05 thanks to @rafale77 for explaining how this works!
SetLight = function (d, args)
local curled = luup.variable_get(SID.SceneControllerLED, "LightSettings", d) or 0
local curbit = num2bits (curled, 8) -- extract 8 LSBs
local colbit = num2bits (args.newValue, 2) -- extract 2 LSBs
local indicator = tonumber(args.Indicator)
for _, lamp in ipairs (indicator==5 and {1,2,3,4} or {indicator}) do
curbit[lamp] = colbit[1] -- green LED
curbit[lamp + 4] = colbit[2] -- red LED
end
local led = bits2num(curbit)
luup.variable_set(SID.SceneControllerLED, "LightSettings", led, d)
local altid = luup.devices[d].id
local id = altid: match (NIaltid)
local cc = 145 --command class
local data = "[%s,0,29,13,1,255,%s,0,0,10]"
data = data: format(cc,led)
Z.zwsend(id,data)
end,
}
SRV.WindowCovering = {
---------------
-- 2020.03.25 rafale77 Additions
--
Up = function (d)
luup.variable_set (SID.SwitchPower, "Target", '1', d)
luup.variable_set (SID.Dimming, "LoadLevelTarget", "100", d)
local altid = luup.devices[d].id
altid = altid: match (NIaltid) and altid.."-38" or altid
Z.command (altid, "up")
end,
Down = function (d)
luup.variable_set (SID.SwitchPower, "Target", '0', d)
luup.variable_set (SID.Dimming, "LoadLevelTarget", '0', d)
local altid = luup.devices[d].id
altid = altid: match (NIaltid) and altid.."-38" or altid
Z.command (altid, "down")
end,
Stop = function (d)
luup.variable_set (SID.SwitchPower, "Target", '1', d)
local val = luup.variable_get (SID.Dimming, "LoadLevelStatus", d)
luup.variable_set (SID.Dimming, "LoadLevelTarget", val, d)
local altid = luup.devices[d].id
altid = altid: match (NIaltid) and altid.."-38" or altid
Z.command (altid, "stop")
end,
}
SRV.Unknown = { } -- "catch-all" service
------------
--
-- Thermostat info
--
-- D_HVAC_ZoneThermostat1.xml uses these default serviceIds and variables...
SRV.HVAC_FanOperatingMode = {
-- Auto Low,On Low,Auto High,On High,Auto Medium,On Medium,Circulation,Humidity and circulation,Left and right,Up and down,Quite
SetMode = function (d, args)
local value = args.NewMode
local altid = luup.devices[d].id
local id, inst = altid: match (NIaltid)
local cc = 68 --command class
local sid = SID.HVAC_FanOperatingMode
local VtoZ = {Auto = "Set(1,0)", ContinuousOn = "Set(1,1)", PeriodicOn = "Set(1,0)"}
local cmd = VtoZ[value]
if cmd then
Z.zwcommand(id, inst, cc, cmd)
luup.variable_set (sid, "Mode", value, d)
end
end,
GetMode = { returns = {CurrentMode = "Mode" } },
GetFanStatus = { returns = {CurrentStatus = "FanStatus" } },
}
SRV.HVAC_OperatingState = { --[[
--["66"] Operating_state
-- ["67"] -- Setpoint
--Setpoint
-- Heating,Cooling,Furnace,Dry Air,Moist Air,Auto Change Over,Energy Save Heating,Energy Save Cooling,Away Heating,Away Cooling,Full Power
urn:micasaverde-com:serviceId:HVAC_OperatingState1,ModeState=Off
<allowedValue>Idle</allowedValue>
<allowedValue>Heating</allowedValue>
<allowedValue>Cooling</allowedValue>
<allowedValue>FanOnly</allowedValue>
<allowedValue>PendingHeat</allowedValue>
<allowedValue>PendingCool</allowedValue>
<allowedValue>Vent</allowedValue>
--]]
}
SRV.HVAC_UserOperatingMode = {
SetModeTarget = function (d, args)
local valid = {Off = true, AutoChangeOver = true, CoolOn = true, HeatOn = true}
local value = args.NewModeTarget
local altid = luup.devices[d].id
local id, inst = altid: match (NIaltid)
local cc = 64 --command class
local sid = SID.HVAC_UserOperatingMode
if valid[value] then
local VtoZ = {Off = "Set(0)", HeatOn = "Set(1)", CoolOn = "Set(2)", AutoChangeOver = "Set(3)"}
local cmd = VtoZ[value]
Z.zwcommand(id, inst, cc, cmd)
luup.variable_set (sid, "ModeTarget", value, d)
luup.variable_set (sid, "ModeStatus", value, d) -- assume it get set... can't read back!
end
end,
-- Off,Heat,Cool,Auto,Auxiliary,Resume,Fan Only,Furnace,Dry Air,Moist Air,Auto Change Over,
-- Energy Save Heat,Energy Save Cool,Away Heat,Away Cool,Full Power,Manufacturer Specific
}
SRV.FanSpeed = { --[[
urn:upnp-org:serviceId:FanSpeed1,FanSpeedTarget=0
urn:upnp-org:serviceId:FanSpeed1,FanSpeedStatus=0
urn:upnp-org:serviceId:FanSpeed1,DirectionTarget=0
urn:upnp-org:serviceId:FanSpeed1,DirectionStatus=0
<name>SetFanSpeed</name>
<name>NewFanSpeedTarget</name>
<relatedStateVariable>FanSpeedTarget</relatedStateVariable>
<name>GetFanSpeed</name>
<name>CurrentFanSpeedStatus</name>
<relatedStateVariable>FanSpeedStatus</relatedStateVariable>
<name>GetFanSpeedTarget</name>
<name>CurrentFanSpeedTarget</name>
<relatedStateVariable>FanSpeedTarget</relatedStateVariable>
<name>SetFanDirection</name>
<name>NewDirectionTarget</name>
<relatedStateVariable>DirectionTarget</relatedStateVariable>
<name>GetFanDirection</name>
<name>CurrentDirectionStatus</name>
<relatedStateVariable>DirectionStatus</relatedStateVariable>
<name>GetFanDirectionTarget</name>
<name>CurrentDirectionTarget</name>
<relatedStateVariable>DirectionTarget</relatedStateVariable>
--]]
}
local function SetCurrentSetpoint (sid, d, args)
local level = args.NewCurrentSetpoint
if level then
luup.variable_set (sid, "CurrentSetpoint", level, d)
local value = "exact?level=" .. level
local altid = luup.devices[d].id
if altid: match (NIaltid) then
local suffix = {
[SID.TemperatureSetpoint] = "-67",
[SID.TemperatureSetpoint1_Heat] = "-67-1",
[SID.TemperatureSetpoint1_Cool] = "-67-2",
}
altid = altid .. (suffix[sid] or '')
Z.command (altid, value)
end
end
end
SRV.TemperatureSetpoint = {
GetCurrentSetpoint = {returns = {CurrentSP = "CurrentSetpoint"}},
GetSetpointAchieved = {returns = {CurrentSPA = "SetpointAchieved"}},
SetCurrentSetpoint = function (...)
return SetCurrentSetpoint (SID.TemperatureSetpoint, ...)
end
}
local function shallow_copy (x)
local y = {}
for a,b in pairs (x) do y[a] = b end
return y
end
-- these copies MUST be separate tables, since they're used to index the SID table
SRV.TemperatureSetpoint1_Heat = shallow_copy (SRV.TemperatureSetpoint)
SRV.TemperatureSetpoint1_Heat.SetCurrentSetpoint = function (...)
return SetCurrentSetpoint (SID.TemperatureSetpoint1_Heat, ...)
end
SRV.TemperatureSetpoint1_Cool = shallow_copy (SRV.TemperatureSetpoint)
SRV.TemperatureSetpoint1_Cool.SetCurrentSetpoint = function (...)
return SetCurrentSetpoint (SID.TemperatureSetpoint1_Cool, ...)
end
----------------------------------------------------
--
-- COMMAND CLASSES - virtual device updates
--
-- CC contains:
-- updater = a function to update device variables on ZWay changes
-- files = a data structure containing {upnp_file, serviceId, json_file}
-- and, optionally, alternatives for specified scales (sub-classes)
--
local CC = { -- command class object
-- scene controller, also used for CC ["1"]
["0"] = {
updater = function (d, inst, meta)
local dev = luup.devices[d]
-- scene controller
if dev.attributes.device_file == DEV.controller then
local click = inst.updateTime
if click ~= meta.click then -- force variable updates
local scene = meta.scale
local time = os.time()
luup.variable_set (SID.SceneController, "sl_SceneActivated", scene, d)
luup.variable_set (SID.SceneController, "LastSceneTime",time, d)
meta.click = click
end
else
-- catch-all
-- local message = "no update for device %d [%s] %s %s"
-- log (message: format (d, inst.id, inst.deviceType or '?', (inst.metrics or {}).icon or ''))
--...
end
end,
files = { nil, SID.HaDevice }, -- device, service, json files
},
-- dumb switch, like ZWave.me battery switch
["1"] = {
updater = function () end, -- dummy stub to be assigned at end of CC table
files = { nil, SID.HaDevice },
},
-- binary switch
["37"] = {
updater = function (d, inst, meta)
setVar ("Status",on_or_off (inst.metrics.level), meta.service, d)
end,
files = { "D_BinaryLight1.xml", SID.SwitchPower },
},
-- multilevel switch
["38"] = {
updater = function (d, inst, meta)
local level = tonumber (inst.metrics.level) or 0
setVar ("LoadLevelStatus", level, meta.service, d)
local status = (level > 0 and "1") or "0"
setVar ("Status", status, SID.SwitchPower, d)
end,
files = { "D_DimmableLight1.xml", SID.Dimming },
},
-- Scene Controller Configuration
["45"] = {
updater = function (d, inst)
d, inst = d, inst
end,
-- Leviton Zone/scene controller
files = { "D_SceneControllerLED1.xml", SID.SceneControllerLED, "D_SceneControllerLED1.json"},
},
-- binary sensor
["48"] = {
updater = function (d, inst)
local sid = SID.SecuritySensor
local tripped = on_or_off (inst.metrics.level)
local old = getVar ("Tripped", sid, d)
local armed = getVar ("Armed", sid, d)
local armtrip = false
setVar ("Tripped", tripped, sid, d)
if tripped == "1" and tripped ~= old then setVar ("LastTrip", os.time(), sid, d) end
if armed == "1" and tripped == "1" then armtrip = true end
setVar ("ArmedTripped", armtrip and "1" or "0" , sid, d)
end,
files = { "D_MotionSensor1.xml", SID.SecuritySensor, -- SensorBinary
["1"] = { nil, nil, "D_MotionSensor1.json" }, -- 1 "Glass Break or Motion Sensor"
["2"] = {"D_SmokeSensor1.xml"}, -- 2 "Smoke"
["3"] = {"D_SmokeSensor1.xml", nil, "D_SmokeCoSensor1.json"}, -- 3 "CO"
-- 4 "CO2"
-- 5 "Heat"
["6"] = { "D_FloodSensor1.xml", nil, "D_FloodSensor1.json" }, -- 6 "Water"
-- 7 "Freeze"
-- 8 "Tamper"
-- 9 "Aux"
["10"] = { "D_DoorSensor1.xml" }, -- 10 "Door/Window"
-- 11 "Tilt"
-- 12 "Motion"
-- 13 "Glass Break"
-- 14 "First supported Sensor Type"
},
},
-- multilevel sensor
["49"] = {
updater = function (d, inst, meta) -- TODO: more to do here to sub-type?
local sensor_variable_name = {
[SID.TemperatureSensor] = "CurrentTemperature",
[SID.EnergyMetering] = "W", -- 2020.03.05 "Watts" conflicts with meter "50-2" if both present
}
local var = sensor_variable_name[meta.service] or "CurrentLevel"
local value = inst.metrics.level
local round = "%0.4f"
value = tonumber(round: format (value) ) -- 2020.02.22 TODO: why are some values not rounded?
setVar (var, value, meta.service, d)
end,
files = { "D_GenericSensor1.xml", SID.GenericSensor, -- generic values for any unknown
["1"] = { "D_TemperatureSensor1.xml", SID.TemperatureSensor }, -- scale: {"C","F"}
["2"] = { "D_GenericSensor1.xml", SID.GenericSensor }, -- scale: {"","%"}
["3"] = { "D_LightSensor1.xml", SID.LightSensor}, -- scale: {"%","Lux"}
["4"] = { "D_PowerMeter1.xml", SID.EnergyMetering}, -- scale: {"W","Btu/h"}
["5"] = { "D_HumiditySensor1.xml", SID.HumiditySensor}, -- scale: {"%","Absolute humidity"}
["27"] = { "D_LightSensor1.xml", SID.LightSensor, "D_UVSensor1.json" }
},
--[[