Skip to content

Instantly share code, notes, and snippets.

@GGn0
Last active November 9, 2021 14:27
Show Gist options
  • Save GGn0/b9ede1e4af3d6822bcce8401a05228df to your computer and use it in GitHub Desktop.
Save GGn0/b9ede1e4af3d6822bcce8401a05228df to your computer and use it in GitHub Desktop.
Setup Home Assistant on Raspberry pi using Docker. Connect it to Google Home

Home Assistant Core on Raspberry

Run Home Assistant docher container

Make sure you have docker and dcker compose installed

docker --version
docker-compose --version

Create a docker-compose.yaml file inside a relevant directory

mkdir homeassistant
cd homeassistant
sudo nano docker-compose.yaml

Paste and edit the configuration

version: '3'
services:
  home-assistant:
    container_name: home-assistant
    image: ghcr.io/home-assistant/home-assistant:stable
    volumes:
      - ~/homeassistant:/config
    environment:
      - TZ=Europe/Rome
    network_mode: host
    restart: always

Create and spin the container

docker-compose up -d home-assistant

Visit the assistant web page:
http://[PI_IP]:8123

Create an account filling the form

Update Home Assistant on docker

cd ~/homeassistant
docker-compose pull home-assistant
docker-compose up --build -d home-assistant 
docker image prune -f

Access Home Assistant from NginX reverse proxy

Configure a new Proxy Host on Nginx Proxy Manager

Domain Names: homeassistant.[duckdns domain]
Scheme: http
Forward Hostname / IP: [raspberry ip]
Forward port: 8123
Block Common Exploits: true
Websockets Support: true
Force SSL: true
HTTP/2 Support: true
HSTS Enabled: true

On the raspberry edit the home assistant config file

sudo nano ~/homeassistant/configuration.yaml

And add the following code:

http:
  use_x_forwarded_for: true
  trusted_proxies:
    - 172.30.33.0/24  # Leave this
    - 172.X.X.X       # Ip address of nginx docker container

Restart the container

docker restart home-assistant

Connect Google Home to your HomeAssistant server

Read the official guide

Create a new Action on Googleconsole:

  • New project
  • Smart Home
  • Start building
  • Overview > Quick setup > Name your Smart Home action
  • Build your action > Add Actions
    • Fullfillment URL: https://[homeassistant nginx URL]/api/google_assistant
    • Save
  • Take note of the project ID on Three dots > Project Settings
  • Overview > Quick setup > Account Linking
    • Client ID: https://oauth-redirect.googleusercontent.com/r/[PROJECT_ID]
    • Client Secret: anything
    • Authorization URL: https://[homeassistant nginx URL]/auth/authorize
    • Token URL: https://[homeassistant nginx URL]/auth/token
    • Configure your client > Scopes textbox:
    • email
    • Add scope
    • name
    • Add scope
    • Do NOT check Google to transmit clientID and secret via HTTP basic auth header
  • Test > Simulator > Settings: On device testing: false
  • Start testing

Open Google Cloud Console

  • Settings > Service account
  • Create a new service account
  • Choose service account token creation as role
  • Click on the newly created account (three dots)
  • Manage keys
  • Add key > Create new key > JSON
  • Menu > API Services
  • Enable API and services
  • Search homegraph api and enable it

On rpi:

sudo nano ~/homeassistant/configuration.yaml

Add the line

google_assistant:
  project_id: [ID found in first steps]
    service_account: !include googlehome.json
    report_state: true
    expose_by_default: false
    entity_config:
      [light_id]:
        name: Luce Cameretta
        room: [room name]

You can find the object id on home assistant under Entity ID

Now move the downladed JSON file from the previous step in ~/homeassistant folder and rename it to googlehome.json
On your computer

scp -i[identity file] -P [port] [JSON file] [USER]@[PI_IP]:~/googlehome.json

On the raspberry

