Example:

Task

How to establish MQTT connection from LogicMachine to external MQTT broker

Install these packages through System config –> System –> Packages

Libcares
Libmosquitto
Luamosquitto

You can also find them in download section.

Resident script

Add Resident script, 0 seconds, to establish MQTT client connection to external broker.

Source code    
  1. mqtt = require("mosquitto")
  2. client = mqtt.new()
  3.  
  4. client.ON_CONNECT = function()
  5. client:publish("world", "hello")
  6. local qos = 1
  7. local retain = true
  8. local mid = client:publish("lm/test/1", "my payload", qos, retain)
  9. end
  10.  
  11. client.ON_PUBLISH = function()
  12. client:disconnect()
  13. end
  14.  
  15. broker = '10.85.0.4' -- default port is 1883. If you need custom port, then use client:connect('10.85.0.4', 12345)
  16.  
  17. client:login_set("user","password")
  18. client:connect(broker)
  19. client:loop_forever()

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')