from __future__ import absolute_import from django.conf import settings from common.models import * from celery.task import Task from devices.PLC import PLCController from utils.JDManipulator import * import utils.Logger as L log = L.setupLogger("MonitoringTaskLogger", "Monitoring") ''' Infinite task created at the program's start. Checks the plc status, parse it, analyse it, store it in db ''' class Monitoring(Task): timers = {} functions = {} def run(self): self.setContext() self.setTime() self.loop() def setContext(self): self.plc = PLCController() self.state = "RUNNING" return (0) def setTime(self): self.timer_status = 2 self.timers = {"timer_status": self.timer_status} self.functions = {"timer_status": self.handleTimerStatus} return (0) def logDB(self, message: str): Log.objects.create(agent='Monitoring', message=message) def handleTimerStatus(self): self.timers["timer_status"] = self.timer_status self.status_plc = self.plc.get("STATUS") log.info("Received status : " + str(self.status_plc)) self.logDB("Received status from plc") if (self.plc.isError(self.status_plc)): if (settings.DEBUG): log.info("Invalid status returned : " + str(self.status_plc)) self.logDB("Status considered as INVALID") return (1) # TODO: parse, analyse, store return (0) def loop(self): while (self.state != "SHUTDOWN"): minimal_timer = min(self.timers, key=self.timers.get) time.sleep(self.timers[minimal_timer]) self.timers = {key: value - self.timers[minimal_timer] for key, value in self.timers.items()} for timer_name, timer_value in self.timers.items(): if (timer_value <= 0): if (timer_name in self.functions): self.functions[timer_name]() else: if (settings.DEBUG): log.info("Timer : " + str(timer_name) + "is not known by the monitoring") self.logDB("Timer " + str(timer_name) + " unknown") if (settings.DEBUG): log.info("Timer : " + str(timer_name) + " executed by monitoring") return (0) if (__name__ == "__main__"): m = Monitoring() m.run()