Thanks, I did figure it out using a similar post.
For future reference for anyone else, I found two different issues I was having that I resolved.
-
The JSON payload ended up larger than the default maximum size. To fix this, either adjust the MQTT_MAX_PACKET_SIZE in <PubSubClient.h> to a suitable number, or, add the following line to your program:
client.setBufferSize(1024);
-
The Device Map needs to be a JSON Object within the JSON document. My final version looks something like this:
StaticJsonDocument<1024> pl_config;
void mqttpub_dscvy(char* node) {
if (!client.connected()) {
mqtt_reconnect();
} else {
;
}
String mqtt_dscvy_t = mqtt_prefix_d + "/" + node + "/config";
mqtt_dscvy_t.replace(":", "-");
Serial.println("");
Serial.print("Initiating MQTT discovery (-t ");
Serial.print(mqtt_dscvy_t + ")...");
pl_config.clear();
pl_config["uniq_id"] = MAC + "_" + String(node);
pl_config["~"] = mqtt_prefix;
pl_config["stat_t"] = "~/state";
pl_config["avty_t"] = "~/status";
pl_config["name"] = MAC.substring(12) + " " + DEVICE_CLASS + " (" + String(node) + ")";
pl_config["ic"] = "mdi:water-percent";
pl_config["val_tpl"] = "{{ value_json." + String(node) + "}}";
mqtt_setDeviceConfig(mqtt_dscvy_t, node);
}
void mqtt_setDeviceConfig(String config_t, String node) {
JsonObject device = pl_config.createNestedObject("dev");
device["name"] = "Garden Sensor (" + MAC.substring(12) + ")";
device["sw"] = SOFTWARE_ID;
device["mdl"] = MODEL_ID;
device["mf"] = MANUFACTURER_ID;
JsonArray identifiers = pl_config["dev"].createNestedArray("ids");
identifiers.add(MAC);
JsonArray connections = device.createNestedArray("cns");
connections.add(serialized("[\"MAC\",\"" + MAC + "\"]"));
//connections.add(serialized("[\"ip\",\"" + ipstr + "\"]"));
char buffer[1024];
serializeJsonPretty(pl_config, buffer);
if (client.publish((char *)config_t.c_str(), buffer, true) == true) {
Serial.println("...success");
} else {
Serial.println("...failed...");
}
}
@123, I did test it with the same MQTT base path, and with different ones as you suggested, and can confirm both work without issue. I did end up using different paths in the end so that I could subscribe to all config topics without subscribing to the state topics.
Please note, I am in no way an expert on this, so if anyone has any comments / suggestions, let me know!