import numpy as np
import json
from aplant import APlant
from math import sqrt
from hendiCtrl import HendiCtrl
from max31865 import Max31865

class Plant(APlant):
	def __init__(self):
		self.heater = HendiCtrl('/dev/ttyUSB0', 115200)
		self.tempsensor = Max31865()
		self.P = 0
		self.isOn = False
		self.cycleTime = 30
		self.dutyCycle = 1
		self.cycleCounter = 0

	def activate(self, enable=True):
		if enable == True:
			self.heater.remoteEnable(enable)
			self.heater.setSwitch(enable)
		else:
			self.heater.setSwitch(enable)
			self.heater.remoteEnable(enable)

	def process(self, dt=1):
		isOn = self.isOn
		self.cycleCounter += dt
		if self.cycleCounter >= self.cycleTime:
			self.cycleCounter -= self.cycleTime
			isOn = 0

		if self.cycleCounter >= (self.cycleTime * (1-self.dutyCycle)):
			if not isOn:
				isOn = 1

		if self.isOn != isOn:
			if isOn:
				self.heater.setSwitch(True)
			else:
				self.heater.setSwitch(False)

		self.isOn = isOn

	def setPower(self, power_w):
		self.P = power_w
		self.heater.setPowerWatts(max(500, power_w))
		self.dutyCycle = min(1, power_w / 500)

	def getPower(self):
		return self.heater.getPowerWatts()

	def getTemperature(self):
		return self.tempsensor.temperature()

