Skip to content

MQTT

The MQTT plugin implements an MQTT client that is able to send and receive messages from a broker, broker configuration can be made in json configuration or during runtime.

Adding MQTT to an Instance lua code

To use the MQTT plugin on any instance only a few steps are needed:

Setup plugin on instance json

Add the MQTT plugin configuration to the existing instance json file:

"MQTT": {
  "config": {
   "mqtt_server": "127.0.0.1",
   "client_id": "CVEDIA-RT",
   "consume_topic": "cvediart"
  }
 }

Setup plugin on instance lua

Declare and initialize the MQTT plugin state Lua variable:

instance = api.thread.getCurrentInstance()

-- Next to other plugin initializations outside any functions
---@class mqttmanaged
mqttInst = api.factory.mqtt.create(instance, "MQTT")

Send messages using the defined MQTT plugin lua variable

Simple string message:

mqttInst:writeMessage("demotopic","demo message")  --Parameters topic, message string

Sending a JSON-like object:

-- make sure you include the json library in the global context
json = dofile(luaroot .. '/api/json.lua')

-- let's assume a object like this
my_object = {
    metric1 = 1,
    types_count = {
        bicycles = 2,
        cars = 1,
        vans = 3
    },
    detection1 = {
        x = 0.542,
        y = 0.120,
        w = 0.1,
        h = 0.2
        class_id = 2
    }
}

-- this usually goes within main loop - runSingleFrame - where you can publish it after all detections:
mqttInst:writeMessage('output_topic', json.encode(my_object))

Defining connections

If mqttInst:connect() is not called on initialization, it will be called automatically when writing a message.


Available MQTT Interfaces

  • mqttInst:connect() : Connect to the MQTT broker defined in the json configuration

  • mqttInst:connect(string server, string clientid, string topic) : Connect to an MQTT broker defined by the specified parameters

  • mqttInst:readMessage() : Read a message from an MQTT broker, topic to listen to is defined by in the json configuration

readMessage Blocking Call

mqttInst:readMessage() is a blocking call, instance runtime will block waiting for messages to arrive.

  • mqttInst:writeMessage(std::string topic, std::string msg) : Send a string message to the MQTT broker with the specified topic