-
Notifications
You must be signed in to change notification settings - Fork 11
/
fibaroExtra.lua
2082 lines (1870 loc) · 79.9 KB
/
fibaroExtra.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
-- luacheck: globals ignore QuickAppBase QuickApp QuickAppChild quickApp fibaro
-- luacheck: globals ignore plugin api net netSync setTimeout clearTimeout setInterval clearInterval json
-- luacheck: globals ignore __assert_type __fibaro_get_device __TAG
-- luacheck: globals ignore utils hc3_emulator FILES urlencode sceneId
fibaro = fibaro or {}
fibaro.FIBARO_EXTRA = "v0.924"
FILES = FILES or {}
FILES['fibaroExtra']=fibaro.FIBARO_EXTRA
local MID = plugin and plugin.mainDeviceId or sceneId or 0
local format = string.format
local function assertf(test,fmt,...) if not test then error(format(fmt,...),2) end end
local debugFlags = {}
local toTime,copy,equal,member,remove,protectFun
-------------------- Utilities ----------------------------------------------
do
utils = {}
if not setTimeout then
function setTimeout(fun,ms) return fibaro.setTimeout(ms,fun) end
function clearTimeout(ref) fibaro.clearTimeout(ref) end
function setInterval(fun,ms) return fibaro.setInterval(ms,fun) end
function clearInterval(ref) fibaro.clearInterval(ref) end
end
function copy(obj)
if type(obj) == 'table' then
local res = {} for k,v in pairs(obj) do res[k] = copy(v) end
return res
else return obj end
end
utils.copy = copy
function utils.copyShallow(t)
if type(t)=='table' then
local r={}; for k,v in pairs(t) do r[k]=v end
return r
else return t end
end
function equal(e1,e2)
if e1==e2 then return true
else
if type(e1) ~= 'table' or type(e2) ~= 'table' then return false
else
for k1,v1 in pairs(e1) do if e2[k1] == nil or not equal(v1,e2[k1]) then return false end end
for k2,_ in pairs(e2) do if e1[k2] == nil then return false end end
return true
end
end
end
utils.equal=equal
if not table.maxn then
function table.maxn(tbl) local c=0; for _ in pairs(tbl) do c=c+1 end return c end
end
function utils.gensym(s) return (s or "G")..fibaro._orgToString({}):match("%s(.*)") end
function member(k,tab) for i,v in ipairs(tab) do if equal(v,k) then return i end end return false end
function remove(obj,list) local i = member(obj,list); if i then table.remove(list,i) return true end end
utils.member,utils.remove = member,remove
function utils.remove(k,tab) local r = {}; for _,v in ipairs(tab) do if not equal(v,k) then r[#r+1]=v end end return r end
function utils.map(f,l) local r={}; for _,e in ipairs(l) do r[#r+1]=f(e) end; return r end
function utils.mapf(f,l) for _,e in ipairs(l) do f(e) end; end
function utils.mapAnd(f,l) for _,e in ipairs(l) do if f(e) then return false end end return true end
function utils.mapOr(f,l) for i,e in ipairs(l) do if f(e) then return i end end end
function utils.reduce(f,l) local r = {}; for _,e in ipairs(l) do if f(e) then r[#r+1]=e end end; return r end
function utils.mapk(f,l) local r={}; for k,v in pairs(l) do r[k]=f(v) end; return r end
function utils.mapkv(f,l) local r={}; for k,v in pairs(l) do k,v=f(k,v) r[k]=v end; return r end
function utils.size(t) local n=0; for _,_ in pairs(t) do n=n+1 end return n end
function utils.keyMerge(t1,t2)
local res = utils.copy(t1)
for k,v in pairs(t2) do if t1[k]==nil then t1[k]=v end end
return res
end
function utils.keyIntersect(t1,t2)
local res = {}
for k,v in pairs(t1) do if t2[k] then res[k]=v end end
return res
end
function utils.zip(fun,a,b,c,d)
local res = {}
for i=1,math.max(#a,#b) do res[#res+1] = fun(a[i],b[i],c and c[i],d and d[i]) end
return res
end
function utils.basicAuthorization(user,password) return "Basic "..utils.base64encode(user..":"..password) end
function utils.base64encode(data)
__assert_type(data,"string" )
local bC='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
return ((data:gsub('.', function(x)
local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
return r;
end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
if (#x < 6) then return '' end
local c=0
for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
return bC:sub(c+1,c+1)
end)..({ '', '==', '=' })[#data%3+1])
end
local function sunturnTime(date, rising, latitude, longitude, zenith, local_offset)
local rad,deg,floor = math.rad,math.deg,math.floor
local frac = function(n) return n - floor(n) end
local cos = function(d) return math.cos(rad(d)) end
local acos = function(d) return deg(math.acos(d)) end
local sin = function(d) return math.sin(rad(d)) end
local asin = function(d) return deg(math.asin(d)) end
local tan = function(d) return math.tan(rad(d)) end
local atan = function(d) return deg(math.atan(d)) end
local function day_of_year(date2)
local n1 = floor(275 * date2.month / 9)
local n2 = floor((date2.month + 9) / 12)
local n3 = (1 + floor((date2.year - 4 * floor(date2.year / 4) + 2) / 3))
return n1 - (n2 * n3) + date2.day - 30
end
local function fit_into_range(val, min, max)
local range,count = max - min
if val < min then count = floor((min - val) / range) + 1; return val + count * range
elseif val >= max then count = floor((val - max) / range) + 1; return val - count * range
else return val end
end
-- Convert the longitude to hour value and calculate an approximate time
local n,lng_hour,t = day_of_year(date), longitude / 15
if rising then t = n + ((6 - lng_hour) / 24) -- Rising time is desired
else t = n + ((18 - lng_hour) / 24) end -- Setting time is desired
local M = (0.9856 * t) - 3.289 -- Calculate the Sun^s mean anomaly
-- Calculate the Sun^s true longitude
local L = fit_into_range(M + (1.916 * sin(M)) + (0.020 * sin(2 * M)) + 282.634, 0, 360)
-- Calculate the Sun^s right ascension
local RA = fit_into_range(atan(0.91764 * tan(L)), 0, 360)
-- Right ascension value needs to be in the same quadrant as L
local Lquadrant = floor(L / 90) * 90
local RAquadrant = floor(RA / 90) * 90
RA = RA + Lquadrant - RAquadrant; RA = RA / 15 -- Right ascension value needs to be converted into hours
local sinDec = 0.39782 * sin(L) -- Calculate the Sun's declination
local cosDec = cos(asin(sinDec))
local cosH = (cos(zenith) - (sinDec * sin(latitude))) / (cosDec * cos(latitude)) -- Calculate the Sun^s local hour angle
if rising and cosH > 1 then return "N/R" -- The sun never rises on this location on the specified date
elseif cosH < -1 then return "N/S" end -- The sun never sets on this location on the specified date
local H -- Finish calculating H and convert into hours
if rising then H = 360 - acos(cosH)
else H = acos(cosH) end
H = H / 15
local T = H + RA - (0.06571 * t) - 6.622 -- Calculate local mean time of rising/setting
local UT = fit_into_range(T - lng_hour, 0, 24) -- Adjust back to UTC
local LT = UT + local_offset -- Convert UT value to local time zone of latitude/longitude
return os.time({day = date.day,month = date.month,year = date.year,hour = floor(LT),min = math.modf(frac(LT) * 60)})
end
local function getTimezone() local now = os.time() return os.difftime(now, os.time(os.date("!*t", now))) end
function utils.sunCalc(time)
local hc3Location = api.get("/settings/location")
local lat = hc3Location.latitude or 0
local lon = hc3Location.longitude or 0
local utc = getTimezone() / 3600
local zenith,zenith_twilight = 90.83, 96.0 -- sunset/sunrise 90°50′, civil twilight 96°0′
local date = os.date("*t",time or os.time())
if date.isdst then utc = utc + 1 end
local rise_time = os.date("*t", sunturnTime(date, true, lat, lon, zenith, utc))
local set_time = os.date("*t", sunturnTime(date, false, lat, lon, zenith, utc))
local rise_time_t = os.date("*t", sunturnTime(date, true, lat, lon, zenith_twilight, utc))
local set_time_t = os.date("*t", sunturnTime(date, false, lat, lon, zenith_twilight, utc))
local sunrise = string.format("%.2d:%.2d", rise_time.hour, rise_time.min)
local sunset = string.format("%.2d:%.2d", set_time.hour, set_time.min)
local sunrise_t = string.format("%.2d:%.2d", rise_time_t.hour, rise_time_t.min)
local sunset_t = string.format("%.2d:%.2d", set_time_t.hour, set_time_t.min)
return sunrise, sunset, sunrise_t, sunset_t
end
end -- Utilities
--------------------- Fibaro functions --------------------------------------
do
local HC3version = nil
function fibaro.HC3version(version) -- Return/optional check HC3 version
if HC3version == nil then HC3version = api.get("/settings/info").currentVersion.version end
if version then return version >= HC3version else return HC3version end
end
local IPaddress = nil
function fibaro.getIPaddress(name)
if IPaddress then return IPaddress end
if hc3_emulator then return hc3_emulator.IPaddress
else
name = name or ".*"
local networkdata = api.get("/proxy?url=http://localhost:11112/api/settings/network")
for n,d in pairs(networkdata.networkConfig or {}) do
if n:match(name) and d.enabled then IPaddress = d.ipConfig.ip; return IPaddress end
end
end
end
end -- Fibaro functions
--------------------- Time functions ------------------------------------------
do
local function toSeconds(str)
__assert_type(str,"string" )
local sun = str:match("(sun%a+)")
if sun then return toSeconds(str:gsub(sun,fibaro.getValue(1,sun.."Hour"))) end
local var = str:match("(%$[A-Za-z]+)")
if var then return toSeconds(str:gsub(var,fibaro.getGlobalVariable(var:sub(2)))) end
local h,m,s,op,off=str:match("(%d%d):(%d%d):?(%d*)([+%-]*)([%d:]*)")
off = off~="" and (off:find(":") and toSeconds(off) or toSeconds("00:00:"..off)) or 0
return 3600*h+60*m+(s~="" and s or 0)+((op=='-' or op =='+-') and -1 or 1)*off
end
fibaro.toSeconds = toSeconds
local function midnight() local t = os.date("*t"); t.hour,t.min,t.sec = 0,0,0; return os.time(t) end
fibaro.midnight = midnight
function fibaro.between(start,stop,optTime)
__assert_type(start,"string" )
__assert_type(stop,"string" )
start,stop,optTime=toSeconds(start),toSeconds(stop),optTime and toSeconds(optTime) or toSeconds(os.date("%H:%M"))
stop = stop>=start and stop or stop+24*3600
optTime = optTime>=start and optTime or optTime+24*3600
return start <= optTime and optTime <= stop
end
local function hm2sec(hmstr)
local offs,sun
sun,offs = hmstr:match("^(%a+)([+-]?%d*)")
if sun and (sun == 'sunset' or sun == 'sunrise') then
hmstr,offs = fibaro.getValue(1,sun.."Hour"), tonumber(offs) or 0
end
local sg,h,m,s = hmstr:match("^(%-?)(%d+):(%d+):?(%d*)")
assertf(h and m,"Bad hm2sec string %s",hmstr)
return (sg == '-' and -1 or 1)*(tonumber(h)*3600+tonumber(m)*60+(tonumber(s) or 0)+(tonumber(offs or 0))*60)
end
-- toTime("10:00") -> 10*3600+0*60 secs
-- toTime("10:00:05") -> 10*3600+0*60+5*1 secs
-- toTime("t/10:00") -> (t)oday at 10:00. midnight+10*3600+0*60 secs
-- toTime("n/10:00") -> (n)ext time. today at 10.00AM if called before (or at) 10.00AM else 10:00AM next day
-- toTime("+/10:00") -> Plus time. os.time() + 10 hours
-- toTime("+/00:01:22") -> Plus time. os.time() + 1min and 22sec
-- toTime("sunset") -> todays sunset in relative secs since midnight, E.g. sunset="05:10", =>toTime("05:10")
-- toTime("sunrise") -> todays sunrise
-- toTime("sunset+10") -> todays sunset + 10min. E.g. sunset="05:10", =>toTime("05:10")+10*60
-- toTime("sunrise-5") -> todays sunrise - 5min
-- toTime("t/sunset+10")-> (t)oday at sunset in 'absolute' time. E.g. midnight+toTime("sunset+10")
function toTime(time)
if type(time) == 'number' then return time end
local p = time:sub(1,2)
if p == '+/' then return hm2sec(time:sub(3))+os.time()
elseif p == 'n/' then
local t1,t2 = midnight()+hm2sec(time:sub(3)),os.time()
return t1 > t2 and t1 or t1+24*60*60
elseif p == 't/' then return hm2sec(time:sub(3))+midnight()
else return hm2sec(time) end
end
utils.toTime,utils.hm2sec = toTime,hm2sec
end -- Time functions
--------------------- Trace functions ------------------------------------------
--------------------- Debug functions -----------------------------------------
do
local fformat
fibaro.debugFlags = debugFlags
debugFlags.debugLevel=nil
debugFlags.traceLevel=nil
debugFlags.notifyError=true
debugFlags.notifyWarning=true
debugFlags.onaction=true
debugFlags.uievent=true
debugFlags.json=true
debugFlags.html=true
debugFlags.reuseNotifies=true
-- Add notification to notification center
local cachedNots = {}
local function notify(priority, text, reuse)
local id = MID
local name = quickApp and quickApp.name or "Scene"
assert(({info=true,warning=true,alert=true})[priority],"Wrong 'priority' - info/warning/alert")
local title = text:match("(.-)[:%s]") or format("%s deviceId:%d",name,id)
if reuse==nil then reuse = debugFlags.reuseNotifies end
local msgId = nil
local data = {
canBeDeleted = true,
wasRead = false,
priority = priority,
type = "GenericDeviceNotification",
data = {
sceneId = sceneId,
deviceId = MID,
subType = "Generic",
title = title,
text = tostring(text)
}
}
local nid = title..id
if reuse then
if cachedNots[nid] then
msgId = cachedNots[nid]
else
for _,n in ipairs(api.get("/notificationCenter") or {}) do
if n.data and (n.data.deviceId == id or n.data.sceneeId == id) and n.data.title == title then
msgId = n.id; break
end
end
end
end
if msgId then
api.put("/notificationCenter/"..msgId, data)
else
local d = api.post("/notificationCenter", data)
if d then cachedNots[nid] = d.id end
end
end
utils.notify = notify
local oldPrint = print
local inhibitPrint = {['onAction: ']='onaction', ['UIEvent: ']='uievent'}
function print(a,...)
if not inhibitPrint[a] or debugFlags[inhibitPrint[a]] then
oldPrint(a,...)
end
end
local old_tostring = tostring
fibaro._orgToString = old_tostring
if hc3_emulator then
function tostring(obj)
if type(obj)=='table' and not hc3_emulator.getmetatable(obj) then
if obj.__tostring then return obj.__tostring(obj)
elseif debugFlags.json then return json.encodeFast(obj) end
end
return old_tostring(obj)
end
else
function tostring(obj)
if type(obj)=='table' then
if obj.__tostring then return obj.__tostring(obj)
elseif debugFlags.json then return json.encodeFast(obj) end
end
return old_tostring(obj)
end
end
local htmlCodes={['\n']='<br>', [' ']=' '}
local function fix(str) return str:gsub("([\n%s])",function(c) return htmlCodes[c] or c end) end
local function htmlTransform(str)
local hit = false
str = str:gsub("([^<]*)(<.->)([^<]*)",function(s1,s2,s3) hit=true
return (s1~="" and fix(s1) or "")..s2..(s3~="" and fix(s3) or "")
end)
return hit and str or fix(str)
end
function fformat(fmt,...)
local args = {...}
if #args == 0 then return tostring(fmt) end
for i,v in ipairs(args) do if type(v)=='table' then args[i]=tostring(v) end end
return (debugFlags.html and not hc3_emulator) and htmlTransform(format(fmt,table.unpack(args))) or format(fmt,table.unpack(args))
end
local function arr2str(...)
local args,res = {...},{}
for i=1,#args do if args[i]~=nil then res[#res+1]=tostring(args[i]) end end
return (debugFlags.html and not hc3_emulator) and htmlTransform(table.concat(res," ")) or table.concat(res," ")
end
local function print_debug(typ,tag,str)
--__fibaro_add_debug_message(tag or __TAG,str or "",typ or "debug")
api.post("/debugMessages",{message=str,messageType=typ or "debug",tag=tag or __TAG})
return str
end
function fibaro.debug(tag,...)
if not(type(tag)=='number' and tag > (debugFlags.debugLevel or 0)) then
return print_debug('debug',tag,arr2str(...))
else return "" end
end
function fibaro.trace(tag,...)
if not(type(tag)=='number' and tag > (debugFlags.traceLevel or 0)) then
return print_debug('trace',tag,arr2str(...))
else return "" end
end
function fibaro.error(tag,...)
local str = print_debug('error',tag,arr2str(...))
if debugFlags.notifyError then notify("alert",str) end
return str
end
function fibaro.warning(tag,...)
local str = print_debug('warning',tag,arr2str(...))
if debugFlags.notifyWarning then notify("warning",str) end
return str
end
function fibaro.debugf(tag,fmt,...)
if not(type(tag)=='number' and tag > (debugFlags.debugLevel or 0)) then
return print_debug('debug',tag,fformat(fmt,...))
else return "" end
end
function fibaro.tracef(tag,fmt,...)
if not(type(tag)=='number' and tag > (debugFlags.traceLevel or 0)) then
return print_debug('trace',tag,fformat(fmt,...))
else return "" end
end
function fibaro.errorf(tag,fmt,...)
local str = print_debug('error',tag,fformat(fmt,...))
if debugFlags.notifyError then notify("alert",str) end
return str
end
function fibaro.warningf(tag,fmt,...)
local str = print_debug('warning',tag,fformat(fmt,...))
if debugFlags.notifyWarning then notify("warning",str) end
return str
end
function protectFun(fun,f,level)
return function(...)
local stat,res = pcall(fun,...)
if not stat then
res = res:gsub("fibaroExtra.lua:%d+:","").."("..f..")"
error(res,level)
else return res end
end
end
for _,f in ipairs({'debugf','tracef','warningf','errorf'}) do
fibaro[f] = protectFun(fibaro[f],f,2)
end
end -- Debug functions
--------------------- Scene function -----------------------------------------
do
function fibaro.isSceneEnabled(sceneID)
__assert_type(sceneID,"number" )
return (api.get("/scenes/"..sceneID) or { enabled=false }).enabled
end
function fibaro.setSceneEnabled(sceneID,enabled)
__assert_type(sceneID,"number" ) __assert_type(enabled,"boolean" )
return api.put("/scenes/"..sceneID,{enabled=enabled})
end
function fibaro.getSceneRunConfig(sceneID)
__assert_type(sceneID,"number" )
return api.get("/scenes/"..sceneID).mode
end
function fibaro.setSceneRunConfig(sceneID,runConfig)
__assert_type(sceneID,"number" )
assert(({automatic=true,manual=true})[runConfig],"runconfig must be 'automatic' or 'manual'")
return api.put("/scenes/"..sceneID, {mode = runConfig})
end
end -- Scene function
--------------------- Globals --------------------------------------------------
do
function fibaro.getAllGlobalVariables()
return utils.map(function(v) return v.name end,api.get("/globalVariables"))
end
function fibaro.createGlobalVariable(name,value,options)
__assert_type(name,"string")
if not fibaro.existGlobalVariable(name) then
value = tostring(value)
local args = utils.copy(options or {})
args.name,args.value=name,value
return api.post("/globalVariables",args)
end
end
function fibaro.deleteGlobalVariable(name)
__assert_type(name,"string")
return api.delete("/globalVariable/"..name)
end
function fibaro.existGlobalVariable(name)
__assert_type(name,"string")
return api.get("/globalVariable/"..name) and true
end
function fibaro.getGlobalVariableType(name)
__assert_type(name,"string")
local v = api.get("/globalVariable/"..name) or {}
return v.isEnum,v.readOnly
end
function fibaro.getGlobalVariableLastModified(name)
__assert_type(name,"string")
return (api.get("/globalVariable/"..name) or {}).modified
end
end -- Globals
--------------------- Custom events --------------------------------------------
do
function fibaro.getAllCustomEvents()
return utils.map(function(v) return v.name end,api.get("/customEvents") or {})
end
function fibaro.createCustomEvent(name,userDescription)
__assert_type(name,"string" )
return api.post("/customEvent",{name=name,uderDescription=userDescription or ""})
end
function fibaro.deleteCustomEvent(name)
__assert_type(name,"string" )
return api.delete("/customEvents/"..name)
end
function fibaro.existCustomEvent(name)
__assert_type(name,"string" )
return api.get("/customEvents/"..name) and true
end
end -- Custom events
--------------------- Profiles -------------------------------------------------
do
function fibaro.activeProfile(id)
if id then
if type(id)=='string' then id = fibaro.profileNameToId(id) end
assert(id,"fibaro.getActiveProfile(id) - no such id/name")
return api.put("/profiles",{activeProfile=id}) and id
end
return api.get("/profiles").activeProfile
end
function fibaro.profileIdtoName(pid)
__assert_type(pid,"number")
for _,p in ipairs(api.get("/profiles").profiles or {}) do
if p.id == pid then return p.name end
end
end
function fibaro.profileNameToId(name)
__assert_type(name,"string")
for _,p in ipairs(api.get("/profiles").profiles or {}) do
if p.name == name then return p.id end
end
end
end -- Profiles
--------------------- Alarm functions ------------------------------------------
do
function fibaro.partitionIdToName(pid)
__assert_type(pid,"number")
return (api.get("/alarms/v1/partitions/"..pid) or {}).name
end
function fibaro.partitionNameToId(name)
assert(type(name)=='string',"Alarm partition name not a string")
for _,p in ipairs(api.get("/alarms/v1/partitions") or {}) do
if p.name == name then return p.id end
end
end
-- Returns devices breached in partition 'pid'
function fibaro.getBreachedDevicesInPartition(pid)
assert(type(pid)=='number',"Alarm partition id not a number")
local p,res = api.get("/alarms/v1/partitions/"..pid),{}
for _,d in ipairs((p or {}).devices or {}) do
if fibaro.getValue(d,"value") then res[#res+1]=d end
end
return res
end
-- helper function
local function filterPartitions(filter)
local res = {}
for _,p in ipairs(api.get("/alarms/v1/partitions") or {}) do if filter(p) then res[#res+1]=p.id end end
return res
end
-- Return all partitions ids
function fibaro.getAllPartitions() return filterPartitions(function() return true end) end
-- Return partitions that are armed
function fibaro.getArmedPartitions() return filterPartitions(function(p) return p.armed end) end
-- Return partitions that are about to be armed
function fibaro.getActivatedPartitions() return filterPartitions(function(p) return p.secondsToArm end) end
-- Return breached partitions
function fibaro.getBreachedPartitions() return api.get("/alarms/v1/partitions/breached") or {} end
--If you want to list all devices that can be part of a alarm partition/zone you can do
function fibaro.getAlarmDevices() return api.get("/alarms/v1/devices/") end
fibaro.ALARM_INTERVAL = 1000
local fun
local ref
local armedPs={}
local function watchAlarms()
for _,p in ipairs(api.get("/alarms/v1/partitions") or {}) do
if p.secondsToArm and not armedPs[p.id] then
setTimeout(function() pcall(fun,p.id) end,0)
end
armedPs[p.id] = p.secondsToArm
end
end
function fibaro.activatedPartitions(callback)
__assert_type(callback,"function")
fun = callback
if fun and ref == nil then
ref = setInterval(watchAlarms,fibaro.ALARM_INTERVAL)
elseif fun == nil and ref then
clearInterval(ref); ref = nil
end
end
--[[ Ex. check what partitions have breached devices
for _,p in ipairs(getAllPartitions()) do
local bd = getBreachedDevicesInPartition(p)
if bd[1] then print("Partition "..p.." contains breached devices "..json.encode(bd)) end
end
--]]
end -- Alarm
--------------------- Weather --------------------------------------------------
do
fibaro.weather = {}
function fibaro.weather.temperature() return api.get("/weather").Temperature end
function fibaro.weather.temperatureUnit() return api.get("/weather").TemperatureUnit end
function fibaro.weather.humidity() return api.get("/weather").Humidity end
function fibaro.weather.wind() return api.get("/weather").Wind end
function fibaro.weather.weatherCondition() return api.get("/weather").WeatherCondition end
function fibaro.weather.conditionCode() return api.get("/weather").ConditionCode end
end --Weather
--------------------- sourceTrigger & refreshStates ----------------------------
do
fibaro.REFRESH_STATES_INTERVAL = 1000
local sourceTriggerCallbacks,refreshCallbacks,refreshRef,pollRefresh={},{}
local ENABLEDSOURCETRIGGERS,DISABLEDREFRESH={},{}
local post,sourceTriggerTransformer,filter
local EventTypes = { -- There are more, but these are what I seen so far...
AlarmPartitionArmedEvent = function(d) post({type='alarm', property='armed', id = d.partitionId, value=d.armed}) end,
AlarmPartitionBreachedEvent = function(d) post({type='alarm', property='breached', id = d.partitionId, value=d.breached}) end,
HomeArmStateChangedEvent = function(d) post({type='alarm', property='homeArmed', value=d.newValue}) end,
HomeDisarmStateChangedEvent = function(d) post({type='alarm', property='homeArmed', value=not d.newValue}) end,
HomeBreachedEvent = function(d) post({type='alarm', property='homeBreached', value=d.breached}) end,
WeatherChangedEvent = function(d) post({type='weather',property=d.change, value=d.newValue, old=d.oldValue}) end,
GlobalVariableChangedEvent = function(d)
post({type='global-variable', name=d.variableName, value=d.newValue, old=d.oldValue})
end,
DevicePropertyUpdatedEvent = function(d)
if d.property=='quickAppVariables' then
local old={}; for _,v in ipairs(d.oldValue) do old[v.name] = v.value end -- Todo: optimize
for _,v in ipairs(d.newValue) do
if not equal(v.value,old[v.name]) then
post({type='quickvar', id=d.id, name=v.name, value=v.value, old=old[v.name]})
end
end
else
if d.property == "icon" or filter(d.id,d.property,d.newValue) then return end
post({type='device', id=d.id, property=d.property, value=d.newValue, old=d.oldValue})
end
end,
CentralSceneEvent = function(d)
d.id = d.id or d.deviceId
d.icon=nil
post({type='device', property='centralSceneEvent', id=d.id, value={keyId=d.keyId, keyAttribute=d.keyAttribute}})
end,
SceneActivationEvent = function(d)
d.id = d.id or d.deviceId
post({type='device', property='sceneActivationEvent', id=d.id, value={sceneId=d.sceneId}})
end,
AccessControlEvent = function(d)
post({type='device', property='accessControlEvent', id=d.id, value=d})
end,
CustomEvent = function(d)
local value = api.get("/customEvents/"..d.name)
post({type='custom-event', name=d.name, value=value and value.userDescription})
end,
PluginChangedViewEvent = function(d) post({type='PluginChangedViewEvent', value=d}) end,
WizardStepStateChangedEvent = function(d) post({type='WizardStepStateChangedEvent', value=d}) end,
UpdateReadyEvent = function(d) post({type='updateReadyEvent', value=d}) end,
DeviceRemovedEvent = function(d) post({type='deviceEvent', id=d.id, value='removed'}) end,
DeviceChangedRoomEvent = function(d) post({type='deviceEvent', id=d.id, value='changedRoom'}) end,
DeviceCreatedEvent = function(d) post({type='deviceEvent', id=d.id, value='created'}) end,
DeviceModifiedEvent = function(d) post({type='deviceEvent', id=d.id, value='modified'}) end,
PluginProcessCrashedEvent = function(d) post({type='deviceEvent', id=d.deviceId, value='crashed', error=d.error}) end,
SceneStartedEvent = function(d) post({type='sceneEvent', id=d.id, value='started'}) end,
SceneFinishedEvent = function(d) post({type='sceneEvent', id=d.id, value='finished'})end,
SceneRunningInstancesEvent = function(d) post({type='sceneEvent', id=d.id, value='instance', instance=d}) end,
SceneRemovedEvent = function(d) post({type='sceneEvent', id=d.id, value='removed'}) end,
SceneModifiedEvent = function(d) post({type='sceneEvent', id=d.id, value='modified'}) end,
SceneCreatedEvent = function(d) post({type='sceneEvent', id=d.id, value='created'}) end,
OnlineStatusUpdatedEvent = function(d) post({type='onlineEvent', value=d.online}) end,
--onUIEvent = function(d) post({type='uievent', deviceID=d.deviceId, name=d.elementName}) end,
ActiveProfileChangedEvent = function(d)
post({type='profile',property='activeProfile',value=d.newActiveProfile, old=d.oldActiveProfile})
end,
ClimateZoneChangedEvent = function(d)
if d.changes and type(d.changes)=='table' then
for _,c in ipairs(d.changes) do
c.type,c.id='ClimateZone',d.id
post(c)
end
end
end,
ClimateZoneSetpointChangedEvent = function(d) d.type = 'ClimateZoneSetpoint' post(d) end,
NotificationCreatedEvent = function(d) post({type='notification', id=d.id, value='created'}) end,
NotificationRemovedEvent = function(d) post({type='notification', id=d.id, value='removed'}) end,
NotificationUpdatedEvent = function(d) post({type='notification', id=d.id, value='updated'}) end,
RoomCreatedEvent = function(d) post({type='room', id=d.id, value='created'}) end,
RoomRemovedEvent = function(d) post({type='room', id=d.id, value='removed'}) end,
RoomModifiedEvent = function(d) post({type='room', id=d.id, value='modified'}) end,
SectionCreatedEvent = function(d) post({type='section', id=d.id, value='created'}) end,
SectionRemovedEvent = function(d) post({type='section', id=d.id, value='removede'}) end,
SectionModifiedEvent = function(d) post({type='section', id=d.id, value='modified'}) end,
DeviceActionRanEvent = function(_) end,
QuickAppFilesChangedEvent = function(_) end,
ZwaveDeviceParametersChangedEvent = function(_) end,
ZwaveNodeAddedEvent = function(_) end,
RefreshRequiredEvent = function(_) end,
DeviceFirmwareUpdateEvent = function(_) end,
GeofenceEvent = function(d)
post({type='location',id=d.userId,property=d.locationId,value=d.geofenceAction,timestamp=d.timestamp})
end,
}
function fibaro.registerSourceTriggerCallback(callback)
__assert_type(callback,"function")
if member(callback,sourceTriggerCallbacks) then return end
if #sourceTriggerCallbacks == 0 then
fibaro.registerRefreshStatesCallback(sourceTriggerTransformer)
end
sourceTriggerCallbacks[#sourceTriggerCallbacks+1] = callback
end
function fibaro.unregisterSourceTriggerCallback(callback)
__assert_type(callback,"function")
if member(callback,sourceTriggerCallbacks) then remove(callback,sourceTriggerCallbacks) end
if #sourceTriggerCallbacks == 0 then
fibaro.unregisterRefreshStatesCallback(sourceTriggerTransformer)
end
end
function post(ev)
if ENABLEDSOURCETRIGGERS[ev.type] then
if #sourceTriggerCallbacks==0 then return end
if debugFlags.sourceTrigger then fibaro.debugf(nil,"Incoming sourceTrigger:%s",ev) end
ev._trigger=true
for _,cb in ipairs(sourceTriggerCallbacks) do
setTimeout(function() cb(ev) end,0)
end
end
end
function sourceTriggerTransformer(e)
local handler = EventTypes[e.type]
if handler then handler(e.data)
elseif handler==nil and fibaro._UNHANDLED_REFRESHSTATES then
fibaro.debugf(__TAG,"[Note] Unhandled refreshState/sourceTrigger:%s -- please report",e)
end
end
function fibaro.enableSourceTriggers(trigger)
if type(trigger)~='table' then trigger={trigger} end
for _,t in ipairs(trigger) do ENABLEDSOURCETRIGGERS[t]=true end
end
fibaro.enableSourceTriggers({"device","alarm","global-variable","custom-event","quickvar"})
function fibaro.disableSourceTriggers(trigger)
if type(trigger)~='table' then trigger={trigger} end
for _,t in ipairs(trigger) do ENABLEDSOURCETRIGGERS[t]=nil end
end
local propFilters = {}
function fibaro.sourceTriggerDelta(id,prop,value)
__assert_type(id,"number")
__assert_type(prop,"string")
local d = propFilters[id] or {}
d[prop] = {delta = value}
propFilters[id] = d
end
function filter(id,prop,new)
local d = (propFilters[id] or {})[prop]
if d then
if d.last == nil then
d.last = new
return false
else
if math.abs(d.last-new) >= d.delta then
d.last = new
return false
else return true end
end
else return false end
end
fibaro._REFRESHSTATERATE = 1000
local lastRefresh = 0
net = net or { HTTPClient = function() end }
local http = net.HTTPClient()
math.randomseed(os.time())
local urlTail = "&lang=en&rand="..math.random(2000,4000).."&logs=false"
function pollRefresh()
local _,_ = http:request("http://127.0.0.1:11111/api/refreshStates?last=" .. lastRefresh..urlTail,{
success=function(res)
local states = res.status == 200 and json.decode(res.data)
if states then
lastRefresh=states.last
if states.events and #states.events>0 then
for _,e in ipairs(states.events) do
fibaro._postRefreshState(e)
end
end
end
refreshRef = setTimeout(pollRefresh,fibaro.REFRESH_STATES_INTERVAL or 0)
end,
error=function(res)
fibaro.errorf(__TAG,"refreshStates:%s",res)
refreshRef = setTimeout(pollRefresh,fibaro._REFRESHSTATERATE)
end,
})
end
function fibaro.registerRefreshStatesCallback(callback)
__assert_type(callback,"function")
if member(callback,refreshCallbacks) then return end
refreshCallbacks[#refreshCallbacks+1] = callback
if not refreshRef then refreshRef = setTimeout(pollRefresh,0) end
if debugFlags._refreshStates then fibaro.debug(__TAG,"Polling for refreshStates") end
end
function fibaro.unregisterRefreshStatesCallback(callback)
remove(callback,refreshCallbacks)
if #refreshCallbacks == 0 then
if refreshRef then clearTimeout(refreshRef); refreshRef = nil end
if debugFlags._refreshStates then fibaro.debug(nil,"Stop polling for refreshStates") end
end
end
function fibaro.enableRefreshStatesTypes(typs)
if type(typs)~='table' then typs={typs} end
for _,t in ipairs(typs) do DISABLEDREFRESH[t]=nil end
end
function fibaro.disableRefreshStatesTypes(typs)
if type(typs)~='table' then typs={typs} end
for _,t in ipairs(typs) do DISABLEDREFRESH[t]=true end
end
function fibaro._postSourceTrigger(trigger) post(trigger) end
function fibaro._postRefreshState(event)
if debugFlags._allRefreshStates then fibaro.debugf(nil,"RefreshState %s",event) end
if #refreshCallbacks>0 and not DISABLEDREFRESH[event.type] then
for i=1,#refreshCallbacks do
setTimeout(function() refreshCallbacks[i](event) end,0)
end
end
end
function fibaro.postGeofenceEvent(userId,locationId,geofenceAction)
__assert_type(userId,"number")
__assert_type(locationId,"number")
__assert_type(geofenceAction,"string")
return api.post("/events/publishEvent/GeofenceEvent",
{
deviceId = MID,
userId = userId,
locationId = locationId,
geofenceAction = geofenceAction,
timestamp = os.time()
})
end
function fibaro.postCentralSceneEvent(keyId,keyAttribute)
local data = {
type = "centralSceneEvent",
source = MID,
data = { keyAttribute = keyAttribute, keyId = keyId }
}
return api.post("/plugins/publishEvent", data)
end
end -- sourceTrigger & refreshStates
--------------------- Net functions --------------------------------------------
do
netSync = { HTTPClient = function(args)
local self,queue,HTTP,key = {},{},net.HTTPClient(args),0
local _request
local function dequeue()
table.remove(queue,1)
local v = queue[1]
if v then
--if _debugFlags.netSync then self:debugf("netSync:Pop %s (%s)",v[3],#queue) end
--setTimeout(function() _request(table.unpack(v)) end,1)
_request(table.unpack(v))
end
end
_request = function(url,params,_)
params = copy(params)
local uerr,usucc = params.error,params.success
params.error = function(status)
--if _debugFlags.netSync then self:debugf("netSync:Error %s %s",key,status) end
dequeue()
--if params._logErr then self:errorf(" %s:%s",log or "netSync:",tojson(status)) end
if uerr then uerr(status) end
end
params.success = function(status)
--if _debugFlags.netSync then self:debugf("netSync:Success %s",key) end
dequeue()
if usucc then usucc(status) end
end
--if _debugFlags.netSync then self:debugf("netSync:Calling %s",key) end
HTTP:request(url,params)
end
function self.request(_,url,parameters)
key = key+1
if next(queue) == nil then
queue[1]='RUN'
_request(url,parameters,key)
else
--if _debugFlags.netSync then self:debugf("netSync:Push %s",key) end
queue[#queue+1]={url,parameters,key}
end
end
return self
end}
end -- Net functions
--------------------- QA functions ---------------------------------------------
do
function fibaro.restartQA(id)
__assert_type(id,"number")
return api.post("/plugins/restart",{deviceId=id or MID})
end
function fibaro.getQAVariable(id,name)
__assert_type(id,"number")
__assert_type(name,"string")
local props = (api.get("/devices/"..(id or MID)) or {}).properties or {}
for _, v in ipairs(props.quickAppVariables or {}) do
if v.name==name then return v.value end
end
end
function fibaro.setQAVariable(id,name,value)
__assert_type(id,"number")
__assert_type(name,"string")
return fibaro.call(id,"setVariable",name,value)
end
function fibaro.getAllQAVariables(id)
__assert_type(id,"number")
local props = (api.get("/devices/"..(id or MID)) or {}).properties or {}
local res = {}
for _, v in ipairs(props.quickAppVariables or {}) do
res[v.name]=v.value
end
return res
end
function fibaro.isQAEnabled(id)
__assert_type(id,"number")
local dev = api.get("/devices/"..(id or MID))
return (dev or {}).enabled
end
function fibaro.setQAValue(device, property, value)
fibaro.call(device, "updateProperty", property, (json.encode(value)))
end
function fibaro.enableQA(id,enable)
__assert_type(id,"number")
__assert_type(enable,"boolean")
return api.post("/devices/"..(id or MID),{enabled=enable==true})
end
if QuickApp then
local _init = QuickApp.__init
local _onInit = nil
local loadQA