mircobabini
6/22/2016 - 9:39 PM

motion-observe.py

#!/usr/bin/python

import re
import time
import shlex
from subprocess import Popen, PIPE

def count_motion(*args, **kwargs):
	query = "motion"
	ps_process = Popen(["ps", "aux"], stdout=PIPE)
	grep1_process = Popen(["grep", "-v", "grep"], stdin=ps_process.stdout, stdout=PIPE)
	grep2_process = Popen(["grep", query], stdin=grep1_process.stdout, stdout=PIPE)
	ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep1_process exits.
	grep1_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep2_process exits.
	output = grep2_process.communicate()[0]

	lines = output.split('\n')
	filtered = filter(lambda x:  not re.match(r'^\s*$', x), lines)

	howmany = len(filtered)

	print howmany
	return howmany

while True:
	if count_motion() < 1:
		ps_process = Popen(["sudo", "motion"], stdout=PIPE)
		ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep1_process exits.
		print 'here we go'


	print 'sleep'
	time.sleep(1)

# usage:
# python observer.py &
#! /bin/sh
# /etc/init.d/motion-observe

### BEGIN INIT INFO 
# Provides:          motion-observe 
### END INIT INFO 

case "$1" in
  start)
    echo "Starting motion-observe"
    # run motion-observe
    # sudo service motion stop
    /home/pi/motion-observe &
    ;;
  stop)
    echo "Stopping motion-observe, motion"
    # kill application you want to stop
    killall motion-observe
    killall motion
    ;;
  *)
    echo "Usage: /etc/init.d/motion-observe{start|stop}"
    exit 1
    ;;
esac

exit 0

# https://github.com/Sonarr/Sonarr/wiki/Autostart-on-Debian
# cd /etc/init.d
# sudo chmod +x motion-observe
# sudo update-rc.d motion-observe defaults
# sudo service motion-observe start
# sudo service motion-observe stop