#!/usr/bin/python
import hal, time, serial, threading

#DEBUG
DEBUG = 1

# Create a new HAL pin which can be hooked to pyvcp
h = hal.component("serial_interface")
h.newpin("vcpt_voltage", hal.HAL_FLOAT, hal.HAL_IN)
h.newpin("vcpc_voltage", hal.HAL_FLOAT, hal.HAL_OUT)
h.ready()

# Serial Stuff, change the serial port address by changing /dev/ttyS0
ser = serial.Serial('/dev/ttyS0', 9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)

# Initialize
vcp_voltage = 0
thc_voltage = 0
old_vcp_voltage = 0
old_thc_voltage = 0
vcp_voltage_changed = 0
thc_voltage_changed = 0

# A thread dedicated to reading from the serial port
class readVoltage(threading.Thread):
    def __init__ ( self, ser ):
	# Initialize
	self.ser = ser
	self.thc_voltage = 0
	self.raw_thc_voltage = 0
	self.refined_thc_voltage = 0
	threading.Thread.__init__ ( self )
    def run ( self ):
	while 1:
	    	# Get voltage reading from THC if it's available, clean up padding, newline,whitespace,etc
    		self.raw_thc_voltage = self.ser.readline()
	    	if self.raw_thc_voltage.strip() != '':
    			self.refined_thc_voltage = self.raw_thc_voltage.strip()
    			self.thc_voltage = int(self.refined_thc_voltage.strip('*'))
		thc_voltage = self.thc_voltage

try:
    # Start thread to read from serial port
    readVoltage(ser).start()
    while 1:
	# Get the VCP voltage from UI
    	vcp_voltage = int(h.vcpt_voltage)

	# Update VCP voltage meter with most recent voltage measurement
	h.vcpc_voltage = thc_voltage
	if DEBUG == 1:
		print "Chars in Serial Reiceive Buffer: " + str(ser.inWaiting())

	# Check if VCP voltage has changed
    	if vcp_voltage != old_vcp_voltage:
		vcp_voltage_changed = 1
    		old_vcp_voltage = vcp_voltage

	# Check if THC voltage has changed, avoid feedback from VCP
    	if thc_voltage != old_thc_voltage and vcp_voltage_changed == 0:
		thc_voltage_changed = 1
    		old_thc_voltage = thc_voltage

	# If voltage numbers don't match anymore we figure out which one has changed, of both have changed VCP voltage rules
    	if thc_voltage == vcp_voltage:
		vcp_voltage_changed = 0
		thc_voltage_changed = 0
	else:
		if vcp_voltage_changed == 1 or thc_voltage_changed != 1:
			ser.write('**' + str(vcp_voltage) + '\n')
			if DEBUG == 1: 
				print "Changing THC Voltage"
		else:
			if DEBUG == 1: 
				print "Changing VCP Voltage"
	time.sleep(1)
except KeyboardInterrupt:
    raise SystemExit
