#!/usr/bin/python


import time
import serial
import os

os.system('clear')  #smaze obrazovku




port = serial.Serial("/dev/ttyACM0", baudrate=9600, timeout=1.0)
#dat = open('/root/uzivatel.dat', 'r+')
#port.open()

print "------------ BodyCom v1.0 ---------------"
print "system is run... "
print "*************EXIT(Ctrl-c)****************"


loop = 1
loop_2 = 1
loop_2 = 3

while True: 
    dat = open('/root/uzivatel.dat', 'r+') 
    cas = time.asctime( time.localtime(time.time()) )
    rcv = port.read(14)
  
    cas_ = cas[11:20]
  
    str_pr = rcv[1:6]     # prijaty prikaz 
    id_ = rcv[6:10]        # -||-    ID
   
    
  
    if loop_2 > 60:  # cetnost opakovani test vzdal jednotky
        port.write("!0000") # prikaz + ID jednotky
        time.sleep(2)
        rcvp = port.read(14)
        str_prp = rcvp[1:6]
        if str_prp != 'ping0':

           print "Zakladna ID:000  CHyba!!", (cas)
           log = open('/root/error.log', 'a')   #ulozi do logu zaznam o povoleni pristupu
           log.write  ("   000") #format textu
           log.write ("         ")
           log.write (cas)
           log.write ("\n")
           log.close() 
          
        loop_2 = 0
    loop_2 = loop_2 + 1
     
             
    if str_pr == 'ver00':  #je li prikaz  
         
    #----------prin ID a Cas--------
       print "ID:", (id_), "Cas:", (cas)
    #--------------------------

       loop = 1
       while loop == 1:  
             str_v = dat.readline()
             
             str_id = str_v[3:7]      # vybere ID z daneho radku 
             str_tim1 = str_v[10:15]  # spodni hranice casu
             str_tim2 = str_v[18:23]  # horni hranice povoleni pristupu
             str_timr = cas[11:16]    # relany cas
            #print str_pr             # tisk prikazu
                        
            
             if str_id != "":   # testuje konec souboru
                if str_id == id_:

                  
                   if str_timr > str_tim1:   # casova podminka
                      if str_timr < str_tim2:
                         print "--- Pristup Povolen ---"
                         port.write("!2000" + cas_)  # odpoved na seriak
                         log = open('/root/uzivatel.log', 'a')       # ulozi do logu zaznam o povoleni pristupu
                         log.write (id_)  # format textu
                         log.write ("       ")
                         log.write (cas)
                         log.write ("\n")
                         log.close()
                         loop = 0
             else:
                print "--- Pristup zamitnut! ---"
                port.write("!1000" + cas_ )    # posle:start znak|prikaz|ID jednotky(pro kterou je prikaz)|  
           
                loop = 0
    else:

       dat.close()









	
	

















