Creating An Entity from a MQTT Topic?

Building a VOC sensor that I found on printables. The included code allows an ESP8266 to play a pre-recorded message and activate an Alexa or Google Home to turn on a fan. I attempted to modify the code so the gas sensor data could be sent to Home Assistant via MQTT. I can then use this data to monitor the VOCs and turn on an exhaust fan via z-wave. The MQTT broadcast seems to work, as the data is picked up when I listen to the topic within the MQTT settings. However, it is not be discovered automatically. I tried manually creating a sensor but could not get it to work, probably using the wrong state topics. Appreciate any suggestions!

Assuming you listen to gas_sensor

mqtt:
  sensor:
    - name: "gas_sensor"
      state_topic: "gas_sensor"

Thanks for the reply! I originally had this in my sensor file.

mqtt:
  sensor:
   - name: "AirDroid Gas Sensor"
     state_topic: "sensor/gas"
     unit_of_measurement: "ppm"
     device_class: "gas"

Tried entering your suggestion, and restarted HA, but didn’t see the gas_sensor entity. In my config file I have

sensor: !include_dir_merge_list sensors/

with an airdroid.yaml file within a sensors folder. This yaml file has the code you suggested and nothing else. It is also the only yaml file within that folder.

mqtt sensors do not work under the top key

sensor:

They need to go under the top key

mqtt:

So you try to put it under the top key ‘sensor:’, and will not work.

Okay, that makes sense. Especially after I tried…

- Platform: MQTT
  name: "gas_sensor"
  state_topic: "gas_sensor"

That caused the MQTT integration to give me an error stating I could not list the sensor that way. So I just took the code you sent me and put it directly in my configuration.yaml file. It worked immedaitly after that…

Screenshot 2023-04-22 172450

Glad I got it working, but is there a reason it is not auto-discovered?

To be auto-discovered, your sensor needs to send a discovery message to HA. If it does not do that, it will not be auto-discovered.

Figured, just didn’t know exactly how to go about it. I asked good old chatGPT and it gave me code to implement…

// Publish discovery message for MQ-135 gas sensor
client.publish("homeassistant/sensor/mq135/config", "{\"name\": \"Living Room Air Quality\", \"state_topic\": \"home/gas\", \"unit_of_measurement\": \"ppm\", \"device_class\": \"gas\", \"unique_id\": \"living_room_gas\", \"icon\": \"mdi:air-filter\"}");

Going to give it a try as soon as I get some time.