import serial
import time
import serial.tools.list_ports
import tkinter as tk
from tkinter import filedialog
import os

root = tk.Tk()
root.withdraw()  #block main GUI window

myportdevice=''
ports = serial.tools.list_ports.comports(include_links=False)
iPANOfound=False
for port in ports :
    print('Checking '+port.device)
    ser = serial.Serial(port.device,115200, timeout=1)  # open serial port
    ser.write(b':01INF#')
    s=ser.read(11)
    #print(s)
    if s==b':10INF3600#':
        print('iPANO mount found on '+port.device)
        myportdevice=port.device
        iPANOfound=True
        break
    ser.close()
if iPANOfound==False:
    print('iPANO mount not found')
    quit()

filename_out=''
continue_meas=False
if os.path.isfile('running.txt'):
    answer=input('Last measurement was stopped unexpectedly. Continue? (y/n): ')
    if(answer!='n'):
        continue_meas=True
    
if(continue_meas==False):
    print('Moving to the start position...')    
    ser.write(b':01SPZ0#')     # write a string - return to zero position
    ser.read(8)   #ignore the answer
    time.sleep(0.1) #aby sa montáž stihla rozbehnúť
    ser.write(b':01GAS#') #get current position and state
    s=ser.read(19)
    while s[17]== ord('1'): #kód jednotky na konci pred # - je v pohybe
        ser.write(b':01GAS#') #get current position and state
        s=ser.read(19)
    print(s)        

continue_no=0
if(continue_meas==True):
    file_run=open("running.txt","r")
    file_path=file_run.readline().strip()
    filename_out=file_run.readline().strip()
    continue_no=int(file_run.readline().strip())
    file_run.close()
else:
    print('Select the file containing head positions...')
    file_path = filedialog.askopenfilename()

print('Reading list of head positions from "',file_path,'" file...')
positions=[]
try:
    subor = open(file_path, 'r')
    riadok = subor.readline()
    while riadok != '':
        cislo = riadok.split("\t")
        azimut=float(cislo[0].strip())
        vyska=float(cislo[1].strip())
        positions.append((azimut,vyska))
        #print((azimut,vyska))
        riadok = subor.readline()
    subor.close()
except FileNotFoundError:
    print("Configuration file '",file_path,"' not found...")
    quit()
print(len(positions),' positions read')

if(continue_meas==False):
    print('Choose the name of the output-file...')
    filename_out = filedialog.asksaveasfilename(defaultextension=".txt")
    if filename_out is None: # asksaveasfile return `None` if dialog closed with "cancel".
        filename_out='measurement.txt'
    fileout=open(filename_out,"w")
    fileout.close() #clear the content of the file

index=0;
for (azimut, vyska) in positions:
    if(index<continue_no):
        index+=1
        continue
    try:
        command=':01SSL+%s%s#' % (str((int)(100*azimut)).zfill(5),str((int)(100*vyska)).zfill(5))
        command=command.encode() #prerobit na postupnot 8-bit znakov
        #print(command)
        ser.write(command) #move to the given position
        ser.read(19) #ignorovať odpoveď
        time.sleep(0.1) #aby sa montáž stihla rozbehnúť
        ser.write(b':01GAS#') #get current position and state
        s=ser.read(19)
    except (serial.serialutil.SerialException):
        print('\a')
        print("USB connection to the iPANO mount is lost. Reconnect and press any key...")
        input('')
        ser = serial.Serial(myportdevice,115200, timeout=1)  # open serial port
        ser.write(command) #move to the given position
        ser.read(19) #ignorovať odpoveď
        time.sleep(0.1) #aby sa montáž stihla rozbehnúť
        ser.write(b':01GAS#') #get current position and state
        s=ser.read(19)

    try:
        while s[17]== ord('1'): #kód jednotky - je v pohybe
            ser.write(b':01GAS#') #get current position and state
            s=ser.read(19)
    except (IndexError,serial.serialutil.SerialException):
        print('\a')
        print("Connection to the iPANO mount is lost. Reconnect and press any key...")
        input('')
        ser.close()
        ser = serial.Serial(myportdevice,115200, timeout=1)  # open serial port

    print(vyska, azimut,int(100.0*(index+1)/len(positions)),'%')
    fileout=open(filename_out,"a")
    fileout.write(str(vyska)+'\t'+str(azimut)+'\t'+str(int(100.0*(index+1)/len(positions)))+'%\n')
    fileout.close()
    index+=1
    #Značka kam sme sa dostali
    subor=open('running.txt','w')
    subor.write(file_path+'\n')
    subor.write(filename_out+'\n')
    subor.write(str(index)+'\n')
    subor.close()
    time.sleep(1.0) #meranie 1.0s
    
if os.path.isfile('running.txt'):
    os.remove('running.txt')
    
print('Moving to the initial position...')
try:
    ser.write(b':01SPZ0#')     # write a string - return to zero position
    ser.read(8)   #ignore the answer
except (serial.serialutil.SerialException,IndexError):
    print('\a')
    print("USB connection to the iPANO mount is lost. Reconnect and press any key...")
    input('')
    ser.write(b':01SPZ0#')     # write a string - return to zero position
    ser.read(8)   #ignore the answer

    
ser.close()             # close port