sudo mv ~/googlehome.json ~/homeassistant/googlehome.json

Restart the homeassistant container

docker restart home-assistant

Open Google Home app on your phone and add a compatible device.

Look for [test] app name and link it

If you find your devices in the wrong room you can move them from the google app

Discover Tasmota Devices over MQTT

Install mosquitto broker

Prepare the retentive data locations

sudo mkdir /srv/mosquitto/config /srv/mosquitto/data /srv/mosquitto/log -p
sudo nano /srv/mosquitto/config/mosquitto.conf

Paste this as initial configuration

ersistence true
persistence_location /mosquitto/data/

log_dest file /mosquitto/log/mosquitto.log
log_dest stdout

listener 1883

Prepare a docker-compose file for the mosquitto image

mkdir ~/mosquitto -p
nano docker-compose.yaml

Paste this

version: '3'
  services:
    mosquitto:
      container_name: mosquitto
      image: eclipse-mosquitto
      volumes:
      - "/srv/mosquitto/config:/mosquitto/config"
      - "/srv/mosquitto/log:/mosquitto/log"
      - "/srv/mosquitto/data/:/mosquitto/data"
      restart: always
      ports:
      - "1883:1883" 

Save the file and start the container

docker-compose up -d mosquitto

After that, log into the new container

docker exec -it mosquitto sh

create an user

mosquitto_passwd -c /mosquitto/config/mosquitto.passwd MOSQUITTO_USER

NOTE: Feel free to choose whatever name for the mqtt user. Just make sure to use the same in the following configurations

Exit from the container

exit

Reference the password file in mosquitto configuration file

sudo nano /srv/mosquitto/config/mosquitto.conf 

Adding these lines

password_file /mosquitto/config/mosquitto.passwd
allow_anonymous false

Restart the mosquitto container

docker restart mosquitto

Confgure MQTT device on HA

Edit the home assistant config file

sudo nano ~/homeassistant/configuration.yaml

Add the following lines

mqtt:
  broker: "localhost"   # Or broker ip
  port: 1883
  username: "MOSQUITTO_USER"
  password: !secret MQTT_PASSWORD

Write the username used in the mosquitto container. The password has to be added in the secret file

sudo nano ~/homeassistant/secrets.yaml

Write the password in clear text here

MQTT_PASSWORD: "[mypasswrd]"

Save the file and restart home assistant

docker restart home-assistant

Add Tasmota integration

On the tasmota device, go to Configuration > Configure MQTT and set the parameters:

Parameter Value
Host [PI_IP]
1883
MOSQUITTO_USER
[mypasswrd]

Remap colors on Tasmotized Dom-E Beghelli RGBW smart bulb

TL;DR,

Go to your Tasmota device page and click on Console. Execute this command

Backlog SetOption0 1; SetOption37 13; Template {"NAME":"Beghelli Smart Bulb","GPIO":[0,0,0,0,416,417,0,0,418,419,420,0,0,0],"FLAG":3,"BASE":18}

Restart your device.
If it doesn't behave as expected, make sure the correct configuration is selected: Configuration > Configure Module > Beghelli Smart Bulb


First install tasmota on the bulb.
I strongly recommend tuya-convert.

Once you have the latest tasmota image installed on your device and you have it configured for your network, go to its ip address and click Console

