forked from xHasKx/luamqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopas-example.lua
91 lines (73 loc) · 2.17 KB
/
copas-example.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
-- example of using luamqtt inside copas ioloop: http://keplerproject.github.io/copas/index.html
local mqtt = require("mqtt")
local copas = require("copas")
local mqtt_ioloop = require("mqtt.ioloop")
local num_pings = 10 -- total number of ping-pongs
local timeout = 1 -- timeout between ping-pongs
local suffix = tostring(math.random(1000000)) -- mqtt topic suffix to distinct simultaneous rinning of this script
-- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform
local token = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9"
local ping = mqtt.client{
uri = "mqtt.flespi.io",
username = token,
clean = true,
version = mqtt.v50,
}
local pong = mqtt.client{
uri = "mqtt.flespi.io",
username = token,
clean = true,
version = mqtt.v50,
}
ping:on{
connect = function(connack)
assert(connack.rc == 0)
print("ping connected")
for i = 1, num_pings do
copas.sleep(timeout)
print("ping", i)
assert(ping:publish{ topic = "luamqtt/copas-ping/"..suffix, payload = "ping"..i, qos = 1 })
end
copas.sleep(timeout)
print("ping done")
assert(ping:publish{ topic = "luamqtt/copas-ping/"..suffix, payload = "done", qos = 1 })
ping:disconnect()
end,
error = function(err)
print("ping MQTT client error:", err)
end,
}
pong:on{
connect = function(connack)
assert(connack.rc == 0)
print("pong connected")
assert(pong:subscribe{ topic="luamqtt/copas-ping/"..suffix, qos=1, callback=function(suback)
assert(suback.rc[1] > 0)
print("pong subscribed")
end })
end,
message = function(msg)
print("pong: received", msg.payload)
assert(pong:acknowledge(msg))
if msg.payload == "done" then
print("pong done")
pong:disconnect()
end
end,
error = function(err)
print("pong MQTT client error:", err)
end,
}
print("running copas loop...")
copas.addthread(function()
local ioloop = mqtt_ioloop.create{ sleep = 0.01, sleep_function = copas.sleep }
ioloop:add(ping)
ioloop:run_until_clients()
end)
copas.addthread(function()
local ioloop = mqtt_ioloop.create{ sleep = 0.01, sleep_function = copas.sleep }
ioloop:add(pong)
ioloop:run_until_clients()
end)
copas.loop()
print("done, copas loop is stopped")