|
| 1 | +-- load mqtt module |
| 2 | +local mqtt = require("mqtt") |
| 3 | +local copas = require("copas") |
| 4 | + |
| 5 | +-- create mqtt client |
| 6 | +local client = mqtt.client{ |
| 7 | + -- NOTE: this broker is not working sometimes; comment username = "..." below if you still want to use it |
| 8 | + -- uri = "test.mosquitto.org", |
| 9 | + uri = "mqtt.flespi.io", |
| 10 | + -- NOTE: more about flespi tokens: https://flespi.com/kb/tokens-access-keys-to-flespi-platform |
| 11 | + username = "stPwSVV73Eqw5LSv0iMXbc4EguS7JyuZR9lxU5uLxI5tiNM8ToTVqNpu85pFtJv9", |
| 12 | + clean = true, |
| 13 | + |
| 14 | + -- NOTE: copas connector |
| 15 | + connector = require("mqtt.luasocket-copas"), |
| 16 | +} |
| 17 | +print("created MQTT client", client) |
| 18 | + |
| 19 | +client:on{ |
| 20 | + connect = function(connack) |
| 21 | + if connack.rc ~= 0 then |
| 22 | + print("connection to broker failed:", connack:reason_string(), connack) |
| 23 | + return |
| 24 | + end |
| 25 | + print("connected:", connack) -- successful connection |
| 26 | + |
| 27 | + -- subscribe to test topic and publish message after it |
| 28 | + assert(client:subscribe{ topic="luamqtt/#", qos=1, callback=function(suback) |
| 29 | + print("subscribed:", suback) |
| 30 | + |
| 31 | + -- publish test message |
| 32 | + print('publishing test message "hello" to "luamqtt/simpletest" topic...') |
| 33 | + assert(client:publish{ |
| 34 | + topic = "luamqtt/simpletest", |
| 35 | + payload = "hello", |
| 36 | + qos = 1 |
| 37 | + }) |
| 38 | + end}) |
| 39 | + end, |
| 40 | + |
| 41 | + message = function(msg) |
| 42 | + assert(client:acknowledge(msg)) |
| 43 | + |
| 44 | + print("received:", msg) |
| 45 | + print("disconnecting...") |
| 46 | + assert(client:disconnect()) |
| 47 | + end, |
| 48 | + |
| 49 | + error = function(err) |
| 50 | + print("MQTT client error:", err) |
| 51 | + end, |
| 52 | + |
| 53 | + close = function() |
| 54 | + print("MQTT conn closed") |
| 55 | + end |
| 56 | +} |
| 57 | + |
| 58 | +-- run io loop for client until connection close |
| 59 | +copas.addthread(function() |
| 60 | + print("running client in separated copas thread #1...") |
| 61 | + mqtt.run_sync(client) |
| 62 | +end) |
| 63 | + |
| 64 | +copas.addthread(function() |
| 65 | + print("execution of separated copas thread #2...") |
| 66 | + copas.sleep(0.1) |
| 67 | + print("thread #2 stopped") |
| 68 | +end) |
| 69 | + |
| 70 | +copas.loop() |
| 71 | +print("done, copas loop is stopped") |
0 commit comments