import RPi.GPIO as GPIO
import time
import datetime
import os

trigger_fileextension = '.trg'
trigger_path = 'trigger/'
trigger = ""

# define GPIO mode, pin and use pin as input
GPIO.setmode(GPIO.BOARD)
GPIO_PIR = 12
GPIO.setup(GPIO_PIR,GPIO.IN)

print("PIR started")
print("Waiting for PIR to get idle ...")

# loop until PIR == 0
while GPIO.input(GPIO_PIR) != 0:
  time.sleep(0.2)
print("Now ready for motion detection")


# Callback-Function
def PIR_signal(GPIO_PIR):
  global trigger
  triggertime = datetime.datetime.now()
# Signal from low to high
  if GPIO.input(GPIO_PIR) == 1:
    trigger = triggertime.strftime("%Y-%m-%d-%H-%M-%S")
    open(trigger_path+trigger+trigger_fileextension, 'w').close()
    print("{0} - Motion detected".format(trigger))
# Signal from high to low
  else:
    os.remove(trigger_path+trigger+trigger_fileextension)
    print("{0:%Y-%m-%d-%H-%M-%S} - Motion terminated".format(triggertime))
    print()


# Event definition: on gpio state change call PIR_signal function
GPIO.add_event_detect(GPIO_PIR, GPIO.BOTH, callback=PIR_signal)
print("{0:%Y-%m-%d-%H-%M-%S} - Waiting for motion".format(datetime.datetime.now()))


# Main loop
while True:
  time.sleep(60)