Having issues with casting the correct variable type

So I have this code running in my RF69 gateway which takes information from remote sensors and publishes everything to an MQTT server. I’m using the hirotakaster/MQTT library. I want to start using retained values on the MQTT server but it appears that the library expects a different payload type to do this. Looking at the library for basic publishing it’s using this:

bool publish(const char *topic, const char* payload);

but if I wish to publish with the retained bit set to “true” it uses this:

bool publish(const char *topic, const uint8_t *payload, unsigned int plength, bool retain);

As you can see the difference now is that the payload is expecting a uint8_t vs the const char. Here is the code I’m using to publish one of my sensors:

    String PRessure = String(inches);
    String INTempF = String(inTempF);
    String INHumidity = String(inHumidity);
    client.publish("weather/inTemp",INTempF,5,true);
    client.publish("weather/pressure",PRessure);
    client.publish("weather/inHumidity",INHumidity);

Which works fine unless I try to publish with the retained bit set to true (third line from the bottom). I admit I’m still pretty deer in the headlights when it comes to the different types the compiler expects to see so any help here that could give me that “aha” moment would be much appreciated.

First I’d keep away from String objects by default, but in this case it would just make things a bit easier to grasp too :wink:

On the other hand you can try this

client.publish("weather/inTemp",(const uint8_t*)INTempF.c_str(),5,true);
//or
client.publish("weather/inTemp",(const uint8_t*)((const char*)INTempF),5,true);
1 Like

Thanks ScruffR as usual your advice is gold, worked like a charm.

1 Like