Automate Your Home With Raspberry Pi, MQTT and Home Assistant

Published on 05 Apr 2021 | Updated on 23 Mar 2022
Written by Pranav Chakkarwar
10 min to read


I previously wrote a post on DIY Home automation with Node-Red, but the project was hosted in the cloud and the communications were dependent on the internet. So, I decided to completely rethink my design and came up with a practical solution that I use everyday.

Benefits of This Approach

Network Map of the Setup

Home automation network map View Image

Requirements

Raspberry Pi 4B

Install Docker on Raspberry Pi

I am using the convenience script.

$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

Install and Run the Home Assistant Container

On Raspberry Pi 3

$ docker run --init -d \
  --name homeassistant \
  --restart=unless-stopped \
  -v /etc/localtime:/etc/localtime:ro \
  -v /PATH_TO_YOUR_CONFIG:/config \
  --network=host \
  homeassistant/raspberrypi3-homeassistant:stable

On Raspberry Pi 4

$ docker run --init -d \
  --name homeassistant \
  --restart=unless-stopped \
  -v /etc/localtime:/etc/localtime:ro \
  -v /PATH_TO_YOUR_CONFIG:/config \
  --network=host \
  homeassistant/raspberrypi4-homeassistant:stable

Tip: Use “docker ps -a” to see all your running containers and their status.

docker ps -a

Setting up the Home Assistant

After your Home Assistant container shows a healthy status, visit the IP Address of your Pi followed by port number 8123 (for e.g. mine is http://192.168.0.119:8123).

Tip: You can also visit http://raspberrypi.local:8123 (works most of the time).

It will ask you to create an user account. It’s not an online account. This account is just used to log in to Home Assistant.

Home Assistant setup

After you create an account It will automatically detect If you have printers, smart lights, chromecast devices, smart speakers that are already setup. You can add them to your dashboard if you wish.

Setting up a MQTT Broker

MQTT is one of the best protocols used for home automation, as it allows two way communication, message quality control and more. Setting up a MQTT broker will allow us to control our smart devices from the Home Assistant and also see device status. I recommend reading MQTT for dummies get a basic understanding of the MQTT protocol.

I am installing the Eclipse Mosquitto MQTT broker (without docker).

$ sudo apt update
$ sudo apt install -y mosquitto mosquitto-clients

Make mosquitto auto-start on boot

$ sudo systemctl enable mosquitto.service

Connect the Home Assistant to the MQTT Broker

Home Assistant dashboard -> Configuration -> Integrations.

Home Assistant integrations

Add Integration -> Search for “MQTT” and complete the setup by entering the IP Address of your MQTT client and it’s port. If you are following this tutorial the IP Address will be 127.0.0.1 and the port will be 1883 (127.0.0.1:1883).

Home Assistant add integrations

Setting up the Arduino IDE

Setting up the ESP-01

Use the following C++ program for the ESP-01 that helps it connect to your WiFi and the MQTT server. I have added useful tips as comments.

Tip: You can also consider installing Tasmota as it has many configuration options that can be set using it’s own easy to use web dashboard.

#include "EspMQTTClient.h"

EspMQTTClient client(
  "WiFi Name",
  "WiFi Password",
  "MQTT Broker server IP Address",      // IP Address of your Raspberry Pi
  "mqtt username",                      // (Leave blank)
  "mqtt password",                      // (Leave blank)
  "light",                               // Client name to identify your device
  1883                                  // The MQTT port, default is 1883.
);

void setup()
{
  Serial.begin(115200);
  pinMode(0, OUTPUT);
}

void onConnectionEstablished()
{
  client.subscribe("livingroom/light/com", [](const String & payload) {
    if (payload == "1") {digitalWrite(0, HIGH);
                          client.publish("livingroom/light/state", "1");
                         }
    if (payload == "0") {digitalWrite(0, LOW);
                           client.publish("livingroom/light/state", "0");
                          }
  });
}

void loop()
{
  client.loop();
}

To flash the ESP-01 (to run the above code), the ESP USB flasher should be modified as described here. After this you can flash the ESP-01 with the above code and connect the circuit as shown below.

Esp8266 board setup

Adding a Switch on the Dashboard

As we are running our Home Assistant in a Docker container we have to ssh into the Home Assistant container by using the command and modify the configuration.yaml file.

$ sudo docker exec –it homeassistant /bin/bash
$ nano configuration.yaml  (If this command doesn't work, you will need to install nano using "apk install nano")

Example config:

light:
  - platform: mqtt
    name: "Living Room Lights"
    state_topic: "livingroom/lights/state"
    command_topic: "livingroom/lights/com"
    payload_on: "1"
    payload_off: "0"
  - platform: mqtt
    name: "Lounge Lights"
    state_topic: "lounge/lights/state"
    command_topic: "lounge/lights/com"
    payload_on: "1"
    payload_off: "0"

This is an example config and you can add more devices and categories if you like. Extended configuration options are explained in the Home Assistant Docs.

Tip: Notice how the Home Assistant publishes command to the “bathroom/lights/com” and the ESP-01 is subscribed to the same topic.

Access your Home Assistant Remotely

I found that most people use Port forwarding and DDNS to access a resource outside a local network. But, I will go for a reverse proxy becasue I am too lazy to get an SSL certificate and also because I am behind a NAT.

Here are the some good reverse proxy providers to choose from:

  1. Nabu Casa - This method is recommended in the Home Assistant Docs.
  2. PageKite - I will use this for a demo.

Setting up Pagekite for remote access is fairly simple and can be done completely from the command line. Just use the commands below.

$ curl -O https://pagekite.net/pk/pagekite.py
$ python2 pagekite.py 8123 SUBDOMAIN-THAT-YOU-WANT.pagekite.me

Once you confirm your details with pagekite, the proxy client will start running and you can now visit SUBDOMAIN-THAT-YOU-WANT.pagekite.me and access your Home Assistant over the Internet. This URL can be used when you sign in on the Mobile apps of Home Assistant.

Customize your Dashboard

To demonstrate customization I applied a custom theme using the configuration.yaml file.

# Example configuration.yaml entry
frontend:
  themes:
    happy:
      primary-color: white
      text-primary-color: black
      background-primary-color: #cefe8e

Automate Your Home With Raspberry Pi, MQTT and Home Assistant



That's it!

I hope you enjoyed this article, as there are - No ads, No trackers, No paywall, No shilling, No affiliate links, No baised opinions. I put a lot of thought into each article, but I'm not perfect. Feedback is always appreciated.