#!/usr/bin/env python
# -*- coding: latin-1 -*-
# ------------------------------------------------------------------------------------
# read caltab from single channel device
# version 1
# used python 2.7.16 and pyserial-2.7
# ------------------------------------------------------------------------------------
COMPORT_TIMEOUT = 1			# in seconds
COMPORT_SPEED =57600		# in baud
DEBUG=0
import serial,time

def get_calibration(ser,channel):
	try:
		rc1=""
		rc2=""
		ser.write("?74 "+str(channel)+"\r\n")
		rc1=ser.readline()
		if DEBUG==1: print "1:" + rc1
		if rc1.find("*FF")==-1:
			rc2=ser.readline()
			if DEBUG==1: print "2:" + rc2
		return rc1
	except:
		return rc1

# --- MAIN ---
print "read calibration from FOTEMP"
print ""
comport=int(raw_input("Which COM (number only)? "))
channel=int(raw_input("Which channel (1-8)? "))
datafile="data_read_ch"+str(channel)+".cal"
ser = serial.Serial("COM"+str(comport), COMPORT_SPEED, timeout=COMPORT_TIMEOUT)
print "used com port: ",ser.name
print "---"
s=get_calibration(ser,channel)
ser.close()
if s.find("*FF")==-1:
	entries=s.split()
	del entries[0]
	f=open(datafile,"w")
	for i in range(0,len(entries),2):
		edge=int(entries[i],16)
		temp=int(entries[i+1],16)
		if (temp & 0x8000) == 0x8000:
			# if set, invert and add one to get the negative value, then add the negative sign
			temp = -( (temp ^ 0xffff) + 1)
		datastring = str(edge) +" "+ str(temp)
		print datastring
		f.write(datastring+"\n")
	f.close()
	print "data written to file <"+datafile+">"
	


