#!/usr/bin/env python

"""Python SQM Utility"""

import wx
import time
import serial
import math
import os

import  FindFTDI 

timevalue=1000 #milliseconds

class MainFrame(wx.Frame):
    global USBDeviceSerial
    global USBDevicePort
    def __init__(self):
	wx.Frame.__init__(self, None, -1, 'pySQM', size=(-1,-1))

	self.CreateStatusBar()

	panel = wx.Panel(self, -1)
	    
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

	font1 = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL)

        self.outputvalue = wx.StaticText(panel, label="")
        self.outputvalue.SetFont(font1)
	
	self.infovalue = wx.StaticText(panel, label="")
        self.infovalue.SetFont(font1)
	
        # Read button
        self.readbutton =wx.Button(panel, label="Read")
        self.Bind(wx.EVT_BUTTON, self.OnReadClick,self.readbutton)

	#Container for widgets
        self.controlgrid = wx.BoxSizer(wx.HORIZONTAL)
	self.controlgrid.Add(self.readbutton,flag=wx.LEFT|wx.RIGHT,border=3)
	self.controlgrid.Add(wx.StaticLine(panel,style=wx.LI_VERTICAL), 0, wx.ALL|wx.EXPAND)
	self.controlgrid.Add(self.outputvalue,flag=wx.LEFT|wx.RIGHT|wx.EXPAND,proportion=1)
	self.controlgrid.Add(wx.StaticLine(panel,style=wx.LI_VERTICAL), 0, wx.ALL|wx.EXPAND)
	self.controlgrid.Add(self.infovalue,flag=wx.LEFT|wx.RIGHT|wx.EXPAND,proportion=1)

	panel.SetSizerAndFit(self.controlgrid)
	framsize=(390,110)
	self.SetMinSize(framsize)
	self.SetSize(framsize)

	#Show reading on start up
	self.Reading()
	
	self.timer.Start(timevalue)

    def Reading(self):
	"""Start button has been clicked"""
	global USBDevicePort
	global USBDeviceSerial
	global timevalue
	(USBDeviceSerial,USBDevicePort)=FindFTDI.find()
	if (USBDeviceSerial == "") or (USBDevicePort == ""):
		self.outputvalue.SetLabel("--.--")
		self.infovalue.SetLabel("")
		self.SetStatusText("USB-port Sky Quality Meter not found.")
	else:
		self.SetStatusText("USB device:"+USBDeviceSerial+"  at:"+USBDevicePort)
		# configure the serial connection. read Timeout in seconds.
		ser = serial.Serial(
			port = USBDevicePort,
			baudrate=115200,
			timeout = 5,
			parity=serial.PARITY_NONE,
			stopbits=serial.STOPBITS_TWO,
			bytesize=serial.EIGHTBITS
		)

		try:
			#Send "Info" command to SQM
			ser.write('ix\r')
			
			#Get "read response" from SQM
			inforesponse=ser.readline().split(",")
			
			#Parse response values
			protocol = "%d" % int(inforesponse[1])
			model = "%d" % int(inforesponse[2])
			feature = "%d" % int(inforesponse[3])
			serialnumber =  "%d" % int(inforesponse[4][:-2])
			outstring = "Protocol: " + protocol + "\n   Model: "+model+"\n Feature: "+feature+"\n  Serial: "+serialnumber
			self.infovalue.SetLabel(outstring)

			#-------------------------------------------------
			#Check for correct model, 3 = SQM
			if (model =="3"):
				#Send "Read" command to SQM
				ser.write('rx\r')
				
				#Get "read response" from SQM
				readout=ser.readline().split(",")
				
				#Parse response values
				mpsas = "%10.2f" % float(readout[1][:-1])
				frequency = "%10d" % int(readout[2][:-2])
				counts = "%10d" % int(readout[3][:-1])
				seconds =  "%10.3f" % float(readout[4][:-1])
				temperature = "%10.1f" % float(readout[5][:-3])
				outstring = mpsas + " mpsas\n"+frequency+" Hz\n"+counts+" counts\n"+seconds+" seconds\n"+temperature+" C\n"
				self.outputvalue.SetLabel(outstring)
			else:
				self.outputvalue.SetLabel("\nWrong model")
		except:
			self.outputvalue.SetLabel("Error")
			self.infovalue.SetLabel("")
			ser.close()
			return
		self.controlgrid.Layout()
		ser.close()
	

    def OnTimer(self, evt):
	self.Reading()

    def OnReadClick(self,evt):
	self.Reading()


USBDeviceSerial, USBDevicePort = FindFTDI.find()
app = wx.App()
frame = MainFrame()
frame.Show()
app.MainLoop()
