import spidev as SPI
import pin as GPIO
GPIO.config('./config.json')

class MCP3204():
	def __init__(self,spiDev,cs):
		GPIO.setmode(GPIO.BCM)
		
		#self.spi = SPI.SpiDev()
		#self.spi.open(spiDev, 0)
		#self.max_speed_hz = 1000000
		#self.spi.mode = 0
		#self.spi.set_bit_order(SPI.MSBFIRST)
		self.csPin = cs
		GPIO.setup(self.csPin,  GPIO.OUT)
		GPIO.output(self.csPin, GPIO.HIGH)
		
		self.clkPin = 21
		GPIO.setup(self.clkPin,  GPIO.OUT)
		GPIO.output(self.clkPin, GPIO.LOW)
		
		self.mosiPin = 20
		GPIO.setup(self.mosiPin,  GPIO.OUT)
		GPIO.output(self.mosiPin, GPIO.LOW)

		self.misoPin = 19
		GPIO.setup(self.misoPin,  GPIO.IN)

	def __del__(self):
		#self.spi.close()
		pass

	def _toggleClock(self):
		GPIO.output(self.clkPin, GPIO.HIGH)
		GPIO.output(self.clkPin, GPIO.LOW)

	def read(self, ch):
		if 4 <= ch <= 0:
			raise Exception('MCP3204 channel must be 0-4: ' + str(ch))

		GPIO.output(self.csPin, GPIO.LOW)

		ret = []
		cmd = 128  # 1000 0000
		cmd += 64  # 1100 0000
		cmd += ((ch & 0x07) << 3)
		#ret = self.spi.xfer2([cmd, 0, 0, 0])
		#print(ret)
		for byte in range(3):
			retVal = 0
			for bit in range(8):
				if cmd & 0b10000000:
					GPIO.output(self.mosiPin, GPIO.HIGH)
				else:
					GPIO.output(self.mosiPin, GPIO.LOW)

				#Shift command by 1 bit for next tick
				cmd <<= 1

				# Read 1 data bit
				if GPIO.input(self.misoPin):
					retVal |= 0x1

				# Advance input to next bit
				retVal <<= 1
			
				self._toggleClock()
			ret.append(retVal)
		# get the 24b out of the return
		print(ret)
		val = (ret[0] & 0x01) << 11  # only B11 is here
		val |= ret[1] << 3           # B10:B3
		val |= ret[2] >> 5           # MSB has B2:B0 ... need to move down to LSB

		GPIO.output(self.csPin, GPIO.HIGH)
		return (val & 0x0FFF)  # ensure we are only sending 12b
		#return(0)