from astirrer import AStirrer
import serial
import time
import serial


class Pololu1376(AStirrer):
	def __init__(self, params):
		super(Pololu1376, self).__init__(params["dt"])
		self.isMasterOn = 0

		self.ser_speed = params["speed"]
		self.ser_port = params["port"]
		self.ser = serial.Serial(self.ser_port, self.ser_speed)
		self.ser.set_output_flow_control(False)
		try:
			self.ser.open()
		except:
			self.ser.close()
			self.ser.open()

		self.ser_send('V')
		print(self.ser_recv())

	def ser_send(self, cmd):
		self.ser.write((cmd + '\r\n').encode())

	def ser_recv(self):
		s = self.ser.readline().decode("utf-8").replace("\n", '').replace("\r", '')
		return s

	def getSpeed(self):
		if self.isOn and self.isMasterOn:
			return self.speed
		return 0

	def activate(self):
		if self.isMasterOn == 0:
			self.log("Stirrer: switched On")
		self.isMasterOn = 1
		self.ser_send("go")

	def deactivate(self):
		if self.isMasterOn == 1:
			self.log("Stirrer: switched Off")
		self.isMasterOn = 0
		self.ser_send("x")

	def onSetSpeed(self, speed):
		self.ser_send("F" + str(speed) + "%")
		self.log("Stirrer: Set speed to {} %".format(speed))


if __name__ == '__main__':
	s = Pololu1376(1.0, "/dev/ttyACM0", "115200")
	s.activate()

	print ("Set some speeds")
	s.setSpeed(50)
	time.sleep(2)
	s.setSpeed(20)
	time.sleep(2)
	s.setSpeed(50)
	time.sleep(2)

	print ("Pulsed operation, duty cycle = 50%")
	s.setDutyCycle(0.5)
	s.setCycleTime(10)
	for i in range(1,30):
		s.process()
		time.sleep(1)

	print ("Pulsed operation, duty cycle = 20%")
	s.setDutyCycle(0.2)
	s.setCycleTime(10)
	for i in range(1,30):
		s.process()
		time.sleep(1)

	s.deactivate()
