Skip to content

Instantly share code, notes, and snippets.

@kabadisha
Created February 13, 2021 18:50
Show Gist options
  • Save kabadisha/0041c8fca7edaad56ddcc6f6e36eda0c to your computer and use it in GitHub Desktop.
Save kabadisha/0041c8fca7edaad56ddcc6f6e36eda0c to your computer and use it in GitHub Desktop.
Script to check if your phone is at home and disable ZoneMinder cameras. Runs as a cron job on an Asus router
#!/bin/sh
set -e
set -u
# Runs on your router to check if devices are connected via wifi.
# Disables motion detection on ZoneMinder network cameras if they are.
# Make sure local dns lookups are enabled on your router.
# On Asus Merlin routers this can be found under Tools > Other Settings >
# 'Wan: Use local caching DNS server as system resolver'
# Requires enabling ZoneMinder's API and generating a secret key. See the ZoneMinder docs for more info:
# https://zoneminder.readthedocs.io/en/1.34.22/api.html
# Also requires curl and jq for processing the JSON response to get the auth token for the ZM API.
ZONEMINDER_URI="https://zoneminder.url/zm"
ZM_USERNAME="user "
ZM_PASSWORD="password"
# MAC addresses of devices to detect
CHARLIE_PHONE="00:00:00:00:00:00"
ABI_PHONE="00:00:00:00:00:00"
# Get an access token using our ZM credentials
ACCESS_TOKEN=$(curl -s -XPOST -d "user=$ZM_USERNAME&pass=$ZM_PASSWORD" "$ZONEMINDER_URI/api/host/login.json" | jq -r '.access_token')
# Create a new file with all of the currently connected devices
echo 'Local results:' > /tmp/wifi-devices.txt
ip neighbour >> /tmp/wifi-devices.txt
# Could also try 'arp -a' command if 'ip neigh' doesnt work.
arp -a >> /tmp/wifi-devices.txt
# Old way (only works on broadcom wifi devices like RT-N66U)
#wl -i eth1 assoclist > /tmp/wifi-devices.txt
#wl -i eth2 assoclist >> /tmp/wifi-devices.txt
echo 'Results from repeater:' >> /tmp/wifi-devices.txt
# Get results from another AP in case devices have roamed there:
#ssh -i id_rsa -t admin@repeater.lan "ip neighbour; arp -a" | tee -a /tmp/wifi-devices.txt
# Check if either of the devices to detect are connected.
if $(grep -q -i "$CHARLIE_PHONE" /tmp/wifi-devices.txt) \
|| $(grep -q -i "$ABI_PHONE" /tmp/wifi-devices.txt); then
echo "Either or both of the devices detected. Disabling motion detection..."
curl -XPOST "$ZONEMINDER_URI/api/monitors/1.json?token=$ACCESS_TOKEN" -d "Monitor[Enabled]=0" >/dev/null
curl -XPOST "$ZONEMINDER_URI/api/monitors/1.json?token=$ACCESS_TOKEN" -d "Monitor[Enabled]=0" >/dev/null
else
echo "Neither device detected. Enabling motion detection..."
curl -XPOST "$ZONEMINDER_URI/api/monitors/1.json?token=$ACCESS_TOKEN" -d "Monitor[Enabled]=1" >/dev/null
curl -XPOST "$ZONEMINDER_URI/api/monitors/1.json?token=$ACCESS_TOKEN" -d "Monitor[Enabled]=1" >/dev/null
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment