#!/usr/bin/python3

import time
import numpy as np
from matplotlib.pyplot import figure, clf, plot, xlabel, ylabel, xlim, ylim, title, grid, axes, show, subplot
import signal
import threading

from tempSensorSim import TempSensorSim
#from max31865 import Max31865

class TempLogger():
	def __init__(self, sensor, filename="temp.log"):
		self.filename = filename
		self.sensor = sensor
		self.temps = np.empty(0)
		self.times = np.empty(0)
		self.count = 0

		self.abort = False
		self.thread = None
		self.sema = threading.Semaphore(0)

	def start(self, dt, duration):
		if self.thread == None:
			self.thread = threading.Thread(target=self.run, args=(dt, duration,))
			self.thread.start()

	def stop(self):
		if self.thread:
			self.abort = True
			self.thread.join()
			self.thread = None

	def run(self, *args):
		dt = args[0]
		duration = args[1]

		fp = open(self.filename, 'w')
		for t in range(0, duration):
			temp = self.sensor.temperature()
			print ("Current temperature is {:0.2f} °C".format(temp))
			self.times = np.append(self.times, self.count)
			self.temps = np.append(self.temps, temp)
			fp.write("{:04d} {:0.2f}\n".format(self.count, temp))
			self.count += 1
			time.sleep(dt)
			if self.abort:
				break

		fp.close()
		self.sema.release()

	def wait(self):
		if self.thread:
			self.sema.acquire()
		pass

	def result(self):
		return self.times, self.temps


if __name__ == '__main__':
	def tempPlot(result):
		figure(1)
		plot(result[0]/60, result[1], 'b-', linewidth=1)

		ylabel('°C/min')
		xlabel('t/min')
		show()

	def handler(signum, frame):
		print('Signal handler called with signal', signum)

		if signum == signal.SIGINT:
			logger.stop()

		if signum == signal.SIGHUP:
			tempPlot(logger.result())

	signal.signal(signal.SIGINT, handler)
	signal.signal(signal.SIGHUP, handler)

#	sensor = Max31865()
	sensor = TempSensorSim("FakeTemp")
	logger = TempLogger(sensor)
	logger.start(1.0, 10)
	logger.wait()
	tempPlot(logger.result())

	print("End of program")

