This is a small script that turns a Raspberry Pi with Bluetooth into a MQTT device tracker for use with Home Assistant (or other IOT) equipment.
This is useful if you have a bunch of Pi's around the home anyway, and want to increase the accuracy of the presence detection.
On the hardware side of things, make sure bluetooth is working.
On the software side, you need to install the following:
sudo apt install bluetooth libbluetooth-dev
sudo pip3 install pybluez paho-mqtt
If you want to use Bluetooth LE discovery, you need those too:
sudo apt install pkg-config libboost-python-dev libboost-thread-dev libglib2.0-dev python-dev
sudo pip3 install gattlib
Update the settings install bt_tracker.py with your own configuration.
Add your devices as per below. Note that these will form part of the state topic of the MQTT signal.
devices = [
{"name": "Device1", "mac": "aa:bb:cc:dd:ee:ff"},
{"name": "Device2", "mac": "aa:bb:cc:dd:ee:f2"}
]
Also, provide a location for your device by changing the location variable:
LOCATION = "Bedroom"
Based on the above settings, the device topic for mqtt messages will be:
bt_mqtt_tracker/presence/Bedroom/Device1
AND
bt_mqtt_tracker/presence/Bedroom/Device2
Next, update the MQTT settings:
# Update the follow MQTT Settings for your system.
MQTT_USER = "mqtt" # MQTT Username
MQTT_PASS = "mqtt_password" # MQTT Password
MQTT_CLIENT_ID = "bttracker" # MQTT Client Id
MQTT_HOST_IP = "127.0.0.1" # MQTT HOST
MQTT_PORT = 1883 # MQTT PORT (DEFAULT 1883)
There are also settings you can mess around with, such as timeout of searching and scan intervals. Defaults work well for me, but feel free to change as required.
If you would like to have the Device Tracker to restart on startup, create the a file in the in the following location /etc/systemd/system/bttracker.service
[Unit]
Description=Raspberry Pi Device Tracker MQTT Service
After=network.target
[Service]
Type=idle
User=root
ExecStart=/usr/bin/python3 /home/pi/bt-mqtt-tracker/bt_tracker.py
Restart=always
[Install]
WantedBy=multi-user.target
Update the file location and other settings as required and then load the service as follows:
$ sudo systemctl daemon-reload
$ sudo systemctl enable bttracker.service
$ sudo systemctl start bttracker.service
The sensors should be discovered automatically. You can configure them manually as well.
To add the sensor to Home Assistant use the MQTT Sensor Component a sample configuration is below (based on settings above):
---
sensor:
- platform: mqtt
state_topic: "bt_mqtt_tracker/presence/Bedroom/Device1"
name: "Device 1 Bedroom Presence"
- platform: mqtt
state_topic: "bt_mqtt_tracker/presence/Bedroom/Device2"
name: "Device 2 Bedroom Presence"
Using the above sensor in conjuction with other device trackers and a bayesian sensor, can make a pretty accurate device tracker.