Send and receive messages

The message sent using MQTT are published on topics and can be subscribed by an other application. MQTT topics are URLs that can be used to communicate specific messages to the MQTT broker.

Custom communication topics

You can use a MQTT topic to share your own data between applications. The messages published do not have any specific format as long as they are jsons. You can chose the topic name of your choice, and use publishOnTopic in C++ or publish_on_topic in Python.

Using the C++ API

Using the C++ API, MQTT communication is easy:

  • As explained in the Connection Section, you must use the connect(…) function in order to connect your application to the cloud.
  • You can publish on the topic of your choice by using the publishOnTopic(…) function.
  • You can subscribe to the topic of your choice by using the subscribeToTopic(…) function.

Publish on a MQTT topic

Lets say you want to publish a message to devices in the same workspace: you must chose TARGET::WORKSPACE as topic prefix. Your want to send data on a topic named my_custom_data.

//Init sl_iot
STATUS_CODE sc = HubClient::connect(val);
if (sc != STATUS_CODE::SUCCESS) {
    HubClient::sendLog("Failed to Init Cloud", LOG_LEVEL::ERROR);
    exit(EXIT_FAILURE);
}

sc = HubClient::registerCamera(p_zed);
if (sc != STATUS_CODE::SUCCESS) {
    HubClient::sendLog("Failed to register camera", LOG_LEVEL::ERROR);
    exit(EXIT_FAILURE);
}

json my_message_js;
my_message_js["message"] = "Hello World";
my_message_js["my_custom data"] = 54;


TARGET topic_prefix = TARGET::WORKSPACE;
std::string topic_name = "/my_custom_data";
HubClient::publishOnTopic(topic_name, my_message_js, topic_prefix);

Subscribe to a MQTT topic

In another application, on another device (or not) of the same local network, you can receive the published messages by subscribing the same MQTT topic. When a message is received the callback onDataReceived is triggered.

//Init sl_iot
STATUS_CODE sc = HubClient::connect(val);
if (sc != STATUS_CODE::SUCCESS) {
    HubClient::sendLog("Failed to Init Cloud", LOG_LEVEL::ERROR);
    exit(EXIT_FAILURE);
}

sc = HubClient::registerCamera(p_zed);
if (sc != STATUS_CODE::SUCCESS) {
    HubClient::sendLog("Failed to register camera", LOG_LEVEL::ERROR);
    exit(EXIT_FAILURE);
}

// Topic to be listen
TARGET topic_prefix = TARGET::WORKSPACE;
std::string topic_name = "/my_custom_data";

// Subscription
HubClient::subscribeToTopic(topic_name, onDataReceived, topic_prefix);

You also define your callback as follow :

void onDataReceived(std::string topic, std::string message, TARGET target, void* arg)
{
    std::cout << "Message received !" << std::endl;
    json my_raw_data = json::parse(message);
    std::cout << "My received message : " << my_raw_data << std::endl;
}

Note that 2 tutorials are available if you want to access the whole code.