<commit_before>import serial 
import socket
import glob
import os
import time
import pickle
import math

class ardustat:
	def __init__(self):	
		self.port = ""
		self.ser = serial.Serial()
		self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.mode = "socket"

	def findPorts(self):
		if os.name == "posix": #Mac OS X and Linux
			return glob.glob("/dev/tty.u*")+glob.glob("/dev/ttyU*")+glob.glob("/dev/ttyA*")
		elif os.name == "nt": #Windows
			ports = []
			for i in range(1,100):
				ports.append("COM"+str(i))
			return ports
			
	#isArdustat() and guessUSB() lifted from the old ardustatlibrary.py with slight modifications to enable an autoConnect function
	def isArdustat(self,port): #Tests whether an ardustat is connected to a given port
		message = ""
		message = message + "\nTesting for ardustat on port "+str(port)+"."
		try:
			ser=serial.Serial(port,57600,timeout=5) #The ardustat uses a baudrate of 57600. This can be changed in the firmware
		except:
			return {"success":False,"message":message}
		time.sleep(0.1)
		ser.readline() #Somehow this initializes the connection or something
		ser.write("s0000\n")
		time.sleep(0.1)
		line = ser.readline()
		if line.find("GO") !=-1 or line.find("ST") !=-1: #These are the start and end markers of the serial lines that the ardustat spits out
			ser.close()
			return {"success":True,"message":message}
		else:
			ser.close()
			message = message + "\nNo ardustat on port "+port+"."
			return {"success":False,"message":message}
		
	def guessUSB(self): #This finds out what the possible serial ports are and runs isArdustat on them. Mac OS X and Linux handle serial ports differently than Windows, so we split the code up for each OS
		message = ""
		possibles = self.findPorts()
		if len(possibles)>=1:
			for port in possibles:
				isardresult = self.isArdustat(port)
				message = message + isardresult["message"]
				if isardresult["success"] == True:
					message = message + "\nArdustat found on "+port+"."
					return {"success":True,"port":port,"message":message}
		else:
			return {"success":False,"message":message+"\nCouldn't find any ardustats."}
	
	def autoConnect(self,mode="serial"):
		guessusbresult = self.guessUSB()
		if guessusbresult["success"] == True:
			if mode == "serial":
				self.mode = "serial"
				print self.connect(guessusbresult["port"])
			elif mode == "socket":
				print "Socket autoconnection not supported yet"
		else:
			print guessusbresult["message"]

	def connect(self,port):
		if self.mode == "serial":
			self.ser = serial.Serial(port,57600)
			self.ser.timeout = 1
			self.ser.open()
			return "connected to serial"
		if self.mode == "socket":
			self.s.connect(("localhost",port))
			return "connected to socket"
		
	
	def ocv(self):
		self.rawwrite("-0000")
	
	def potentiostat(self,potential):
		potential = str(int(1023*(potential/5.0))).rjust(4,"0")
		self.rawwrite("p"+potential)
	
		
	def rawwrite(self,command):
		if self.mode == "serial":
			self.ser.write(command+"\n")
		if self.mode == "socket":
			self.s.send(command)
	
	def rawread(self):
		self.rawwrite("s0000")
		time.sleep(.01)
		if self.mode == "serial":
			return self.ser.readlines()[-1] #If readlines returns a list, get the last element in the list
		if self.mode == "socket":
			a = ""
			while 1:
				a += self.s.recv(1024)
				if a.find("ST\r\n") > 1: return a.strip()
	
	def last_raw_reading(self):
		out = ""
		while self.ser.inWaiting() > 0: out = self.ser.readline()
		return out
	
	def refbasis(self,reading,ref):
		"""returns an absolute potential based on the ADC reading against the 2.5 V reference
		   (reading from pot as a value between 0 and 1023, reference value in V (e.g. 2.5))"""
		return round((float(reading)/float(ref))*2.5,3)
	
	def resbasis(self,pot,id=None):
		"""returns the value for the givening potentiometer setting 
			(reading as value between 0 and 255, pot lookup variable)"""
		message = ""
		if isinstance(id,int):
			try:
				f = open("resistances.pickle","r")
				resdict = pickle.load(f)
				f.close()
				res = resdict[str(id)] #This variable stores the resistance data for the Ardustat with that specific ID number
				message = message + "Calibration data found for id#"+str(id)
				calibrated = True
			except: #If there's no resistance data
				message = message + "Calibration data not found for id #"+str(id)
				res = []
				for i in range(256):
					res.append(i/255.*10000 + 100)
				calibrated = False
		else:
			message = message + "No ID # passed to this function. Using non-calibrated resistances."
			res = []
			for i in range(256):
				res.append(i/255.*10000 + 100)
			calibrated = False
		return {"success":True,"message":message,"resistance":res[pot],"calibrated":calibrated}
		
	def parse(self,reading,id=None):
		outdict = {}
		#format GO,1023,88,88,255,0,1,-0000,0,0,510,ST 
		#0 -> "GO"
		#1 -> DAC Setting
		#2 -> Cell Voltage
		#3 -> DAC Measurement
		#4 -> DVR Setting
		#5 -> Setting that potentiostat or galvanostat functions are using
		#6 -> Mode (0 = manual, 1 = OCV, 2 = potentiostat, 3 = galvanostat)
		#7 -> Last command received
		#8 -> GND Measurement
		#9 -> Reference Electrode
		#10 -> Reference Voltage
		#11 -> "ST"
		if reading.find("GO") == 0 and reading.find("ST") and reading.rfind("GO") == 0:
			outdict['success'] = True
			outdict['raw'] = reading
			outdict['time'] = time.time()
			parts = reading.split(",")
			outdict['ref'] = float(parts[len(parts)-2])
			outdict['DAC0_setting'] = int(parts[2]) / 1023.0 * 5.0
			outdict['DAC0_ADC'] = self.refbasis(parts[3],outdict['ref'])
			outdict['cell_ADC'] = self.refbasis(parts[2],outdict['ref'])
			outdict['pot_step'] = int(parts[4])
			outdict['resistance'] = self.resbasis(outdict['pot_step'],id)["resistance"]
			try:
				current = (float(outdict['DAC0_ADC'])-float(outdict['cell_ADC']))/outdict['resistance']
						 #(float(outdict['DAC0_ADC'])-float(outdict['cell_ADC']))/outdict['res']			
			except: #Divide by 0
				current = False
			outdict['current'] = current
			try:
				cellresistance = (outdict['cell_ADC']/outdict['DAC0_ADC'])*outdict['resistance']/(1-(outdict['cell_ADC']/outdict['DAC0_ADC']))
			except:
				cellresistance = False
			outdict['cell_resistance'] = cellresistance
			outdict['GND'] = self.refbasis(parts[8],outdict['ref'])
			outdict['reference_electrode'] = self.refbasis(parts[9],outdict['ref'])<commit_msg>Fixed bug w/cell resistance calc & neg. voltage<commit_after>import serial 
