Home Assistant Setup + Integration â
BEFORE YOU READ
These are the logs I wrote when I started out setting up Home Assistant back in January 2023. Beware as the content are unsorted and might possibly outdated!
Update Log â
- [2023.07.13] Update HA 2023.1.7 to 2023.7.1
My Smart Devices Connected to HA â
Smart IoT devices that I owned that connects to HA
Camera
- Dahua 1435 IPC-HFW1435S-W-S2 x2
- IMOU Ranger 2
Hub/IR Blaster
- Broadlink RM4 Pro
- SwitchBot Hub Mini
Curtain
- Switchbot Curtain U-Rail 2
Contact Sensor
- SwitchBot Contact Sensor
Motion Sensor
- Philips Hue Motion Sensor x2
- SwitchBot Motion Sensor x4
Lights
- Philips Hue RGB 60W (800 Lumens) x4
- Philips Hue Bright White (800 Lumens) x1
- Philips Hue Go
- Wiz Connected Color 100W (1600 Lumens) x9
Temperature/Humidity Sensor
- TUYA Wireless Temperature Humidity Sensor (brand: Gaoducash) x3
Install Additional Plugins â
Before you can install any additional plugins like lovelace slider entity row mod (https://github.com/thomasloven/lovelace-slider-entity-row), use HACS (Home Assistant Custom Store) instead to manage those plugins.
Go to add-on store
Install SSH add-ons
Go to Configuration
tab and make sure username and password is set.
Start
Terminal
add-on on the sidebarRun HACS download script
wget -O - https://get.hacs.xyz | bash -
Restart HACS
Go to
Settings -> Integration
and search forHACS
.
- Accept all
Install Slider Entity Row â
Enable Kodi Integration â
Home Assistant will send JSON-GRPC to Kodi on nVidia Shield.
Since Kodi Leia, you must enable SSL on Kodi since JSON-GRPC can only be sent to HTTPS channel.
Without SSL, you will see issue
Install Self-Signed SSL to nVidia Shield â
Establish
adb shell
to nVidia ShieldGenerate self-signed certificate using online SSL website such as https://regery.com/en/security/ssl-tools/self-signed-certificate-generator
Enter the IP address of your nVidia Shield.
Then click Generate SSL
. Two files will be generated.
Save this as server.pem
Save this as server.key
Kodi expected to have these two files named as it-is, so do it.
Example certificate when you try to access Kodi
- Push the cert to
sdcard
on nvidia Shield usingadb
adb push server.pem /sdcard/Android/data/org.xbmc.kodi/files/.kodi/userdata
adb push server.key /sdcard/Android/data/org.xbmc.kodi/files/.kodi/userdata
Enable SSL on Kodi Settings > Control â
Go to Kodi Settings > Control, then turn on Enable SSL
button.
Try to open browser and type in the IP address of nVidia Shield using HTTPS. Note that http will fail now.
Enable JSON-RPC â
Since the interface is available on many transports enabling it depends on the transport.
Python: Always enabled
HTTP: In System/Settings/Network/Services activate Allow control of Kodi via HTTP (see Enabling the webserver)
TCP: In System/Settings/Network/Services activate Allow programs on this system to control Kodi for localhost access only and Allow programs on other systems to control Kodi for access from other computers as well
Note: The EventServer is a different interface for sending remote keypresses to Kodi, and must be enabled separately, some programs may use both interfaces.
Verify JSON-RPC â
Test: Sending Input Use curl
and issue the following to test sending a down command
curl -s -X POST -H "content-type:application/json" "https://kodi:kodi@192.168.1.2:8080/jsonrpc" -d '{"jsonrpc": "2.0", "id": "1", "method": "Input.ExecuteAction", "params": {"action": "down"}}' -k
Expectation: You should see the selection changed.
Test: Changing TV Channel
curl -s -X POST -H "content-type:application/json" "https://kodi:kodi@192.168.1.2:8080/jsonrpc" -d '{"jsonrpc": "2.0", "id": "1", "method": "Player.Open", "params": {"item":{"channelid":1}}}' -k
Expectation: You should see it changed to Live Channel TV 1
Setup JSON-GRPC on Kodi HA Integration â
Test: Sending input up via HA Service
service: kodi.call_method
data:
method: Input.Up
target:
entity_id: media_player.android_kodi
Expectation: You should see selection UP
Example JSON-GRPC to tune to Channel 1 in PVR
service: kodi.call_method
data:
method: Player.Open
item:
channelid: 1
target:
entity_id: media_player.android_kodi
It might be hard since it uses channel_id
. To get the real channel number, call the following service
curl -s -X POST -H "content-type:application/json" "https://kodi:kodi@192.168.1.2:8080/jsonrpc" -d '{"jsonrpc": "2.0", "id": "1", "method": "PVR.GetChannels", "params": {"channelgroupid": 1}}' -k
example output:
Install MotionEye â
MotionEye is used as NVF for IP Cameras.
There are two recommended ways to install MotionEye. I recommend Docker since it is easier and unRAID can easily install it.
Method 1: Run as Container â
For UnRAID, search for MotionEye in Apps, then install it to run as docker container.
Following is a screenshot of the container template
Before running the container, login to UnRAID shell as root, and copy the motioneye.conf
to /etc/motioneye
. The Dockerfile
used to build this container image (https://github.com/malvarez00/Docker-MotionEye/blob/master/Dockerfile) does has that config file, but since we map the /etc/motioneye
with the host folder in unRAID server, it will be emptied.
To initialize the config file, launch unRAID shell and execute the following.
cd /mnt/cache/appdata/MotionEye/config
wget https://raw.githubusercontent.com/box18box/motioneye/master/extra/motioneye.conf.sample
mv motioneye.conf.sample motioneye.conf
By default the container will use UTC+0 timezone, to set to your own region timezone, add a new environment variable TZ
and set the value to your region. Click the container setting and click Add another path, port, variable
.
The final tempalte should look like this.
Then run the container
Open a browser using Microsoft Edge on http://UNRAID_SERVER_IP:8765
. For some reason launching it using Firefox will cause no response when adding any camera.
Enter admin
as username and leave the password blank.
Add camera â
MotionEye support ONVIF! So we can add any ONVIF compliant camera. In my case I added IMOU Ranger 2 camera.
Fill in the following:
URL: rtsp://192.168.1.18:554/cam/realmonitor?channel=1&subtype=0&unicast=true&proto=Onvif
Username: admin (default)
Password: Find the Safety Code at the bottom of IMOU camera. It should be something like L276XX6F
Camera: Select RTSP/UDP for best performance
Adding MotionEye Integration in Home Assistant â
The MotionEye Integration in HA require setting password for admin and surveillance. So set it on Motioneye webpage first.
Method 2: Run in VM â
Python 3 version â
sudo apt update
sudo apt --no-install-recommends install ca-certificates curl python3 python3-distutils -y
sudo apt --no-install-recommends install ca-certificates curl python3 python3-dev libcurl4-openssl-dev gcc libssl-dev -y
# install pip
curl -sSfO 'https://bootstrap.pypa.io/get-pip.py'
sudo python3 get-pip.py
rm get-pip.py
# install and setup motioneye
sudo python3 -m pip install 'https://github.com/motioneye-project/motioneye/archive/dev.tar.gz'
sudo motioneye_init
Find for MotionEye Integration in HA.
Be sure to add http://
prefix in URL, other wise it will return error!
Click it and enable all settings!
There are some entities that are disabled by default, so we will enable all. Click Entities
Enable all integration
IMOU Camera Related Settings â
RTSP Link URL â
for imou camera
H.265
rtsp://admin:PWD@IP:554/cam/realmonitor?channel=1&subtype=0&unicast=true&proto=Onvif
H.264
rtsp://admin:PWD@IP:554/cam/realmonitor?channel=1&subtype=1&unicast=true&proto=Onvif
Configure Advanced Settings â
More advanced settings can be configured by downloading https://dahuawiki.com/ConfigTool. You can use Dahua tool to config IMOU since IMOU is selling Dahua camera too, but they rebrand it for consumer side. Dahua is setting B2B.
Glances - System Monitor â
@ref: https://github.com/nicolargo/glances/issues/1381 Run glance server with username and password
glances -w --username --password
Home Automation Scripts â
Service â
Ask Alexa to speak a sentence
- service: notify.alexa_media
data:
message: Gary, stand up and drink water!
target: media_player.gary_s_echo_dot
data:
type: tts
Note: tts
won't play notification sound. If you want, change to announce
Speak something to Alexa and ask her to response
service: media_player.play_media
target:
entity_id: media_player.gary_s_echo_dot
data:
media_content_type: custom
media_content_id: 'what time is it'
service: media_player.play_media
target:
entity_id: media_player.gary_s_echo_dot
data:
media_content_type: custom
media_content_id: 'play love song'
Style â
Add color to button card
Dahua WiFi IP Camera 1435 â
Connect the camera to both power adapter and RJ45 to your router. For some reason I can't see the device hotspot appearing, so I have to setup using Dahua ConfigTool
.
Select the IPC from the menu. It should show as Uninitialized
.
After initialized
Click the Config
button and it should open a web page. We shall configure it to connect to WiFi 2.4GHz.
Main page
Click Setting
> Network
Wifi connection successful!
Let's look at some of the settings
Frigate â
Frigate requires a MQTT server to sent event JSON.
Run MQTT Server Mosquitto as Docker Container â
Install Mosquitto
from unRAID Add-On menu.
Then go to /mnt/user/appdata/mosquitto/config
and create a mosquitto.conf
file.
Include the following options in the config file.
listener 1883
persistence true
allow_anonymous true
Without these settings, you will encounter the Error: Address not available
error in the log when launching the container. See https://stackoverflow.com/questions/66402009/docker-eclipse-mosquitto2-0-7-error-address-not-available for more info.
Add Frigate Add-on to HA â
Add the repo https://github.com/blakeblackshear/frigate-hass-addons
We will add Frigate Proxy since we already have it running as Docker Container. The purpose is to have an icon at the sidebar.
Add Frigate camera â
Note that as of 2022-11-15 Frigate does not support h265 stream with rtmp. So you have to configure all existing main stream on your camera to use h264 instead, using either ConfigTool
or the web UI.
On my IMOU Ranger 2 via ConfigTool
On my Dahua 1435W via Web UI
Configure Frigate HASS Card â
After configuring Frigate Proxy add-on, configure the card to use Frigate JSMpeg
as the live view provider for 10 FPS and smoother frame rate. The default is 1FPS. See https://github.com/blakeblackshear/frigate/discussions/3066 for more info. From the official description:
Switch bot API â
- Get Token and Secret for mobile app
Run the following script to get the sign
.
output
$ python3 get-switchbot-api-credentials.py
Authorization: <TOKEN>
t: 1668525489890
sign: 0BxAZpv8ZQlUwTdaq32F2C/iTNDsjyRoXi4DAgVZEv8=
nonce:
Next, let's get a list of device ID that is linked to our Switch Mini.
curl -H "Authorization: <TOKEN>" https://api.switch-bot.com/v1.0/devices
output
Webhook configuration â
My attempt:
Flow
- Device state change
- Switchbot API server call registered web hook
- JSON payload sent to Home Assistant Automation for that webhook
- Parse payload and sent to MQTT server (on another VM)
- Sensor defined in configuration.yaml update its sensor value based on payload received from MQTT server
From motion sensor webhook
{'eventType': 'changeReport', 'eventVersion': '1', 'context': {'deviceType': 'WoPresence', 'deviceMac': 'D7F9AC484301', 'detectionState': 'DETECTED', 'timeOfSample': 1668615591571}}
# Example configuration.yaml entry
mqtt:
sensor:
- name: "Switchbot Motion Sensor Staircase Downstair"
state_topic: "/home/staircase/switchbot/motion/D7F9AC484301"
value_template: "{{ value_json.detectionState }}"
availability:
- topic: "/home/staircase/switchbot/motion"
payload_available: "true"
payload_not_available: "false"
# json_attributes_topic: "home/sensor1/attributes"
share to reddit â
Hi guys, in light of learning more about jinja2 templating and webhook automation in Home Assistant I've created an webhook automation using some SwitchBot sensors that I bought that is efficient in responding to Switchbot Webhook API for asynchronous event like door open, motion on.
Others solution that I found online and in HA forum usually parse the webhook payload on the mqtt
sensor defined in configuration.yaml
, whereas the service that I did will did all the parsing at the Automation script instead. It will then set the right state (as a string instead of JSON payload) to a dynamic topic depending on the type of the Switchbot sensor. The mqtt
sensor defined in configuration.yaml
will just have to specify a topic to subscribe for a state and just compare the string inside that topic. This method doesn't require any restart since no changes is done in configuration.yaml
.
Of course you could create a binary_sensor
in configuration.yaml
without having to use the webhook that periodially pool SwitchBot API for any status. In fact this is how I started, but then it's not efficient since the event should be asynchronous, and that is exactly why Webhook is so important!
binary_sensor:
# for switchbot motion sensor
- platform: rest
name: "Motion Sensor Staircase Downstair"
device_class: motion
resource: !secret switchbot_staircase_downstair_motion_sensor_status_url
method: GET
scan_interval: 1
headers:
Authorization: !secret switchbot_api
Content-Type: "application/json"
value_template: "{{ value_json.body.moveDetected }}"
Devices Used â
- Switchbot Hub Mini
- SwitchBot Door Contact Sensor
- SwitchBot Motion Sensor
- Amazon Alexa
Prerequisite â
You need to install
MQTT
integration and created an Automation withWebhook
as trigger. I setup my MQTT broker as another VM in my unRAID server rather than an Add-on to simplify my workflow.Register the Webhook URL that you received from Home Assistant Cloud (NabuCasa) and call Switchbot API. Note I'm still using Switchbot API v1 to simplify token auth đ
curl
example to register your HA webhook URL to Switchbot API server
curl -H "Content-Type: application/json" -H "Authorization: <YOUR_SWITCHBOT_TOKEN>" -X POST https://api.switch-bot.com/v1.0/webhook/setupWebhook -d '{"action":"setupWebhook", "url": "https://hooks.nabu.casa/<AUTO_GENERATED_URL_FROM_NABUCASE>", "deviceList": "ALL"}'
You should receive the following response code 100
if it works
{"statusCode":100,"body":{},"message":"success"}
How the Webhook works â
- Your Switchbot sensor detected a state change and sent a message to Switchbot Hub.
- Your Switchbot hub sent an update to Switchbot API server
- Switchbot API server call registered web hook pointed to your HA (routed via NabuCasa server)
- The webhook JSON payload is then sent to HA Automation for that registered webhook
- Parse JSON payload and construct the right topic that is subscribed by each sensor defined in
configuration.yaml
, and update the value of that state. To keep it simple, the value is a string, rather than a JSON body that yourmqtt sensor
defined atconfiguration.yaml
had to parse. - SEnd the payload to the MQTT server that you setup in HA
MQTT
integration. mqtt sensor
defined inconfiguration.yaml
update its state value based on the payload (string) payload received from a subscribed topic from MQTT server
Implementation â
What the Script Does â
- Alexa announce the notification depending on the sensor type, e.g.
door open
for Contact Sensor, andmotion on
for Motion Sensor. - The state is parsed from Switchbot Webhook JSON payload. The value depend on the sensor type, e.g.
on/off
for motion sensor andopen/close
for contact sensor. - An additional availability is parse, not needed for these kind of sensor but just to demonstrate you could do it too
- The JSON received from Switchbot Webhook API is sent to another topic for debugging purpose.
MQTT Topic Design â
The topic uses the following hierarchy:
/<HOME_NAME>/<SENSOR_LOCATION>/<MANUFACTURER>/<SENSOR_TYPE>/<DEVICE_ID>/{state,availability,json}
For Contact Sensor Note: My motion sensor device ID is C8F7D45BB07B
State change (open/close): /home/staircase/switchbot/contact/C8F7D45BB07B/state
Availability (online/offline): /home/staircase/switchbot/contact/C8F7D45BB07B/availability
Full JSON from Switchbot Webhook API: /home/staircase/switchbot/contact/C8F7D45BB07B/json
For Motion Sensor Note: My motion sensor device ID is D7F9AC484301
State change (open/close): /home/staircase/switchbot/motion/D7F9AC484301/state
Availability (online/offline): /home/staircase/switchbot/motion/D7F9AC484301/availability
Full JSON from Switchbot Webhook API: /home/staircase/switchbot/motion/D7F9AC484301/json
Paste the following YAML to the Automation Webhook trigger. You may change the topic accordingly.
Paste the following to configuration.yaml
. Be sure to change the device ID to the one in your Switchbot Hub. You can run the following curl
command to get a list of device ID currently connected to your SwitchBot Hub Mini.
curl -H "Authorization:<SWITCHBOT_TOKEN>" https://api-switch-bot.com/v1.0/devices/
configuration.yaml
Check your configuration from Developer page, if all well, restart and profit!
New Bluetooth â
# lsusb
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 002: ID 0b05:17cb ASUSTek Computer, Inc. Broadcom BCM20702A0 Bluetooth <-- New BT Adapter
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 003: ID 174c:3074 ASMedia Technology Inc. ASM1074 SuperSpeed hub
Bus 002 Device 002: ID 0951:1666 Kingston Technology DataTraveler 100 G3/G4/SE9 G2/50
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 2516:003b Cooler Master Co., Ltd. MasterKeys Pro L
Bus 001 Device 002: ID 0b05:19af ASUSTek Computer, Inc. AURA LED Controller
Bus 001 Device 005: ID 8087:0026 Intel Corp. AX201 Bluetooth
Bus 001 Device 004: ID 174c:2074 ASMedia Technology Inc. ASM1074 High-Speed hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Homekit Infused 5 â
My findings: DON"T USE IT, hard to customize. Use Dwain Dashboard instead TBA
Installation â
Move all zip files into config
folder
after install
Dwain Dashboard â
Unraid â
Install Unraid API â
Note: Currenlty it might OOM and cause major slowdown in unRAID web GUI!
Find Unraid-API
from Docker store
Be sure to configure the keys as follows. You'll need to add two keys manually since they were not there by default, MQTTRefreshRate
and MQTTCacheTime
. Notice I use the IP address in MQTTBroker
variable since I run it as docker in unRAID, instead of running as HA add-on mosquitto.
After the container is running, go to its web UI and add a new instance.
Use the IP address for unRAID server instead of hostname, and uncheck HTTPS
After configure
Tuya Smart App â
Read the following to enable Tuya integration in HA:
- https://developer.tuya.com/en/docs/iot/Home-assistant-tuya-intergration?id=Kb0eqjig0utdd
- https://developer.tuya.com/en/docs/iot/Platform_Configuration_smarthome?id=Kamcgamwoevrx
In summary:
- Register account in iot.tuya.com. Note this is different than the Tuya smart app. I used the same email and password in both sites.
- Create a new Cloud Project
- Link the account with
After linking:
References â
https://github.com/OpenWonderLabs/SwitchBotAPI/blob/main/README-v1.0.md#setup-webhook