#!/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 import logging from tempSensorSim import TempSensorSim as TempSensor #from tempSensor_max31865 import TempSensor_max31865 as TempSensor 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.time = 0 self.abort = False self.thread = None self.sema = threading.Semaphore(0) def start(self, dt, duration): try: if self.thread == None: self.thread = threading.Thread(target=self.run, args=(dt, duration,)) self.thread.start() except: self.sema.release() 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') while self.time < duration: temp = self.sensor.temperature() print ("Current temperature is {:0.2f} °C".format(temp)) self.times = np.append(self.times, self.time) self.temps = np.append(self.temps, temp) fp.write("{:0.2f} {:0.2f}\n".format(self.time, temp)) self.time += dt 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()) logging.getLogger().setLevel(logging.INFO) FORMAT = '%(asctime)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGHUP, handler) sensor = TempSensor() logger = TempLogger(sensor) logger.start(1.0, 30*60) logger.wait() tempPlot(logger.result()) print("End of program")