import asyncio
from tasks import ATask
from ws.message import MsgIo
from utils.value import ChangedFloat
from components import ATemperatureSensor, TemperatureSensorException


class TempSensorTask(ATask):
	def __init__(self, sensor_device: ATemperatureSensor, interval, msg_handler: MsgIo):
		ATask.__init__(self, interval)

		self.msg_handler = msg_handler
		msg_handler.set_recv_handler(self.recv)
		self.sensor = sensor_device
		self.temp = self.sensor.temperature()

	def on_temp_changed(self, value):
		asyncio.create_task(self.send({'Temp': value}))

	async def recv(self, data):
		pass

	async def send(self, data):
		await self.msg_handler.send(data)

	async def on_process(self):
		print("{}: Started with interval {} s".format(self.msg_handler.get_key(), self.interval))
		temp = ChangedFloat(self.on_temp_changed, prec=1)
		self.set_on_changed("temp", temp.set)
		while True:
			try:
				self.temp = self.sensor.temperature()
			except TemperatureSensorException as e:
				print(e)
			await asyncio.sleep(self.interval)
