#!/usr/bin/python
# ************ KONCENTRATOR PRO MERENI KVALITY VZDUCHU ****************
# script logujici zapravy z mericich modulu

from __future__ import print_function
import serial, io, time, datetime, sys

addr  = '/dev/ttyAMA0'  # adresa serioveho portu (UART)
baud  = 9600            # baud rate pro UART
file1 = '/usr/bin/koncentrator/log1.txt' # soubory logu.
#Protoze neni script
file2 = '/usr/bin/koncentrator/log2.txt' # volan z teto slozky, je nutne
file3 = '/usr/bin/koncentrator/log3.txt' # uvest absolutni cestu
#k souboru
fmode = 'a'             # mod pro otevirane soubory = append

with serial.Serial(addr,baud,timeout=3.0) as port : 
# otevre instanci portu
    spb = io.TextIOWrapper(io.BufferedRWPair(port,port,1),
        encoding='ascii', errors='ignore', newline='\r' ,line_buffering=True)
    print ('Log hodnot ', time.strftime("%Y-%m-%d %H:%M:%S"))#vypis do konzoly
    timenow = time.strftime("%Y-%m-%d %H:%M  ") # naformatovani data
a casu
    mID = 1     # nejnizsi ID modulu
    mIDmax = 3  # nejvyssi ID modulu
    while (mID < (mIDmax+1)):
        if mID == 1:    # pro kazdy modul se otevre jiny soubor
                outf = open(file1,fmode)
        if mID == 2:
                outf = open(file2,fmode)
        if mID == 3:
                outf = open(file3,fmode)
        port.write(str(unichr(0x30 + mID))) # poslani zadosti o report
        x = spb.readline()                # precteni radku ze sériového
portu
        #spb.writelines(x)                # pro testovani. vrati data
na port
        if(x):                            # pokud prisla zprava pøed
timeoutem
                outf.write(timenow + x)   # zapis zpravy do souboru
                outf.flush()              #
        mID=mID+1                         # nasleduje dalsi modul
        outf.close()                      # zavreni souboru
    print('Konec logovani.')              # vypis na konzolu
   # spb.close()
   # exit()
