18 Jan 2022

Automatically Start/Stop Motion Activated Camera When Cellphone Not On Local Network

Automatically Start/Stop Motion Activated Camera When Cellphone Not On Local Network

Note: This Systemd service will detect if your mobile phone is on the local network using ping, therefore, it should have a static IP address when it connects to your Wi-Fi network.

  1. ~/.config/systemd/user/surveillance-system.service

     [Unit]
     Description=Automatically Start/Stop Surveillance System if phone not on local network
     Wants=surveillance-system.timer
    
     [Service]
     Type=simple
     ExecStart=/home/USERNAME/.config/systemd/user/start-motion-detection.sh
    
     [Install]
     WantedBy=multi-user.target
    
  2. ~/.config/systemd/user/surveillance-system.timer (check for mobile phone presence every minute)

     [Unit]
     Description=Automatically Start/Stop Surveillance System if phone not on local network
    
     [Timer]
     OnCalendar=*:0/1
    
     [Install]
     WantedBy=timers.target
    
  3. ~/.config/systemd/user/start-motion-detection.sh

     #!/bin/bash
     XDG_RUNTIME_DIR=/run/user/$(id -u)
     DBUS_SESSION_BUS_ADDRESS=unix:path=${XDG_RUNTIME_DIR}/bus
     export DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR
    
     ping -W 1 -c 1 192.168.0.20 > /dev/null
     if [ $? -ne 0 ]; then # Host is down, start motion
       echo "Host is down..."
         if pgrep -x "motion" >/dev/null
         then
           echo "Motion already running..."
         else
           echo "Motion is not running, sarting it..."
           motion
         fi
    
     else # Host is up, stop processes
       echo "Host is up..."
       if pgrep -x "motion" >/dev/null
       then
         echo "Stopping Motion..."
         killall motion
       else
         echo "Motion is not running."
       fi
     fi
    
  4. Commands to start the service and check its status:

     systemctl --user enable surveillance-system.timer --now
     systemctl --user start surveillance-system.timer --now
     systemctl --user list-timers
     systemctl --user status surveillance-system
    
  5. I hade issues where the phone would not connect to Wi-Fi fast enought when I was in range of the router, and it helped when I did this:

    In LineageOS 18.1 > Network & internet > Wi-Fi > Wi-Fi preferences > toggle On: Turn on Wi-Fi automatically: “Wi-Fi will turn back on near high-quality saved networks, like your home network”. (unfortunately, this requires location to be turned ON, also)