Set up the MQTT on Home Assistant

One of the add-ons readily available on Home Assistant is the Mosquitto one, a very popular MQTT broker.
In this brief tutorial we will see how to set-up a MQTT broker with Mosquitto and create a client and a topic for our sensor.

From the Hass.io tab, look for the add-on and install Mosquitto.
Once the installation is completed you will see something like:

{
  "plain": true,
  "ssl": false,
  "anonymous": true,
  "logins": [],
  "customize": {
    "active": false,
    "folder": "mosquitto"
  },
  "certfile": "fullchain.pem",
  "keyfile": "privkey.pem"
}

Where it says “logins”, between the square parenthesis (keep them), you want to add something like:

    {
      "username": "YOU_USERNAME",
      "password": "YOUR_PASSWORD"
    }

It should indent the code while you write. Then click save and start your broker.

Now you need to open your configuration.yaml file (you can do this via samba or ssh). Within the file you add:

mqtt:
  broker: "the server IP"
  port: "1883" #This is the port it automatically works on
  username: "username as above"
  password: "password as above"

Save, from the configuration tab click on general and the con “check config”. Checking the configuration before reloading or rebooting is a simple habit which can help you avoid unpleasant things.

To reboot Hass.io / system / reboot

Once the system has restarted, reopen configuration.yaml look for “sensor” and underneath add:

#Bedroom sensor
  - platform: mqtt
    name: "Bedroom"
    state_topic: "sensor/temperature"
    unit_of_measurement: "°C"

Obviously the name of the topic and element like the unit of measurement depends on what you are aiming at and what sort of sensor you are connecting.

The information you have here in the configuration file are the same you need to add to the code you load on the sensor.

Save, check the configuration, reboot.

If everything is in order and the sensor is working correctly – to be sure at this point I still keep REPL open to see the messages it prints –  on your dashboard you should see your new entity and the value read by the sensor.

Back to: The code || Back to: My Internet of Things