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.

Source code    
  1. broker = "192.168.1.101"
  2. port = 1883
  3. username = "user"
  4. password = "123456"
  5. topic = "lm/test/1"
  6. payload = event.getvalue()
  7.  
  8. mqtt = require("mosquitto")
  9. client = mqtt.new()
  10.  
  11. client.ON_CONNECT = function(status, rc, msg)
  12. if status then
  13. log("mqtt connected")
  14. client:publish(topic, tostring(payload))
  15. else
  16. log("mqtt connect failed " .. tostring(msg))
  17. client:disconnect()
  18. end
  19. end
  20.  
  21. client.ON_PUBLISH = function()
  22. client:disconnect()
  23. end
  24.  
  25. client:login_set(username, password)
  26. status, rc, msg = client:connect(broker, port)
  27.  
  28. if status then
  29. client:loop_forever()
  30. else
  31. log("connect failed: " .. tostring(msg))
  32. end

To enable security for MQTT connection

Source code    
  1. -- ca.pem is uploaded via `ftp` account to ftp root directory
  2. client:tls_set('/data/ftp/ca.pem')
  3.  
  4. If you also need client certificate/private key:
  5. client:tls_set('/data/ftp/ca.pem', nil, '/data/ftp/client.crt', '/data/ftp/client.key')