#!/usr/bin/env python
# -*- coding: latin-1 -*-
# ------------------------------------------------------------------------------------
# read caltab from single channel device
# version 1
# used python 2.7.16 and pyserial-2.7
# ------------------------------------------------------------------------------------
# SETTINGS ... change for your own needs
COMPORT = "COM6"
DATAFILE = "dataw.cal"
# ------------------------------------------------------------------------------------
COMPORT_TIMEOUT = 1			# in seconds
COMPORT_SPEED =57600		# in baud
DEBUG=0
import serial,time

def write_calib_table(self, channel, data):
		cmd = ":74 {0}".format(channel)
		
		for entry in data:
				#print entry
				edge, temp = entry
				#print "Edge=", edge, " Temp=", temp
				if temp < 0:
					   temp = 0xffff + temp + 1
				cmd = "{0} {1:X} {2:X}".format(cmd, edge, temp)
		print "executing ", cmd
		ser = serial.Serial(COMPORT, COMPORT_SPEED, timeout=COMPORT_TIMEOUT)
		print "used com port: ",ser.name
		ser.write(cmd+"\r\n")
		ser.close()


#---------------------------------------
#main
#---------------------------------------

print "write calibration to FOTEMP"
print ""
print "for writing to channel 1, the file <data_write_ch1.cal> is expected"
print "for writing to channel 2, the file <data_write_ch2.cal> is expected"
print "for writing to channel 3, the file <data_write_ch3.cal> is expected"
print "for writing to channel 4, the file <data_write_ch4.cal> is expected"

comport=int(raw_input("Which COM (number only)? "))
channel=int(raw_input("Which channel (1-8)? "))
if channel==1: datafile="data_write_ch1.cal"
if channel==2: datafile="data_write_ch2.cal"
if channel==3: datafile="data_write_ch3.cal"
if channel==4: datafile="data_write_ch4.cal"
data = list()
cmd = ":74 {0}".format(channel)
f=open(datafile,'r')
for sLine in f:
	rowData = sLine.rsplit()
	#print len(rowData),rowData
	edge = int( rowData[0])
	temp10 = int(rowData[1])
	dataEntry = (edge, temp10)
	data.append(dataEntry)
for entry in data:
		edge, temp = entry
		#print "Edge=", edge, " Temp=", temp
		if temp < 0:
			   temp = 0xffff + temp + 1
		cmd = "{0} {1:X} {2:X}".format(cmd, edge, temp)
ser = serial.Serial("COM"+str(comport), COMPORT_SPEED, timeout=COMPORT_TIMEOUT)
print "used com port: ",ser.name
print "executing "+cmd
ser.write(cmd+"\r\n")
ser.close()
print "done."