Chat freely about anything...

User avatar
By helpme
#38727 The MQTT library provided in the SMING framework only supports String data type. However, I need to send binary data through MQTT. I managed to do that but there is a problem with my solution. Here is the relevant code;
Code: Select allMqttClient mqtt("192.168.1.71", 1883, onMessageReceived);
char buffer[100];
//buffer filled with binary data terminated with null character at this point
mqtt_msg = String(buffer);
String topic = "XXX";
mqtt.publish(topic, mqtt_msg );


I will terminate the binary data in buffer with a null character 0x00. The problem comes when 0x00 happened to be part of the binary data. How can this problem be solved?
Last edited by helpme on Thu Jan 14, 2016 12:20 am, edited 1 time in total.
User avatar
By eduperez
#38743 Looks like that library is not ready to accept binary data, as it always uses NULL characters for termination. Perhaps you can reroute your project around that limitation: for example, you could use Base64 or some other algorithm to encode your binary data to ASCII. On the other hand, after a quick glimpse to the source code, it does not seem quite hard to modify that library to accept binary data.
User avatar
By helpme
#38749
eduperez wrote:Looks like that library is not ready to accept binary data, as it always uses NULL characters for termination. Perhaps you can reroute your project around that limitation: for example, you could use Base64 or some other algorithm to encode your binary data to ASCII. On the other hand, after a quick glimpse to the source code, it does not seem quite hard to modify that library to accept binary data.


I tried to do just that. Modify the library to accept binary data.

The original code was;
Code: Select allbool MqttClient::publish(String topic, String message, bool retained /* = false*/)
{
   int res = mqtt_publish(&broker, topic.c_str(), message.c_str(), retained);
   return res > 0;
}


I added a new function to handle binary data.

Code: Select allbool MqttClient::publish_binary(String topic, const char* message, bool retained /* = false*/)
{
   int res = mqtt_publish(&broker, topic.c_str(), message, retained);
   return res > 0;
}


Unfortunately, this new function publish_binary takes in messages that are null-terminated like a normal string. What can be done to have a mqtt function that sends binary data? What is wrong with my code?