MQTT client
Example:
Task
How to establish MQTT connection from LogicMachine to external MQTT broker
Event script
This example will publish event value and then disconnect from MQTT broker.
- broker = "192.168.1.101"
- port = 1883
- username = "user"
- password = "123456"
- topic = "lm/test/1"
- payload = event.getvalue()
-
- mqtt = require("mosquitto")
- client = mqtt.new()
-
- client.ON_CONNECT = function(status, rc, msg)
- if status then
- log("mqtt connected")
- client:publish(topic, tostring(payload))
- else
- log("mqtt connect failed " .. tostring(msg))
- client:disconnect()
- end
- end
-
- client.ON_PUBLISH = function()
- client:disconnect()
- end
-
- client:login_set(username, password)
- status, rc, msg = client:connect(broker, port)
-
- if status then
- client:loop_forever()
- else
- log("connect failed: " .. tostring(msg))
- end
To enable security for MQTT connection
- -- ca.pem is uploaded via `ftp` account to ftp root directory
- client:tls_set('/data/ftp/ca.pem')
-
- If you also need client certificate/private key:
- client:tls_set('/data/ftp/ca.pem', nil, '/data/ftp/client.crt', '/data/ftp/client.key')