-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfibaroapiHC3.lua
9608 lines (8808 loc) · 341 KB
/
fibaroapiHC3.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
--[[
FibaroAPI HC3 SDK
Copyright (c) 2020 Jan Gabrielsson
Email: [email protected]
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Contributions & bugfixes:
- @petergebruers, forum.fibaro.com
- @tinman, forum.fibaro.com
- @10der, forum.fibaro.com
- @rangee, forum.fibaro.com
- @petrkl12, forum.fibaro.com
Sources included:
json -- Copyright (c) 2019 rxi
persistence -- Copyright (c) 2010 Gerhard Roethlin
file functions -- Credit pkulchenko - ZeroBraneStudio
copas -- Copyright 2005-2016 - Kepler Project (www.keplerproject.org)
timerwheel -- Credit https://github.com/Tieske/timerwheel.lua/blob/master/LICENSE
binaryheap -- Copyright 2015-2019 Thijs Schreijer
--]]
local FIBAROAPIHC3_VERSION = "0.315"
assert(_VERSION:match("(%d+%.%d+)") >= "5.3","fibaroapiHC3.lua needs Lua version 5.3 or higher")
--[[
Best way is to conditionally include this code at the top of your lua file
if dofile and not hc3_emulator then
hc3_emulator = {
name = "My QA", -- Name of QA
poll = 2000, -- Poll HC3 for triggers every 2000ms
--offline = true,
quickVars = {["Hue_User"]="$CREDS.Hue_user",["Hue_IP"]=$CREDS.Hue_IP}
}
dofile("fibaroapiHC3.lua")
end--hc3
Then define another file, credentials.lua, where we define credentials to access the HC3 etc:
return {
ip = <IP>,
user = <username>,
pwd = <password>
}
This file will be read by the emulator when it starts up and the table returned
will be assigned to hc3_emulator.credentials.
hc3_emulator.credentials.ip,hc3_emulator.credentials.user,hc3_emulator.credentials.pwd will
be used by the emulator to authorize calls to the HC3.
This way the credentials are not visible in your code and you will not accidently upload them :-)
You can also predefine quickvars that are accessible with self:getVariable() when your code starts up.
quickVar names starting with '$CREDS.' will be replaced with values from hc3_emulator.credentials.
--]]
--[[
Common hc3_emulator parameters:
---------------------------------
hc3_emulator.name=<string> -- Name of QuickApp, default "QuickApp"
hc3_emulator.id=<QuickApp ID> -- ID of QuickApp. Normally let emulator asign ID. (usually 999 for non-proxy QA)
hc3_emulator.poll=<poll interval> -- Time in ms to poll the HC3 for triggers. default false
hc3_emulator.type=<type> -- default "com.fibaro.binarySwitch"
hc3_emulator.speed=<speedtime> -- If not false, time in hours the emulator should speed. default false
hc3_emulator.proxy=<boolean> -- If true create HC3 procy. default false
hc3_emulator.UI=<UI table> -- Table defining buttons/sliders/labels. default {}
hc3_emulator.quickVars=<table> -- Table with values to assign quickAppVariables. default {},
hc3_emulator.offline=<boolean> -- If true run offline with simulated devices. default false
hc3_emulator.autocreate=<boolean> -- Autocreate local resources
hc3_emulator.breakOnInit=<boolean> -- Tries to set breakpoint on QuickApp:onInit (mobdebug)
hc3_emulator.breakOnLoad=<boolean> -- Tries to set breakpoint on first line in loaded file (mobdebug)
hc3_emulator.breakOnError=<boolean> -- Tries to break after error (makes it easier to look at call stack etc)
hc3_emulator.apiHTTPS=<boolean> -- If true use https to call HC3 REST apis. default false
hc3_emulator.deploy=<boolean>, -- If true deploy code to HC3 instead of running it. default false
hc3_emulator.assetDirectory=<string> -- Directory where assets shoud be downloaded (ZBS). Default ~/.zbstudio/hc3emu
hc3_emulator.resourceFile=<string> -- When doing a resource download, use this file as default.
hc3_emulator.db=<boolean/string>, -- If true load a "resource download" from hc3_emulator.resourceFile or string
hc3_emulator.htmlDebug=<boolean> -- Try to convert html tags to ZBS console cmds (i.e. colors)
hc3_emulator.terminalPort=<boolean> -- Port used for socket/telnet interface
hc3_emulator.webPort=<number> -- Port used for web UI and events from HC3
hc3_emulator.HC3_logmessages=<boolean> -- Defult false. If true will push log messages to the HC3 also.
hc3_emulator.supressTrigger -- Make the emulator ignore certain events from the HC3, like = PluginChangedViewEvent
hc3_emulator.negativeTimeout=<boolean> -- Allow specification of negative timeout for setTimeout (will fire immediatly)
hc3_emulator.strictClass=<boolean> -- Strict class semantics, requiring initializers
hc3_emulator.consoleColors=<table> -- Maps fibaro.debug/self:debug etc to color (debug.color enables color debugging)
hc3_emulator.sysConsoleColors=<table> -- Maps colors used for system logs
hc3_emulator.userdataType=<boolean> -- If true intercepts type(...) to return userdate for our Lua classes. Some apps tests this...
hc3_emulator.package=... -- Lua library paths (.path, .cpath)
Common hc3_emulator functions:
---------------------------------
hc3_emulator.setOffline(<boolean>,<boolean>) --
hc3_emulator.getIPaddress() -- Return HC3 IP address
hc3_emulator.prettyJsonFormat(<table>) -- Return json formatted string of Lua table
hc3_emulator.postTrigger(<event>,[<time ms>]) -- Posts a trigger to the emulator...
hc3_emulator.loadScene(...) -- Load scene from file or HC3...
hc3_emulator.loadQA(...) -- Load QA from file or HC3...
hc3_emulator.downloadPlugin() -- (ZBS). Default ~/.zbstudio/packages
hc3_emulator.downloadAssets() -- (ZBS). Default ~/.zbstudio/hc3emu
hc3_emulator.downloadResources([<filename>]) -- Downloads a "backup" of HC3 resources
hc3_emulator.loadResources([<filename>]) -- ...that can be loaded as "local" resources for the emulator.
Implemented APIs:
---------------------------------
fibaro.debug(type,str)
fibaro.warning(type,str)
fibaro.trace(type,str)
fibaro.error(type,str)
fibaro.call(deviceID, actionName, ...)
fibaro.getType(deviceID)
fibaro.getValue(deviceID, propertyName)
fibaro.getName(deviceID)
fibaro.get(deviceID,propertyName)
fibaro.getGlobalVariable(varName)
fibaro.setGlobalVariable(varName ,value)
fibaro.getRoomName(roomID)
fibaro.getRoomID(deviceID)
fibaro.getRoomNameByDeviceID(deviceID)
fibaro.getSectionID(deviceID)
fibaro.getIds(devices)
--fibaro.getAllDeviceIds()
fibaro.getDevicesID(filter)
fibaro.scene(action, sceneIDs)
fibaro.profile(profile_id, action)
fibaro.callGroupAction(action,args)
fibaro.alert(alert_type, user_ids, notification_content)
fibaro.alarm(partition_id, action)
fibaro.setTimeout(ms, func)
fibaro.clearTimeout(ref)
fibaro.emitCustomEvent(name)
fibaro.wakeUpDeadDevice
fibaro.sleep(ms) -- blocking wait...
net.HTTPClient()
net.TCPSocket()
net.UDPSocket()
net.WebSocketClient() -- needs extra download
net.WebSocketClientTls() -- needs extra download
mqtt.Client() -- needs extra download
api.get(call)
api.put(call <, data>)
api.post(call <, data>)
api.delete(call <, data>)
setTimeout(func, ms)
clearTimeout(ref)
setInterval(func, ms)
clearInterval(ref)
plugin.mainDeviceId
plugin.deleteDevice(deviceId)
plugin.restart(deviceId)
plugin.getProperty(id,prop)
plugin.getChildDevices(id)
plugin.createChildDevice(prop)
class QuickAppBase
class QuickApp
class QuickAppChild
QuickApp:onInit() -- called at startup if defined
QuickApp - self:setVariable(name,value)
QuickApp - self:getVariable(name)
QuickApp - self:debug(...)
QuickApp - self:trace(...)
QuickApp - self:warning(...)
QuickApp - self:error(...)
QuickApp - self:updateView(elm,type,value)
QuickApp - self:updateProperty()
QuickApp - self:createChildDevice(props,device)
QuickApp - self:initChildDevices(table)
QuickApp - self:removeChildDevice(id)
sourceTrigger - scene trigger
Scene events:
{type='alarm', property='armed', id=<id>, value=<value>}
{type='alarm', property='breached', id=<id>, value=<value>}
{type='alarm', property='homeArmed', value=<value>}
{type='alarm', property='homeBreached', value=<value>}
{type='weather', property=<prop>, value=<value>, old=<value>}
{type='global-variable', property=<name>, value=<value>, old=<value>}
{type='device', id=<id>, property=<property>, value=<value>, old=<value>}
{type='device', id=<id>, property='centralSceneEvent', value={keyId=<value>, keyAttribute=<value>}}
{type='device', id=<id>, property='accessControlEvent', value=<value>}
{type='device', id=<id>, property='sceneActivationEvent', value=<value>}
{type='profile', property='activeProfile', value=<value>, old=<value>}
{type='custom-event', name=<name>}
json.encode(expr)
json.decode(string)
hc3_emulator.createQuickApp{ -- creates and deploys QuickApp on HC3
name=<string>,
type=<string>,
code=<string>,
UI=<table>,
quickVars=<table>,
dryrun=<boolean>
}
hc3_emulator.createProxy(<name>,<type>,<UI>,<quickVars>) -- create QuickApp proxy on HC3 (usually called with
hc3_emulator.post(ev,t) -- post event/sourceTrigger
--]]
local _debugFlags = {
fibaro=false, -- Logs calls to fibaro api
trigger=true, -- Logs incoming triggers from HC3 or internal emulator
timers=nil, -- Logs low level info on timers being called, very noisy.
refreshloop=false, -- Logs evertime refreshloop receives events
mqtt=true, -- Logs mqtt message and callbacks
http=false, -- Logs all net.HTTPClient():request. ALso includes the time the request took
api=false, -- Logs all api request to the HC3
onAction=true, -- Logs call to onAction (incoming fibaro.calls etc
UIEvent=true, -- Logs incoming UIEvents, from GUI elements
zbsplug=true, -- Logs call from ZBS plugin calls
webServer=false, -- Logs requests to /web/ including headers
webServerReq=false, -- Logs requests to /web/ excluding headers
files=false, -- Logs files loaded and run
color=true, -- Logs in console using ANSI colors (see hc3_emulator.consoleColors for mapping)
locl=true, -- Log creation of local devices
breakOnError=false, -- Logs files loaded and run
breakOnLoad=false, -- Sets breakpoint on first line of file loaded
ctx=false, -- Logs Lua context switches
timersSched=false, -- Logs when timers are scheduled
timersWarn=0.500, -- Logs when timers are called late or setTimeout with time < 0
timersExtra=true, -- Adds extra info to timers, like from where it's called and definition of function (small time penalty)
}
local function merge(t1,t2)
if type(t1)=='table' and type(t2)=='table' then for k,v in pairs(t2) do if t1[k]==nil then t1[k]=v else merge(t1[k],v) end end end
return t1
end
-- luacheck: globals ignore QuickAppBase QuickApp QuickAppChild quickApp hc3_emulator os
QuickApp,QuickAppBase,QuickAppChild = nil,nil,nil
local function DEF(x,y) if x==nil then return y else return x end end
hc3_emulator = hc3_emulator or {}
hc3_emulator.version = FIBAROAPIHC3_VERSION
hc3_emulator.credentialsFile = hc3_emulator.credentialsFile or "credentials.lua"
hc3_emulator.resourceFile = DEF(hc3_emulator.resourceFile,"HC3resources.data")
hc3_emulator.HC3dir = hc3_emulator.HC3dir or "HC3files" -- not used
hc3_emulator.backupDir = hc3_emulator.backupDir or "/tmp" -- not used
hc3_emulator.backDirFmt = "%m-%d-%Y %H.%M.%S" -- not used
hc3_emulator.conditions = false
hc3_emulator.actions = false
hc3_emulator.offline = DEF(hc3_emulator.offline,false)
hc3_emulator.autoCreate = DEF(hc3_emulator.autoCreate,hc3_emulator.offline)
hc3_emulator.emulated = true
hc3_emulator.debug = merge(hc3_emulator.debug or {},_debugFlags)
hc3_emulator.runSceneAtStart = false
hc3_emulator.webPort = hc3_emulator.webPort or 6872
hc3_emulator.terminalPort = hc3_emulator.terminalPort or 6972
hc3_emulator.quickVars = hc3_emulator.quickVars or {}
hc3_emulator.htmlDebug = DEF(hc3_emulator.htmlDebug,true)
hc3_emulator.supressTrigger = {["PluginChangedViewEvent"] = true} -- Ignore noisy triggers...
hc3_emulator.negativeTimeout = DEF(hc3_emulator.negativeTimeout,true)
hc3_emulator.strictClass = true
hc3_emulator.HC3_logmessages = DEF(hc3_emulator.HC3_logmessages,false)
hc3_emulator.githubSrc = "https://raw.githubusercontent.com/jangabrielsson/EventRunner/master/"
hc3_emulator.deviceIDs = DEF(hc3_emulator.deviceIDs,9000)
hc3_emulator.emu = {}
hc3_emulator.emu.EMURUNNING = "HC3Emulator"
hc3_emulator.emu.EMURUNNING_INTERVAL = 4.0
_debugFlags = hc3_emulator.debug
do
local cr = loadfile(hc3_emulator.credentialsFile)
--hc3_emulator.credentials = hc3_emulator.credentials or {}
if cr then hc3_emulator.credentials = merge(hc3_emulator.credentials or {},cr() or {}) end
end
do
if type(package)=='table' then -- For VS.
-- See https://forum.fibaro.com/topic/49488-sdk-for-remote-and-offline-hc3-development/page/8/?tab=comments#comment-225963
if hc3_emulator.package then
package.path,package.cpath = package.path..";"..hc3_emulator.package.path, package.cpath..";"..hc3_emulator.package.cpath
else
package.path = package.path .. ";./libs/?.lua";
package.cpath = package.cpath .. ";./libs/?.dll";
end
end
local socket = require("socket") -- LuaSocket, these are the dependencies we have
local url = require("socket.url") -- LuaSocket
local headers = require("socket.headers") -- LuaSocket
local ltn12 = require("ltn12") -- LuaSocket
local mime = require("mime") -- LuaSocket
local lfs = require("lfs") -- LuaFileSystem,
-- optional require('mobdebug') -- Lua remote debugger
assert(socket and url and headers and ltn12 and mime and lfs,"Missing libraries")
local stat,mobdebug = pcall(function() return require('mobdebug') end) -- Load mobdebug if available to debug coroutines..
local fid = function() end
hc3_emulator.mobdebug = stat and mobdebug or {coro=fid, pause=fid, setbreakpoint=fid, on=fid, off=fid}
hc3_emulator.mobdebug.coro()
end
local profiler = nil
local function osExit()
if hc3_emulator.profile and profiler then
profiler.stop()
profiler.report("profiler.log")
end
os.exit(0,true)
end
collectgarbage("setpause",100)
collectgarbage("setstepmul",150)
-- Globals
-- luacheck: globals ignore LOG Log json assertf api net onAction onUIEvent
LOG,Log,json,assertf,api,net=nil,nil,nil,nil,nil,nil
local module,commandLines,terminals = {},{},{}
onAction,onUIEvent = nil,nil
-- luacheck: globals ignore Device class property getHierarchy Hierarchy
local function d2str(...) local r,s={...},{} for i=1,#r do if r[i]~=nil then s[#s+1]=tostring(r[i]) end end return table.concat(s," ") end
------------------- Contexts, QuickApps and Scenes -------------------------
local contexts = {}
setmetatable(contexts,{__mode='k'})
local function setContext(env)
local co = coroutine.running()
if _debugFlags.ctx then print("SC:",((env or _ENV).plugin or {}).mainDeviceId,tostring(co),tostring(env.quickApp)) end
contexts[co]=env or _ENV
end
local function getContext()
local co = coroutine.running()
local env = contexts[co] or {}
if _debugFlags.ctx then print("GC:",(env.plugin or {}).mainDeviceId,tostring(co),tostring(env.quickApp)) end
return env
end
setContext(_G) -- Start, main thread
-------------- Fibaro API functions ------------------
function module.Fibaro(hc3)
local self,fibaro = {},{version = "1.0.0"}
local Util,Trigger,Timer = hc3.module.Util
local copas,cache,safeDecode,urlencode,colorStr
local _debugFlags = hc3.debug
local format = string.format
local GET_DEVICE,GET_SCENE,GET_PROPERTY,GET_VARIABLE,PUT_VARIABLE,CALL_ACTION,POST_DEBUGMESSAGE
Log,LOG,json,api,net,assert,assertf=Log,LOG,json,api,net,assert,assertf
function self.initialise() --luacheck: ignore
Trigger,Timer = hc3.module.Trigger,hc3.module.Timer
cache,safeDecode,urlencode,colorStr = Trigger.cache,Util.safeDecode,Util.urlencode,Util.colorStr
copas = Timer.copas
local API = hc3.module.API
GET_DEVICE = API.GET_DEVICE
GET_SCENE = API.GET_SCENE
GET_PROPERTY = API.GET_PROPERTY
GET_VARIABLE = API.GET_VARIABLE
PUT_VARIABLE = API.PUT_VARIABLE
CALL_ACTION = API.CALL_ACTION
POST_DEBUGMESSAGE = API.POST_DEBUGMESSAGE
end
local function __assert_type(value,typeOfValue )
if type(value) ~= typeOfValue then -- Wrong parameter type, string required. Provided param 'nil' is type of nil
error(format("Wrong parameter type, %s required. Provided param '%s' is type of %s",
typeOfValue,tostring(value),type(value)),
3)
end
end
local function __fibaro_get_device(id) __assert_type(id,"number") return GET_DEVICE(nil,"/devices/"..id,id) end
local function __fibaro_get_devices() return api.get("/devices") end
local function __fibaro_get_room (id) __assert_type(id,"number") return api.get("/rooms/"..id) end
local function __fibaro_get_scene(id) __assert_type(id,"number") return GET_SCENE(nil,"/scenes/"..id,id) end
local function __fibaro_get_global_variable(name) __assert_type(name ,"string")
local c = cache.read('globals',0,name) or GET_VARIABLE(nil,"/globalVariables/"..name,name)
cache.write('globals',0,name,c)
return c
end
local function __fibaro_get_device_property(id ,prop)
__assert_type(id,"number")
__assert_type(prop,"string")
local c = cache.read('devices',id,prop) or GET_PROPERTY(nil,"/devices/"..id.."/properties/"..prop,id,prop)
cache.write('devices',id,prop,c)
return c
end
local function __fibaroSleep(ms)
__assert_type(ms,'number')
--local ctx = getContext()
--if ctx.getLock then ctx.getLock() end
copas.sleep(ms/1000.0)
--if ctx.releaseeLock then ctx.releaseLock() end
end
local function __fibaro_add_debug_message(tag,str,typ)
assert(str,"Missing tag for debug")
POST_DEBUGMESSAGE({message=str,messageType=typ,tag=tag},"/debugMessages")
end
function fibaro.debug(tag,...) __fibaro_add_debug_message(tag,d2str(...),"DEBUG") end
function fibaro.warning(tag,...) __fibaro_add_debug_message(tag,d2str(...),"WARNING") end
function fibaro.trace(tag,...) __fibaro_add_debug_message(tag,d2str(...),"TRACE") end
function fibaro.error(tag,...) __fibaro_add_debug_message(tag,d2str(...),"ERROR") end
function fibaro.getName(deviceID)
__assert_type(deviceID,'number')
local dev = __fibaro_get_device(deviceID)
return dev and dev.name
end
function fibaro.get(deviceID,propertyName)
local property = __fibaro_get_device_property(deviceID ,propertyName)
if property then return property.value, property.modified end
end
function fibaro.getValue(deviceID, propertyName) return (fibaro.get(deviceID , propertyName)) end
function fibaro.wakeUpDeadDevice(deviceID )
__assert_type(deviceID,'number')
fibaro.call(1,'wakeUpDeadDevice',deviceID)
end
function fibaro.call(deviceID, actionName, ...)
__assert_type(actionName ,"string")
if type(deviceID)=='table' then
for _,d in ipairs(deviceID) do fibaro.call(d, actionName, ...) end
else
__assert_type(deviceID ,"number")
local a = {args={},delay=0}
local args = {...}
for i,v in ipairs(args) do a.args[i]=v end
local res,stat = CALL_ACTION(a,"/devices/"..deviceID.."/action/"..actionName,deviceID,actionName)
if stat>202 then Log(LOG.ERROR,"Device %s does not exists - %s",deviceID,stat) end
return res
end
end
function fibaro.getType(deviceID)
local dev = __fibaro_get_device(deviceID)
return dev and dev.type or nil
end
function fibaro.getGlobalVariable(varName)
local globalVar = __fibaro_get_global_variable(varName)
if globalVar then return globalVar.value , globalVar.modified end
end
function fibaro.setGlobalVariable(name , value)
__assert_type(name ,"string")
local data = {["value"] = tostring(value) , ["invokeScenes"] = true}
PUT_VARIABLE(data,"/globalVariables/"..name,name)
end
function fibaro.emitCustomEvent(name) return api.post("/customEvents/"..name,{}) end
function fibaro.setTimeout(value, func) return Timer.setTimeout(func, value) end
function fibaro.clearTimeout(ref) return Timer.clearTimeout(ref) end
function fibaro.getRoomName(roomID)
__assert_type(roomID,'number')
local room = __fibaro_get_room(roomID)
return room and room.name
end
function fibaro.getRoomID(deviceID)
local dev = __fibaro_get_device(deviceID)
return dev and (dev.roomID or 0)
end
function fibaro.getRoomNameByDeviceID(deviceID)
local roomID = fibaro.getRoomID(deviceID)
return roomID == 0 and "unassigned" or fibaro.getRoomName(roomID)
end
function fibaro.getSectionID(deviceID)
local roomID = fibaro.getRoomID(deviceID)
return roomID == 0 and 0 or __fibaro_get_room(roomID).sectionID
end
function fibaro.getIds(devices)
local ids = {}
for _,a in pairs(devices) do
if a ~= nil and type (a) == 'table' and a['id'] ~= nil and a['id'] > 3 then
ids[#ids+1]=a['id']
end
end
return ids
end
function fibaro.getAllDeviceIds() return api.get('/devices/') end
function fibaro.getDevicesID(filter)
local function encode(s) return tostring(s) end -- urlencode(tostring(s)) end
if type(filter) ~= 'table' or (type(filter) == 'table' and next( filter ) == nil) then
return fibaro.getIds(__fibaro_get_devices())
end
local args = '/?'
for c,d in pairs(filter) do
if c == 'properties' and d ~= nil and type(d) == 'table' then
for a,b in pairs (d) do
if b == "nil" then
args = args..'property='..encode(a)..'&'
else
args = args..'property=['..encode(a)..','..encode(b)..']&'
end
end
elseif c == 'interfaces' and d ~= nil and type(d) == 'table' then
for _,b in pairs(d) do
args = args..'interface='..encode(b)..'&'
end
else
args = args..encode(c).."="..encode(d)..'&'
end
end
args = string.sub(args,1,-2)
return fibaro.getIds(api.get(urlencode('/devices'..args)))
end
function fibaro.scene(action, sceneIDs) -- execute or kill
__assert_type(sceneIDs,'table')
assert(action=='execute' or action=='kill',"fibaro.scene arguments mist be execute/kill")
for _,id in ipairs(sceneIDs) do api.post("/scenes/"..id.."/"..action,{}) end
end
function fibaro.profile(profile_id, action)
if hc3.codeType == 'QA' then
profile_id,action = action,profile_id
end
__assert_type(profile_id,'number')
__assert_type(action,'string')
return api.post("/profiles/"..action.."/"..profile_id,{})
end
function fibaro.callGroupAction(action,args)
__assert_type(action,'string')
__assert_type(args,'table')
local res,stat = api.post("/devices/groupAction/"..action,args)
return stat==202 and res.devices
end
function fibaro.alert(alertType, users, msg)
alertType = ({simplePush='simplePush',push='sendGlobalPushNotifications',email='sendGlobalEmailNotifications',sms='sendSms'})[alertType]
assert(alertType,"Missing alert type: 'push', 'email', 'sms'")
__assert_type(users,'table')
for _,u in ipairs(users) do fibaro.call(u,alertType,msg,"false") end
end
-- User PIN?
function fibaro.alarm(partition_id, action)
if action==nil then
action = partition_id
assert(action=='arm' or action=='disarm',"alarm action is 'arm' or 'disarm'")
if action=='arm' then
api.post("/alarms/v1/partitions/actions/arm",{})
elseif action=='disarm' then
api.delete("/alarms/v1/partitions/actions/arm",{})
end
else
assert(action=='arm' or action=='disarm',"alarm action is 'arm' or 'disarm'")
__assert_type(partition_id,'number')
if action=='arm' then
return api.post(format("/alarms/v1/partitions/%s/actions/arm",partition_id),{})
elseif action=='disarm' then
return api.delete(format("/alarms/v1/partitions/%s/actions/arm",partition_id),{})
end
end
end
function fibaro.__houseAlarm() end -- ToDo:
function fibaro.sleep(ms) __fibaroSleep(ms) end
fibaro.homeCenter = {
PopupService = {
publish = function(request)
return api.post("/popups",request)
end
},
climate = {
setClimateZoneToScheduleMode = fibaro.setClimateZoneToScheduleMode,
setClimateZoneToManualMode = fibaro.setClimateZoneToManualMode,
setClimateZoneToVacationMode = fibaro.setClimateZoneToVacationMode
},
SystemService = {
reboot = function() api.post("/service/reboot") end,
suspend = function() api.post("/service/suspend") end,
shutdown = function() api.post("/service/shutdown") end,
},
notificationService = {
publish = function(request)
request.canBeDeleted = true
request.canBeDeleted = true
return api.post('/notificationCenter', request)
end,
update = function(id, request)
__assert_type(id, "number")
request.canBeDeleted = true
return api.put('/notificationCenter/'..id, request)
end,
remove = function(id)
__assert_type(id, "number")
return api.delete('/notificationCenter/'..id)
end
},
}
local fjson = Util.prettyJson
local function patchFibaro(name)
local oldF,flag = fibaro[name],"f"..name
fibaro[name] = function(...)
local args = {...}
local res = {oldF(...)}
if _debugFlags[flag] then
args = #args==0 and "" or fjson(args):sub(2,-2)
Log(LOG.LOG,"fibaro.%s(%s) => %s",name,args,#res==0 and "nil" or #res==1 and res[1] or res)
end
return table.unpack(res)
end
end
local fibaroFunsToPatch = {
"call","getType","getValue","getName","get","getGlobalVariable","setGlobalVariable","getRoomName",
"getRoomID","getRoomNameByDeviceID","getSectionID","getIds","getDevicesID","scene","profile","callGroupAction",
"alert","alarm","setTimeout","clearTimeout","emitCustomEvent","wakeUpDeadDevice","sleep"
}
function self.traceFibaro()
for _,name in ipairs(fibaroFunsToPatch) do patchFibaro(name) end
_debugFlags["f".."call"]=true
end
self.fibaro = fibaro
self.__assert_type = __assert_type
self.__fibaro_get_device = __fibaro_get_device
self.__fibaro_get_devices = __fibaro_get_devices
self.__fibaro_get_room = __fibaro_get_room
self.__fibaro_get_scene = __fibaro_get_scene
self.__fibaro_get_global_variable = __fibaro_get_global_variable
self.__fibaro_get_device_property = __fibaro_get_device_property
self.__fibaro_add_debug_message = __fibaro_add_debug_message
self.__fibaroSleep = __fibaroSleep
return self
end--module Fibaro
------------ HTTP support ---------------------
-- An emulation of Fibaro's net.HTTPClient, net.TCPSocket() and net.UDPSocket()
function module.HTTP(hc3)
local selfHTTP = {}
local Util,Trigger,Timer = hc3.module.Util
local _debugFlags = hc3.debug
local urlencode,copas=Util.urlencode
Log,LOG,json,api,net,assert,assertf=Log,LOG,json,api,net,assert,assertf
local socket = require("socket") -- LuaSocket, these are the dependencies we have
local ltn12 = require("ltn12") -- LuaSocket
function selfHTTP.initialise() --luacheck: ignore
Trigger,Timer = hc3.module.Trigger,hc3.module.Timer
copas = Timer.copas
end
local function interceptLocal(url,options,success,_) --error)
if url:match("://(127%.0%.0%.1)[:/]") then
local refresh = url:match("/api/refreshStates%?last=(%d+)")
if refresh then
local state = Trigger.refreshStates.getEvents(tonumber(refresh))
if success then success({status=200,data=json.encode(state)}) end
return true
end
url = url:gsub("(://127%.0%.0%.1)","://"..(hc3.credentials.ip or "127.0.0.1"))
if url:match("://.-:11111/") then
url = url:gsub("(:11111)","")
options.headers = options.headers or {}
options.headers['Authorization'] = hc3.BasicAuthorization or ""
end
end
return false,url
end
local net = net or {}
local outstanding = 0
function net.HTTPClient(i_options)
local self = {}
function self:request(url,args)
if outstanding > 30 then
Log(LOG.WARNING,"Number of outstanding http requests %s",outstanding)
end
local req,resp = {},{}; for k,v in pairs(i_options or {}) do req[k]=v end
for k,v in pairs(args.options or {}) do req[k]=v end
req.timeout = req.timeout or (i_options and i_options.timeout)
if req.timeout then req.timeout = req.timeout / 1000.0 end -- timeout in ms -> s
local s,u = interceptLocal(url,req,args.success,args.error)
if s then return else url=u end
req.url = url
req.headers = req.headers or {}
req.sink = ltn12.sink.table(resp)
if req.data then
req.headers["Content-Length"] = #req.data
req.source = ltn12.source.string(req.data)
else req.headers["Content-Length"]=0 end
local ctx = getContext()
local sync = i_options and i_options.sync==true
if not sync then assert(ctx._getLock,"net.HTTPClient() not called from QuickApp/Scene") end
local call = sync and (function(f) f() end) or ctx.setTimeout
call(function()
local t1 = os.milliTime()
if not sync then ctx._releaseLock() end -- release lock so other timers in the QA can run during the request
outstanding = outstanding +1
local _,status,headers = copas.http.request(req)
outstanding = outstanding -1
if not sync then ctx._getLock() end
if _debugFlags.http then Log(LOG.LOG,"httpRequest(%.03fs): %s %s %s",os.milliTime()-t1,req.method,url,req.data or "") end
if tonumber(status) and status >= 200 and status < 400 then
if args.success then
call(function()
args.success(
{status=status, headers=headers, data=table.concat(resp)})
end,
0,"HTTP Success handler",nil,nil,_debugFlags.timersExtra and debug.getinfo(args.success,"Sl")
)
end
elseif args.error then call(function() args.error(status) end,0,"HTTP Error handler") end
end, 0, "HTTPClient", ctx)
return nil
end
local pstr = "HTTPClient object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function() return pstr end})
return self
end
function net.TCPSocket(opts)
local self = { opts = opts or {} }
local sock --= socket.tcp()
function self:connect(ip, port, opts)
for k,v in pairs(self.opts) do opts[k]=v end
local err
sock,err = socket.connect(ip,port)
if err==nil and opts and opts.success then sock:settimeout(0) opts.success()
elseif opts and opts.error then opts.error(err) end
end
function self:read(opts) -- I interpret this as reading as much as is available...?
copas.addthread(function()
local data,res = {}
local b,err = copas.receive(sock,1)
if not err then
data[#data+1]=b
while socket.select({sock},nil,0.1)[1] do
b,err = copas.receive(sock,1)
if b then data[#data+1]=b else break end
end
res = table.concat(data)
end
if res and opts and opts.success then opts.success(res)
elseif res==nil and opts and opts.error then opts.error(err) end
end)
end
local function check(data,del)
local n = #del
for i=1,#del do if data[#data-n+i]~=del:sub(i,i) then return false end end
return true
end
function self:readUntil(delimiter, opts) -- Read until the cows come home, or closed
copas.addthread(function()
local data,ok,res = {},true,nil
local b,err = copas.receive(sock,1)
if not err then
data[#data+1]=b
if not check(data,delimiter) then
ok = false
while true do
b,err = copas.receive(sock,1)
if b then
data[#data+1]=b
if check(data,delimiter) then ok=true break end
else break end
end -- while
end
if ok then
for i=1,#delimiter do table.remove(data,#data) end
res = table.concat(data)
end
end
if res and opts and opts.success then opts.success(res)
elseif res==nil and opts and opts.error then opts.error(err) end
end)
end
function self:write(data, opts)
copas.addthread(function()
local res,err = copas.send(sock,data)
if res and opts and opts.success then opts.success(res)
elseif res==nil and opts and opts.error then opts.error(err) end
end)
end
function self:close() sock:close() end
local pstr = "TCPSocket object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function() return pstr end})
return self
end
function net.UDPSocket(opts)
local self = { opts = opts or {} }
local sock = socket.udp()
if self.opts.broadcast~=nil then
sock:setsockname(Util.getIPaddress(), 0)
sock:setoption("broadcast", self.opts.broadcast)
end
if opts.timeout~=nil then sock:settimeout(opts.timeout / 1000) end
function self:sendTo(datagram, ip,port, callbacks) -- udp sendTo doesn't block.
local stat, res = copas.sendto(sock, datagram, ip, port)
if stat and callbacks.success then
pcall(callbacks.success,1)
elseif stat==nil and callbacks.error then
pcall(callbacks.error,res)
end
end
function self:bind(ip,port) sock:setsockname(ip, port) end
function self:receive(callbacks)
copas.addthread(function()
local stat, res = copas.receivefrom(sock,ip,port)
if stat and callbacks.success then
pcall(callbacks.success,stat, res)
elseif stat==nil and callbacks.error then
pcall(callbacks.error,res)
end
end)
end
function self:close() sock:close() end
local pstr = "UDPSocket object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function() return pstr end})
return self
end
-------------- MQTT support ---------------------
local function safeJson(e)
if type(e)=='table' then
for k,v in pairs(e) do e[k]=safeJson(v) end
return e
elseif type(e)=='function' or type(e)=='thread' or type(e)=='userdata' then return tostring(e)
else return e end
end
local mqtt
local stat,_mqtt=pcall(function() return require("mqtt") end)
if stat then
mqtt={
Client = {},
QoS = {EXACTLY_ONCE=1},
MSGT = {
CONNECT = 1,
CONNACK = 2,
PUBLISH = 3,
PUBACK = 4,
PUBREC = 5,
PUBREL = 6,
PUBCOMP = 7,
SUBSCRIBE = 8,
SUBACK = 9,
UNSUBSCRIBE = 10,
UNSUBACK = 11,
PINGREQ = 12,
PINGRESP = 13,
DISCONNECT = 14,
AUTH = 15,
},
MSGMAP = {
[9]='subscribed',
[11]='unsubscribed',
[4]='published', -- Should be onpublished according to doc?
[14]='closed',
}
}
function mqtt.Client.connect(uri, options)
options = options or {}
local args = {}
args.uri = uri
args.uri = string.gsub(uri, "mqtt://", "")
args.username = options.username
args.password = options.password
args.clean = options.cleanSession
if args.clean == nil then args.clean=true end
args.will = options.lastWill
args.keep_alive = options.keepAlivePeriod
args.id = options.clientId
--cafile="...", certificate="...", key="..." (default false)
if options.clientCertificate then -- Not in place...
args.secure = {
certificate= options.clientCertificate,
cafile = options.certificateAuthority,
key = "",
}
end
local _client = _mqtt.client(args)
local client={ _client=_client, _handlers={} }
function client:addEventListener(message,handler)
self._handlers[message]=handler
end
function client:subscribe(topic, options)
options = options or {}
local args = {}
args.topic = topic
args.qos = options.qos or 0
args.callback = options.callback
return self._client:subscribe(args)
end
function client:unsubscribe(topics, options)
if type(topics)=='string' then return self._client:unsubscribe({topic=topics})
else
local res
for _,t in ipairs(topics) do res=self:unsubscribe(t) end
return res
end
end
function client:publish(topic, payload, options)
options = options or {}
local args = {}
args.topic = topic
args.payload = payload
args.qos = options.qos or 0
args.retain = options.retain or false
args.callback = options.callback
return self._client:publish(args)
end
function client:disconnect(options)
options = options or {}
local args = {}
args.callback = options.callback
return self._client:disconnect(args)
end
--function client:acknowledge() end
_client:on{
--{"type":2,"sp":false,"rc":0}
connect = function(connack)
Debug(_debugFlags.mqtt,"MQTT connect:"..Util.prettyJson(connack))
if client._handlers['connected'] then
client._handlers['connected']({sessionPresent=connack.sp,returnCode=connack.rc})
end
end,
subscribe = function(event)
Debug(_debugFlags.mqtt,"MQTT subscribe:"..Util.prettyJson(event))
if client._handlers['subscribed'] then client._handlers['subscribed'](safeJson(event)) end
end,
unsubscribe = function(event)
Debug(_debugFlags.mqtt,"MQTT unsubscribe:"..Util.prettyJson(event))
if client._handlers['unsubscribed'] then client._handlers['unsubscribed'](safeJson(event)) end
end,
message = function(msg)
Debug(_debugFlags.mqtt,"MQTT message:"..Util.prettyJson(msg))
local msgt = mqtt.MSGMAP[msg.type]
if msgt and client._handlers[msgt] then client._handlers[msgt](msg)
elseif client._handlers['message'] then client._handlers['message'](msg) end
end,
acknowledge = function(event)
Debug(_debugFlags.mqtt,"MQTT acknowledge:"..Util.prettyJson(event))
if client._handlers['acknowledge'] then client._handlers['acknowledge']() end
end,
error = function(err)
if _debugFlags.mqtt then Log(LOG.ERROR,"MQTT error:"..err) end
if client._handlers['error'] then client._handlers['error'](err) end
end,
close = function(event)
Debug(_debugFlags.mqtt,"MQTT close:"..Util.prettyJson(event))
event = safeJson(event)
if client._handlers['closed'] then client._handlers['closed'](safeJson(event)) end
end,
auth = function(event)
Debug(_debugFlags.mqtt,"MQTT auth:"..Util.prettyJson(event))
if client._handlers['auth'] then client._handlers['auth'](safeJson(event)) end
end,
}
_mqtt.get_ioloop():add(client._client)
if not mqtt._loop then
local iter = _mqtt.get_ioloop()
mqtt._loop = os.setTimer(function() iter:iteration() end,1000,true)
end
return client
end
else