MQTT from RPi Pico W in Micropython Auto Discovery HA

Hi everyone,

I have been battling with this for days. I am trying to get HA to discover my device that is sending BME280 data from RPi Pico W using MQTT. I have setup the MQTT addon in HA. I can see the data being sent when I open MQTT Explorer. I cannot get the data to show in HA. I can also see data when I put the full topic in MQTT configuration in HA and select ‘Listen’
I am running HA on RPi 3B
I am very new to this and this is my first job I would like to do as I have a buch of PicoW’s that I use around my place that I would like to send data from to HA.
Any assistance would be greatly appreciated.
Here is my code from the Pico W. I appologies if there is a specific format that I am supposed to add code to message, I couldnt find an answer.

from PiicoDev_BME280 import PiicoDev_BME280
from PiicoDev_Unified import sleep_ms
import network
import umqtt.simple as mqtt
import ujson
import gc

# Function to publish Home Assistant MQTT Discovery messages
def publish_discovery(client, sensor_type, unit):
    topic = f"homeassistant/sensor/{sensor_type}/config"
    unique_id = f"pico_{sensor_type}"
    state_topic = f"homeassistant/sensor/{sensor_type}/state"
    availability_topic = "homeassistant/sensor/availability"

    # Capitalize the first letter of sensor_type
    sensor_name = sensor_type[0].upper() + sensor_type[1:]

    payload = {
        "name": f"Pico {sensor_name}",
        "unique_id": unique_id,
        "state_topic": state_topic,
        "unit_of_measurement": unit,
        "availability": {
            "topic": availability_topic
        }
    }
    
    # Convert payload to JSON string for publishing
    payload_json = ujson.dumps(payload)

    # Print the payload for debugging
    print(f"Publishing to {topic}: {payload_json}")
    
    client.publish(topic, ujson.dumps(payload), retain=True)

Then I have my mqtt and wifi login details.

Then I have the publishing of my data

# Initialize MQTT client
client = mqtt.MQTTClient('RPi_Pico_W', mqtt_server, mqtt_port, mqtt_user, mqtt_password)
reconnect()  # Connect to MQTT broker with reconnection logic

#Test to see if publishing to mqtt 
client.publish('test/rpipicow', 'Hello from RPi_Pico_W')



# Send discovery messages for each sensor to Home Assistant
publish_discovery(client, "temperature", "°C")
publish_discovery(client, "pressure", "hPa")
publish_discovery(client, "humidity", "%")


# Initialize BME280 sensor
sensor = PiicoDev_BME280()

# Main loop
# Main loop
while True:
    try:
        # If disconnected, attempt to reconnect
        reconnect()

        # Read sensor data
        tempC, presPa, humRH = sensor.values()
        pres_hPa = presPa / 100  # Convert air pressure from Pascals to hPa

        # Prepare individual sensor data payloads
        temperature_data = {"temperature": tempC}
        pressure_data = {"pressure": pres_hPa}
        humidity_data = {"humidity": humRH}

        # Publish individual sensor data to MQTT
        client.publish('homeassistant/sensor/temperature/state', ujson.dumps(temperature_data), retain=True)
        client.publish('homeassistant/sensor/pressure/state', ujson.dumps(pressure_data), retain=True)
        client.publish('homeassistant/sensor/humidity/state', ujson.dumps(humidity_data), retain=True)
    except Exception as e:
        print("Failed to publish data:", e)
        gc.collect()  # Invoke garbage collector after failed publishing attempt
        sleep_ms(5000)

A few things, I don’t recommend the default library’s MQTT client, had nothing but problems with them falling offline. I’ve had sucess with GitHub - peterhinch/micropython-mqtt: A 'resilient' asynchronous MQTT driver. Plus a means of using an ESP8266 to bring MQTT to non-networked targets..

That doesn’t help you as far as Mqtt discovery though. My recommendation is to make sure that you are seeing properly formatted messages on the broker, use something like MQTT Explorer. If those look good then find your device under the MQTT integration in settings and check the MQTT info link. It will tell you what topics it’s listening for and what the latest messages were. From there you can verify that it’s listening to the correct topics and that you see properly formated messages. You should see something like this.

Finally, you can enable debug logging from the MQTT integration and see if you have any errors when it attempted to parse the discovery message and subsequent status messages.

If you want to see a working example, here’s two I put together.

Good luck!