If you use Pi-Hole as a DHCP server, you can use it to trigger an update to a device tracker as soon as the device connects to the network. This allows the device to be detected much more quickly than the traditional ping (ICMP) device tracker.
The dnsmasq daemon has the option to run a script when it issues a DHCP address. To do this, add a config file, eg: /etc/dnsmasq.d/05-dhcp-script.conf
with the line:
dhcp-script=/home/homeassistant/.homeassistant/dhcp.sh
Check the script is executable then restart dnsmasq via the pi-hole interface.
The script receives four parameters from dnsmasq: operation
, mac address
, ip address
and hostname
. Iāve used the hostname
to identify the device and convert it to the dev_id
used by the device tracker. If the script identifies an expected device, it uses the API to set the device status to āhomeā.
Youāll need to modify the script with the correct hostnames, dev_ids and your home assistant details.
dhcp.sh:
#!/bin/sh
op="${1:-op}"
mac="${2:-mac}"
ip="${3:-ip}"
hostname="${4}"
# Don't report on deleted leases
if [ $op = "del" ]
then
exit 0
fi
# Convert $hostname (or $mac, or $ip) into the device_tracker.dev_id.
case $hostname in
"paulus_oneplus")
dev_id="paulus"
;;
"annetherese_n4")
dev_id="anne_therese"
;;
*)
# other devices we're not tracking
exit 0
;;
esac
curl -H "Content-Type: application/json" -X POST \
-d '{"dev_id": "'$dev_id'", "location_name":"home"}' \
https://xxxx.example.com:8123/api/services/device_tracker/see?api_password=yourpassword
Once this is sorted, you can relax the the time between pings, as weāre now only relying on it to detect when the device goes away.
Due respects to reddit user /u/blackbear85 for the initial script (which used MQTT instead of kicking the device tracker directly).