import socket
import glob
import os
import time
import pickle
import math

class ardustat:
	def __init__(self):	
		self.port = ""
		self.ser = serial.Serial()
		self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.mode = "socket"

	def findPorts(self):
		if os.name == "posix": #Mac OS X and Linux
			return glob.glob("/dev/tty.u*")+glob.glob("/dev/ttyU*")+glob.glob("/dev/ttyA*")
		elif os.name == "nt": #Windows
			ports = []
			for i in range(1,100):
				ports.append("COM"+str(i))
			return ports
			
	#isArdustat() and guessUSB() lifted from the old ardustatlibrary.py with slight modifications to enable an autoConnect function
	def isArdustat(self,port): #Tests whether an ardustat is connected to a given port
		message = ""
		message = message + "\nTesting for ardustat on port "+str(port)+"."
		try:
			ser=serial.Serial(port,57600,timeout=5) #The ardustat uses a baudrate of 57600. This can be changed in the firmware
		except:
			return {"success":False,"message":message}
		time.sleep(0.1)
		ser.readline() #Somehow this initializes the connection or something
		ser.write("s0000\n")
		time.sleep(0.1)
		line = ser.readline()
		if line.find("GO") !=-1 or line.find("ST") !=-1: #These are the start and end markers of the serial lines that the ardustat spits out
			ser.close()
			return {"success":True,"message":message}
		else:
			ser.close()
			message = message + "\nNo ardustat on port "+port+"."
			return {"success":False,"message":message}
		
	def guessUSB(self): #This finds out what the possible serial ports are and runs isArdustat on them. Mac OS X and Linux handle serial ports differently than Windows, so we split the code up for each OS
		message = ""
		possibles = self.findPorts()
		if len(possibles)>=1:
			for port in possibles:
				isardresult = self.isArdustat(port)
				message = message + isardresult["message"]
				if isardresult["success"] == True:
					message = message + "\nArdustat found on "+port+"."
					return {"success":True,"port":port,"message":message}
		else:
			return {"success":False,"message":message+"\nCouldn't find any ardustats."}
	
	def autoConnect(self,mode="serial"):
		guessusbresult = self.guessUSB()
		if guessusbresult["success"] == True:
			if mode == "serial":
				self.mode = "serial"
				print self.connect(guessusbresult["port"])
			elif mode == "socket":
				print "Socket autoconnection not supported yet"
		else:
			print guessusbresult["message"]

	def connect(self,port):
		if self.mode == "serial":
			self.ser = serial.Serial(port,57600)
			self.ser.timeout = 1
			self.ser.open()
			return "connected to serial"
		if self.mode == "socket":
			self.s.connect(("localhost",port))
			return "connected to socket"
		
	
	def ocv(self):
		self.rawwrite("-0000")
	
	def potentiostat(self,potential):
		potential = str(int(1023*(potential/5.0))).rjust(4,"0")
		self.rawwrite("p"+potential)
	
		
	def rawwrite(self,command):
		if self.mode == "serial":
			self.ser.write(command+"\n")
		if self.mode == "socket":
			self.s.send(command)
	
	def rawread(self):
		self.rawwrite("s0000")
		time.sleep(.01)
		if self.mode == "serial":
			return self.ser.readlines()[-1] #If readlines returns a list, get the last element in the list
		if self.mode == "socket":
			a = ""
			while 1:
				a += self.s.recv(1024)
				if a.find("ST\r\n") > 1: return a.strip()
	
	def last_raw_reading(self):
		out = ""
		while self.ser.inWaiting() > 0: out = self.ser.readline()
		return out
	
	def refbasis(self,reading,ref):
		"""returns an absolute potential based on the ADC reading against the 2.5 V reference
		   (reading from pot as a value between 0 and 1023, reference value in V (e.g. 2.5))"""
		return round((float(reading)/float(ref))*2.5,3)
	
	def resbasis(self,pot,id=None):
		"""returns the value for the givening potentiometer setting 
			(reading as value between 0 and 255, pot lookup variable)"""
		message = ""
		if isinstance(id,int):
			try:
				f = open("resistances.pickle","r")
				resdict = pickle.load(f)
				f.close()
				res = resdict[str(id)] #This variable stores the resistance data for the Ardustat with that specific ID number
				message = message + "Calibration data found for id#"+str(id)
				calibrated = True
			except: #If there's no resistance data
				message = message + "Calibration data not found for id #"+str(id)
				res = []
				for i in range(256):
					res.append(i/255.*10000 + 100)
				calibrated = False
		else:
			message = message + "No ID # passed to this function. Using non-calibrated resistances."
			res = []
			for i in range(256):
				res.append(i/255.*10000 + 100)
			calibrated = False
		return {"success":True,"message":message,"resistance":res[pot],"calibrated":calibrated}
		
	def parse(self,reading,id=None):
		outdict = {}
		#format GO,1023,88,88,255,0,1,-0000,0,0,510,ST 
		#0 -> "GO"
		#1 -> DAC Setting
		#2 -> Cell Voltage
		#3 -> DAC Measurement
		#4 -> DVR Setting
		#5 -> Setting that potentiostat or galvanostat functions are using
		#6 -> Mode (0 = manual, 1 = OCV, 2 = potentiostat, 3 = galvanostat)
		#7 -> Last command received
		#8 -> GND Measurement
		#9 -> Reference Electrode
		#10 -> Reference Voltage
		#11 -> "ST"
		if reading.find("GO") == 0 and reading.find("ST") and reading.rfind("GO") == 0:
			outdict['success'] = True
			outdict['raw'] = reading
			outdict['time'] = time.time()
			parts = reading.split(",")
			outdict['ref'] = float(parts[len(parts)-2])
			outdict['DAC0_setting'] = int(parts[2]) / 1023.0 * 5.0
			outdict['DAC0_ADC'] = self.refbasis(parts[3],outdict['ref'])
			outdict['cell_ADC'] = self.refbasis(parts[2],outdict['ref'])
			outdict['pot_step'] = int(parts[4])
			outdict['resistance'] = self.resbasis(outdict['pot_step'],id)["resistance"]
			outdict['GND'] = self.refbasis(parts[8],outdict['ref'])
			try:
				current = (float(outdict['DAC0_ADC'])-float(outdict['cell_ADC']))/outdict['resistance']
						 #(float(outdict['DAC0_ADC'])-float(outdict['cell_ADC']))/outdict['res']			
			except: #Divide by 0
				current = False
			outdict['current'] = current
			try:
				if outdict['DAC0_ADC'] == 0: #DAC 1 is set...
					cellresistance = (outdict['cell_ADC']/outdict['GND'])*outdict['resistance']/(1-(outdict['cell_ADC']/outdict['GND']))
				elif outdict['GND'] == 0:
					cellresistance = (outdict['cell_ADC']/outdict['DAC0_ADC'])*outdict['resistance']/(1-(outdict['cell_ADC']/outdict['DAC0_ADC']))
				else:
					cellresistance = False
			except:
				cellresistance = False
			outdict['cell_resistance'] = cellresistance
			outdict['reference_electrode'] = self.refbasis(parts[9],outdict['ref'])
{'fraction_non_alphanumeric': 0.15433663670584621, 'fraction_numerical': 0.02588922178689406, 'mean_word_length': 3.9592380952380952, 'pattern_counts': {'":': 50, '<': 3, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1407828', 'n_tokens_mistral': 5254, 'n_tokens_neox': 4343, 'n_words': 1168}