Virtual MQTT Sensor in Home Assistant

As I keep using Home Assistant for my home temperatures, I started looking at my hard disks. Why shouldn’t I see their temperatures in Home assistant too? Well, considering I’m using MQTT already, that wasn’t that hard.

The first step was installing MQTT client on my machine.

sudo apt install -y mosquitto-clients

Once client was installed, I was ready to create a device with a single command.

Register device (notice -r to retain config it in MQTT so HA can rediscover it).

mosquitto_pub -h 192.168.1.1 -p 1883 \
              -u 'mqttuser' -P 'password' \
              -t 'homeassistant/sensor/virtual_disk_test_device/temperature/config' -r -m \
  '{
    "name": "Temperature",
    "unique_id": "virtual_disk_test_temperature",
    "state_topic": "homeassistant/sensor/virtual_disk_test_device/temperature/state",
    "device_class": "temperature",
    "state_class": "measurement",
    "unit_of_measurement": "°C",
    "device": {
      "identifiers": ["virtual_disk_test_device"],
      "name": "Disk",
      "manufacturer": "Virtual",
      "model": "Test"
    }
  }'

With this, our new disk temperature device should instantly become visible in Home Assistant. If you made an error, you can remove device using the same topic and -n.

mosquitto_pub -h 192.168.1.1 -p 1883 \
              -u 'mqttuser' -P 'password' \
              -t 'homeassistant/sensor/virtual_disk_test_device/config' \
              -r -n

Alternatively, if you wish to monitor messages, you can also subscribe using mosquitto_sub.

mosquitto_sub -h 192.168.1.1 -p 1883 \
              -u 'mqttuser' -P 'password' \
              -t 'homeassistant/sensor/virtual_disk_test_device/config' -v

And now finally, we can send temperature using mosquitto_pub.

mosquitto_pub -h 192.168.1.1 -p 1883 \
              -u 'mqttuser' -P 'virtual_disk_test_device' \
              -t 'homeassistant/sensor/virtual_disk_test_device/temperature/state' -r -m '23.5'

If you script around smartctl, this is all you need. However, if you need a bit of a starting point, I’m also including an example.