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

# Importovanie kniznic
import time
import datetime
import RPi.GPIO as GPIO
import os
import signal
# Definovanie funkci

def measure():
  # Funkcia pre meranie vzdialenosti

  GPIO.output(GPIO_TRIGGER, True)
  time.sleep(0.00001)
  GPIO.output(GPIO_TRIGGER, False)
  start = time.time()
  
  while GPIO.input(GPIO_ECHO)==0:
    start = time.time()

  while GPIO.input(GPIO_ECHO)==1:
    stop = time.time()

  elapsed = stop-start
  distance = (elapsed * 34300)/2

  return distance

def measure_average():
  # Funkcia s tromi meraniami vracia priemer

  distance1=measure()
  time.sleep(0.1)
  distance2=measure()
  time.sleep(0.1)
  distance3=measure()
  distance = distance1 + distance2 + distance3
  distance = distance / 3
  return distance

# Hlavny program

GPIO.setmode(GPIO.BCM)

# Definovanie GPIO pre pouzitie ultrazvuku
GPIO_TRIGGER = 23
GPIO_ECHO    = 24


print "Pre ukoncenie stlacte CTRL-C"

print "Ultrazvuk hranica 120cm"

# Nastavenie vstupnych vystupnych pinov
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  
GPIO.setup(GPIO_ECHO,GPIO.IN)      


GPIO.output(GPIO_TRIGGER, False)

try:

  while True:
    
    distance = measure_average()
    print "Vzdialenost : %.1f" % distance
    
    datcas = datetime.datetime.utcnow()   # datcas bude obsahovat aktualni datum a cas v UTC (GMT)
    print "Systemovy cas :" , datcas , ""
    time.sleep(1)
    
    # podmienka alarmu
    x = distance
    if x < 120:
      print "Alarm : Nepovoleny vstup"
      bashCommand = "killall raspivid"
      os.system(bashCommand)
      bashCommand = "raspivid -o /var/www/'datcas'.h264  -w 240 -h 320"
      os.system(bashCommand)
      start_time=time.time()
      bashCommand = "sudo python /home/pi/test_lcd4.py"
      os.system(bashCommand)
    elif x > 120:
      distance = measure_average()
      print "Vzdialenost : %.1f" % distance
      
except KeyboardInterrupt:
  GPIO.cleanup()
