-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
59 lines (53 loc) · 1.61 KB
/
init.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
config = {
host="192.168.0.108",
clientid="lua-interpreter",
topic="/lua-interpreter"
}
function interpret(client, topic, data)
print("message on " .. topic .. " with body " .. data)
if topic == config["topic"] and data ~= nil then
print("interpreting message")
local req_t = sjson.decode(data)
local status, val = pcall(loadstring(req_t["chunk"]))
if status then
print("interpreting successful")
end
local replyto = req_t["reply-to"]
if replyto ~= nil then
local resp_t = {success=status, message=val}
local resp_json = sjson.encode(resp_t)
print("publishing to " .. replyto .. " with " .. resp_json)
client:publish(replyto, resp_json, 0, 0, function () print("publish success") end)
end
end
end
function onconnect(client)
client:subscribe(config["topic"], 0, function () print("subscribe success") end)
end
function mqttsetup()
local client = mqtt.Client(config["clientid"], 120)
client:on("message", interpret)
client:connect(config["host"], 1883, false, function ()
print("connect success")
onconnect(client)
end,
function (_, reason)
print('connect failed reason: ' .. reason)
end
)
end
function wificheck(timer)
if wifi.sta.status() == wifi.STA_GOTIP then
print('wifi connected')
timer:unregister()
mqttsetup()
else
print('wifi not connected...')
timer:start()
end
end
function init()
local inittimer = tmr.create()
inittimer:alarm(1000, tmr.ALARM_SEMI, wificheck)
end
init()