###############################################################################
import sys
from defines import *

import struct
import time
from six import byte2int

# Tkinter importy
from Tkinter import *
import ttk
from tkFileDialog import askopenfilename, asksaveasfile
from threading import Timer,Thread,Event

# importy pre serial komunikaciu
import serial
import glob

#importy pre grafy
import matplotlib
import matplotlib.pyplot as plt
from distutils.tests.test_register import RawInputs
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg

from matplotlib.figure import Figure
from Tkinter import *

from matplotlib import dates
import datetime

            
def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result

class IotGui:
    
    def __init__(self,master):
        self.master = master
        self.path = StringVar()
        self.path.set('Ziadna cesta')
        self.dataSource = 'Ziadne data'
        
        self.voltage = DoubleVar()
        self.LTC3335stavVar = BooleanVar()
        self.voltageLabel = StringVar()
        self.meranieSpustene = BooleanVar()
        
        self.priemerTeplota = 0.0
        self.prudJednotka = 1.0
        self.prudJednotkyGrafOld = self.prudJednotka
        self.accJednotka = 1.0
        self.accJednotkyGrafOld = self.accJednotka
        
        self.priemerneQjednotka = 1.0
        self.celkoveQjednotka = 1.0
        self.celkoveWhjednotka = 1.0
        
        self.comm_value = StringVar()
        self.casovaOs = [0]
        
        self.createWidgets()
        
        self.createFigure()
        self.noveOkno.destroy()
        
    def createWidgets(self):
        self.frame = Frame(self.master,width=505,height=545)
        self.frame.grid()
                
        #######################################################
        # Volba programu meranie/spracovanie
        #######################################################
        self.nastavenieProgramu = LabelFrame(self.master, text="Volba cinnosti programu", width=495, height=50)
        self.nastavenieProgramu.place(x=5,y=5)
        
        self.MeranieVar = BooleanVar()
        
        spracovanieRadio = Radiobutton(self.nastavenieProgramu,  text="Spracovanie", anchor=W, variable=self.MeranieVar, value=False, command=self.zmenaPopisov, font=("Arial", 18))
        spracovanieRadio.place(x=20, y=0, width=180, heigh=30)
        
        meranieRadio = Radiobutton(self.nastavenieProgramu, text="Meranie", anchor=W, variable=self.MeranieVar, value=True, command=self.zmenaPopisov, font=("Arial", 18))
        meranieRadio.place(x=280, y=0, width=160, heigh=30)
        
        #spracovanie Label
        self.spracovanieLabel = LabelFrame(self.master, text="Spracovanie", width=320, height=395)
        self.spracovanieLabel.place(x=5,y=145)
        
        self.bOpen = Button(self.spracovanieLabel,text='Nacti', command=self.openfile)
        self.bOpen.place(x=3, y=0, width = 60, height = 30)
        
        self.lPath = Label(self.spracovanieLabel, textvariable=self.path, anchor=NW, justify=LEFT, wraplength = 230)
        self.lPath.place(x=70,y=-3)
       
        #######################################################
        #Pole prace s COM portom
        #######################################################
        self.meranieLabel = LabelFrame(self.master, text="Meranie", width=320, height=395)
        self.meranieLabel.place(x=5,y=145)
        
        self.nastavenieCom = LabelFrame(self.meranieLabel, text="COM port:", width=95, height=110)
        self.nastavenieCom.place(x=3,y=0)
        
        self.bUpdateCom = Button(self.nastavenieCom,text='Aktualizuj', command=self.updateComm)
        self.bUpdateCom.place(x=5, y=0, width = 80, height = 25)
        
        self.bConnect = Button(self.nastavenieCom,text='Pripojit', command=self.connectComm)
        self.bConnect.place(x=5, y=30, width = 80, height = 25)
               
        self.cComm = ttk.Combobox(self.nastavenieCom, textvariable=self.comm_value)
        self.cComm['values'] = serial_ports()
        self.cComm['state'] = "readonly"
        self.cComm.place(x=0, y=65, heigh=25, width=80)
       
        #######################################################
        #Pole nastavenia napatia radiobuttonov
        #######################################################
        
        self.nastavenieNapatia = LabelFrame(self.meranieLabel, text="Napatie:", width=75, height=140)
        self.nastavenieNapatia.place(x=10,y=120)
        
        self.radio1 = Radiobutton(self.nastavenieNapatia, text="1.8V", anchor=W, variable=self.voltage, value=1.8, command=self.setVoltage)
        self.radio1.select()
        self.radio1.place(x=0, y=0, width=70, heigh=15)
        
        self.radio2 = Radiobutton(self.nastavenieNapatia, text="2.5V", anchor=W, variable=self.voltage, value=2.5, command=self.setVoltage)
        self.radio2.place(x=0, y=15, width=70, heigh=15)
        
        self.radio8 = Radiobutton(self.nastavenieNapatia, text="2.8V", anchor=W, variable=self.voltage, value=2.8, command=self.setVoltage)
        self.radio8.place(x=0, y=30, width=70, heigh=15)
        
        self.radio3 = Radiobutton(self.nastavenieNapatia, text="3.0V", anchor=W, variable=self.voltage, value=3.0, command=self.setVoltage)
        self.radio3.place(x=0, y=45, width=70, heigh=15)
        
        self.radio4 = Radiobutton(self.nastavenieNapatia, text="3.3V", anchor=W, variable=self.voltage, value=3.3, command=self.setVoltage)
        self.radio4.place(x=0, y=60, width=70, heigh=15)
        
        self.radio5 = Radiobutton(self.nastavenieNapatia, text="3.6V", anchor=W, variable=self.voltage, value=3.6, command=self.setVoltage)
        self.radio5.place(x=0, y=75, width=70, heigh=15)
        
        self.radio6 = Radiobutton(self.nastavenieNapatia, text="4.5V", anchor=W, variable=self.voltage, value=4.5, command=self.setVoltage)
        self.radio6.place(x=0, y=90, width=70, heigh=15)
        
        self.radio7 = Radiobutton(self.nastavenieNapatia, text="5.0V", anchor=W, variable=self.voltage, value=5.0, command=self.setVoltage)
        self.radio7.place(x=0, y=105, width=70, heigh=15)
        
        #######################################################
        # Konzola pre vypis nastavenia
        #######################################################
        self.konzolaTextLabel = LabelFrame(self.master, text="Konzola:", width=170, height=395)
        self.konzolaTextLabel.place(x=330,y=145)

        self.txt = Text(self.konzolaTextLabel, borderwidth=3, relief="sunken")
        self.txt.config(font=("consolas", 8), undo=True, wrap='word')
        self.txt.place(x=2, y=0, width=145, height=374)
        
        scrollb = Scrollbar(self.konzolaTextLabel, command=self.txt.yview)
        scrollb.place(x=160, y=0, width=5, height=374, anchor=NW)
        self.txt['yscrollcommand'] = scrollb.set
        
        #######################################################
        # Pole pre poznamky
        #######################################################
        self.poznamkyTextLabel = LabelFrame(self.master, text="Poznamky:", width=495, height=80)
        self.poznamkyTextLabel.place(x=5,y=60)
        
        self.textPoznamky = StringVar()        
        self.poznamkyText = Text(self.poznamkyTextLabel , borderwidth=3, relief="sunken")
        self.poznamkyText.config(font=("consolas", 8), undo=True, wrap='word')
        self.poznamkyText['state'] = DISABLED
        self.poznamkyText.place(x=5, y=5, width=400, height=50)
              
              
        poznamkyScrollb = Scrollbar(self.poznamkyTextLabel, command=self.poznamkyText.yview)
        poznamkyScrollb.place(x=415, y=5, width=8, height=50, anchor=NW)
        self.poznamkyText['yscrollcommand'] = poznamkyScrollb.set
        
        self.editujVar = BooleanVar()
        self.editujVar.set(True)
        self.bEditujPoznamky = Button(self.poznamkyTextLabel,text='Editovat',command=self.editujPoznamky)
        self.bEditujPoznamky.place(x=430,y=0, width = 50, height = 30)
        
        self.bUlozPoznamky = Button(self.poznamkyTextLabel,text='Ulozit',command=self.ulozPridajPoznamky)
        self.bUlozPoznamky['state'] = DISABLED
        self.bUlozPoznamky.place(x=430,y=30, width = 50, height = 30)

        ############################################
        # Hlavicka data
        ############################################
        self.hlavickaData = LabelFrame(self.spracovanieLabel, text="Hlavicka dat:", width=80, height=80)
        self.hlavickaData.place(x=3,y=40)
        
        self.hlavickaVoutVar = StringVar()
        hlavickaVoutLabel = Label(self.hlavickaData, textvariable=self.hlavickaVoutVar)
        hlavickaVoutLabel.place(x=0,y=0)
        
        self.hlavickaMVar = StringVar()
        hlavickaMVarLabel = Label(self.hlavickaData, textvariable=self.hlavickaMVar)
        hlavickaMVarLabel.place(x=0,y=18)
        
        self.hlavickaTvzVar = StringVar()
        hlavickaTvzLabel = Label(self.hlavickaData, textvariable=self.hlavickaTvzVar)
        hlavickaTvzLabel.place(x=0,y=36)

        #######################################################
        # Pole pre vypocitane hodnoty
        #######################################################
        self.vypocitaneHodnotyLabel = LabelFrame(self.spracovanieLabel, text="Vypocitane hodnoty", width=310, height=250)
        self.vypocitaneHodnotyLabel.place(x=3,y=123)
        
        #vseobecne hodnoty
        self.vseobecneHodnotyLabel = LabelFrame(self.vypocitaneHodnotyLabel, text="Vseobecne hodnoty", width=300, height=60)
        self.vseobecneHodnotyLabel.place(x=5,y=0)
                
        self.celkovyCasVar = StringVar()
        celkovyCasL = Label(self.vseobecneHodnotyLabel, textvariable=self.celkovyCasVar, anchor=NW, justify=LEFT)
        celkovyCasL.place(x=0,y=0)
        
        self.priemernaTeplotaVar = StringVar()
        priemernaTeplotaL = Label(self.vseobecneHodnotyLabel, textvariable=self.priemernaTeplotaVar, anchor=NW, justify=LEFT)
        priemernaTeplotaL.place(x=150,y=0)
        
        self.priemerneVinVar = StringVar()
        priemerneVinL = Label(self.vseobecneHodnotyLabel, textvariable=self.priemerneVinVar, anchor=NW, justify=LEFT)
        priemerneVinL.place(x=0,y=18)
        
        self.ucinnostPredpokladVar = StringVar()
        ucinnostPredpokladL = Label(self.vseobecneHodnotyLabel, textvariable=self.ucinnostPredpokladVar, anchor=NW, justify=LEFT)
        ucinnostPredpokladL.place(x=150,y=18)

        #vstupne hodnoty
        self.vstupneHodnotyLabel = LabelFrame(self.vypocitaneHodnotyLabel, text="Vstupne hodnoty", width=300, height=60)
        self.vstupneHodnotyLabel.place(x=5,y=60)
        
        self.celkoveQVar = StringVar()
        celkoveQL = Label(self.vstupneHodnotyLabel, textvariable=self.celkoveQVar, anchor=NW, justify=LEFT)
        celkoveQL.place(x=0,y=0)
        
        self.priemerneQVar = StringVar()
        priemerneQVarL = Label(self.vstupneHodnotyLabel, textvariable=self.priemerneQVar, anchor=NW, justify=LEFT)
        priemerneQVarL.place(x=150,y=0)
        
        self.celkoveWhVar = StringVar()
        celkoveWhL = Label(self.vstupneHodnotyLabel, textvariable=self.celkoveWhVar, anchor=NW, justify=LEFT)
        celkoveWhL.place(x=0,y=18)
        
        self.priemernyPrudVar = StringVar()
        priemernyPrudL = Label(self.vstupneHodnotyLabel, textvariable=self.priemernyPrudVar, anchor=NW, justify=LEFT)
        priemernyPrudL.place(x=150,y=18)
        
        #vystupne hodnoty
        self.vystupneHodnotyLabel = LabelFrame(self.vypocitaneHodnotyLabel, text="Vystupne hodnoty", width=300, height=60)
        self.vystupneHodnotyLabel.place(x=5,y=120)
        
        self.celkoveQOutVar = StringVar()
        celkoveQOutL = Label(self.vystupneHodnotyLabel, textvariable=self.celkoveQOutVar, anchor=NW, justify=LEFT)
        celkoveQOutL.place(x=0,y=0)
        
        self.priemerneQOutVar = StringVar()
        priemerneQOutVarL = Label(self.vystupneHodnotyLabel, textvariable=self.priemerneQOutVar, anchor=NW, justify=LEFT)
        priemerneQOutVarL.place(x=150,y=0)
        
        self.celkoveWhOutVar = StringVar()
        celkoveWhOutL = Label(self.vystupneHodnotyLabel, textvariable=self.celkoveWhOutVar, anchor=NW, justify=LEFT)
        celkoveWhOutL.place(x=0,y=18)
               
        self.priemernyPrudOutVar = StringVar()
        priemernyPrudOutL = Label(self.vystupneHodnotyLabel, textvariable=self.priemernyPrudOutVar, anchor=NW, justify=LEFT)
        priemernyPrudOutL.place(x=150,y=18)
        
        #############################################
        # Nastavenie jednotiek
        #############################################3
        self.nastavenieJednotiekLabel = LabelFrame(self.vypocitaneHodnotyLabel, text="Nastavenie jednotiek", width=300, height=40)
        self.nastavenieJednotiekLabel.place(x=5,y=185)

        # pre celkoveQjednotka
        self.celkoveJednotkyQVar = StringVar()
        self.celkoveQCombo = ttk.Combobox(self.nastavenieJednotiekLabel, textvariable=self.celkoveJednotkyQVar)
        self.celkoveQCombo['values'] = jednotkyList
        self.celkoveQCombo.insert(0, ' ')
        self.celkoveQCombo['state'] = "readonly"
        celkoveQL = Label(self.nastavenieJednotiekLabel, text="Qcelk:", anchor=NW, justify=LEFT)
        celkoveQL.place(x=5, y=0, heigh=20, width=40)
        self.celkoveQCombo.place(x=50, y=0, heigh=20, width=35)
        
        #priemerne jednotky
        self.jednotkyQVar = StringVar()
        self.jednotkyQCombo = ttk.Combobox(self.nastavenieJednotiekLabel, textvariable=self.jednotkyQVar)
        self.jednotkyQCombo['values'] = jednotkyList
        self.jednotkyQCombo.insert(0, ' ')
        self.jednotkyQCombo['state'] = "readonly"
        jednotkyL = Label(self.nastavenieJednotiekLabel, text="I,Qpr: ", anchor=NW, justify=LEFT)
        jednotkyL.place(x=100, y=0, heigh=20, width=35)
        self.jednotkyQCombo.place(x=140, y=0, heigh=20, width=35)
        
        # pre celkoveWhjednotka 
        self.celkoveJednotkyWhVar = StringVar()
        self.celkoveWhCombo = ttk.Combobox(self.nastavenieJednotiekLabel, textvariable=self.celkoveJednotkyWhVar)
        self.celkoveWhCombo['values'] = jednotkyList
        self.celkoveWhCombo.insert(0, ' ')
        self.celkoveWhCombo['state'] = "readonly"
        jednotkyL = Label(self.nastavenieJednotiekLabel, text="Wh:", anchor=NW, justify=LEFT)
        jednotkyL.place(x=195, y=0, heigh=20, width=30)
        self.celkoveWhCombo.place(x=225, y=0, heigh=20, width=35)
        
        self.jednotkyQButton = Button(self.nastavenieJednotiekLabel,text='OK',command=self.setQjednotky, height=1)
        self.jednotkyQButton.place(x=265, y = -6)
        
        self.ulozHodnotyButton = Button(self.spracovanieLabel,text='Uloz',command=self.file_save)
        self.ulozHodnotyButton.place(x=240, y = 49, height = 70, width = 70)
        
        ############################################
        # Dalsie nastavovacky
        ############################################
        self.testovanieData = LabelFrame(self.spracovanieLabel, text="Nastavenie testu:", width=150, height=80)
        self.testovanieData.place(x=86,y=40)
        
        self.hlavickaPWMdutyVar = StringVar()
        hlavickaPWMdutyLabel = Label(self.testovanieData, textvariable=self.hlavickaPWMdutyVar)
        hlavickaPWMdutyLabel.place(x=0,y=0)
        
        self.hlavickaPWMfreqVar = StringVar()
        hlavickaPWMfreqLabel = Label(self.testovanieData, textvariable=self.hlavickaPWMfreqVar)
        hlavickaPWMfreqLabel.place(x=0,y=18)
        
        self.hlavickaRloadVar = StringVar()
        hlavickaRloadLabel = Label(self.testovanieData, textvariable=self.hlavickaRloadVar)
        hlavickaRloadLabel.place(x=0,y=36)
        
        #PWM
        self.dalsieNastavenia = LabelFrame(self.meranieLabel, text="Dalsie nastavenia", width=180, height=170)
        self.dalsieNastavenia.place(x=105,y=0)

        pwmLable = Label(self.dalsieNastavenia, text='PWM duty [%]: ')
        pwmLable.place(x=0,y=0)
        
        self.pwmDutyVar = StringVar()
        self.pwmDutyVar.set('0')
        self.pwmDutyE = Entry(self.dalsieNastavenia, textvariable=self.pwmDutyVar, width=5, font=("Calibri",12))
        self.pwmDutyE.place(x=90, y=0)
        
        self.pwmDutySetButton = Button(self.dalsieNastavenia,text='OK',command=self.setPWM, height=3)
        self.pwmDutySetButton.place(x=140)   
        
        pwmFrekvLable = Label(self.dalsieNastavenia, text='PWM frek [Hz]: ')
        pwmFrekvLable.place(x=0,y=35)
        
        self.pwmFrekvVar = StringVar()
        self.pwmFrekvVar.set('100')
        self.pwmFrekvE = Entry(self.dalsieNastavenia, textvariable=self.pwmFrekvVar, width=5, font=("Calibri",12))
        self.pwmFrekvE.place(x=90, y=35) 
        
        # R load
        self.rLoadCheckButtonVar = BooleanVar();
        self.rLoadCheckButtonVar.set(False)
        self.rLoadc = Checkbutton(self.dalsieNastavenia, text='', command=self.rLoadOnOff, onvalue=1, offvalue=0, variable=self.rLoadCheckButtonVar, anchor=NW, justify=LEFT)
        self.rLoadc.place(x=105,y=120, width = 20, height = 20)
        rloadLabel = Label(self.dalsieNastavenia, anchor=NW, text='Rload On/Off:')
        rloadLabel.place(x=0,y=122, width = 90, height = 20)
        
        #Preddeicka
        PreddelickaL = Label(self.dalsieNastavenia, text='Preddelicka: ')
        PreddelickaL.place(x=0,y=65)
        
        self.predelickaVar = StringVar()
        self.predelickaCombo = ttk.Combobox(self.dalsieNastavenia, textvariable=self.predelickaVar)
        self.predelickaCombo['values'] = preddelickaList
        self.predelickaCombo.insert(0, '15')
        self.predelickaCombo['state'] = "readonly"
        self.predelickaCombo.place(x=90, y=65, heigh=25, width=45)
        
        self.predelickaButton = Button(self.dalsieNastavenia,text='OK',command=self.setPrescaler, height=1)
        self.predelickaButton.place(x=140, y = 65)
        
        # nastavenie periody vzorkovania
        self.ukladanieTvzVar = StringVar()
        self.ukladanieTvzVar.set(TVZ_DEF_VAL)
        self.ukladanieTvzE = Entry(self.dalsieNastavenia, textvariable=self.ukladanieTvzVar, width=5, font=("Calibri",12))
        self.ukladanieTvzE.place(x=90,y=95)
        ukladanieTvzL = Label(self.dalsieNastavenia, text='Perioda Tvz:')
        ukladanieTvzL.place(x=0,y=95)
        
        self.ukladanieTvzB = Button(self.dalsieNastavenia,text='OK',command=self.setTvz, height=1)
        self.ukladanieTvzB.place(x=140, y = 95) 
           
        # ukladanie dat, resp. zapnutie merania
        self.ukladanieDatB = Button(self.meranieLabel,text='SPUSTIT MERANIE',command=self.zapniUkladanieDat, height=1, width = 15, font=("Arial", 18))
        self.ukladanieDatB.place(x=70, y = 300)  
        ###########################################
        
        self.xScaleVar = DoubleVar()
        self.xScale = Scale(self.master, variable=self.xScaleVar, orient=HORIZONTAL, length=600, from_= 0, to=0,command=self.zoomXScale)
        
        self.xsrcollVar = DoubleVar()
        self.xScroll = Scale(self.master, variable=self.xsrcollVar, orient=HORIZONTAL, length=600, from_= 0, to=0,command=self.scrollXScale)

        self.zmenaPopisov()
        
    def grafyMenu(self):
        #######################################################
        #Pole pre nastavenie grafov
        #######################################################
        self.nastavenieGrafu = LabelFrame(self.noveOkno, text="Nastavenia grafov", width=740, height=115)
        self.nastavenieGrafu.place(x=5,y=5)
              
        self.VinCheckButtonVar = BooleanVar()
        self.VinCheckButtonVar.set(False)
        self.Vinc = Checkbutton(self.nastavenieGrafu, text='Uin', command=self.zapVypVinLine, onvalue=1, offvalue=0, variable=self.VinCheckButtonVar, anchor=NW, justify=LEFT, fg='green')
        self.Vinc.place(x=0,y=0, width = 80, height = 20)

        self.VinGridCheckButtonVar = BooleanVar();
        self.VinGridCheckButtonVar.set(False)
        self.VinGridc = Checkbutton(self.nastavenieGrafu, text='Mriezka', command=self.zapVypVinGrid, onvalue=1, offvalue=0, variable=self.VinGridCheckButtonVar, anchor=NW, justify=LEFT, fg='green')
        self.VinGridc.place(x=0,y=20, width = 80, height = 20)      
               
        self.accVypocitaneCheckButtonVar = BooleanVar()
        self.accVypocitaneCheckButtonVar.set(True)
        self.accVypocitanec = Checkbutton(self.nastavenieGrafu, text='Qin', command=self.zapVypAccVypocitaneLine, onvalue=1, offvalue=0, variable=self.accVypocitaneCheckButtonVar, anchor=NW, justify=LEFT, fg='blue')
        self.accVypocitanec.select()
        self.accVypocitanec.place(x=80,y=0,width=80,height=20)

        self.accVypocitaneGridCheckButtonVar = BooleanVar();
        self.accVypocitaneGridCheckButtonVar.set(False)
        self.accVypocitaneGridc = Checkbutton(self.nastavenieGrafu, text='Mriezka', command=self.zapVypAccVypocitaneGrid, onvalue=1, offvalue=0, variable=self.accVypocitaneGridCheckButtonVar, anchor=NW, justify=LEFT, fg='blue')
        self.accVypocitaneGridc.place(x=80,y=20, width = 80, height = 20)
              
        self.prudCheckButtonVar = BooleanVar()
        self.prudCheckButtonVar.set(False)
        self.prudc = Checkbutton(self.nastavenieGrafu, text='Iin', command=self.zapVypPrudLine, onvalue=1, offvalue=0, variable=self.prudCheckButtonVar, anchor=NW, justify=LEFT, fg='black')
        self.prudc.place(x=160,y=0, width = 80, height = 30)

        self.prudGridCheckButtonVar = BooleanVar();
        self.prudGridCheckButtonVar.set(False)
        self.prudGridc = Checkbutton(self.nastavenieGrafu, text='Mriezka', command=self.zapVypPrudGrid, onvalue=1, offvalue=0, variable=self.prudGridCheckButtonVar, anchor=NW, justify=LEFT, fg='black')
        self.prudGridc.place(x=160,y=20, width = 80, height = 20)
         
        self.teplotaCheckButtonVar = BooleanVar();
        self.teplotaCheckButtonVar.set(False)
        self.teplotac = Checkbutton(self.nastavenieGrafu, text='Teplota', command=self.zapVypTeplotaLine, onvalue=1, offvalue=0, variable=self.teplotaCheckButtonVar, anchor=NW, justify=LEFT, fg='red')
        self.teplotac.place(x=240,y=0, width = 80, height = 20)
        
        self.teplotaGridCheckButtonVar = BooleanVar();
        self.teplotaGridCheckButtonVar.set(False)
        self.teplotaGridc = Checkbutton(self.nastavenieGrafu, text='Mriezka', command=self.zapVypTeplotaGrid, onvalue=1, offvalue=0, variable=self.teplotaGridCheckButtonVar, anchor=NW, justify=LEFT, fg='red')
        self.teplotaGridc.place(x=240,y=20, width = 80, height = 20)
          
    def createFigure(self):
        self.fig = Figure(figsize=(11.5,5))
        self.graf1 = self.fig.add_subplot(111)
        self.fig.subplots_adjust(left= 0.14, top=0.95, right=0.86, bottom=0.12)
 
        self.noveOkno = Toplevel(self.master, width=1160,height=635)
        
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.noveOkno)
        self.grafyMenu()
       
        ##################################################
        #pridanie toolbaru k nastaveniu grafov
        ##################################################
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.nastavenieGrafu)
        self.toolbar.place(x=340,y=5, anchor=NW)
        self.toolbar.update() 
        
    def showGraf(self):
        self.graf1 = self.fig.add_subplot(111)     
        
        ##################################################
        # Nastavenie zoomu alebo posun kriviek grafu
        # pridanie toolbaru k nastaveniu grafov
        ##################################################
        self.xScaleVar = DoubleVar()
        self.xScale = Scale(self.nastavenieGrafu, variable=self.xScaleVar, orient=HORIZONTAL, length=710, from_= 1, to=(len(self.casovaOs)-1),command=self.zoomXScale, showvalue=0)
        self.xScale.set(len(self.casovaOs)-1)
        self.xScale.place(x=5,y=50)
        
        self.xsrcollVar = DoubleVar()
        self.xScroll = Scale(self.nastavenieGrafu, variable=self.xsrcollVar, orient=HORIZONTAL, length=710, from_= 0, to=100,command=self.scrollXScale, showvalue=0)
        self.xScroll.set(0)
        self.xScroll.place(x=5,y=70)
        
        
        self.graf1.xaxis.set_major_locator(dates.HourLocator())
        self.graf1.xaxis.set_major_formatter(dates.DateFormatter('%m/%d %H:%M:%S'))
        self.graf1.axes.get_yaxis().set_visible(False)
        self.graf1.xaxis.grid(True)

        self.yOsAccVypocitane = self.graf1.twinx()
        self.yOsAccVypocitane.tick_params(axis='y', colors='b')
        self.yOsAccVypocitane.spines["left"].set_position(("axes", 0))
        self.yOsAccVypocitane.spines["left"].set_edgecolor('b')
        self.yOsAccVypocitane.yaxis.set_label_position('left')
        self.yOsAccVypocitane.yaxis.set_ticks_position('left')
        self.yOsAccVypocitane.yaxis.label.set_color('b')
        
        self.yOsAccVypocitane.set_ylabel("Qin [" + self.celkoveJednotkyQVar.get() + "C]")
        self.yOsAccVypocitane.set_ylim(0.0, max(self.accVypocitane)*1.1)
        self.accVypocitaneLine = self.yOsAccVypocitane.step(self.casovaOspreAcc, self.accVypocitane,'b-', label='Acc Vypocitane')
        
        self.accLine = self.yOsAccVypocitane.step(self.casovaOs, self.acc, 'g-', label='Acc')
        
        self.yOsVin = self.graf1.twinx()
        self.yOsVin.tick_params(axis='y', colors='g')
        self.yOsVin.spines["left"].set_position(("axes", -0.1))
        self.yOsVin.spines["left"].set_edgecolor('g')
        self.yOsVin.set_ylabel("Uin [V]")
        self.yOsVin.yaxis.set_label_position('left')
        self.yOsVin.yaxis.set_ticks_position('left')
        self.yOsVin.yaxis.label.set_color('g')
        self.yOsVin.set_ylim(0.0, max(self.Vin) *1.2)
        self.VinLine = self.yOsVin.plot(self.casovaOs, self.Vin, 'g-', label='Uin')
        self.graf1.set_ylabel('Uin')
        

        self.yOsTeplota = self.graf1.twinx()
        self.yOsTeplota.tick_params(axis='y', colors='r')
        self.yOsTeplota.spines["right"].set_position(("axes", 1.1))
        self.yOsTeplota.spines["right"].set_edgecolor('r')
        self.yOsTeplota.set_ylabel("t ['C]")
        self.yOsTeplota.yaxis.label.set_color('r')
        self.yOsTeplota.set_ylim(min(self.teplota)*0.9, max(self.teplota) *1.1)
        self.teplotaLine = self.yOsTeplota.plot(self.casovaOs, self.teplota, 'r-', label='Teplota')

        self.yOsPrud = self.graf1.twinx()
        self.yOsPrud.tick_params(axis='y', colors='k')
        self.yOsPrud.set_ylabel("Iin [" + self.jednotkyQVar.get() +"A]") 
        self.yOsPrud.spines["right"].set_edgecolor('k')
        self.yOsPrud.set_ylim(0.0, max(self.prud)*1.1)
        self.prudLine = self.yOsPrud.plot(self.casovaOspreAcc, self.prud, 'k-', label='Iin')
    
        self.graf1.set_xlim(self.casovaOs[0], self.casovaOs[-1]);   
        
        for label in self.graf1.xaxis.get_ticklabels():
            label.set_rotation(20)
        
        self.yOsTeplota.set_visible(self.teplotaCheckButtonVar.get())
        self.yOsPrud.set_visible(self.prudCheckButtonVar.get())
        self.yOsVin.set_visible(self.VinCheckButtonVar.get())
        self.yOsAccVypocitane.set_visible(self.accVypocitaneCheckButtonVar.get())
        
        if app.teplotaGridCheckButtonVar.get():
            self.yOsTeplota.grid(b=True, color='r', linestyle=':', linewidth=0.5, axis='both')
        else:
            self.yOsTeplota.grid(b=False)
        if app.prudGridCheckButtonVar.get():
            self.yOsPrud.grid(b=True, color='k', linestyle=':', linewidth=0.5, axis='both')
        else:
            self.yOsPrud.grid(b=False)
        if app.VinGridCheckButtonVar.get():
            self.yOsVin.grid(b=True, color='g', linestyle=':', linewidth=0.5)
        else:
            self.yOsVin.grid(b=False)
        if app.accVypocitaneGridCheckButtonVar.get():
            self.yOsAccVypocitane.grid(b=True, color='b', linestyle=':', linewidth=0.5, axis='both')
        else:
            self.yOsAccVypocitane.grid(b=False)
        
        self.canvas.draw()

    def zmenaPopisov(self):
        if self.MeranieVar.get() == True:
            self.meranieLabel.configure(height=395)
            self.spracovanieLabel.configure(height=-1)
            self.bEditujPoznamky['text'] = 'Pridat'
            self.bUlozPoznamky['text'] = 'OK'
            self.path.set("")
            self.fig.clf()
            self.xScale.destroy()
            self.xScroll.destroy()
            self.canvas.draw()
        else:
            self.spracovanieLabel.configure(height=395)
            self.meranieLabel.configure(height=-1)
            self.bEditujPoznamky['text'] = 'Editovat'
            self.bUlozPoznamky['text'] = 'Ulozit'            
    
    def zapVypTeplotaGrid(self):
        if app.teplotaGridCheckButtonVar.get():
            self.yOsTeplota.grid(b=True, color='r', linestyle=':', linewidth=0.5, axis='both')
        else:
            self.yOsTeplota.grid(b=False)
        self.canvas.draw()
        
    def zapVypPrudGrid(self):
        if app.prudGridCheckButtonVar.get():
            self.yOsPrud.grid(b=True, color='k', linestyle=':', linewidth=0.5, axis='both')
        else:
            self.yOsPrud.grid(b=False)
        self.canvas.draw()
       
    def zapVypVinGrid(self):
        if app.VinGridCheckButtonVar.get():
            self.yOsVin.grid(b=True, color='g', linestyle=':', linewidth=0.5)
        else:
            self.yOsVin.grid(b=False)
        self.canvas.draw()
        
    def zapVypAccVypocitaneGrid(self):
        if app.accVypocitaneGridCheckButtonVar.get():
            self.yOsAccVypocitane.grid(b=True, color='b', linestyle=':', linewidth=0.5, axis='both')
        else:
            self.yOsAccVypocitane.grid(b=False)
        self.canvas.draw()
        
    def zapVypTeplotaLine(self):
        self.yOsTeplota.set_visible(self.teplotaCheckButtonVar.get())
        self.canvas.draw()

    def zapVypPrudLine(self):
        self.yOsPrud.set_visible(self.prudCheckButtonVar.get())
        self.canvas.draw()

    def zapVypVinLine(self):
        self.yOsVin.set_visible(self.VinCheckButtonVar.get())
        self.canvas.draw() 
        
    def zapVypAccVypocitaneLine(self):
        self.yOsAccVypocitane.set_visible(self.accVypocitaneCheckButtonVar.get())
        self.canvas.draw() 
        
    def zoomXScale(self,var):
        velkostOkna = int(var)
        
        if self.xsrcollVar.get() >= velkostOkna:
            self.xScroll.set(velkostOkna)
            
        self.xScroll['to'] =  len(self.casovaOs) - velkostOkna-1
        self.graf1.set_xlim(self.casovaOs[int(self.xsrcollVar.get())], self.casovaOs[int(self.xsrcollVar.get() + velkostOkna)]);
        self.canvas.draw()  

    def scrollXScale(self,var): 
        stopIndex = int(var) + int(self.xScaleVar.get())
        
        if stopIndex >= (len(self.casovaOs)):
            stopIndex = len(self.casovaOs)-1
            
        self.graf1.set_xlim(self.casovaOs[int(var)], self.casovaOs[stopIndex]);
        self.canvas.draw()
        
    def nainicializujData(self):
        self.datum = []
        self.acc = []
        self.accVypocitane = []
        self.irqCount = []
        self.teplota = []
        self.cas = []
        self.krok = []
        self.prud = []
        self.casovaOs = []
        self.Vin = []
        self.spotrebaWh = []
        
        self.textPoznamky.set('') 
        self.poznamkyVlozText(self.textPoznamky.get())
        
        self.celkoveQCombo['state'] = "normal"
        self.celkoveQCombo.delete(0, END)
        self.celkoveQCombo.insert(0, ' ')
        self.celkoveQCombo['state'] = "readonly"
        self.celkoveQjednotka = jedntky_enum[self.celkoveJednotkyQVar.get()]
        self.accJednotkyGrafOld = self.celkoveQjednotka
        
        self.jednotkyQCombo.insert(0, ' ')
        self.jednotkyQCombo['state'] = "normal"
        self.jednotkyQCombo.delete(0, END)
        self.jednotkyQCombo.insert(0, ' ')
        self.jednotkyQCombo['state'] = "readonly"
        self.priemerneQjednotka = jedntky_enum[self.jednotkyQVar.get()]
        self.prudJednotkyGrafOld = self.priemerneQjednotka
        
        self.celkoveWhCombo.insert(0, ' ')
        self.celkoveWhCombo['state'] = "normal"
        self.celkoveWhCombo.delete(0, END)
        self.celkoveWhCombo.insert(0, ' ')
        self.celkoveWhCombo['state'] = "readonly"
        self.celkoveWhjednotka = jedntky_enum[self.celkoveJednotkyWhVar.get()]
        
        self.f = self.createFigure()
        self.canvas.get_tk_widget().place(x=5,y=130) 
        
    def file_save(self):
        f = asksaveasfile(mode='w', defaultextension=".txt")
        if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
            return
        text =  "--Nazov a Cesta spracovaneho suboru:--\r\n"
        text += self.path.get() + "\r\n"
        text += "\r\n---------Hlavicka merania:------------\r\n"
        text += self.hlavickaVoutVar.get() + "\r\n"
        text += self.hlavickaMVar.get() + "\r\n"
        text += self.hlavickaTvzVar.get() + "\r\n"
        text += self.hlavickaPWMdutyVar.get() + "\r\n"
        text += self.hlavickaPWMfreqVar.get() + "\r\n"
        text += self.celkovyCasVar.get() + "\r\n"
        text += self.priemernaTeplotaVar.get() + "\r\n"
        text += self.priemerneVinVar.get() + "\r\n"
        text += self.ucinnostPredpokladVar.get() + "\r\n"

        text += "\r\n------Vstupne vypocitane hodnoty:-----\r\n"
        text += self.priemerneQVar.get() + "\r\n"
        text += self.celkoveQVar.get() + "\r\n"
        text += self.celkoveWhVar.get() + "\r\n"
        text += self.priemernyPrudVar.get() + "\r\n"
        
        text += "\r\n-----Vystupne vypocitane hodnoty:-----\r\n"
        text += self.priemernyPrudOutVar.get() + "\r\n"
        text += self.priemerneQOutVar.get() + "\r\n"
        text += self.celkoveQOutVar.get() + "\r\n"
        text += self.celkoveWhOutVar.get() + "\r\n"
        
        text += "\r\n------------Poznamky:-----------------\r\n" + self.textPoznamky.get()

        text2save = text
        f.write(text2save)
        f.close()
        
    def openfile(self):
        self.path.set(askopenfilename(parent=self.master))
        try:
            with open(self.path.get()) as self.file:
                temp =  self.file.readlines()
            self.file.close() 
        except:
            self.textPrint("ERROR: Neuspesne nacitany subor")
            return
        
        self.nainicializujData()
        
        try:
            self.hlavickaIndexStart = temp.index('#*#\n') + 1
            self.hlavickaIndexStop = temp.index('##**##\n')
            self.poznamkyIndexStop = temp.index('###***###\n')
                        
            self.dataHlavicka = temp[self.hlavickaIndexStart].split()
            self.hlavickaVoutVar.set('Uout = ' + str(self.dataHlavicka[1]) + ' V')
            self.voltage.set(self.dataHlavicka[1])
            
            self.dataHlavicka = temp[self.hlavickaIndexStart+1].split()
            self.hlavickaMVar.set('M = ' + str(self.dataHlavicka[1]))
            M = float(self.dataHlavicka[1])
            qLsbM = float(IP_250_QLSB * 3600 /(2**M))
            
            self.dataHlavicka = temp[self.hlavickaIndexStart+2].split()
            self.hlavickaTvzVar.set('Tvz = ' + str(self.dataHlavicka[1]) + ' sec')
            perioda = str(self.dataHlavicka[1])
            
            self.dataHlavicka = temp[self.hlavickaIndexStart+3].split()
            self.hlavickaPWMdutyVar.set('PWMduty = ' + str(self.dataHlavicka[1]) + ' %')
            
            self.dataHlavicka = temp[self.hlavickaIndexStart+4].split()
            self.hlavickaPWMfreqVar.set('PWMfreq = ' + str(self.dataHlavicka[1]) + ' Hz')
            
            self.dataHlavicka = temp[self.hlavickaIndexStart+5].split()
            if int(self.dataHlavicka[1]):
                rLoadTextTemp = 'On'
            else:
                rLoadTextTemp = 'Off'
            self.hlavickaRloadVar.set('Rload: ' + rLoadTextTemp)

            for i in range(self.hlavickaIndexStop+1, self.poznamkyIndexStop):
                self.textPoznamky.set(self.textPoznamky.get() + temp[i])
            
            self.poznamkyVlozText(self.textPoznamky.get())
            
            accActual = 0
            accVysl = 0
            accOld = 0
            j = 0
            for i in range(self.poznamkyIndexStop+2, len(temp)):
                self.data = temp[i].split()
                self.datum.append(self.data[0] +' '+ self.data[1])
                accActual = int(self.data[2])
                if accActual != accOld:
                    if accOld > accActual:
                        j += 1
                    accVysl = accActual + j*256
                    accOld = accActual
                self.acc.append(float( accVysl * qLsbM) - (prud_naprazdno_enum[self.voltage.get()] * float(perioda)) ) # v culomboch teda A*s
                self.irqCount.append(int(self.data[3]))
                self.teplota.append(float(self.data[4]))
                self.Vin.append(float(int(self.data[5]) * UIN_KOMPENZACNE / 1000.0))
    
            for i in range(0, len(self.acc)):
                self.cas.append(datetime.datetime.strptime(self.datum[i], "%Y-%m-%d %H:%M:%S"))
            
            self.casovaOs = dates.date2num(self.cas)
            self.casovaOspreAcc = self.casovaOs[0:-1]
            
        except:
            self.textPrint("ERROR: Nepodporovany alebo poskodeny subor")
            pass
                    
        self.prud = []
        self.krok = []
        
        tfs = 0.00001174
        Ipeak = DEF_IPEAK
        self.priemerTeplota = 0.0
        self.priemerVin = 0.0

        for i in range(0,len(self.acc)-1):
            self.krok.append((self.cas[i+1] - self.cas[i]).total_seconds())                    
            self.accVypocitane.append( float(self.irqCount[i] * tfs * Ipeak / 2) ) 
            self.prud.append( float(self.irqCount[i] * tfs * Ipeak / 2) / float(perioda))
            self.spotrebaWh.append( float(self.accVypocitane[i] * self.Vin[i]) / 3600.0 )
            self.priemerTeplota = self.priemerTeplota + self.teplota[i] 
            self.priemerVin = self.priemerVin + self.Vin[i]
            if i > 0:
                if self.acc[i-1] < self.acc[i]:
                    self.accVypocitane[i] = self.acc[i]
                else:
                    self.accVypocitane[i] = self.accVypocitane[i-1] + self.accVypocitane[i]
                self.spotrebaWh[i] = self.spotrebaWh[i-1] + self.spotrebaWh[i]

        self.setQjednotky()
        
        self.showGraf()
        self.textPrint("Uspesne nacitany subor")
            
    def dopocitajHodnoty(self):        
        # vypocitane hodnoty vseobecne
        Tcelkovo = (self.cas[-1] - self.cas[1]).total_seconds()
        self.celkovyCasVar.set("Tcelkom = " + str( round(Tcelkovo / 3600.0, 3) ) + " Hod")
        self.priemernaTeplotaVar.set("Teplota = " + str( round( (self.priemerTeplota / (len(self.acc)-1)), 2) ) + " 'C" )
        self.priemerneVinVar.set("UinPriem = " + str( round( (self.priemerVin / (len(self.acc)-1)), 2) ) + " V") 
        self.ucinnostPredpokladVar.set("Odhad Efekivity = " + str( round(ucinnost_enum[self.voltage.get()] * 100.0, 2)) + "%" )
        
        # vypocitane hodnoty vstupne
        self.priemerneQVar.set("Qpriem = " + str( round(self.accVypocitane[-1] * (self.priemerneQjednotka / self.celkoveQjednotka) / Tcelkovo ,3) ) + " " + self.jednotkyQVar.get() + "C")
        self.celkoveQVar.set("Qcelkom = " + str( round( self.accVypocitane[-1], 3) ) + " " + self.celkoveJednotkyQVar.get() + "C")
        self.celkoveWhVar.set("Whcelkom = " + str( round( self.spotrebaWh[-1] * self.celkoveWhjednotka, 3) ) + " " + self.celkoveJednotkyWhVar.get() + "Wh")
        self.priemernyPrudVar.set("IinPriem =  " + str( round(self.accVypocitane[-1] * (self.priemerneQjednotka / self.celkoveQjednotka) / Tcelkovo ,3) ) + " " + self.jednotkyQVar.get() + "A")
        
        # vypocitane hodnoty vystupne
        IoutPriemer = self.spotrebaWh[-1] * 3600.0 * ucinnost_enum[self.voltage.get()] / (Tcelkovo * self.voltage.get())
        self.priemernyPrudOutVar.set("IoutPriem = " + str(round(IoutPriemer * self.priemerneQjednotka,3)) + " " + self.jednotkyQVar.get() + "A")
        self.priemerneQOutVar.set("Qpriem = " + str(round(IoutPriemer * self.priemerneQjednotka,3)) + " " + self.jednotkyQVar.get() + "C")
        self.celkoveQOutVar.set("Qcelkom = " + str( round( IoutPriemer * Tcelkovo * self.celkoveQjednotka, 3) ) + " " + self.celkoveJednotkyQVar.get() + "C")
        self.celkoveWhOutVar.set("Whcelkom = " + str( round( self.spotrebaWh[-1] * ucinnost_enum[self.voltage.get()] * self.celkoveWhjednotka, 3) ) + " " + self.celkoveJednotkyWhVar.get() +  "Wh")
       
    
    def setQjednotky(self):
        self.priemerneQjednotka = jedntky_enum[self.jednotkyQVar.get()]
        self.celkoveQjednotka = jedntky_enum[self.celkoveJednotkyQVar.get()]
        self.celkoveWhjednotka = jedntky_enum[self.celkoveJednotkyWhVar.get()]
        
        if self.priemerneQjednotka!= self.prudJednotkyGrafOld:
            for i in range(0, len(self.prud)):
                self.prud[i] *= float(self.priemerneQjednotka/self.prudJednotkyGrafOld)
            self.prudJednotkyGrafOld =  self.priemerneQjednotka
            self.fig.clf()
            try:
                self.showGraf()
            except:
                pass
        if self.celkoveQjednotka != self.accJednotkyGrafOld:
            for i in range(0, len(self.accVypocitane)):
                self.acc[i] *= float(self.celkoveQjednotka/self.accJednotkyGrafOld)
                self.accVypocitane[i] *= float(self.celkoveQjednotka/self.accJednotkyGrafOld)
            self.accJednotkyGrafOld =  self.celkoveQjednotka
            self.fig.clf()
            try:
                self.showGraf()
            except:
                pass
        
        self.dopocitajHodnoty()
        

    def setPrescaler(self):
        if self.meranieSpustene.get():
            data2comm = []
            data2comm.append(CMD_ltc3335SetPrescaler)
            data2comm.append(int(self.predelickaVar.get()))
            data2comm.append(0x00)
            data2comm.append(0x00)
            data2comm.append(0x00)
            
            if self.commTransfer(data2comm):
                self.textPrint("Uspesne nastavena preddelicka " + str(self.predelickaVar.get()))
            else:
                self.textPrint("ERROR: Nepodarilo sa")
    
    
    def setTvz(self):
        try:
            Tvz = int(float(self.ukladanieTvzVar.get()))
        except:
            self.ukladanieTvzE.delete(0, -1)
            self.ukladanieTvzVar.set(str(TVZ_DEF_VAL))
            Tvz  = int(float(self.ukladanieTvzVar.get()))
                    
        if Tvz > TVZ_MAX_VAL:
            Tvz = TVZ_MAX_VAL
        if Tvz < TVZ_MIN_VAL:
            Tvz = TVZ_MIN_VAL
        
        self.ukladanieTvzE.delete(0, -1)
        self.ukladanieTvzVar.set(str(int(Tvz))) 
        
        if self.meranieSpustene.get():
            data2comm = []
            data2comm.append(CMD_saveDataEnable)
            data2comm.append(Tvz)
            data2comm.append(0x00)
            data2comm.append(0x00)
            data2comm.append(0x00)
            
            if self.commTransfer(data2comm):
                self.textPrint("Tvz = " + str(self.ukladanieTvzVar.get()))
            else:
                self.textPrint("ERROR: Nepodarilo sa nastavit Tvz")    

    def setVoltage(self):
        selection = "Napatie: " + str(self.voltage.get())
        self.voltageLabel.set(selection)
        
        if self.meranieSpustene.get():
            data2comm = []
            data2comm.append(CMD_ltc3335SetOutVoltage)
            data2comm.append(napatie_enum[self.voltage.get()])
            data2comm.append(0x00)
            data2comm.append(0x00)
            data2comm.append(0x00)
            
            if self.commTransfer(data2comm):
                self.textPrint("Uspesne nastavene napatie " + str(self.voltage.get()))
                return 1
            else:
                self.textPrint("ERROR: Nepodarilo sa nastavit napatie")
                return 0
            
    def rLoadOnOff(self):
        if self.meranieSpustene.get():
            data2comm = []
            data2comm.append(CMD_rLoadOnOff)
            data2comm.append(self.rLoadCheckButtonVar.get())
            data2comm.append(0x00)
            data2comm.append(0x00)
            data2comm.append(0x00)
            
            if self.rLoadCheckButtonVar.get():
                stav = "zapnuty"
            else:
                stav = "vypnuty"
            
            if self.commTransfer(data2comm):
                self.textPrint("GPIO Rload je " + stav)
                return 1
            else:
                self.textPrint("ERROR: Nepodarilo sa nastavit GPIO Rload")
                return 0

    def zapniLTC3335(self, zapnute):
        self.LTC3335stavVar.set(zapnute)
        data2comm = []
        data2comm.append(CMD_ltc3335TurnOn)
        data2comm.append(self.LTC3335stavVar.get())
        data2comm.append(0x00)
        data2comm.append(0x00)
        data2comm.append(0x00)
        
        if self.commTransfer(data2comm):
            if self.LTC3335stavVar.get():
                self.textPrint("Menic zapnuty")
            else:
                self.textPrint("Meranie zastavene")
            return 1
        else:            
            return 0
            
    def clearAccumCharge(self):
        data2comm = []
        data2comm.append(CMD_ltc3335SetAccumCharge)
        data2comm.append(0x00)
        data2comm.append(0x00)
        data2comm.append(0x00)
        data2comm.append(0x00)
        
        if self.commTransfer(data2comm):
            self.textPrint("Culombmeter vynulovany")
            return 1
        else:
            self.textPrint("ERROR: Nepodarilo sa vynulovat culombmeter")
            return 0
    
    def setPWM(self):
        try:
            PWMval = int(float(self.pwmDutyVar.get()))
        except:
            self.pwmDutyE.delete(0, -1)
            self.pwmDutyVar.set('0')
            PWMval = int(float(self.pwmDutyVar.get()))
            
        try:
            PWMfrek = int(float(self.pwmFrekvVar.get()))
        except:
            self.pwmFrekvE.delete(0, -1)
            self.pwmFrekvVar.set('10')
            PWMfrek = int(float(self.pwmFrekvVar.get()))
        
        if PWMval > 100:
            PWMval = 100
        if PWMval < 0:
            PWMval = 0
        
        self.pwmDutyE.delete(0, -1)
        self.pwmDutyVar.set(str(int(PWMval)))
        
        if PWMfrek > PWM_FREK_MAX:
            PWMfrek = PWM_FREK_MAX
        if PWMfrek < PWM_FREK_MIN:
            PWMfrek = PWM_FREK_MIN
        
        self.pwmFrekvE.delete(0, -1)
        self.pwmFrekvVar.set(str(int(PWMfrek)))
        
        PWMfrekByte =  bytearray(struct.pack("i", PWMfrek))  
       
        if self.meranieSpustene.get():
            data2comm = []
            data2comm.append(CMD_pwmStart)
            data2comm.append(PWMval)
            data2comm.append(PWMfrekByte[2])
            data2comm.append(PWMfrekByte[1])
            data2comm.append(PWMfrekByte[0])
                   
            if self.commTransfer(data2comm):
                self.textPrint("Nastavena PWM= " + str(self.pwmDutyVar.get()) + " %\nPWMf= " + str(self.pwmFrekvVar.get()) + " Hz")
                return 1
            else:
                self.textPrint("Nepodarilo sa nastavit PWM")
                return 0
            
    def commTransfer(self, sendData):      
        tempData = []
        if not commPort.is_open:
            self.textPrint('ERROR: COM nie je pripojeny!')
            return 0      
        try:
            commPort.write(sendData)
            commPort.flush()
            
            c = byte2int(commPort.read())
            if c == UART_ACK:
                return 1
            else:
                if c != sendData[UART_INDEX_ID]:
                    return 0   
   
            for i in range(0, UART_FRAME_LENGTH - UART_ACK_LENGTH):
                c = byte2int(commPort.read())
                tempData.append(c)
                
            c = byte2int(commPort.read())
            if c == UART_ACK:
                return tempData
            else:
                return 0 
        except:
            self.textPrint('ERROR: COM pripojenie')
            return 0      
        
    def updateComm(self):
        self.cComm['state'] = "normal"
        self.cComm.delete(0, 5)
        self.cComm['state'] = "readonly"
        self.cComm['values'] = serial_ports()
        self.textPrint("Port list aktualizovany")
        
    def connectComm(self):
        self.bConnect['command'] = self.disconnetComm
        self.bConnect['text'] = "Odpojit"
        commPort.port = self.comm_value.get()
        try:
            commPort.open()
            self.textPrint("pripojeny: " + self.comm_value.get())
            self.bUpdateCom['state'] = DISABLED
        except:
            self.bConnect['command'] = self.connectComm
            self.bConnect['text'] = "Pripojit"
            self.bUpdateCom['state'] = NORMAL
            self.textPrint("Nepodarilo sa pripojit")
        
    def disconnetComm(self):
        self.bConnect['command'] = self.connectComm
        self.bConnect['text'] = "Pripojit"
        self.bUpdateCom['state'] = NORMAL
        try:
            commPort.close()
            self.textPrint("uspesne odpojeny Com Port")
        except:
            self.textPrint("neuspesne odpojeny Com Port")
        
    def textPrint(self, text):
        self.txt['state'] = "normal"
        self.txt.insert(END, text + "\n\r")
        self.txt.see(END)
        self.txt['state'] = "disabled"
        
    def poznamkyVlozText(self, val):
        self.poznamkyText['state'] = "normal"
        self.poznamkyText.delete(1.0,END)
        self.poznamkyText.insert(END, val)
        self.poznamkyText.see(END)
        self.poznamkyText['state'] = "disabled"
    
    def editujPoznamky(self):
        if self.editujVar.get():
            self.bUlozPoznamky['state'] = NORMAL
            self.bEditujPoznamky['text'] = 'Zrusit'
            self.poznamkyText['state'] = NORMAL
        else:
            if self.MeranieVar.get() == False:
                self.bUlozPoznamky['state'] = DISABLED
                self.bEditujPoznamky['text'] = 'Editovat'
                self.poznamkyText['state'] = DISABLED
                self.poznamkyVlozText(self.textPoznamky.get())
            else:
                self.bUlozPoznamky['state'] = DISABLED
                self.bEditujPoznamky['text'] = 'Pridat'
                self.poznamkyText['state'] = DISABLED
                self.poznamkyVlozText("")
        self.editujVar.set(not self.editujVar.get())
        
    def ulozPridajPoznamky(self):
        if self.MeranieVar.get() == False:
            self.ulozPoznamky()
        else:
            self.skontrolujPoznamky()
            
    def skontrolujPoznamky(self):
        novaPoznamka = self.poznamkyText.get("1.0",'end-1c')
        self.textPoznamky.set(novaPoznamka + '\n')
        
        if len(novaPoznamka) > NOTE_VELKOST:
            self.textPrint("Poznamka preteka o " + str(len(novaPoznamka) - NOTE_VELKOST) + " znakov")
        else:
            self.bEditujPoznamky['text'] = 'Pridat'
            self.bEditujPoznamky['state'] = NORMAL
            self.bUlozPoznamky['state'] = DISABLED
            self.textPrint("Poznamka pripravena")

    def ulozPoznamky(self):
        self.bEditujPoznamky['text'] = 'Editovat'
        self.bEditujPoznamky['state'] = NORMAL
        self.bUlozPoznamky['state'] = DISABLED
        
        novaPoznamka = self.poznamkyText.get("1.0",'end-1c')
        self.textPoznamky.set(novaPoznamka + '\n')
        
        try:
            with open(self.path.get()) as self.file:
                temp =  self.file.readlines()
            self.file.close()
        except:
            self.textPrint("Nie je zvoleny subor")
            self.poznamkyText['state'] = DISABLED
            self.editujVar.set(True)
            return 
        
        with open(self.path.get(), 'w+') as subor:
            subor.writelines("")

            self.hlavickaIndexStopTemp = temp.index('##**##\n')
            self.poznamkyIndexStopTemp = temp.index('###***###\n')
            
            for i in range(0, self.hlavickaIndexStopTemp+1):
                subor.write(temp[i])
        
            subor.write(self.textPoznamky.get())
            
            for i in range(self.poznamkyIndexStopTemp, len(temp)):
                subor.write(temp[i])
            subor.close() 

        self.poznamkyText['state'] = DISABLED
        self.editujVar.set(True)
    
    def zapniUkladanieDat(self):
        if not self.meranieSpustene.get():
            self.meranieSpustene.set(True)
            self.textPrint("\n--------------------\nSpustam meranie")
            if self.setVoltage() == 0:
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
            if self.setPrescaler() == 0:
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
            if self.setPWM() == 0:
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
            if self.rLoadOnOff() == 0:
                self.meranieSpustene.set(False)
                return
            if self.clearAccumCharge() == 0:
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
          
            if self.setTvz() == 0:
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
            
            if self.odosliPoznaky():
                self.textPrint("Poznamky ulozene")
            else:
                self.textPrint("ERROR: Poznamky neulozene")
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
            
            if self.zapniLTC3335(True) == 0:
                self.textPrint("MERANIE NEBOLO SPUSTENE\n--------------------\n")
                self.meranieSpustene.set(False)
                return
            
            self.textPrint("--------------------\n")
            self.ukladanieDatB.config(text= "Zastavit meranie")
            self.meranieSpustene.set(True)
        else:
            if self.zapniLTC3335(False) == 0:
                self.textPrint("MERANIE NEBOLO ZASTAVENE\n--------------------\n")
                return
            self.ukladanieDatB.config(text= "SPUSTIT MERANIE")
            self.meranieSpustene.set(False)
        self.zapVypNasavenia()
            
    def zapVypNasavenia(self):
        if self.meranieSpustene.get():
            self.radio1.configure(state=DISABLED)
            self.radio2.configure(state=DISABLED)
            self.radio3.configure(state=DISABLED)
            self.radio4.configure(state=DISABLED)
            self.radio5.configure(state=DISABLED)
            self.radio6.configure(state=DISABLED)
            self.radio7.configure(state=DISABLED)
            self.radio8.configure(state=DISABLED)
            self.bEditujPoznamky.configure(state=DISABLED)
            self.bUlozPoznamky.configure(state=DISABLED)
            self.pwmDutyE.configure(state=DISABLED)
            self.pwmFrekvE.configure(state=DISABLED)
            self.pwmDutySetButton.configure(state=DISABLED)
            self.predelickaCombo.configure(state=DISABLED)
            self.predelickaButton.configure(state=DISABLED)
            self.ukladanieTvzE.configure(state=DISABLED)
            self.ukladanieTvzB.configure(state=DISABLED)
            self.rLoadc.configure(state=DISABLED)
        else:
            self.radio1.configure(state=NORMAL)
            self.radio2.configure(state=NORMAL)
            self.radio3.configure(state=NORMAL)
            self.radio4.configure(state=NORMAL)
            self.radio5.configure(state=NORMAL)
            self.radio6.configure(state=NORMAL)
            self.radio7.configure(state=NORMAL)
            self.radio8.configure(state=NORMAL)
            self.bEditujPoznamky.configure(state=NORMAL)
            self.bUlozPoznamky.configure(state=NORMAL)
            self.pwmDutyE.configure(state=NORMAL)
            self.pwmFrekvE.configure(state=NORMAL)
            self.pwmDutySetButton.configure(state=NORMAL)
            self.predelickaCombo.configure(state=NORMAL)
            self.predelickaButton.configure(state=NORMAL)
            self.ukladanieTvzE.configure(state=NORMAL)
            self.ukladanieTvzB.configure(state=NORMAL)
            self.rLoadc.configure(state=NORMAL)
    
    def odosliPoznaky(self):
        novaPoznamka = self.poznamkyText.get("1.0",'end-1c')
        self.textPoznamky.set(novaPoznamka + '\n')
        
        note = list(str(self.textPoznamky.get()))
        noteLen = len(note)
        MSB = noteLen/256
        LSB = noteLen%256
    
        try:
            commPort.close()
            commPort.open()
        except:
            self.textPrint("ERR: Chyba pri ukladani poznamky")
            return
                
        data2comm = []
        data2comm.append(CMD_saveMeasurementNote)
        data2comm.append(0x00)
        data2comm.append(0x00)
        data2comm.append(MSB)
        data2comm.append(LSB)
       
        self.commTransfer(data2comm)
        
        for i in range(0, noteLen):
            commPort.write(note[i])
        
        for i in range(0,10):
            if commPort.inWaiting():
                c = byte2int(commPort.read())
                if c == UART_ACK:
                    return 1
            else:
                time.sleep(0.5)
        return 0
    
    def fx(self):
        return
top = Tk(className= " Iot Spotreba")

app = IotGui(top)

commPort = serial.Serial(port=None, baudrate=115200, timeout=COMM_PORT_TIMEOUT)  
top.mainloop()
