0

I am using a function which accepts String objects as parameters. This function is used to send out data through the MQTT protocol. 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;

MqttClient 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?

The String object is similar to the String object used in Arduino.

4
  • 1
    I suggest checking whether this mysterious String class has a constructor that takes both a const char* and a (hopefully size_t) length/size value. That's the way std::string allows you to construct it with arbitrary binary data of a specific length, possibly including NULs, without any need for the buffer you're copying data from to be NUL terminated. Commented Jan 14, 2016 at 5:16
  • @Robert Crovella, You are sharp. I just corrected that part of the code. Commented Jan 14, 2016 at 5:18
  • I think @TonyD is on the right track. Have a look here. So find the API documentation for the specific MQTT client you are using, and look for an alternate publish method that takes a pointer to the payload and the length. (And that particular method may require other parameters such as QoS, etc.) Commented Jan 14, 2016 at 5:50
  • @Robert Crovella, thanks but the MQTT library which I happened to be using only accepts string type for the message parameter. I could switch library but that would take quite a lot of work. Commented Jan 14, 2016 at 5:54

1 Answer 1

2

Have you considered base64 encoding the data before sending it? This would give a string safe version of the data, but it would need decoding before use at the other end.

The is an Arduino base64 library here (not used it myself)

https://github.com/adamvr/arduino-base64

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.