Refer to the ]original guide](https://tasmota.github.io/docs/Configuration-Procedure-for-New-Devices/) for more details

Enable boot loop control to ensure that in case of a wrong configuration the device comes back to a safe state

Backlog SetOption0 0; SetOption36 1

Create a configuration and set the GPIOs as relays.
Then you can check which one is associated with each color.

TEMPLATE {"NAME":"ID Relays","GPIO":[0,0,0,0,224,225,0,0,226,227,228,229,230,0],"FLAG":0,"BASE":18}

Numbers 224 through 230 define that the corresponding GPIOs are configured as Relay 1 through 7 "Base": 18 indicates that the model is based on a generic device

Restart the device and you will see 8 switches on the main page. For more details, visit the module configuration page (e.g. you can see which pins are being controlled)

GPIO Color
GPIO_04 Red
GPIO_05 Cold white
GPIO_12 Green
GPIO_13 Warm white
GPIO_14 Blu

At this point we recognize that the slide bars act in an unexpected way (e.g. thewarmth slider changes the color to blu)

Following the table on tasmota site we can re-map the color channels.
By default the channels are R G B Wc Ww, but in our case we found that they are R Wc G B Ww so we can set this:

SetOption37 13

Now you can set the device to save power state changes with

SetOption0 1

Done!

Setup automatic updates

Home Assistant uses an integration (a binary sensor) to check for updates.
We will setup an automation for automatically upgrading the homeassistant docker image.

The proposed approach is:

  • Home Assistant detects an update
  • Home Assistant writees a file on the config folder
  • RPi periodically checks the content of the said file
  • When appropriate RPi launches a script to update the docker image

Create the 'interface file' and make sure it is writable by the user:

sudo touch ~/homeassistant/updateHA
sudo chown $(whoami):$(whoami) ~/homeassistant/updateHA

Create a script for the update

sudo touch ~/homeassistant/autoupdate.sh
sudo chmod +x ~/homeassistant/autoupdate.sh
sudo nano ~/homeassistant/autoupdate.sh

Paste the update commands in it

#!/bin/sh

HOMEPATH='/home/ubuntu/homeassistant'
FILE="$HOMEPATH/updateHA"

echo "$(date) running script as: $(whoami)"

# Create the file if it doesn't exist
touch $FILE

# Check if the update is required

if grep -q "1" "$FILE"; then

  echo "$(date) update is required!"

  cd $HOMEPATH

  echo "$(date) currently in $(pwd)"

  # Update the docker image
  echo "$(date) pulling latest imge"
  docker-compose pull home-assistant
  echo "$(date) running new image"
  docker-compose up --build -d home-assistant
  echo "$(date) deleting unused images"
  docker image prune -f

  echo "$(date) Resetting the update flag"
  echo 0 >$FILE
fi

You can create a crontab to call the script (crontab) or use a service with timers:

mkdir ~/.config/systemd/user -p
cd ~/.config/systemd/user
touch updateHA.service
touch updateHA.timer

nano updateHA.service

updateHA.service

[Unit]
Description=Periodically check for HomeAssistan>
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/home/ubuntu/homeassistant/autoupdate>
#User= ubuntu
StandardOutput=file:/home/ubuntu/logSO.log
StandardError=file:/home/ubuntu/logERR.log

[Install]
RequiredBy=autoupdateHA.timer
WantedBy= multi-user.target

Edit autoupdateHA.timer

autoupdateHA.timer

[Unit]
Description=Timer that periodically triggers autoupdateHA.service
After=network-online.target

[Timer]
OnCalendar=hourly

[Install]
RequiredBy=autoupdateHA.service
WantedBy=default.target

You can now activate and start the services

systemctl --user enable autoupdateHA.service autoupdateHA.timer
systemctl --user start autoupdateHA.timer

And check if the timer is active

systemctl --user list-timers

Now add a shell_command integraton in your confiiguration

sudo nano ~/homeassistant/configuration.yaml

Add these lines

# Exposes service shell_command.update
shell_command:
  autoupdate: 'echo 1 > /config/updateHA'

NOTE: Shell commands are called from wiithin the docker container, therefore use its internal paths

On Home Assistant:

  • Go to Configuration > Server Controls > RESTART
  • Go to Configuration > Automation > Add automation (empty)
Name Autoupdate
Description Automatically update HA docker image
Mode Single (default)
Triggers
Trigger type State
Entity binary_sensor.updater
from off
to on
Acrions
Action type Call service
Service shell_command.autoupdate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment