-1

I don't understand how to publish to mqtt with retain option (The fourth parameters)

I know that I need length in an byte array but I've try allot to determine how to calculate my payload message to an byte var.

here is my code to publish once I am connected.

String str;
char chBright[4];
str = String(ledBrightness); //converting integer into a string
str = str + '%';
str.toCharArray(chBright, 4);
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", chBright);

document ask the third parameter to be an byte

topic – the topic to publish to char*

payload – the message to publish byte array

length – the length of the message byte

retained – whether the message should be retained byte

0 – not retained

1 – retained

mqtt client for Arduino

How in c++ to get bytes from the message I want to publish?

Tank you to clarify my knowledge

3
1

How to Publish to MQTT with retain option?

The quick answer is add payload length, and retained as true as the last parameters to publish().

const int BUF_MAX = 8;
char buf[BUF_MAX];
itoa(ledBrightness, buf, 10);
strcat(buf, "%");
int len = strlen(buf) + 1;
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", buf, len, true);

Above is a rewrite with the extra parameter for "retained", payload length, and payload as a null-terminated string.

Cheers!

2

How in c++ to get bytes length from the message I want to publish?

For a String object, the method length() tells you the length.

eg.

int len = str.length ();

For a null-terminated C-type string, you can use strlen, eg.

char foo [20] = "bar";
int len = strlen (foo);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.