Files

114 lines
2.1 KiB
Bash
Raw Permalink Normal View History

2022-10-28 17:15:16 +00:00
#!/usr/bin/env bash
# Devices to check -- if populated and up, no notifications are sent.
readonly DEVICES=()
# COCO Labels
readonly LABEL_PERSON=0
readonly LABEL_CAT=15
# Lockfile to ensure that only one instance of the script is running.
readonly LOCKFILE="/tmp/motion-notify.lock.d"
2026-10-22 12:53:52 +00:00
# yolo26 working directory.
readonly PROJECT="/tmp/yolo26"
2022-10-28 17:15:16 +00:00
# Notification recipient.
readonly RECIPIENT="${NOTIFICATION_RECIPIENT}"
2023-05-28 18:28:18 +00:00
# rsync user and server for backups.
readonly RSYNC_USER="${RSYNC_USER}"
readonly RSYNC_SERVER="${RSYNC_SERVER}"
2022-10-28 17:15:16 +00:00
acquire_lock () {
while true; do
if mkdir "${LOCKFILE}"; then
break;
fi
sleep 1
done
}
check_devices() {
for device in "${DEVICES[@]}"; do
if ping -c 1 -w 1 "${device}" &> "/dev/null"; then
return 0
fi
done
return 255
}
detect_objects() {
local filepath="$1"
2026-10-22 12:53:52 +00:00
"${HOME}/.venv/bin/yolo" predict \
classes=0 \
conf=0.5 \
model="${HOME}/yolo26n.pt" \
name="motion" \
project="${PROJECT}" \
save_txt=true \
source="$1"
2022-10-28 17:15:16 +00:00
}
notify() {
local name="$1"
echo "${HOSTNAME} at $(date '+%Y-%m-%dT%H:%M:%S%:z')" | \
mutt -a "${PROJECT}/motion/${name}.jpg" \
-s "${HOSTNAME}: Motion Detected" \
-- "${RECIPIENT}"
}
upload() {
local name="$1"
2023-05-28 18:28:18 +00:00
rsync --archive --verbose \
"${PROJECT}/motion/${name}.jpg" \
"${RSYNC_USER}@${RSYNC_SERVER}:/photo/${name}.jpg"
2022-10-28 17:15:16 +00:00
}
delete_outdated() {
local filepath="$1"
rm -f "$1"
2026-10-22 12:53:41 +00:00
rm -rf "${PROJECT}"
2022-10-28 17:15:16 +00:00
}
release_lock () {
rmdir "${LOCKFILE}"
}
main() {
local filepath="$1"
local name
name="$(basename "${filepath}" .jpg)"
2026-10-22 12:52:36 +00:00
acquire_lock
2022-10-28 17:15:16 +00:00
# If devices are present, don't notify.
if (( "${#DEVICES[@]}" )); then
if check_devices; then
delete_outdated "${filepath}" "${name}"
2026-10-22 12:52:36 +00:00
release_lock
2022-10-28 17:15:16 +00:00
exit 0
fi
fi
detect_objects "${filepath}"
# Send a notification if we match any labels.
labels="$(awk '{print $1}' "${PROJECT}/motion/labels/${name}.txt")"
if echo "${labels}" | grep -qw "${LABEL_PERSON}\|${LABEL_CAT}"; then
notify "${name}"
fi
upload "${name}"
delete_outdated "${filepath}" "${name}"
2026-10-22 12:52:36 +00:00
release_lock
2022-10-28 17:15:16 +00:00
}
main "$@"