Incorrect value obtained from mqtt

I am having an issue with a received mqtt topic value and I think it might be due to the int conversion below:

void callback(char* topic, byte* payload, unsigned int length) {
  int value = String((char*) payload).toInt();
  String topicString = String(topic);
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.print("Value [");
  Serial.println(value);
  Serial.print("] ");

The problem is that I can always see the correct via mqtt explorer, i.e. 5000 but sometimes (not always) my value is read as 50000.
As a work around I am just diving by 10 if the value is > 10000 but that's not right, I need to fix the value conversion, can someone see anything wrong with that? Or suggest alternatives?

Print the payload to serial too, so you can verify that the number from MQTT is correct.

Hmm I tried and got this:

 error: call of overloaded 'println(byte*&)' is ambiguous

   Serial.println(payload);

Which is the proper way of calling that?

try:

Serial.println((char*)payload);

Not sure if it is the cause but I see an extra t at the end?

[13:37:55]] Extending for 5000 msMessage arrived [home/left-recliner/extend] Payload [50000t
[13:37:55]] Value [50000

50000t is the result of printing the payload it seems.
I send the payload via Home Assistant to the mqtt topic.

Sometimes it even gets 500000 instead of the 5000 value:

[13:49:31]] Extending for 10000 msMessage arrived [home/left-recliner/extend] Payload [500000
[13:49:31]] Value [500000

And the value is always correct ok in MQTT explorer so I have no idea.
This the raw YAML for HA that I call, maybe I need to formulate my payload differently? Like JSON?:

service: mqtt.publish
data:
  topic: home/left-recliner/retract
  payload: '5000'

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.