-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathmain-sync.lua
89 lines (72 loc) · 2.06 KB
/
main-sync.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
-- luacheck: globals ngx
local log = ngx.log
local timer_at = ngx.timer.at
local ERR = ngx.ERR
local tbl_concat = table.concat
local function trace(...)
local line = {}
for i = 1, select("#", ...) do
line[i] = tostring(select(i, ...))
end
log(ERR, tbl_concat(line, " "))
end
trace("main.lua started")
local start_timer
local function on_timer(...)
trace("on_timer: ", ...)
local mqtt = require("mqtt")
-- create mqtt client
local client = mqtt.client{
-- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it
-- uri = "test.mosquitto.org",
uri = "mqtt.flespi.io",
-- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform
username = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9",
clean = true,
connector = require("mqtt.ngxsocket"),
secure = true, -- optional
}
trace("created MQTT client", client)
client:on{
connect = function(connack)
if connack.rc ~= 0 then
trace("connection to broker failed:", connack)
return
end
trace("connected:", connack) -- successful connection
-- subscribe to test topic and publish message after it
assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function(suback)
trace("subscribed:", suback)
-- publish test message
trace('publishing test message "hello" to "luamqtt/simpletest" topic...')
assert(client:publish{
topic = "luamqtt/simpletest",
payload = "hello",
qos = 1
})
end})
end,
message = function(msg)
assert(client:acknowledge(msg))
trace("received:", msg)
end,
error = function(err)
trace("MQTT client error:", err)
end,
close = function(conn)
trace("MQTT conn closed:", conn.close_reason)
end
}
trace("running client in synchronous input/output loop")
mqtt.run_sync(client)
trace("done, synchronous input/output loop is stopped")
-- to reconnect
start_timer()
end
start_timer = function()
local ok, err = timer_at(1, on_timer)
if not ok then
trace("failed to start timer:", err)
end
end
start_timer()