#!/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 Magcontakt
GPIO_Magcontakt = 8
 
print "Pre ukoncenie stlacte CTRL-C"
 
# Nastavenie vstupneho pinu
GPIO.setup(GPIO_Magcontakt,GPIO.IN)      # Echo

Okno_Zatvorené  = 0
Okno_Otvorene = 0

try:

  # print "Cakam na Magcontakt  ..."

  # Slucka pokial je vystup Magcontakt 0
  while GPIO.input(GPIO_Magcontakt)==1:
    Okno_Zatvorené  = 0

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

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

    # Citanie stavu Magcontakt
    Okno_Zatvorené = GPIO.input(GPIO_Magcontakt)

    if Okno_Zatvorené==1 and Okno_Otvorene==0:
      # Magcontakt 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 "  Okno otvorené !"
      # Vrati predchadzajuci stav
      Okno_Otvorene=1
    elif Okno_Zatvorené==0 and Okno_Otvorene==1:
      # Magcontakt 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)"
      Okno_Otvorene=0

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