1b85fb1c8052c7f9e4d404e3c71f7be06c595180
[matches/honours.git] / research / TCS / interface.py
1 #!/usr/bin/python
2
3 # @file "interface.py"
4 # @author Sam Moore
5 # @purpose AVR Butterfly Datalogger control for Total Current Spectroscopy Measurements
6 #       The AVR responds to a limited number of RS232 commands to read ADC channels and set the DAC
7 #       This script can be used to control the DAC and monitor initial energy & sample current over RS232
8
9 import sys
10 import os
11 import time
12 import serial
13 import datetime
14
15 import odict
16 import Gnuplot, Gnuplot.funcutils
17
18 gnuplot = Gnuplot.Gnuplot()
19
20 # TODO: Insert variables for calibration purposes here.
21 calibrate = {
22         "ADC_Counts" : [2**10,2**10,2**10,2**10,2**10,2**10,2**10], # Maxed counts on ADC channels (10 bits = 2**10 = 1024)
23         "DAC_Counts" : 2**12, # Maxed counts on DAC channel (12 bits = 2**12 = 4096)
24
25         # Calibration data for DAC and ADC
26         "DAC" : None, 
27         "ADC" : [None, None, None, None, None, None, None, None],
28
29         # Data used for rough calibration if above data is not present
30         "Vref" : 3.3, # The output of the voltage regulator (Vref = Vcc) relative to signal ground
31         "ADC_Rin" : [None, None, None, None, 15000, 1100, 1100, 1100],
32         "ADC_Rvar" : [None, None, None, None, 1000, 5000, 10000, 50000],
33         "DAC_Gain" : 1
34 }
35
36 # TODO: Adjust aqcuisition parameters here
37 aquire = { "DAC_Sweep" : "0.0 + 50.0*int(step)", # DAC Sweep value (t is in STEPS, not seconds!)
38         "ADC_Averages" : 200,
39         #"ADC_Vi" : 5, # ADC channel to read back Vi (set by DAC) through
40         #"ADC_Is" : 4, # ADC channel to read back Is through
41         #"ADC_Ie" : 4, # ADC channel to read back Ie through
42         "DAC_Settle" : 0.0, # Time in seconds to wait for DAC to stabilise
43         #"response_wait" : 0.2, # Time to wait in seconds between sending data and reading back
44         "start_date" : None,
45         "open_files" : []
46 }
47
48 #Setup the serial connection parameters
49 ser = serial.Serial(
50         port="/dev/ttyUSB1", # Modify as needed (note: in linux need to run `sudo chmod a+rw /dev/ttyUSBX' to set permissions)
51
52         # Do not change the values below here (unless AVR butterfly is reprogrammed to use different values)
53         baudrate=4800,
54         parity="N",
55         stopbits=1,
56         bytesize=8,
57         timeout=None,
58         xonxoff=0,
59         rtscts=0
60 )
61
62 parameters = odict.odict([
63         ("Accelerating Voltage" , None),
64         ("Focus Voltage" , None),
65         ("Deflection Voltage" , None),
66         ("Venault Voltage" , None),
67         ("Initial Voltage" , None),
68         ("Heating Current" , None),
69         ("Heating Voltage" , None),
70         ("Chamber Pressure" , None),
71         ("610B Zero" , None),
72         ("602 Zero" , None),
73         ("610B Scale" , None),
74         ("602 Scale" , None),
75         ("602 0.1 Battery" , None),
76         ("602 0.03 Battery" , None),
77         ("602 0.01 Battery" , None),
78         ("602 0.003 Battery" , None),
79         ("602 0.001 Battery" , None), 
80         ("ADC Regulator" , None),
81         ("Sample", None),
82         ("Sample Angle", None),
83         ("Title" , None),
84         ("Comment" , None),
85         ("Data" , None),
86         ("Parameters last checked", None)
87 ])
88
89 def getTime():
90         return str(datetime.datetime.now()).split(" ")[1].split(".")[0].replace(":","")
91
92 def getDate():
93         return str(datetime.datetime.now()).split(" ")[0]
94
95 # Used for when I press Control-C to stop things
96 def set_exit_handler(func):
97     if os.name == "nt":
98         try:
99             import win32api
100             win32api.SetConsoleCtrlHandler(func, True)
101         except ImportError:
102             version = ".".join(map(str, sys.version_info[:2]))
103             raise Exception("pywin32 not installed for Python " + version)
104     else:
105         import signal
106         signal.signal(signal.SIGTERM, func)
107         signal.signal(signal.SIGINT, func)
108
109 def killed_handler(signal, frame):
110         reason = ""
111         sys.stdout.write("\n# Reason for killing program? ")
112         reason = sys.stdin.readline().strip("\r\n ")
113         for out in aquire["open_files"]:
114                 sys.stdout.write("# Closing file " + str(out) + "\n")
115                 out.write("# Recieved KILL signal.\n# Reason: " + str(reason) + "\n")
116                 log_close(out)
117
118         
119
120 def cleanup():
121         for out in aquire["open_files"]:
122                 out.write("# Program exits.\n")
123                 log_close(out)
124
125 def log_open(a, b):
126         result = open(a, b,0)
127         if (b == "w"):
128                 result.write("# File opened at " + str(datetime.datetime.now()) + "\n")
129                 aquire["open_files"].append(result)
130         return result
131
132 def log_close(afile):
133         if (afile in aquire["open_files"]):
134                 afile.write("# File closed at " + str(datetime.datetime.now()) + "\n")
135                 aquire["open_files"].remove(afile)
136         
137         afile.close()
138
139
140 def init():
141         #import atexit
142         #atexit.register(cleanup)
143         set_exit_handler(killed_handler)
144         
145         aquire["start_date"] = getDate()
146
147
148
149         # Connect serial
150         ser.open()
151         ser.isOpen()
152 #       print("Waiting for \"# hello\" from device...")
153 #       while (ser.readline().strip("\r\n") != "# hello"):
154 #               pass
155         #while (ser.readline().strip("\r\n ") != "#"):
156         #       pass
157         time.sleep(1.0)
158
159         ser.write("a "+str(aquire["ADC_Averages"]) + "\r\n")
160         print(ser.readline().strip("\r\n"))
161         print(ser.readline().strip("\r\n"))
162         print(ser.readline().strip("\r\n"))
163
164         #print("Writing config information to config.dat...")
165         #output = log_open("config.dat", "w", 1)
166
167         #output.write("# Initialise " + str(datetime.datetime.now()) + "\n")
168
169         #for field in calibrate:
170         #       output.write("# calibrate["+str(field)+"] = "+str(calibrate[field]) + "\n")
171         #output.write("\n")
172         #for field in aquire:
173         #       output.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
174
175         #output.write("# Ready " + str(datetime.datetime.now()) + "\n# EOF\n")
176         #output.close()
177
178 def main():
179
180         init()
181         
182         # I haven't ever used calibrated results, and yet this code is still here, why???
183         #if (loadCalibration_DAC() == False):
184         #       if (calibrateDAC() == False):
185         #               return -1
186         #if (loadCalibration_ADC(aquire["ADC_Is"]) == False):
187         #       if (calibrateADC_usingDAC(aquire["ADC_Is"], False) == False):
188         #               if (calibrateADC(aquire["ADC_Is"]) == False):
189         #                       return -1
190
191         #if (loadCalibration_ADC(aquire["ADC_Vi"]) == False):
192         #       if (calibrateADC_usingDAC(aquire["ADC_Vi"], True) == False):
193         #               if (calibrateADC(aquire["ADC_Vi"]) == False):
194         #                       return -1
195         
196
197         # Make directory for today, backup calibration files
198         os.system("mkdir -p " + getDate())
199         #os.system("cp *.dat " + getDate() +"/")
200
201         checkList()
202
203         
204         
205                 
206
207         # Experiment
208         # TODO: Modify data to record here
209         sweep = 1
210         while True:
211                 os.system("mkdir -p " + getDate())
212                 record_data([5], getDate()+"/"+str(getTime())+".dat", None, 4000)
213                 sweep += 1
214         
215
216 def checkList():
217         try:
218                 input_file = log_open(getDate()+"/checklist", "r")
219         except:
220                 input_file = None
221
222         if (input_file != None):
223                 for line in input_file:
224                         k = line.split("=")
225                         item = None
226                         if (len(k) >= 2):
227                                 item = k[0].strip("# \r\n")
228                                 value = k[1].strip("# \r\n")
229
230                         if (item in parameters):
231                                 parameters[item] = value
232         
233                 print("Checklist found. Overwrite? [Y/n]")
234                 response = sys.stdin.readline().strip(" \r\n")
235                 if (response == "" or response == "y" or response == "Y"):
236                         input_file = log_open(getDate()+"/checklist.old", "w")
237                         for item in parameters:
238                                 input_file.write("# " + str(item) + " = " + str(parameters[item]) + "\n")
239                         input_file.write("\n")
240                         log_close(input_file)
241                         input_file = None
242         
243         if (input_file == None):
244                 for item in parameters:
245                         if item == "Parameters last checked":
246                                 continue
247                         sys.stdout.write("\""+str(item)+"\" = " + str(parameters[item]) + " New value?: ")
248                         response = sys.stdin.readline().strip("\r\n ")
249                         if (response != ""):
250                                 parameters[item] = response
251                         sys.stdout.write("\n")
252                 parameters["Parameters last checked"] = str(datetime.datetime.now())
253                         
254
255         checklist = log_open(getDate()+"/checklist", "w")
256         for item in parameters:
257                 checklist.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
258                 #output_file.write("# "+str(item) + " = " + str(parameters[item]) + "\n")
259         log_close(checklist)
260         
261
262 def record_data(ADC_channels, output, pollTime = None, dac_max = None):
263         
264         if (output != None):
265                 gnuplot("set title \""+str(output)+"\"")
266                 output = [log_open(output, "w"), sys.stdout]
267
268         else:
269                 gnuplot("set title \"<No file>\"")
270                 output = [sys.stdout]
271
272         for field in aquire:
273                 for out in output:
274                         out.write("# aquire["+str(field)+"] = "+str(aquire[field]) + "\n")
275         
276         for out in output:
277                 out.write("# Parameters:\n")
278
279         for field in parameters:
280                 for out in output:
281                         out.write("# "+str(field)+" = " + str(parameters[field]) + "\n")
282
283
284         start_time = time.time()
285         
286         gnuplot("set xlabel \"DAC (counts)\"")
287         gnuplot("set ylabel \"ADC (counts)\"")
288         
289         
290         for out in output:
291                 out.write("\n")
292                 out.write("# Experiment " + str(datetime.datetime.now()) + "\n")
293                 out.write("# Polling for " + str(pollTime) + "s.\n")
294                 out.write("\n")
295                 out.write("# Data:\n")
296                 out.write("# time\tDAC")
297                 for channel in ADC_channels:
298                         out.write("\tADC"+str(channel))
299                 out.write("\n")
300
301         step = 0
302         data = [] # Keep track of data for dynamic plotting
303         dacValue = int(eval(aquire["DAC_Sweep"]))
304         if (setDAC(dacValue) == False):
305                 setDAC(dacValue)
306         time.sleep(2.0)
307         while (pollTime == None or time.time() < start_time + pollTime):
308                 if (aquire["DAC_Sweep"] != None):
309                         nextDacValue = int(eval(aquire["DAC_Sweep"]))
310                         if (nextDacValue != dacValue):
311                                 dacValue = nextDacValue
312                                 if (dacValue < 0):
313                                         break
314                                 setDAC(dacValue)
315                         step += 1
316                 
317
318                 if (dac_max != None and dacValue >= dac_max):
319                         break
320
321                 measure_start = time.time()
322
323                 raw_adc = []
324
325                 for channel in ADC_channels:
326                         read = readADC(channel)
327                         if read == False:
328                                 for out in output:              
329                                         print("# Abort data collection due to failed ADC read")                                 
330                                         if out != sys.stdout:
331                                                 log_close(out)
332                                         return False
333                         raw_adc.append((channel, read[0], read[1]))
334
335                 end_time = time.time()
336
337                 for out in output:
338                         measure_time = measure_start + (end_time - measure_start)/2.0 - start_time
339                         out.write(str(measure_time))
340                         out.write("\t"+str(dacValue))
341                         data.append([measure_time, dacValue])
342
343                         for adc in raw_adc:
344                                 out.write("\t" + str(adc[1]) + "\t" + str(adc[2]))
345                                 data[len(data)-1].append(adc[1])
346                                 data[len(data)-1].append(adc[2])
347                         out.write("\n") 
348         
349         
350                 gnuplot.plot(Gnuplot.Data(data, title="t = "+str(measure_time), with_="lp", using="2:3"))
351         for out in output:              
352                 if out != sys.stdout:
353                         log_close(out)
354         return True
355
356 def loadCalibration_ADC(channel):
357         try:
358                 input_file = log_open("calibrateADC"+str(channel)+".dat")
359         except:
360                 print("Couldn't find calibration file for ADC " + str(channel))
361                 return False
362         
363         calibrate["ADC"][channel] = []
364         for l in input_file:
365                 l = l.split("#")[0].strip("\r\n ")
366                 if (l == ""):
367                         continue
368                 else:
369                         split_line = l.split("\t")
370                         calibrate["ADC"][channel].append((float(split_line[0]), float(split_line[1])))
371         log_close(input_file)
372
373         if (len(calibrate["ADC"][channel]) <= 0):
374                 print("Empty calibration file for ADC " + str(channel))
375                 return False
376         return True
377
378 def loadCalibration_DAC():
379         try:
380                 input_file = log_open("calibrateDAC.dat")
381         except:
382                 print("Couldn't find calibration file for DAC")
383                 return False
384         
385         calibrate["DAC"] = []
386         for l in input_file:
387                 #print("Line is: "+str(l))
388                 l = l.split("#")[0].strip("\r\n ")
389                 if (l == ""):
390                         continue
391                 else:
392                         split_line = l.split("\t")
393                         if (len(split_line) >= 3):
394                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1]), float(split_line[2])))
395                         else:
396                                 calibrate["DAC"].append((int(split_line[0]), float(split_line[1])))
397
398
399         log_close(input_file)
400
401         if (len(calibrate["DAC"]) <= 0):
402                 print("Empty calibration file for DAC")
403                 return False
404         return True
405
406 def getADC_Voltage(channel, counts):
407         if (calibrate["ADC"][channel] == None or len(calibrate["ADC"][channel]) <= 0):
408                 if (calibrate["ADC_Rin"][channel] != None and calibrate["ADC_Rvar"][channel] != None):
409                         print("Warning: Using rough calibration for ADC"+str(channel) + " = " + str(counts))
410                         ratio = float(calibrate["ADC_Rin"][channel]) / (float(calibrate["ADC_Rin"][channel]) + float(calibrate["ADC_Rvar"][channel]))
411                         return ratio * (float(counts) / float(calibrate["ADC_Counts"][channel]) * Vref)
412                 else:
413                         print("Error: No calibration for ADC"+str(channel))
414                         return False
415
416         c = calibrate["ADC"][channel]
417         valueIndex = 1
418         for i in range(0, len(c)-1):
419                 if (c[i][0] <= counts and i + 1 < len(c)):
420                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
421                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
422                         return value
423
424         
425         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
426
427         grad = (float(c[len(c)-1][valueIndex]) - float(c[len(c)-2][valueIndex])) / (float(c[len(c)-1][0]) -  float(c[len(c)-2][0]))
428         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
429                 
430 def readADC(channel):
431         #for i in range(0, aquire["ADC_Averages"]):
432         #       ser.write("r "+str(channel)+"\r") # Send command to datalogger
433                 #time.sleep(aquire["response_wait"])
434         #       response = ser.readline().strip("#\r\n ")
435         #       if (response != "r "+str(channel)):
436         #               print("Received wierd response reading ADC ("+response+")")
437         #               return False                    
438                 #time.sleep(aquire["response_wait"])
439         #       values.append(int(ser.readline().strip("\r\n ")))
440         #       adc_sum += float(values[len(values)-1])
441         ser.write("r "+str(channel)+"\r")
442         response = ser.readline().strip("#\r\n")
443         if (response != "r "+str(channel)):
444                 print("Received wierd response reading ADC ("+response+")")
445                 return False                    
446         return ser.readline().strip("\r\n").split(" ")
447
448 def getDAC_Voltage(counts, gain = True):
449         if (calibrate["DAC"] == None or len(calibrate["DAC"]) <= 0):
450                 if (calibrate["DAC_Gain"] != None):
451                         print("Warning: Using rough calibration for DAC = " + str(counts))
452                         return float(counts) / float(calibrate["DAC_Counts"]) * float(calibrate["Vref"]) * float(calibrate["DAC_Gain"])
453                 else:
454                         print("Error: No calibrate for DAC")
455                         return False
456
457         valueIndex = 1
458         if (gain == False):
459                 valueIndex = 2
460                 if (len(calibrate["DAC"][0]) < 3):
461                         print("Error: No data for unamplified DAC")
462                         return False
463         
464         c = calibrate["DAC"]
465         if (len(c) == 1):
466                 print("Warning: Only one point in calibration data!")
467                 return float(c[0][valueIndex])
468         
469         for i in range(0, len(c)-1):
470                 if (c[i][0] <= counts and i + 1 < len(c)):
471                         grad = (float(c[i+1][valueIndex]) - float(c[i][valueIndex])) / (float(c[i+1][0]) - float(c[i][0]))
472                         value = float(c[i][valueIndex]) + grad * (float(counts) - float(c[i][0]))
473                         return value
474
475         
476         print("Warning: Extrapolating outside calibration range for DAC = " + str(counts))
477
478         grad = (float(c[len(c)-1][valueIndex]) - float(c[len(c)-2][valueIndex])) / (float(c[len(c)-1][0]) -  float(c[len(c)-2][0]))
479         value = float(c[len(c)-1][valueIndex]) + grad * (float(counts) - float(c[len(c)-1][0]))
480         return value
481
482
483 def setDAC(level):
484         
485         ser.write("d "+str(level)+"\r") 
486         
487         response = ser.readline().strip("#\r\n ")
488         if (response != "d "+str(level)):
489                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
490                 return False
491         #time.sleep(aquire["response_wait"])
492         #time.sleep(aquire["DAC_Settle"])
493         #time.sleep(aquire["DAC_Settle"])
494         response = ser.readline().strip("#\r\n ")
495         if (response != "DAC "+str(level)):
496                 print("Recieved wierd response setting DAC to "+str(level) + " ("+response+")")
497                 return False
498         #time.sleep(aquire["response_wait"])
499         time.sleep(aquire["DAC_Settle"])
500                 
501
502 def calibrateADC_usingDAC(channel, gain = True):
503         if (calibrate["DAC"] == None):
504                 print("ERROR: DAC is not calibrated, can't use to calibrate ADC!")
505                 return False
506
507         calibrate["ADC"][channel] = []
508         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
509         outfile.write("# Calibrate ADC " + str(channel) + "\n")
510         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
511
512         print("Connect DAC output to ADC " + str(channel) + " and press enter\n")
513         sys.stdin.readline()
514         
515         for dac in calibrate["DAC"]:
516                 if (setDAC(dac[0]) == False):
517                         return False
518                 
519                 value = readADC(channel)
520                 if (value == False):
521                         return False
522                 canadd = (len(calibrate["ADC"][channel]) <= 0)
523                 if (canadd == False):
524                         canadd = True
525                         for adc in calibrate["ADC"][channel]:
526                                 if adc[0] == value[0]:
527                                         canadd = False
528                                         break
529
530                 if (canadd):            
531
532                         if gain:
533                                 input_value = dac[1]
534                         else:
535                                 input_value = dac[2]
536
537                         #input_value = getDAC_Voltage(dac[0], gain)
538                         if (input_value == False):
539                                 return False
540         
541                         outfile.write(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]) + "\n")
542                         print(str(value[0]) + "\t" + str(input_value) + "\t" + str(value[1]))
543
544                         calibrate["ADC"][channel].append((value[0], input_value, value[1]))
545
546         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
547         log_close(outfile)
548         if (setDAC(0) == False):
549                 return False
550         if (len(calibrate["ADC"][channel]) <= 0):
551                 print("Error: No calibration points taken for ADC " + str(channel))
552                 return False
553         return True
554
555 def calibrateADC(channel):      
556         calibrate["ADC"][channel] = []
557         outfile = log_open("calibrateADC"+str(channel)+".dat", "w")
558         outfile.write("# Calibrate ADC " + str(channel) + "\n")
559         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
560
561         print("Calibrating ADC...\n")
562         print("Enter measured voltage, empty line stops.\n")
563
564         while True:
565                 read = sys.stdin.readline().strip("\r\n ")
566                 if (read == ""):
567                         break
568                 input_value = float(read)
569                 output_value = readADC(channel)
570                 if (output_value == False):
571                         return False
572                 
573                 calibrate["ADC"][channel].append((output_value[0], input_value))
574                 print(str(output_value[0]) + "\t" + str(input_value))
575                 
576         calibrate["ADC"][channel].sort(lambda e : e[1], reverse = False)
577         
578         
579         
580
581         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
582         log_close(outfile)
583         if (len(calibrate["ADC"][channel]) <= 0):
584                 print("Error: No calibration points taken for ADC " + str(channel))
585                 return False
586
587         return True
588
589 def calibrateDAC():
590         calibrate["DAC"] = []
591
592         outfile = log_open("calibrateDAC.dat", "w")
593         outfile.write("# Calibrate DAC\n")
594         outfile.write("# Start " + str(datetime.datetime.now()) + "\n")
595
596         print("Calibrating DAC...")
597         sys.stdout.write("Number of counts to increment per step: ")
598         read = sys.stdin.readline().strip("\r\n")
599         if (read == ""):
600                 return False
601         stepSize = max(1, int(read))
602         sys.stdout.write("\n")
603
604         outfile.write("# Increment by " + str(stepSize) + "\n")
605         print("Input measured DAC voltage for each level; empty input ends calibration.")
606         print("You may optionally input the DAC voltage before it is amplified too.")
607
608         level = 0
609         while (level < calibrate["DAC_Counts"]):
610
611                 setDAC(level)
612
613                 sys.stdout.write(str(level) + " ?")
614                 read = sys.stdin.readline().strip("\r\n ")
615                 if (read == ""):
616                         break
617                 else:
618                         read = read.split(" ")
619                         if (len(calibrate["DAC"]) > 0 and len(calibrate["DAC"][len(calibrate["DAC"])-1]) != len(read)):
620                                 print("Either give one value for EVERY point, or two values for EVERY point. Don't mess around.")
621                                 return False
622                         if (len(read) == 2):
623                                 calibrate["DAC"].append((level, float(read[0]), float(read[1])))
624                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\t" + str(float(read[1])) + "\n")
625                         else:
626                                 calibrate["DAC"].append((level, float(read[0])))
627                                 outfile.write(str(level) + "\t" + str(float(read[0])) + "\n")
628                 
629
630
631                 level += stepSize
632
633         outfile.write("# Stop " + str(datetime.datetime.now()) + "\n# EOF\n")
634         log_close(outfile)
635         if (len(calibrate["DAC"]) <= 0):
636                 print("Error: No calibration points taken for DAC")
637                 return False
638         return setDAC(0)
639
640 # Run the main function
641 if __name__ == "__main__":
642         sys.exit(main())

UCC git Repository :: git.ucc.asn.au