forked from jangabrielsson/EventRunner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHC2.lua
3543 lines (3206 loc) · 127 KB
/
HC2.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
--[[
EventRunner. HC2 scene emulator
Copyright (c) 2019 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.
json library - Copyright (c) 2018 rxi https://github.com/rxi/json.lua
--]]
_version,_fix = "0.11","fix14" --Oct 22, 2019
_sceneName = "HC2 emulator"
_LOCAL=true -- set all resource to local in main(), i.e. no calls to HC2
_EVENTSERVER = 6872 -- To receieve triggers from external systems, HC2, Node-red etc.
_SPEEDTIME = false -- Run faster than realtime, if set to false run in realtime
_MAXTIME = 24*135 -- Max hours to run emulator
_BLOCK_PUT=false -- Block http PUT commands to the HC2 - e.g. changing resources on the HC2
_BLOCK_POST=true -- Block http POST commands to the HC2 - e.g. creating resources on the HC2
_AUTOCREATEGLOBALS=true -- Will (silently) autocreate a local fibaro global if it doesn't exist
_AUTOCREATEDEVICES=true -- Will (silently) autocreate a local fibaro device if it doesn't exist
_VALIDATECHARS = true -- Check rules for invalid characters (cut&paste, multi-byte charqcters)
_COLOR = true -- Log with colors on ZBS Output console
_HC2_FILE = "HC2.data" -- Default name of data file
_HC2_IP=_HC2_IP or "192.198.1.84" -- HC2 IP address
_HC2_USER=_HC2_USER or "xxx@yyy" -- HC2 user name
_HC2_PWD=_HC2_PWD or "xxxxxx" -- HC2 password
_EVENTRUNNER_SUPPORT=true -- Announce presence to HC2 and other ER scenes
_DEBUGREMOTERSRC=true
_FORCERESOURCEUPDATE=false
local creds = loadfile("HC2credentials.lua") -- To not accidently commit credentials to Github...
if creds then creds() end
--------------------------------------------------------
-- Main, register scenes, create temporary deviceIDs, schedule triggers...
--------------------------------------------------------
function main()
if HC2.getIPadress():match("192%.168") then -- only of we are on the local network
--HC2.copyConfigFromHC2(_HC2_FILE) -- read in configuration HC2 and write to file
end
HC2.loadConfigFromFile(_HC2_FILE) -- read in HC2 configuration data from file
if _LOCAL then -- Set all resources to local
HC2.setLocal("devices",true) -- set all devices to local /api/devices
HC2.setLocal("virtualDevices",true) -- set all devices to local /api/virtualDevices
HC2.setLocal("globalVariables",true) -- set all globals to local /api/globals
HC2.setLocal("rooms",true) -- set all rooms to local /api/rooms
HC2.setLocal("scenes",true) -- set all scenes to local /api/scenes
HC2.setLocal("settings","info") -- set info to local. /api/settings/info
HC2.setLocal("settings","location") -- set location to local. /api/settings/location
HC2.setLocal("settings","network") -- set location to local. /api/settings/network
HC2.setLocal("weather",true) -- set weather to local. /api/weather
HC2.setLocal("users",true) -- set users to local. /api/users
HC2.setLocal("iosDevices",true) -- set iPhones to local /api/iosDevices
end
--HC2.setRemote("devices",{1,2}) -- sunset/sunrise/latitude/longitude etc.
--HC2.setRemote("devices",{66,88}) -- We still want to run local, except for deviceID 66,88 that will be controlled on the HC2
--HC2.createDevice(88,"Test")
--HC2.setRemote("devices",{5})
HC2.loadEmbedded() -- If we are called from another scene (dofile...)
local setup = loadfile("HC2setup.lua") -- To not accidently commit credentials to Github...
if setup then setup() end
--Proxy.installProxy()
--Proxy.removeProxy()
--HC2.loadScenesFromDir("scenes") -- Load all files with name <ID>_<name>.lua from dir, Ex. 11_MyScene.lua
--HC2.createDevice(77,"Test") -- Create local deviceID 77 with name "[[Test"
--HC2.registerScene("EventRunnerSub3",21,"EventRunnerSub3.lua")
--HC2.registerScene("EventRunnerPub3",22,"EventRunnerPub3.lua")
--HC2.registerScene("Publisher",32,"EventRunnerPub.lua")
--HC2.registerScene("Pars",30,"Pars.lua")
--HC2.registerScene("Lib",33,"Lib1.lua")
-- Simple test scene
--[[
HC2.registerScene("SceneTest",99,"sceneTest.lua",nil,
{"+/00:00:02;call(66,'turnOn')", -- breached after 2 sec
"+/00:01:02;call(66,'turnOff')"}) -- safe after 1min and 2sec
--]]
--HC2.runTriggers{"+/00:00;startScene(".._EMULATED.id..")"} -- another way to autostart an embedded scene
--HC2.runTriggers{"+/00:00:02;call(54,'turnOn')"}
-- EventRunner test scenes
--HC2.registerScene("Supervisor",11,"SupervisorEM.lua")
--HC2.registerScene("iosLocator",14,"IOSLOcatorEM.lua")
-- List known devices and scenes
--HC2.listDevices()
--HC2.listScenes()
-- Test scenes
--HC2.registerScene("Scene1",21,"EventRunner.lua")
--HC2.registerScene("Scene1",22,"GEA 6.11.lua")
--HC2.registerScene("Scene1",23,"Main scene for time based events v1.3.3.lua",{Darkness=0,TimeOfDay='Morning',Latitude="",Longitude="",MarginSunset="0",MarginSunrise="0"})
--Log fibaro:* calls
HC2.logFibaroCalls()
--Debug filters can be used to trim debug output from noisy scenes...
--HC2.addDebugFilter("Memory used:",true)
--HC2.addDebugFilter("GEA run since",true)
--HC2.addDebugFilter("%.%.%. check running",true)
HC2.addDebugFilter("%b<>(.*)</.*>")
--dofile("HC2verify.lua")
end
_debugFlags = {
threads=false, triggers=true, eventserver=true, hc2calls=true, globals=false, web=true,
fcall=true, fglobal=false, fget=false, fother=false
}
------------------------------------------------------
-- Context, functions exported to scenes
------------------------------------------------------
function setupContext(id) -- Table of functions and variables available for scenes
return
{
__fibaroSceneId=id, -- Scene ID
__threads=0, -- Currently number of running threads
_EMULATED=true, -- Check if we run in emulated mode
fibaro=Util.copy(fibaro), -- scenes may patch fibaro:*...
__fibaro_get_device = __fibaro_get_device,
_System=_System, -- Available for debugging tasks in emulated mode
dofile=Runtime.dofile, -- Allow dofile for including code for testing, but use our version that sets context
loadfile=Runtime.loadfile,
os={clock=os.clock,date=osDate,time=osTime,difftime=os.difftime},
json=json,
print=print,
net = net,
api = api,
setTimeout=Runtime.setTimeoutContext,
clearTimeout=Runtime.clearTimeout,
setInterval=Runtime.setIntervalContext,
clearInterval=Runtime.clearInterval,
urlencode=urlencode,
select=select,
split=split,
tostring=tostring,
tonumber=tonumber,
table=table,
string=string,
math=math,
pairs=pairs,
ipairs=ipairs,
pcall=pcall,
xpcall=xpcall,
error=error,
io=io,
collectgarbage=collectgarbage,
type=type,
next=next,
bit32=bit32,
debug=debug
}
end
------------------------------------------------------------------------------
-- Startup
------------------------------------------------------------------------------
function startup()
-- Intro
Log(LOG.WELCOME,"HC2 %s v%s %s",_sceneName,_version,_fix)
if _SPEEDTIME then Log(LOG.WELCOME,"Running speedtime") end
if _LOCAL then Log(LOG.WELCOME,"Local mode, will not access resources on HC2") end
-- Setup watcher for end of time
local endTime= osTime()+_MAXTIME*3600
Runtime.speed(_SPEEDTIME)
local function cloop()
if osTime()>endTime then
Log(LOG.SYSTEM,"%s, End of time (%s hours) - exiting",osDate("%c"),_MAXTIME)
os.exit()
end
Runtime.setTimeout(cloop,1000*3600,"Time watch")
end
cloop()
Event.schedule("n/00:00",updateSun)
updateSun()
-- Setup process manager (calls GUI etc)
ProcessManager = Runtime.makeProcessManager()
Runtime.idleHandler = ProcessManager.idleHandler
-- Setup webserver
local ipAddress = HC2.getIPadress()
local GUIServer = createWebserver(ipAddress)
-- Create webserver
GUIServer.createServer("Event server",_EVENTSERVER,GUIhandler,GUIhandler)
Log(LOG.LOG,"Web GUI at http://%s:%s/emu/main",ipAddress,_EVENTSERVER)
-- Call main
local mainPosts={}
function HC2.post(event,t) mainPosts[#mainPosts+1]={event,t} end
main()
-- Post autostart and posts done in main()
Event.post({type='autostart'}) -- Post autostart to get things going
for _,e in ipairs(mainPosts) do Event.post(e[1],e[2]) end
-- Announce to HC2 ER scenes that we are up and running
if _EVENTRUNNER_SUPPORT then ER.announceEmulator(ipAddress,_EVENTSERVER) end
-- Start running timers
Runtime.runTimers() -- Run our simulated threads...
os.exit()
end
------------------------------------------------------------------------
-- Support functions - don't touch
-- requires
------------------------------------------------------------------------
function Support_functions()
require('mobdebug').coro() -- Allow debugging of Lua coroutines
--mime = require('mime')
https = require ("ssl.https")
ltn12 = require("ltn12")
--json = require("json")
socket = require("socket")
http = require("socket.http")
cfg = require "dist.config"
lfs = require("lfs")
_ENV = _ENV or _G or {} -- Environment
_HCPrompt="[HC2 ]"
function printf(...) print(string.format(...)) end -- Lazy printing - should use Log(...)
_format=string.format
LOG = {WELCOME = "orange",DEBUG = "white", SYSTEM = "Cyan", LOG = "green", ERROR = "Tomato"}
-- ZBS colors, works best with dark color scheme http://bitstopixels.blogspot.com/2016/09/changing-color-theme-in-zerobrane-studio.html
if _COLOR=='Dark' then
_LOGMAP = {orange="\027[33m",white="\027[37m",Cyan="\027[1;43m",green="\027[32m",Tomato="\027[39m"} -- ANSI escape code, supported by ZBS
else
_LOGMAP = {orange="\027[33m",white="\027[34m",Cyan="\027[35m",green="\027[32m",Tomato="\027[31m"} -- ANSI escape code, supported by ZBS
end
_LOGEND = "\027[0m"
--[[Available colors in Zerobrane
for i = 0,8 do print(("%s \027[%dmXYZ\027[0m normal"):format(30+i, 30+i)) end
for i = 0,8 do print(("%s \027[1;%dmXYZ\027[0m bright"):format(38+i, 30+i)) end
--]]
local function prconvert(o)
if type(o)=='table' then
if o.__tostring then return o.__tostring(o)
else return tojson(o) end
else return o end
end
local function tprconvert(args) local r={}; for _,o in ipairs(args) do r[#r+1]=prconvert(o) end return r end
Util = Util or {}
function Util.Msg(color,message,...)
color = _COLOR and _LOGMAP[color] or ""
local args = type(... or 42) == 'function' and {(...)()} or {...}
--message = #args>0 and _format(message,table.unpack(args)) or message
message = #args>0 and _format(message,table.unpack(tprconvert(args))) or prconvert(message)
local env,sceneid = Scene.global(),_HCPrompt
if env then sceneid = _format("[%s:%s]",env.__fibaroSceneId,env.__orgInstanceNumber) end
print(_format("%s%s%s %s%s",color,osOrgDate("%a/%b/%d,%H:%M:%S:",osTime()),sceneid,message,_COLOR and _LOGEND or ""))
return message
end
function Util.isEvent(e) return type(e) == 'table' and e.type end
function Util.copy(obj) return Util.transform(obj, function(o) return o end) end
function Util.equal(e1,e2)
local t1,t2 = type(e1),type(e2)
if t1 ~= t2 then return false end
if t1 ~= 'table' and t2 ~= 'table' then return e1 == e2 end
for k1,v1 in pairs(e1) do if e2[k1] == nil or not Util.equal(v1,e2[k1]) then return false end end
for k2,v2 in pairs(e2) do if e1[k2] == nil or not Util.equal(e1[k2],v2) then return false end end
return true
end
function Util.transform(obj,tf)
if type(obj) == 'table' then
local res = {} for l,v in pairs(obj) do res[l] = Util.transform(v,tf) end
return res
else return tf(obj) end
end
function Util.isRemoteEvent(e) return type(e)=='table' and type(e[1])=='string' end
function Util.encodeRemoteEvent(e) return {urlencode(json.encode(e)),'%%ER%%'} end
function Util.decodeRemoteEvent(e) return (json.decode((urldecode(e[1])))) end
function _assert(test,msg,...)
if not test then
msg = _format(msg,...) error(msg,3)
end
end
function _assertf(test,msg,fun) if not test then msg = _format(msg,fun and fun() or "") error(msg,3) end end
function Debug(flag,message,...) if flag then Util.Msg(LOG.DEBUG,message,...) end end
function Log(color,message,...) return Util.Msg(color,message,...) end
Util.getIDfromEvent={ CentralSceneEvent=function(d) return d.deviceId end,AccessControlEvent=function(d) return d.id end }
Util.getIDfromTrigger={
property=function(e) return e.deviceID end,
event=function(e) return e.event and Util.getIDfromEvent[e.event.type or ""](e.event.data) end
}
end
------------------------------------------------------------
-- Webserver GUI
---------------------------------------------------------------
function Web_functions()
function createWebserver(ipAdress)
local self = { ipAdress = ipAdress }
local function clientHandler(client,getHandler,postHandler,putHandler)
client:settimeout(0,'b')
client:setoption('keepalive',true)
local ip=client:getpeername()
--printf("IP:%s",ip)
while true do
local l,e,j = client:receive()
--print(string.format("L:%s, E:%s, J:%s",l or "nil", e or "nil", j or "nil"))
if l then
local body,referer,header,e,b
local method,call = l:match("^(%w+) (.*) HTTP/1.1")
repeat
header,e,b = client:receive()
--print(string.format("H:%s, E:%s, B:%s",header or "nil", e or "nil", b or "nil"))
if b and b~="" then body=b end
referer = header and header:match("^[Rr]eferer:%s*(.*)") or referer
until header == nil or e == 'closed'
if method=='POST' and postHandler then postHandler(method,client,call,body,referer)
elseif method=='PUT' and putHandler then putHandler(method,client,call,body,referer)
elseif method=='GET' and getHandler then getHandler(method,client,call,body,referer) end
--client:flush()
client:close()
return
end
coroutine.yield()
end
end
local function socketServer(server,getHandler,postHandler,putHandler)
while true do
repeat
client, err = server:accept()
if err == 'timeout' then coroutine.yield() end
until err ~= 'timeout'
ProcessManager.create(clientHandler,"client",client,getHandler,postHandler,putHandler)
end
end
function self.createServer(name,port,getHandler,postHandler,putHandler)
local server,c,err=assert(socket.bind("*", port))
local i, p = server:getsockname()
local timeoutCounter = 0
assert(i, p)
--printf("http://%s:%s/test",ipAdress,port)
server:settimeout(0,'b')
server:setoption('keepalive',true)
ProcessManager.create(socketServer,"server",server,getHandler,postHandler,putHandler)
Log(LOG.LOG,"Created %s at %s:%s",name,self.ipAdress,port)
end
return self
end
local GUI_HANDLERS = {
["GET"] = {
["(.*)"] = function(client,ref,body,call)
local page = Pages.getPath(call)
if page~=nil then client:send(page) return true
else return false end
end,
["/emu/code/(.*)"]=function(client,ref,body,code)
if code then
loadstring(urldecode(code))()
client:send("HTTP/1.1 302 Found\nLocation: "..(ref or "/emu/triggers").."\n")
return true
end
end,
["/images/(.*)"]=function(client,ref,body,image) -- only small images, so we don't chunk it... move to getPages
local f = io.open(image)
if not f then error("No such file:"..image) end
local src = f:read("*all")
local len = string.len(src)
client:send("HTTP/1.1 200 OK\nContent-Type: image/jpeg\nContent-Length: "..len.."\n\n")
client:send(src)
f:close()
end,
["/emu/fibaro/(%w+)/(%w+)/?(.-)%?(.*)"]=function(client,ref,body,method,id,action,args)
args = args and args~="" and args:match("value=(.+)") or nil
if method and fibaro[method] then
if action=="" then
if args ~= nil and method~="setGlobal" then args=json.decode(urldecode(args)) end
--printf("Calling fibaro:%s(%s)",method,id)
fibaro[method](fibaro,tonumber(id) and tonumber(id) or id,args)
else
--printf("Calling fibaro:%s(%s,'%s')",method,id,action,args and _format(", '%s'",args) or "")
fibaro[method](fibaro,tonumber(id),action,args)
end
client:send("HTTP/1.1 302 Found\nLocation: "..(ref or "/emu/main").."\n")
return true
end
return false
end,
},
["POST"] = {
["^/api(/.*)"] = function(client,ref,body,call)
api.post(call,json.decode(body))
client:send("HTTP/1.1 201 Created\nETag: \"c180de84f991g8\"\n\n")
return true
end,
["^/trigger/(%-?%d+)"] = function(client,ref,body,id)
Event.post({type='other', _id=math.abs(tonumber(id)), _args=json.decode(body)})
client:send("HTTP/1.1 201 Created\nETag: \"c180de84f991g8\"\n\n")
return true
end,
["^/trigger$"] = function(client,ref,body)
e = json.decode(body)
Event.post(e)
client:send("HTTP/1.1 201 Created\nETag: \"c180de84f991g8\"\n")
return true
end,
},
["PUT"] = {
["(.*)"] = function(client,ref,body,call)
if _debugFlags.web then Log(LOG.LOG,"PUT %s %s",call,body) end
client:send("HTTP/1.1 201 Created\nETag: \"c180de84f991g8\"\n")
return true
end,
}
}
function GUIhandler(method,client,call,body,ref)
local stat,res = pcall(function()
for p,h in pairs(GUI_HANDLERS[method] or {}) do
local match = {call:match(p)}
if match and #match>0 then
if h(client,ref,body,table.unpack(match)) then return end
end
end
client:send("HTTP/1.1 501 Not Implemented\nLocation: "..(ref or "/emu/triggers").."\n")
end)
if not stat then
local p = Pages.renderError(res)
client:send(p)
end
end
end
------------------------------------------------------------------------------
-- Scene support
-- load
-- start
-- kill
------------------------------------------------------------------------------
function Proxy_functions()
Proxy = {}
function Proxy.installProxy(name)
name = name or "_EMULATOR_PROXY"
local id,proxy
local nproxies=0
local scenes = api.rawGet(false,"/scenes")
for _,s in ipairs(scenes) do
if s.name==name then id = s.id; proxy = s break end -- already exist, return ID
end
if not id then
proxy = {actions = {devices = {}, groups = {}, scenes = {}},
alexaProhibited = true, autostart = true, --iconID = 0,
isLua = true, killOtherInstances = false, killable = true,
lua = "", maxRunningInstances = 10,
name = name,properties = "", protectedByPIN = false,runConfig = "TRIGGER_AND_MANUAL",
triggers = {events = {}, globals = {}, properties = {}, weather = {}},
type = "com.fibaro.luaScene",visible = false}
proxy = api.rawPost(false,"/scenes",proxy)
id = proxy and type(proxy)=='table' and proxy.id
end
if id then
local trH = {autostart={},properties={},globals={},events={}}
for _,tr in ipairs(Scene.getAllLoadedTriggers()) do
if tr.type=='property' and HC2.getDevice(tr.deviceID,true)._local == false then
trH.properties[#trH.properties+1]=_format("%d %s",tr.deviceID,tr.propertyName)
elseif tr.type=='global' and HC2.getGlobal(tr.name,true)._local == false then
trH.globals[#trH.globals+1]=tr.name
elseif tr.type=='event' and HC2.getDevice(Util.getIDfromTrigger[tr.type](tr),true) then
local id = Util.getIDfromTrigger[tr.type](tr)
trH.events[#trH.events+1]=_format("%d %s",id,tr.event.type)
end
end
local trH2 = {}
for h,v in pairs(trH) do
trH2[#trH2+1]="%% "..h
for _,t in ipairs(v) do nproxies=nproxies+1; trH2[#trH2+1]=t end
end
trH2=table.concat(trH2,"\n")
proxy.runConfig = "TRIGGER_AND_MANUAL"
proxy.maxRunningInstances = 10
proxy.lua =
"--[[".."\n"..trH2.."\n".."--]]\n"..[[
local host,port = "]]..HC2.getIPadress()..[[",6872 -- IP and port of emulator
local URL = string.format("http://%s:%s/trigger",host,port)
local trigger = fibaro:getSourceTrigger()
local data = json.encode(trigger)
fibaro:debug(data)
if trigger.type == 'autostart' or trigger.type=='other' then
fibaro:abort()
end
local req = net.HTTPClient()
req:request(URL,{options = {method = 'POST', data=data, timeout=500},
error = function(status) fibaro:debug(json.encode(status)) end})
]]
api.rawPut(false,"/scenes/"..id,proxy)
Log(LOG.SYSTEM,"HC2 trigger proxy installed (%s)",nproxies)
return id
end
end
function Proxy.removeProxy(name)
name = name or "_EMULATOR_PROXY"
local scenes = api.rawGet(false,"/scenes")
for _,s in ipairs(scenes) do
if s.name==name then
api.rawDelete(false,"/scenes/"..s.id)
Log(LOG.SYSTEM,"HC2 trigger proxy removed")
break;
end
end
end
end
------------------------------------------------------------------------------
-- Scene support
-- load
-- start
-- kill
------------------------------------------------------------------------------
function Scene_functions()
Scene={ scenes={} }
_SceneContext = {} -- Map from thread -> environment
local mt = {}; mt.__mode = "k";
setmetatable(_SceneContext,mt) -- weak keys (keys are coroutines)
function YIELD(ms)
local co = coroutine.running()
if _SceneContext[co] then
BREAKIDLE=true; pcall(function() coroutine.yield(co,(ms and ms > 0 and ms or 100)/1000) end)
end
end
-- If we need to access local scene variables
function Scene.global() return _SceneContext[coroutine.running()] end -- global().<var>
function Scene.setGlobal(v,s) _SceneContext[coroutine.running()][v]=s end -- setGlobal('v',42)
function Scene.load(name,id,file,fullname)
if Scene.scenes[id] then
Log(LOG.LOG,"Scene %s already loaded",id)
return false
end
Scene.scenes[id] = Scene.scenes[id] or {}
local scene,msg = Scene.scenes[id]
scene.name = name
scene.fullname=fullname
scene.id = id
scene.fromFile=true
scene.runningInstances = 0
scene._local = true
scene.runConfig = "TRIGGER_AND_MANUAL"
scene.triggers,scene.lua = Scene.parseHeaders(file,id)
scene.isLua = true
ER.checkForEventRunner(scene)
scene.code,msg=loadfile(file)
_assert(scene.code~=nil,"Error in scene file %s: %s",file,msg)
Log(LOG.SYSTEM,"Loaded scene:%s, id:%s, file:'%s'",name,id,file)
return scene
end
function Scene.start(scene,event,args)
if not scene._local then return end
local globals,env = setupContext(scene.id)
if nil then -- If we need to intercept access to globals, however it slows down debugging (stepping)
local context = {
__index = function (t,k) --printf("Get %s=%s",k,globals[k])
return globals[k]
end,
__newindex = function (t,k,v) --printf("Set %s=%s",k,globals[k])
globals[k] = v
end
}
env = {}
setmetatable(env,context)
else
env=globals
end
globals._ENV=env
globals.__fibaroSceneSourceTrigger = event
globals.__fibaroSceneArgs = args
globals.__sceneCode = scene.code
globals.__fullFileName = scene.fullname
globals.__debugName=_format("[%s:%s]",scene.id,scene.runningInstances+1)
globals.__sceneCleanup = function(co)
if (not scene._terminateMsg) or (scene._terminateMsg and not scene._terminateMsg(scene.id,env.__orgInstanceNumber,env)) then
Log(LOG.LOG,"Scene %s terminated (%s)",env.__debugName,co)
end
scene.runningInstances=scene.runningInstances-1
end
local tr = Runtime.setTimeoutContext(function()
scene.runningInstances=scene.runningInstances+1
env.__orgInstanceNumber=scene.runningInstances
setfenv(scene.code,env)
--require('mobdebug').on()
scene.code()
end,
0,scene.name,env)
_SceneContext[tr]=env
if Util.isRemoteEvent(args) then args=Util.decodeRemoteEvent(args) end
if (not scene._startMsg) or (scene._startMsg and not scene._startMsg(scene.id,scene.runningInstances,env)) then
Log(LOG.LOG,"Scene %s started (%s), trigger:%s %s(%s)",globals.__debugName,scene.name,tojson(event),args and tojson(args) or "",tr)
end
end
function Scene.stop(scene)
if scene.runningInstances>0 then
Runtime.clearAllTimeoutFilter(function(t) return t.env and t.env.__fibaroSceneId==scene.id end)
Log(LOG.LOG,"Stopping scene %s (%s)",scene.id, scene.name)
else Log(LOG.LOG,"Scene %s not running (%s)",scene.id, scene.name) end
end
function Scene.checkValidCharsInFile(src,fileName)
local lines = split(src,'\r')
local function ptr(p) local r={}; for i=1,p+9 do r[#r+1]=' ' end return table.concat(r).."^" end
for n,s in ipairs(lines) do
s=s:match("^%c*(.*)")
local p = s:find("\xEF\xBB\xBF")
if p then
local err = string.format("Illegal UTF-8 sequence in file:%s\rLine:%3d, %s\r%s",fileName,n,s,ptr(p))
err=err:gsub("%%","%%%%")
Log(LOG.ERROR,err)
end
end
end
function Scene.parseHeaders(fileName,id)
local headers = {}
local f = io.open(fileName)
if not f then error("No such file:"..fileName) end
local src = f:read("*all") f:close()
Scene.checkValidCharsInFile(src,fileName)
local c = src:match("--%[%[.-%-%-%]%]")
local curr = nil
if c==nil or c=="" then c = "--%[%[\n%%%% autostart\n%]%]--" end
if c and c~="" then
c=c:gsub("([\r\n]+)","\n")
c = split(c,'\n')
for i=2,#c-1 do
if c[i]:match("^%%%%") then curr=c[i]:match("%a+"); headers[curr]={}
elseif curr then
local h = headers[curr] or {}
h[#h+1] = c[i]
headers[curr]=h
end
end
end
local events={}
for i=1,headers['properties'] and #headers['properties'] or 0 do
local id,name = headers['properties'][i]:match("(%d+)%s+([%a]+)")
if id and id ~="" and name and name~="" then events[#events+1]={type='property',deviceID=tonumber(id), propertyName=name} end
end
for i=1,headers['globals'] and #headers['globals'] or 0 do
local name = headers['globals'][i]:match("([%w]+)")
if name and name ~="" then events[#events+1]={type='global', name=name} end
end
for i=1,headers['events'] and #headers['events'] or 0 do
local id,t = headers['events'][i]:match("(%d+)%s+(CentralSceneEvent)")
if id and id~="" and t and t~="" then events[#events+1]={type='event',event={type='CentralSceneEvent',data={deviceId=tonumber(id)}}}
else
id,t = headers['events'][i]:match("(%d+)%s+(AccessControlEvent)")
if id and id~="" and t and t~="" then events[#events+1]={type='event',event={type='AccessControlEvent',data={id=tonumber(id)}}} end
end
end
if headers['autostart'] then events[#events+1]={type='autostart'} end
return events,src
end
function Scene.getAllLoadedTriggers()
Scene.allLoadedTriggers = {}
local ts={}
for id,scene in pairs(HC2.rsrc.scenes) do
if scene.fromFile then
for _,t in pairs(scene.triggers) do
if t.type=='property' or t.type=='global' or t.type=='event' then
local f=true
for _,t0 in pairs(ts) do if Util.equal(t0,t) then f= false break end end
if f then ts[#ts+1]=t
end
end
end
end
end
Scene.allLoadedTriggers = ts
return ts
end
end
------------------------------------------------------------------------
-- HC2 functions
-- Creating and managing HC2 resources
------------------------------------------------------------------------
function HC2_functions()
HC2 = { rsrc={} }
local function initRsrcses()
HC2.rsrc.globalVariables = {}
HC2.rsrc.devices = {}
HC2.rsrc.virtualDevices = {}
HC2.rsrc.iosDevices = {}
HC2.rsrc.users = {}
HC2.rsrc.scenes = {}
HC2.rsrc.sections = {}
HC2.rsrc.rooms = {}
HC2.rsrc.settings ={} --
HC2.rsrc.weather = {} -- { 1 = weather }
HC2.rsrc.count = {glob=0,dev=0,vdev=0,ios=0,users=0,scenes=0,sect=0,rooms=0}
end
initRsrcses()
_IPADDRESS = nil
function HC2.getIPadress()
if _IPADDRESS then return _IPADDRESS end
local someRandomIP = "192.168.1.122" --This address you make up
local someRandomPort = "3102" --This port you make up
local mySocket = socket.udp() --Create a UDP socket like normal
mySocket:setpeername(someRandomIP,someRandomPort)
local myDevicesIpAddress, somePortChosenByTheOS = mySocket:getsockname()-- returns IP and Port
_IPADDRESS = myDevicesIpAddress == "0.0.0.0" and "127.0.0.1" or myDevicesIpAddress
return _IPADDRESS
end
function HC2.runTriggers(tab)
if type(tab)=='string' then tab={tab} end
for _,s in ipairs(tab or {}) do
local t,cmd = s:match("(.-);(.*)")
cmd = loadstring("fibaro:"..cmd)
Event.post(cmd,t)
end
end
function HC2.registerSceneTrigger(t,sceneID)
local scene = HC2.rsrc.scenes[sceneID]
Event.event(t,function(env) Scene.start(scene,env.event) end)
end
function HC2.registerScene(name,id,file,globVars,triggers,fullname)
local scene = Scene.load(name,id,file,fullname)
if not scene then return end
HC2.rsrc.scenes[id]=scene
for _,t in ipairs(scene.triggers) do
Log(LOG.SYSTEM,"Scene:%s [ Trigger:%s ]",id,tojson(t))
Event.event(t,function(env) Scene.start(scene,env.event) end)
end
Event.event({type='other',_id=id}, -- startup event
function(env)
local event = env.event
local args = event._args
event._args=nil
event._id=nil
Scene.start(scene,event,args)
end)
for name,value in pairs(globVars or {}) do HC2.createGlobal(name,value) end
HC2.runTriggers(triggers)
end
local function patchID(t)
local res,c={},0;
for k,v in pairs(t) do if type(v)=='table' then res[tonumber(k)]=v; if v._local==nil then v._local=false end c=c+1 end end
return res,c
end
function HC2.copyConfigFromHC2(file)
file = file or _HC2_FILE
initRsrcses()
local rsrc,count = HC2.rsrc,HC2.rsrc.count
Log(LOG.SYSTEM,"Reading configuration from H2C...")
local vars = api.rawGet(false,"/globalVariables/")
for _,v in ipairs(vars) do rsrc.globalVariables[v.name] = v; v._local=false; count.glob=count.glob+1; end
local s = api.rawGet(false,"/sections")
for _,v in ipairs(s) do rsrc.sections[v.id] = v; v._local=false; count.sect=count.sect+1 end
s = api.rawGet(false,"/rooms")
for _,v in ipairs(s) do rsrc.rooms[v.id] = v; v._local=false; count.rooms=count.rooms+1 end
s = api.rawGet(false,"/devices")
for _,v in ipairs(s) do rsrc.devices[v.id] = v; v._local=false; count.dev=count.dev+1 end
s = api.rawGet(false,"/virtualDevices")
for _,v in ipairs(s) do rsrc.virtualDevices[v.id] = v; v._local=false; count.vdev=count.vdev+1 end
s = api.rawGet(false,"/scenes") -- need to retrieve once more to get the Lua code
for _,v in ipairs(s) do
local scene = api.rawGet(false,"/scenes/"..v.id)
rsrc.scenes[v.id] = scene; scene._local=false; count.scenes=count.scenes+1;
scene.EventRunner = scene.lua and scene.lua:match(ER.gEventRunnerKey)
end
s = api.rawGet(false,"/iosDevices")
for _,v in ipairs(s) do rsrc.iosDevices[v.id] = v; v._local=false; count.ios=count.ios+1 end
rsrc.settings.info = api.rawGet(false,"/settings/info"); rsrc.settings.info._local=false
rsrc.settings.location = api.rawGet(false,"/settings/location"); rsrc.settings.location._local=false
rsrc.settings.network = api.rawGet(false,"/settings/network"); rsrc.settings.network._local=false
rsrc.weather[1] = api.rawGet(false,"/weather"); rsrc.weather[1]._local=false
HC2.writeConfigurationToFile(file)
Log(LOG.SYSTEM,"Configuration from HC2, Globals:%s, Scenes:%s, Device:%s, virtualDevice:%s, Rooms:%s",count.glob,count.scenes,count.dev,count.vdev,count.rooms)
end
function HC2.loadConfigFromFile(file)
file = file or _HC2_FILE
local rsrc,count = HC2.rsrc,HC2.rsrc.count
local f = io.open(file)
if f then
local stat,res = pcall(function()
count.glob=0
Log(LOG.SYSTEM,"Reading and decoding configuration from %s",file)
rsrc=persistence.load(file);
for n,v in pairs(rsrc.globalVariables or {}) do if v._local==nil then v._local=false end; count.glob=count.glob+1 end
rsrc.devices,count.dev=patchID(rsrc.devices or {});
rsrc.virtualDevices,count.vdev=patchID(rsrc.virtualDevices or {});
rsrc.scenes,count.scenes=patchID(rsrc.scenes);
rsrc.rooms,count.rooms=patchID(rsrc.rooms or {});
rsrc.sections,count.sect=patchID(rsrc.sections);
rsrc.iosDevices,count.ios=patchID(rsrc.iosDevices or {});
if not rsrc.settings then rsrc.settings = {} end
rsrc.settings.info = rsrc.settings.info or rsrc["settings/info"] or rsrc.info[1]
if rsrc.settings.info and not next(rsrc.settings.info) then rsrc.settings.info = nil end
if rsrc.settings.info and rsrc.settings.info._local==nil then rsrc.settings.info._local=false end
rsrc.settings.location = rsrc.settings.location or rsrc["settings/location"] or rsrc.location[1]
if rsrc.settings.location and not next(rsrc.settings.location) then rsrc.settings.location = nil end
if rsrc.settings.location and rsrc.settings.location._local==nil then rsrc.settings.location._local=false end
rsrc.settings.network = rsrc.settings.network or rsrc["settings/network"] or rsrc.network[1]
if rsrc.settings.network and not next(rsrc.settings.network) then rsrc.settings.network = nil end
if rsrc.settings.network and rsrc.settings.network._local==nil then rsrc.settings.network._local=false end
rsrc.weather = rsrc.weather or {}
if not rsrc.weather[1] then rsrc.weather = {rsrc.weather} end
if rsrc.weather[1]._local==nil then rsrc.weather[1]._local=false end
HC2.rsrc=rsrc
HC2.rsrc.count = count
end)
if not stat then
Log(LOG.SYSTEM,"Bad format for HC2 data file (%s)(%s), please re-generate",file,res)
end
else Log(LOG.SYSTEM,"No HC2 data file found (%s)",file) end
Log(LOG.SYSTEM,"Configuration from file, Globals:%s, Scenes:%s, Device:%s, Rooms:%s",count.glob,count.scenes,count.dev,count.rooms)
end
function HC2.writeConfigurationToFile(file)
Log(LOG.SYSTEM,"Writing configuration data to '%s'",file)
persistence.store(file, HC2.rsrc);
end
local function standardInfo()
local rsrc=
[[{"serialNumber":"HC2-999999","hcName":"Home","mac":"00:22:4d:ab:83:46",
"_local":true,
"zwaveVersion":"4.33","timeFormat":24,"zwaveRegion":"EU","serverStatus":1550914298,
"defaultLanguage":"en","sunsetHour":"18:20","sunriseHour":"05:27","hotelMode":false,
"temperatureUnit":"C","batteryLowNotification":false,"smsManagement":false,"date":"07:25 | 28.3.2019","softVersion":"4.530",
"beta":false,
"currentVersion":{"version":"4.530","type":"stable"},
"installVersion":{"version":"","type":"","status":"","progress":0},
"timestamp":1553754343,"online":true,"updateStableAvailable":false,
"updateBetaAvailable":true,"newestStableVersion":"4.530","newestBetaVersion":"4.532"}]]
return json.decode(rsrc)
end
local function standardOne()
local rsrc=
[[{"properties":{"sunsetHour":"06:00","sunriseHour":"20:00"},"_local":true}]]
return json.decode(rsrc)
end
local function standardLocation()
local rsrc=
[[{"houseNumber":3,"timezone":"Europe/Stockholm","timezoneOffset":3600,"ntp":true,
"_local":true,
"ntpServer":"pool.ntp.org","date":{"day":28,"month":3,"year":2019},"time":{"hour":7,"minute":27},
"latitude":61.33,"longitude":19.787,"city":"","temperatureUnit":"C","windUnit":"km/h",
"timeFormat":24,"dateFormat":"dd.mm.yy","decimalMark":"."}]]
return json.decode(rsrc)
end
local function standardNetwork()
local rsrc=
[[{"dhcp":true,"ip":"192.168.1.84","mask":"255.255.255.0","gateway":"192.168.1.1",
"dns":"192.168.1.1","remoteAccess":true,"remoteAccessSupport":0}]]
return json.decode(rsrc)
end
local function standardWeather()
local rsrc=
[[{"Temperature": 9.5,"TemperatureUnit": "C","_local":true,
"Humidity": 91.8,
"Wind": 11.52,
"WindUnit": "km/h",
"WeatherCondition": "cloudy",
"ConditionCode": 26}]]
return json.decode(rsrc)
end
local autocreate = {
globalVariables = function(name)
if not _AUTOCREATEGLOBALS then return end
Debug(_debugFlags.autocreate,"Autocreating global '%s'",name)
return HC2.createGlobal(name)
end,
devices = function(id)
if id > 3 and not _AUTOCREATEDEVICES then return end
Debug(_debugFlags.autocreate,"Autocreating deviceID:%s",id)
if id==1 then return standardOne()
elseif id==2 then return standardTwo() -- FIX
else return HC2.createDevice(id) end
end,
settings = function(t)
Debug(_debugFlags.autocreate,"Autocreating /settings/%s",t);
return t=='info' and standardInfo() or t=='location' and standardLocation() or t=='network' and standardNetwork()
end,
weather = function(id) Debug(_debugFlags.autocreate,"Autocreating /weather"); return standardWeather() end,
}
function HC2.getRsrc(name,id,f)
local rsrcs=HC2.rsrc[name]
local rsrc=rsrcs[id]
if not rsrc and autocreate[name] then-- rsrc doesn't exists
rsrc = autocreate[name](id)
rsrcs[id]=rsrc
end
if rsrc and rsrc._local==false and not f then -- remote resource - get it from HC2
local url = "/"..name.."/"..id
if name == "weather" then url="/weather" end
rsrc = api.rawGet(_DEBUGREMOTERSRC,url)
rsrcs[id] = rsrc -- cache it
rsrc._local = false
end
return rsrc
end
function HC2.getAllRsrc(name,filter)
local function getId(n,r) return n=='globalVariables' and r.name or r.id end
filter = filter or function() return true end
if _FORCERESOURCEUPDATE then
local rrs = api.rawGet(false,"/"..name)
local lrs = HC2.rsrc[name]
for _,r in ipairs(rrs) do
local id2 = getId(name,r)
if lrs[id2] then r._local = lrs[id2]._local; lrs[id2] = r
else lrs[id2] = r; r._local = false end
end
local res = {}
for _,r in pairs(lrs) do res[#res+1]=r end
return res
end
local res,rems,rm = {},{},0
for id,r in pairs(HC2.rsrc[name]) do
if r._local then
if filter(r) then res[#res+1]=r end
else rm=rm+1; rems[id]=r end
end
local rs={}
if rm > 8 then -- Over 5 items, do a get all...
rs = api.rawGet(false,"/"..name)
else
for id,_ in pairs(rems) do res[#rs+1] = api.rawGet(false,"/"..name.."/"..id) end
end
for _,d in ipairs(rs) do
if HC2.rsrc[name][getId(name,d)] then res[#res+1]=d end
end
return res