Home automation using Raspberry Pi, MQTT and Home Assistant

Home automation using Raspberry Pi, MQTT and Home Assistant

Written by Pranav Chakkarwar on 05 Apr 2021 • 14 minutes to read

HomeAutomation Privacy RaspberryPi Tutorial

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

Before we get started let’s take a look at some GREAT BENEFITS of this approach:
A network map of the setup will give you a much clearer idea.

Home automation network map

Requirements:

Esp8266 board

Esp8266 board flasher usb

Setting up the Home Assistant server

There are several ways to install Home assistant on a Raspberry Pi. But, I am gonna go the containerized way because I don’t want my RPi 4 to run only a Home Assistant OS 🙃

I have already setup my Raspberry Pi 4B and use it for self-hosting many services, but that’s a talk for another article. Currently this is my Raspberry Pi setup.

Raspberry Pi 4BRaspberry Pi 4B server

Installing docker on raspberrypi using the convenience script
$ curl -fsSL https://get.docker.com -o get-docker.sh
$ sudo sh get-docker.sh

Install docker on raspberry pi

Installing the Home Assistant docker 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

home assistant docker image install on raspberry pi

Setting up the Home Assistant

In your browser, visit the ip address of your pi followed by port number :8123 on the local network (for e.g. mine is 192.168.0.119:8123).

Tip: Find your pi’s ip by pinging raspberrypi.local (works most of the time).

Now create a username and password. This process won’t create any online accounts but these details will enable us to log in to our Home Assistant when we visit the next time.

Home Assistant setup

The Home Assistant will automatically detect If you have printers, smart lights, chromecast devices, smart speakers already setup. You can add them to your dashboard if you wish!

Setting up a local MQTT broker and connecting it to your Home assistant

A MQTT broker will allow us to send messages from the Home Assistant to the controlling devices and the device will report their state back. I recommend reading MQTT for dummies to understand the working of the MQTT protocol.

I am going for the Eclipse Mosquitto MQTT broker (without docker)

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

To make mosquitto auto-run on boot

$ sudo systemctl enable mosquitto.service

Connecting to the MQTT server from the Home Assistant integrations page.

Home Assistant integrations

Home Assistant add integrations

Setting up an ESP-01 Relay board
C++ program for the ESP-01 to connect to the WiFi and MQTT server
#include "EspMQTTClient.h"

EspMQTTClient client(
  "WiFi Name",
  "WiFi Password",
  "ip address of your raspberrypi",      // MQTT Broker server ip
  "mqtt username",          // (Not needed)
  "mqtt password",          // (Not needed)
  "Fan1",     // Client name that uniquely identify your device
  1883                      // The MQTT port, default to 1883. this line can be omitted
);

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

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

void loop()
{
  client.loop();
}
Remember the ESP USB Flasher?

To flash the ESP-01, The ESP USB flasher should be modified as described in ESP8266 firmware flasher. After this you can flash the ESP-01 with the above program and connect circuit as shown below!

Esp8266 board setup

Changing the configuration.yaml of the Home assistant.

As we are running our Home Assistant in a Docker container we have to ssh into the Home Assistant container by using the command

$ 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")

Now insert this below configuration in the configuration.yaml and save it!

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"

switch:
  - platform: mqtt
    name: "Outlet 1"
    state_topic: "bedroom/outlet1/state"
    command_topic: "bderoom/outlet1/com"
    payload_on: "1"
    payload_off: "0"
  - platform: mqtt
    name: "Outlet 2"
    state_topic: "bedroom/outlet2/state"
    command_topic: "bderoom/outlet2/com"
    payload_on: "1"
    payload_off: "0"

fan:
  - platform: mqtt
    name: "Living Room"
    state_topic: "livingroom/on/state"
    command_topic: "livingroom/on/com"
    speed_state_topic: "livingroom/speed/state"
    speed_command_topic: "livingroom/speed/set"
    payload_on: "1"
    payload_off: "0"
    payload_low_speed: "1"
    payload_medium_speed: "2"
    payload_high_speed: "3"
    speeds:
      - low
      - medium
      - high

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

Notice how the Home Assistant publishes command to the “bathroom/lights/com” and the ESP-01 is subscribed to the same topic. If you don’t understand feel free to ask me in the comments if you cant understand the config.

Remote access of the Home Assistant Dashboard!

Several options are available to access your dashboard over the internet. 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 which is far more secure.

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.
  3. Cloudflare Argo tunnels - Best for security and protection.

Setting up Pagekite for remote access is fairly simple and can be done completely from a 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

The sign up process will start in your terminal. Once you confirm your details 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.

SSL setup for home assistant on raspberry pi

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

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

That’s it! Now my setup looks great and works flawlessly.

Home automation using Raspberry Pi, MQTT and Home Assistant



Enjoyed this article?

Buy a coffee for the author



Get the latest articles in your inbox or Get the RSS Feed

Comments

Post a comment

Comments will be manually approved and will take time to reflect.

More from the blog

A personal dashboard with bookmarks and search that works across browsers.

Crossbrowser personal dashboard

Published on 05 Jun 2021 • 1 minutes to read

A tutorial to setup a personal dashboard with bookmarks and search that works across browsers. No...

An interactive tutorial to implement a dark mode on any website.

Adding a dark mode to any website

Published on 02 Jun 2021 • 7 minutes to read

Adding a dark mode to a website is an excellent way to make it more visually appealing. It also m...

Understanding the importance of design with the help of dark patterns on the internet

Avoid using dark patterns!

Published on 27 May 2021 • 3 minutes to read

Dark patterns cause more harm than good! It not just the visuals that count but the whole experie...