#!/usr/bin/python
#
# Diplomova praca
# Martin Judiny

# Importovanie kniznic 
import time
import RPi.GPIO as GPIO
import os
import signal
import datetime
 
GPIO.setmode(GPIO.BCM)
datcas = datetime.datetime.utcnow()
 
# Definovanie GPIO pre pouzitie PIR
GPIO_PIR = 7
 
print "Pre ukoncenie stlacte CTRL-C"
 
# Nastavenie vstupneho pinu
GPIO.setup(GPIO_PIR,GPIO.IN)      # Echo

Aktualny_Stav  = 0
Predchadzajuci_Stav = 0

try:

  # print "Cakam na PIR  ..."

  # Slucka pokial je vystup PIR 0
  while GPIO.input(GPIO_PIR)==1:
    Aktualny_Stav  = 0

  print "  Ready"
  datcas = datetime.datetime.utcnow() 
  print "Systemovy cas :" , datcas , ""

  # Slucka pokial sa program neukonci s CTRL-C
  while True :

    # Citanie stavu PIR cidla
    Aktualny_Stav = GPIO.input(GPIO_PIR)

    if Aktualny_Stav==1 and Predchadzajuci_Stav==0:
      # PIR je aktivne
      datcas = datetime.datetime.utcnow()
      #start_time=time.time()
      bashCommand = "killall raspivid"
      os.system(bashCommand) 
      bashCommand = "sudo bash /var/www/rec.sh"                                          ###"raspivid -o /var/www/vid%03d.h264  -w 240 -h 320"
      os.system(bashCommand)
      start_time=time.time()
      print "  Pohyb !"
      # Vrati predchadzajuci stav
      Predchadzajuci_Stav=1
    elif Aktualny_Stav==0 and Predchadzajuci_Stav==1:
      # PIR sa vratil do stavu pripravenosti
      stop_time=time.time()
      print "  Ready ",
      elapsed_time=int(stop_time-start_time)
      print " (Elapsed time : " + str(elapsed_time) + " secs)"
      Predchadzajuci_Stav=0

except KeyboardInterrupt:
  print "  Quit"
  # Restartovanie GPIO nastaveni
  GPIO.cleanup()
