Search code examples
c++mqttarduino-idearduino-esp8266

MacAddress for topic name - Arduino IDE MQTT


I want to use the mac address of my system as a topic name.

I want something like : project/00:1B:44:11:3A:B7/temperature/status

I tried in this way:

#define TEMP_STATUS_TOPIC "project/" + WiFi.macAddress() + "temperature/status"   
#define TEMP_CONTROL_TOPIC "project/temperature/control"

But I get this error:

no matching function for call to 'MQTTClient::publish(StringSumHelper&, char [128], size_t&)'

Any tip will be greatly appriciated!

EDIT:

I am using mqtt.fx client.

Here is where I call publish:

sensors.requestTemperatures(); 
  float t = sensors.getTempCByIndex(0);
  bool static led_temp_status = HIGH;
  
  const int capacity = JSON_OBJECT_SIZE(3);
  StaticJsonDocument<capacity> poolsystem;
  
  if (t < destemp) {
    led_temp_status = LOW;
    digitalWrite(LED_EXTERNAL_TEMP, led_temp_status);
    const int capacity = JSON_OBJECT_SIZE(3);
StaticJsonDocument<capacity> poolsystem;

    poolsystem["temp"] = t;
    poolsystem["heatstatus"] = "on";
    char buffer[128];
    size_t n = serializeJson(poolsystem, buffer);
    Serial.print(F("JSON message: "));
    Serial.println(buffer);
    mqttClient.publish(TEMP_STATUS_TOPIC, buffer, n);   
  } else {
    led_temp_status = HIGH;
    digitalWrite(LED_EXTERNAL_TEMP, led_temp_status);

    poolsystem["temp"] = t;
    poolsystem["heatstatus"] = "off";
    char buffer[128];
    size_t n = serializeJson(poolsystem, buffer);
    Serial.print(F("JSON message: "));
    Serial.println(buffer);
    mqttClient.publish(TEMP_STATUS_TOPIC, buffer, n); 
  }

Solution

  • First you shouldn't use a #define in that way, like pointed out in another answer.

    You could instead declare TEMP_STATUS_TOPIC as a const String:

    const String TEMP_STATUS_TOPIC = "project/" + WiFi.macAddress() + "temperature/status";
    

    The problem with MQTTClient::publish() is that the first argument requires a C string, const char*, for the topic name. Replace the lines with:

    mqttClient.publish(TEMP_STATUS_TOPIC.c_str(), buffer, n);