Efficient way to add a mqtt prefix before a topic?

I am using an esp32 to publish to a mqtt broker. Users are able to enter a mqtt prefix to a mqtt topic using wifimanager. All boards using the mqtt prefix are hanging within a couple of days. All boards where no prefix is entered are working fine. I use the following code to put the prefix before the topic:

    String topicPostFix31 = "/meter/temperature/bedroom";
    String myString31 = custom_MQTT_PREFIX + topicPostFix31;
    const char * msg31 = myString31.c_str();
    client.publish(msg31, StringTemperature);

Can this code cause some instability? Is there a better way to put the topic before the string?

I am running this code every 10 seconds to publish to the broker.

The use of Strings has a bad reputation in the forum mainly for potentially causing memory fragmentation when the contents of a String is changed, which you are doing very frequently

Why not use C strings throughout rather than Strings. This is especially the case since the Strings are eventually converted to a C string anyway

I try to understand C strings but I can't manage to convert the code to it. Is the only thing I have to do is point the string to a place in memory using straight brackets like this?

String[0] topicPostFix31 = "/meter/temperature/bedroom";

A small example using C strings rather than Strings

char * prefix = "aPrefix";
char * topicPostFix31 = "/meter/temperature/bedroom";
char temperatureOutput[50];

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  strcpy(temperatureOutput, prefix);  //copy the prefix to the output variable
  strcat(temperatureOutput, topicPostFix31);  //concatenate the data
  Serial.println(temperatureOutput);
}

void loop()
{
}

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