0

First of all, I am a far cry from a being an experienced programmer, so please forgive me if I am asking beginners question here.

I encountered a problem trying to publish a payload using the PubSubClient on an ESP8266. I am using VS Code with Platformio.

During Build I receive the following error. It seems like the PubSubClient is trying to convert the payload from char to unsinged int, even though the payload is defined as const char in the API of the PubSubClient library.

src\main.cpp: In function 'void sendStatusViaMqtt(String)': src\main.cpp:389:39: error: invalid conversion from 'char*' to 'const uint8_t*' {aka 'const unsigned char*'} [-fpermissive] 389 |     mqttClient->publish(relay_Status, mqttMessageCharArray, msglength, false); |                                       ^~~~~~~~~~~~~~~~~~~~ |                                       | |                                       char* In file included from src\main.cpp:15: .pio\libdeps\esp12e\PubSubClient\src/PubSubClient.h:154:55: note:   initializing argument 2 of 'boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)' 154 |    boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);

This is the code snipped I used. Actually I went out of my way to convert a string into a char needed per PubSubClient documentation.

void sendStatusViaMqtt()
{
  unsigned long now = millis();
  if (now - lastMqttMsg > 100000) //Making sure I only send messages after a certain time has elapsed
  {
    String mqttMessage = generateStatusString(); //Function generateStatusString()puts putting current values of variables of the running code on the ESP8266 into a String and returns it
    unsigned int msglength = mqttMessage.length();
    char mqttMessageCharArray[mqttMessage.length()]; 
    mqttMessage.toCharArray(mqttMessageCharArray, mqttMessage.length()); //Generating a CHAR Array out of the String
    lastMqttMsg = now; 
    Serial.print("Publish message: ");
    Serial.println(mqttMessage);
    mqttClient->publish(relay_Status, mqttMessageCharArray, msglength, false);
  }  
}

I am thankful for any hint!

1 Answers1

0

Your mqttMessageCharArray is of type char[] (which decays to char* on passing to function), whereas your mqttClient->publish() takes a uint8_t* as its second argument.

It can simply be fixed by replacing the last line with :-

mqttClient->publish(relay_Status, (uint8_t*)&mqttMessageCharArray, msglength, false);

Here we take adress of mqttMessageCharArray using the & and then cast it to a uint8_t*.

uint8_t (aka. unsigned 8bit integer) is basically same as unsigned char on virtually every system. Both of them are by definition 1 byte in size so its safe to cast between them without any data loss.

0xB00B
  • 1,598
  • 8
  • 26