forked from jangabrielsson/EventRunner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibaroapiHC3_classic.lua
5622 lines (5150 loc) · 198 KB
/
fibaroapiHC3_classic.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: jan@gabrielsson.com
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
Sources:
json -- Copyright (c) 2019 rxi
persistence -- Copyright (c) 2010 Gerhard Roethlin
file functions -- Credit pkulchenko - ZeroBraneStudio
--]]
local FIBAROAPIHC3_VERSION = "0.158"
--[[
Best way is to conditionally include this code at the top of your lua file
if dofile and not hc3_emulator then
hc3_emulator = {
quickVars = {["Hue_User"]="$CREDS.Hue_user",["Hue_IP"]=$CREDS.Hue_IP}
}
dofile("fibaroapiHC3.lua")
end
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 {}, should be a key-value table
hc3_emulator.offline=<boolean>, -- If true run offline with simulated devices. default false
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.db=<boolean/string>, -- If true load data from "HC3sdk.db" or string file
hc3_emulator.colorDebug=<bbolean> -- If use color console logs in ZBS - not so good if you cut&paste to other apps...
hc3_emulator.backupDir=<dir> -- Default directory to store backup files
hc3_emulator.HC3_logmessages=<boolean> -- Defult false. If true will push log messages to the HC3 also.
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) -- simple busy 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 = {fcall=true, fget=true, post=true, trigger=true, timers=nil, refreshLoop=false, creation=true, mqtt=true}
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
local Util,Timer,QA,Scene,Web,Trigger,Offline,Files -- local modules
-- luacheck: globals hc3_emulator fibaro json plugin quickApp
-- luacheck: globals QuickApp QuickAppBase QuickAppChild
fibaro,json,plugin,quickApp = {},{},nil,nil -- global exports
QuickApp,QuickAppBase,QuickAppChild = nil,nil,nil -- global exports
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.HC3dir = hc3_emulator.HC3dir or "HC3files"
hc3_emulator.backupDir = hc3_emulator.backupDir or "/tmp"
hc3_emulator.backDirFmt = "%m-%d-%Y %H.%M.%S"
hc3_emulator.conditions = false
hc3_emulator.actions = false
hc3_emulator.offline = DEF(hc3_emulator.offline,false)
hc3_emulator.emulated = true
hc3_emulator.debug = merge(hc3_emulator.debug or {},_debugFlags)
_debugFlags = hc3_emulator.debug
hc3_emulator.runSceneAtStart = false
hc3_emulator.webPort = hc3_emulator.webPort or 6872
hc3_emulator.quickVars = hc3_emulator.quickVars or {}
hc3_emulator.colorDebug = DEF(hc3_emulator.colorDebug,true)
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)
local cr = loadfile(hc3_emulator.credentialsFile);
if cr then hc3_emulator.credentials = merge(hc3_emulator.credentials or {},cr() or {}) end
local https = require("ssl.https")
local http = require("socket.http")
local socket = require("socket")
local ltn12 = require("ltn12")
pcall(function() require('mobdebug').coro() end) -- Load mobdebug if available to debug coroutines...
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
local ostime,osclock,osdate,tostring = os.time,os.clock,os.date,tostring
local _timeAdjust = 0
local LOG,Log,Debug,assert,assertf
local module,commandLines = {},{}
local HC3_handleEvent = nil -- Event hook...
local typeHierarchy = nil
local format = string.format
local onAction,onUIEvent,_quickApp
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
-------------- Fibaro API functions ------------------
function module.FibaroAPI()
--luacheck: globals __assert_type __fibaro_get_device __assert_type __fibaro_get_devices __fibaro_get_room
--luacheck: globals __fibaro_get_scene __fibaro_get_global_variable __fibaro_get_device_property __fibaro_add_debug_message
--luacheck: globals plugin
fibaro.version = "1.0.0"
local cache,safeDecode = Trigger.cache,Util.safeDecode
local function __convertToString(value)
if type(value) == 'boolean' then
return value and '1' or '0'
elseif type (value) == 'number' then
return tostring(value)
elseif type(value) == 'table' then
return json.encode(value)
end
return value
end
function assert(value,errmsg) if not value then error(errmsg,3) end end
function assertf(value,errmsg,...)
if not value then
local args = {...}
if #args==0 then error(errmsg,3) else error(format(errmsg,...),3) end
end
end
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
function __fibaro_get_device(deviceID) __assert_type(deviceID,"number")
if _quickApp and _quickApp.id == deviceID then
return _quickApp
end
return api.get("/devices/"..deviceID)
end
function __fibaro_get_devices() return api.get("/devices") end
function __fibaro_get_room (roomID) __assert_type(roomID,"number") return api.get("/rooms/"..roomID) end
function __fibaro_get_scene(sceneID) __assert_type(sceneID,"number") return api.get("/scenes/"..sceneID) end
function __fibaro_get_global_variable(varName) __assert_type(varName ,"string")
local c = cache.read('globals',0,varName) or api.get("/globalVariables/"..varName)
cache.write('globals',0,varName,c)
return c
end
function __fibaro_get_device_property(deviceId ,propertyName)
__assert_type(deviceId,"number")
__assert_type(propertyName,"string")
local c = cache.read('devices',deviceId,propertyName) or api.get("/devices/"..deviceId.."/properties/"..propertyName)
cache.write('devices',deviceId,propertyName,c)
return c
end
local function addDebugMessage(tag,type,message)
local a,b = api.post("/debugMessages", {
tag = tag,
messageType = type,
message = message
})
return a,b
end
local ZBCOLORMAP = Util.ZBCOLORMAP
local DEBUGCOLORS = {['DEBUG']='green', ['TRACE']='orange', ['WARNING']='purple', ['ERROR']='red'}
local function html2color(str,startColor)
local st,p = {startColor or '\027[0m'},1
return str:gsub("(</?font.->)",function(s)
if s=="</font>" then
p=p-1; return st[p]
else
local color = s:match("color=(%w+)")
color=ZBCOLORMAP[color] or ZBCOLORMAP['black']
p=p+1; st[p]=color;
return color
end
end)
end
local function fibaro_debug(tag,type,str)
assert(str,"Missing tag for debug")
if hc3_emulator.HC3_debugmessages then addDebugMessage(__TAG,type:lower(),str) end
if hc3_emulator.colorDebug then
local color = DEBUGCOLORS[type] or "black"
color = ZBCOLORMAP[color]
type = format('%s%s\027[0m', color, type)
if hc3_emulator.htmlDebug then -- A bit messy, but try to convert html tags to ZBSconsole equivalents
str = html2color(str,'\027[0m')
str=str:gsub(" "," ")
end
end
print(format("%s [%s]: %s",os.date("[%d.%m.%Y] [%X]"),type,str))
end
function __fibaro_add_debug_message(type,str) fibaro_debug("DEBUG",type,str) end
function fibaro.debug(tag,...) fibaro_debug(tag,"DEBUG",d2str(...)) end
function fibaro.warning(tag,...) fibaro_debug(tag,"WARNING",d2str(...)) end
function fibaro.trace(tag,...) fibaro_debug(tag,"TRACE",d2str(...)) end
function fibaro.error(tag,...) fibaro_debug(tag,"ERROR",d2str(...)) end
function fibaro.getName(deviceID)
__assert_type(deviceID,'number')
local dev = __fibaro_get_device(deviceID)
return dev and dev.name
end
sourceTrigger = nil -- global containing last trigger for scene
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")
if actionName == "toggle" then
local val = fibaro.getValue(deviceID,'value')
if tonumber(val) then val=val> 0 end
return fibaro.call(deviceID,val and 'turnOff' or 'turnOn')
end
local a = {args={},delay=0}
for i,v in ipairs({...}) do a.args[i]=v end
if deviceID == plugin.mainDeviceId and not _quickApp.hasProxy then
_quickApp[actionName](_quickApp,...)
else
local res,stat = api.post("/devices/"..deviceID.."/action/"..actionName,a)
if stat==404 then Log(LOG.ERROR,"Device %s does not exists",deviceID) end
end
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(varName , value)
__assert_type(varName ,"string")
local data = {["value"] = tostring(value) , ["invokeScenes"] = true}
api.put("/globalVariables/"..varName , data)
end
function fibaro.emitCustomEvent(name) return api.post("/customEvents/"..name,{}) end
function fibaro.setTimeout(value, func) return setTimeout(func, value) end
function fibaro.clearTimeout(ref) return 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
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')
for _,id in ipairs(sceneIDs) do api.post("/scenes/"..id.."/"..action,{}) end
end
function fibaro.profile(profile_id, action)
if hc3_emulator.isQA 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) -- raw sleep, ignoring sleep.
local t = ostime()+ms; -- Use real clock
while ostime() <= t do socket.sleep(0.01) end -- save batteries...
end
function fibaro.sleep(ms)
__assert_type(ms,'number')
if hc3_emulator.speeding then
_timeAdjust=_timeAdjust+ms/1000
--Timer.runSystemTimers()
return
else
local t = os.time()+ms/1000;
while os.time() < t do
--Timer.runSystemTimers()
socket.sleep(0.01) -- without waking up QA/scene timers
end -- ToDo: we probably need 2 timer queues...
end
end
local rawCall
api={} -- Emulation of api.get/put/post/delete
function api.get(call)
local last = call:match("/refreshStates%?last=(%d+)") -- Always fetch from emulator cache...
if last then
return Trigger.refreshStates.getEvents(tonumber(last))
end
return rawCall("GET",call)
end
function api.put(call, data) return rawCall("PUT",call,json.encode(data),"application/json") end
function api.post(call, data, hs, to) return rawCall("POST",call,data and json.encode(data),"application/json",hs,to) end
function api.delete(call, data) return rawCall("DELETE",call,data and json.encode(data),"application/json") end
------------ HTTP support ---------------------
local function interceptLocal(url,options,success,error)
if url:match("://(127%.0%.0%.1)[:/]") then
url = url:gsub("(://127%.0%.0%.1)","://"..hc3_emulator.credentials.ip)
if url:match("://.-:11111/") then
url = url:gsub("(:11111)","")
options.headers = options.headers or {}
options.headers['Authorization'] = hc3_emulator.BasicAuthorization
end
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
end
return false,url
end
-- An emulation of Fibaro's net.HTTPClient, net.TCPSocket() and net.UDPSocket()
net = net or {mindelay=10,maxdelay=1000,_http=http}
function net.HTTPClient(i_options) -- It is synchronous, but synchronous is a speciell case of asynchronous.. :-)
local self = {} -- Not sure I got all the options right..
function self:request(url,args)
local req = {}; 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
local s,u = interceptLocal(url,req,args.success,args.error)
if s then return else url=u end
local resp = {}
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)
end
local response, status, headers, timeout
http.TIMEOUT,timeout=req.timeout and math.floor(req.timeout/1000) or http.TIMEOUT, http.TIMEOUT
if url:lower():match("^https") then
response, status, headers = https.request(req)
else
response, status, headers = http.request(req)
end
http.TIMEOUT = timeout
if response == 1 then
local d = table.concat(resp)
if args.success then -- simulate asynchronous callback
if net.maxdelay>=net.mindelay then
Timer.setTimeout(function() args.success({status=status, headers=headers, data=d}) end,math.random(net.mindelay,net.maxdelay))
else
args.success({status=status, headers=headers, data=table.concat(resp)})
end
end
else
if args.error then
if net.maxdelay>=net.mindelay then
Timer.setTimeout(function() args.error(status) end,math.random(net.mindelay,net.maxdelay))
else
args.error(status)
end
end
end
end
local pstr = "HTTPClient object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function(s) return pstr end})
return self
end
local HTTPSyncClient = net.HTTPClient
function net.HTTPAsyncClient(i_options) -- It is synchronous, but synchronous is a speciell case of asynchronous.. :-)
local self = {} -- Not sure I got all the options right..
function self:request(url,args)
local req = {}; 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
local s,u = interceptLocal(url,req,args.success,args.error)
if s then return else url=u end
local resp = {}
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)
end
local response, status, headers, timeout, oldTimeout = nil,'timeout'
--http.TIMEOUT,timeout=req.timeout and math.floor(req.timeout/1000) or http.TIMEOUT, http.TIMEOUT
oldTimeout,timeout=http.TIMEOUT,os.time()+(req.timeout and math.floor(req.timeout/1000) or http.TIMEOUT or 60)
local reqFun = url:lower():match("^https") and https.request or http.request
local function getHTTP()
http.TIMEOUT=1
response, status, headers = http.request(req)
http.TIMEOUT=oldTimeout
if status=='timeout' and os.time()<=timeout then
setTimeout(getHTTP,1)
else
if response==1 then
if args.success then
Timer.setTimeout(function() args.success({status=status, headers=headers, data=table.concat(resp)}) end,0)
end
else
if args.error then
Timer.setTimeout(function() args.error(status) end,0)
end
end
end
end
getHTTP()
return
end
local pstr = "HTTPClient object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function(s) 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 sock, err = sock:connect(ip,port)
if err==nil and opts.success then opts.success()
elseif opts.error then opts.error(err) end
end
function self:read(opts)
local data,err = sock:receive()
if data and opts.success then opts.success(data)
elseif data==nil and opts.error then opts.error(err) end
end
function self:readUntil(delimiter, callbacks) end
function self:write(data, opts)
local res,err = sock:send(data)
if res and opts.success then opts.success(res)
elseif res==nil and opts.error then opts.error(err) end
end
function self:close() sock:close() end
local pstr = "TCPSocket object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function(s) 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)
local stat, res = sock:sendto(datagram, ip, port)
if stat and callbacks.success then
pcall(function() callbacks.success(1) end)
elseif stat==nil and callbacks.error then
pcall(function() callbacks.error(res) end)
end
end
function self:bind(ip,port) sock:setsockname(ip,port) end
function self:receive(callbacks)
local stat, res = sock:receivefrom()
if stat and callbacks.success then
pcall(function() callbacks.success(stat, res) end)
elseif stat==nil and callbacks.error then
pcall(function() callbacks.error(res) end)
end
end
function self:close() sock:close() end
local pstr = "UDPSocket object: "..tostring(self):match("%s(.*)")
setmetatable(self,{__tostring = function(s) return pstr end})
return self
end
local function readQuickAppFile(name)
if not hc3_emulator.FILES[name] then return end
if not hc3_emulator.FILES[name].content then
f = io.open(hc3_emulator.FILES[name].file)
if f then
hc3_emulator.FILES[name].content = f:read("*all")
f:close()
else
Log(LOG.WARNING,"QuickApp file '%s' not found",hc3_emulator.FILES[name].file)
end
end
end
local function quickAppApi(call)
if not hc3_emulator.FILES['main'] then hc3_emulator.FILES['main'] = {file=hc3_emulator.sourceFile} end
if call:match("/quickApp/%d+/files") then
local res = {}
for name,s in pairs(hc3_emulator.FILES) do
readQuickAppFile(name)
res[#res+1]={name=name,isMain=name=="main",isOpen=false,content=hc3_emulator.FILES[name].content}
end
return res
else
local name = call:match("/quickApp/%d/files/(.*)")
if name then
readQuickAppFile(name)
return {name=name,isMain=name=="main",isOpen=false,content=hc3_emulator.FILES[name].content}
end
end
Log(LOG.WARNING,"api call '%s' not supported",call)
end
function rawCall(method,call,data,cType,hs,to)
if hc3_emulator.offline then return Offline.api(method,call,data,cType,hs) end
if call:match("/refreshStates") then return Offline.api(method,call,data,cType,hs) end
if call:match("/devices/%?.+") then call=urlencode(call) end
if quickApp and call:match("/quickApp/"..quickApp.id) then return quickAppApi(call,data) end
local resp = {}
local req={ method=method, timeout=to or 5000,
url = "http://"..hc3_emulator.credentials.ip.."/api"..call, --urlencode(call),
sink = ltn12.sink.table(resp),
user=hc3_emulator.credentials.user,
password=hc3_emulator.credentials.pwd,
headers={}
}
if (method == "POST" or method=="PUT") and data == nil then data = "[]" end
--req.headers["Accept"] = 'application/json'
req.headers["Accept"] = '*/*'
req.headers["X-Fibaro-Version"] = 2
req.headers["Fibaro-User-PIN"] = hc3_emulator.USERPIN
if data then
req.headers["Content-Type"] = cType
req.headers["content-length"] = #data
req.source = ltn12.source.string(data)
end
if hs then for k,v in pairs(hs) do req.headers[k]=v end end
local r, c, h
if hc3_emulator.apiHTTPS then
req.url = "https"..req.url:sub(5)
r,c,h = https.request(req)
else
r,c,h = http.request(req)
end
if not r then
Log(LOG.ERROR,"Error connnecting to HC3: '%s' - URL: '%s'.",c,req.url)
return nil,c, h
end
if c>=200 and c<300 then
return resp[1] and safeDecode(table.concat(resp)) or nil,c
end
return nil,c, h
--error(format("HC3 returned error '%d %s' - URL: '%s'.",c,resp[1] or "",req.url))
end
hc3_emulator.rawCall = rawCall
-------------- 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 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 = Timer.setInterval(function() iter:iteration() end,1000)
end
return client
end
else
mqtt={ Client = {} }
function mqtt.Client.connect()
Log(LOG.ERROR,
[[You need to have installed https://github.com/xHasKx/luamqtt so that require("mqtt") works from fibaroapiHC3.lua]]
)
end
end
-------------- WebSocket support ---------------------
local stat2,websocket = pcall(function() return require("wsLua_ER") end)
if stat then
function net.WebSocketClientTls()
local POLLINTERVAL = 1000
local conn,err,lt = nil
local self = { }
local handlers = {}
local function dispatch(h,...)
if handlers[h] then
h = handlers[h]
local args = {...}
setTimeout(function() h(table.unpack(args)) end,0)
end
end
local function listen()
if not conn then return end
local function loop()
if lt == nil then return end
websocket.wsreceive(conn)
if lt then lt = setTimeout(loop,POLLINTERVAL) end
end
lt = setTimeout(loop,0)
end
local function stopListen() if lt then clearTimeout(lt) lt = nil end end
local function disconnected() websocket.wsclose(conn) conn=nil; stopListen(); dispatch("disconnected") end
local function connected() self.co = true; listen(); dispatch("connected") end
local function dataReceived(data) dispatch("dataReceived",data) end
local function error(err) dispatch("error",err) end
local function message_handler( conn, opcode, data, ... )
if not opcode then
error(data)
disconnected()
else
dataReceived(data)
end
end
function self:addEventListener(h,f) handlers[h]=f end
function self:connect(url)
if conn then return false end
conn, err = websocket.wsopen( url, message_handler, nil ) --options )