#-------------------------------------------------------------------------------
# Copyright (c) 2015, Thomas Mohaupt <Thomas.Mohaupt@gmail.com>
# All rights reserved.
# 
# This is a BSD 2-Clause license, 
# see http://opensource.org/licenses/bsd-license.php
# 
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions are met:
# 
# - Redistributions of source code must retain the above copyright notice, 
#   this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#-------------------------------------------------------------------------------

import time,math,os
import syslog
import subprocess

try:
	import RPi.GPIO as GPIO
except RuntimeError:
	print ("Unable to import GPIO library.")

PIN_LED_1 = 24
PIN_LED_2 = 25

PIN_PIR_1 = 18
PIN_PIR_2 = 23

# additional timeout after pir switch output off (in sec)
TIMEOUT = 300

current_timestamp = lambda: int(round(time.time()))

monitor_is_off = True
timeout_mode = False
last_pir_event_timestamp = current_timestamp()

def pir_event_rising(ch):
	global timeout_mode

	syslog.syslog("Detect rising edge")
	monitor_on()
	timeout_mode = False

def pir_event_falling(ch):
	global last_pir_event_timestamp
	global timeout_mode

	syslog.syslog("Detect falling edge")
	last_pir_event_timestamp = current_timestamp()
	timeout_mode = True

	GPIO.output(PIN_LED_1, 0)
	GPIO.output(PIN_LED_2, 1)

def is_timeout():
	global last_pir_event_timestamp
	global TIMEOUT

	return math.fabs(current_timestamp() - last_pir_event_timestamp) > TIMEOUT

def monitor_on():
	global monitor_is_off

	if monitor_is_off:
		syslog.syslog("Monitor on")
		subprocess.call("sh /usr/local/bin/monitor_on.sh", shell=True)
		GPIO.output(PIN_LED_1, 1)
		GPIO.output(PIN_LED_2, 0)
		monitor_is_off = False

def monitor_off():
	global monitor_is_off

	syslog.syslog("Monitor off")
	subprocess.call("sh /usr/local/bin/monitor_off.sh", shell=True)
	GPIO.output(PIN_LED_1, 0)
	GPIO.output(PIN_LED_2, 0)
	monitor_is_off = True

# ++++++++ MAIN +++++++++++++++++++++++++++++++++++++++++++++

syslog.syslog("Start pi-pir.py")

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_LED_1, GPIO.OUT)
GPIO.setup(PIN_LED_2, GPIO.OUT)

GPIO.setup(PIN_PIR_1, GPIO.IN)
GPIO.setup(PIN_PIR_2, GPIO.IN)

try:
	GPIO.add_event_detect(PIN_PIR_1, GPIO.RISING)
	GPIO.add_event_callback(PIN_PIR_1, pir_event_rising)

	GPIO.add_event_detect(PIN_PIR_2, GPIO.FALLING)
	GPIO.add_event_callback(PIN_PIR_2, pir_event_falling)

	while (1):
		if timeout_mode:
			if is_timeout():
				timeout_mode = False
				monitor_off()

		time.sleep(0.5)

except KeyboardInterrupt:
	#Restore GPIO to default state
	GPIO.remove_event_detect(PIN_PIR_1)
	GPIO.remove_event_detect(PIN_PIR_2)
	GPIO.cleanup()

	syslog.syslog("Stop pi-pir.py")