MQTT will not publish payload

Hey Guys,

I'm hoping someone here can help me with this. I've built this program to receive data over an espNOW connection and publish to an MQTT server. The topics are arranged to be recognized by Home Assistant's MQTT auto discovery feature. To that end, each sensor has a config topic and a state topic. The code works for the most part, except for the publishing for the config topics for temperature and humidity. For someone reason it is not publishing the payloads. It's not throwing any errors that I can find. I've checked the Serial output and the topics and the payloads are being made properly, but nothing is making to the broker. Can anyone tell me what's going on?

   //Get and publish Temperature
    
    strcpy (mqttConfigTopic1, "homeassistant/sensor/espNOW_sensor_");
    strcat (mqttConfigTopic1, macAddr);
    strcat (mqttConfigTopic1, "_temperature");
    strcat (mqttConfigTopic1, "/config");
    
    strcpy (mqttStateTopic1, "homeassistant/sensor/espNOW_sensor_");
    strcat (mqttStateTopic1, macAddr);
    strcat (mqttStateTopic1, "_temperature");
    strcat (mqttStateTopic1, "/state");

    sensor1["name"] = "ESP-NOW Temperature Sensor";
    sensor1["unique_id"] = String(macAddr) + "_temp";
    sensor1["device_class"] = "temperature";
    if (  use_fahrenheit   ) sensor1["unit_of_measurement"]  = "°F";
    else sensor1["unit_of_measurement"]  = "°C";
    sensor1["state_topic"] = mqttStateTopic1;
    size_t sensor1Len = serializeJson(sensor1, payload1);
    Serial.println(mqttConfigTopic1);
    Serial.println(mqttStateTopic1);
    Serial.println(payload1);
    mqttClient.publish(mqttConfigTopic1, payload1);
    mqttClient.publish(mqttStateTopic1, temperature.c_str());

    //Get and publish Humidity

    strcpy (mqttConfigTopic2, "homeassistant/sensor/espNOW_sensor_");
    strcat (mqttConfigTopic2, macAddr);
    strcat (mqttConfigTopic2, "_humidity");
    strcat (mqttConfigTopic2, "/config");


    strcpy (mqttStateTopic2, "homeassistant/sensor/espNOW_sensor_");
    strcat (mqttStateTopic2, macAddr);
    strcat (mqttStateTopic2, "_humidity");
    strcat (mqttStateTopic2, "/state");

    sensor2["name"] = "ESP-NOW Humidity Sensor";
    sensor2["unique_id"] = String(macAddr) + "_humidity";
    sensor2["device_class"] = "humidity";
    sensor2["unit_of_measurement"]  = "%";
    sensor2["state_topic"] = mqttStateTopic2;
    size_t sensor2Len = serializeJson(sensor2, payload2);

    mqttClient.publish(mqttConfigTopic2, payload2, sensor2Len);
    mqttClient.publish(mqttStateTopic2, humidity.c_str());
  }

This is not a program, it's a small excerpt. We made the experience that in most situations the error is in that part of the code people are hiding from us. Post complete code!

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