plc_checker.py 6.1 KB
import json
import logging
logger = logging.getLogger(__name__)




class PlcChecker(object):

    def __init__(self):
        self.origin = {}
        self.origin["plc_from"] = None
        self.origin["plc_site"] = None
        self.struct = None
        self.path_list = None
        # self.plc_global = copy.copy(self.struct["devices"])
        self.device_name = None
        self.device_type = None
        self.serial_number = None
        self.valid = None
        self.sensors_monitor = {
            "Temperature_outside": None,
            "Humidity_outside": None,
            "Rain_boolean": None,
            "Wind_direction": None,
            "Wind_speed": None,
            "Temperature_sky": None,
            "status": None,
            "current": None,
            "plc_mode": None,
            "LIGHTS": None,
            "SHUTTERS": None,
        }
        #self.sensors_conf = {}
        self.sensors_table = []
        self.load_config()

    def load_config(self):
        try:
            colibri_json = open("./monitoring/plc_config.json")
            _struct = json.load(colibri_json)
            self.origin = _struct["origin"]
            self.sensors_table = _struct["sensors"]
            self.sensors_monitor= _struct["selected_sensors"]
            logger.info("Loaded : plc_config.json")
            colibri_json.close
        except:
            logger.info("No plc_config.json")

    def save_config(self):
        #try:
            _struct = {}
            _struct["origin"] = self.origin
            _struct["sensors"] = self.sensors_table
            _struct["selected_sensors"] = self.sensors_monitor
            _file = open("./monitoring/plc_config.json" , 'w')
            _file.write(json.dumps(_struct))
            _file.close()
            logger.info("Saved : plc_config.json")
        #except:
            logger.info("Not saved plc_config.json")

    def chk_config(self, status_plc):
        try:
            struct = json.loads(status_plc)
        except:
            logger.info("Error loading plc json")
        if isinstance(struct, list):
            self.struct = struct[0]
        else:
            self.struct = struct
        if not self.same_origin():
                self.scan_sensors()
                self.save_config()
        return True

    def monitored_sensor(self, name, _sensor_id):
        known = None
        selected = ""
        if name in self.sensors_monitor.keys():
            known = name
            if self.sensors_monitor[name] == None:
               self.sensors_monitor[name] = _sensor_id
               selected = "checked"
        return known, selected

    def same_origin(self):
        # check new origin
        if self.struct["from"] == self.origin["plc_from"] and self.struct["site"] == self.origin["plc_site"]:
            return True
        else:
            # update origin
            self.origin["plc_from"] = self.struct["from"]
            self.origin["plc_site"] = self.struct["site"]
            return False

    def get_key(self, struct, key):
        try:
            ret = struct[key]
        except:
            ret = None
        return ret

    def get_sensor(self, monitored):
        #id:'DHT22:/MiFe_DHT1_1:/Humidity'
        _value = self.sensors_monitor[monitored]
        if _value != None:
            sp_id = _value.split(":/")
            for device in self.struct["devices"]:
                if device["device_name"] == sp_id[0] and device["serial_number"] == sp_id[1]:
                    for device_values in device["device_values"]:
                        if device_values["name"] == sp_id[2]:
                            _value = device_values["value"]
        return _value


    def scan_sensors(self):
        # return sensors table from struct
        self.sensors_table = []
        try:
            logger.debug(self.struct["date"])
        except Exception as e:
            logger.debug("No date")

        for device in self.struct["devices"]:
            self.device_name = self.get_key(device, "device_name")
            self.device_type = self.get_key(device, "device_type")
            self.serial_number = self.get_key(device, "serial_number")
            self.valid = self.get_key(device, "valid")
            for device_values in device["device_values"]:
                sensor = []
                sensor.append(self.device_name)
                sensor.append(self.device_type)
                sensor.append(self.serial_number)
                sensor.append(self.valid)
                _name = self.get_key(device_values, "name")
                sensor.append(_name)
                _sensor_id = self.device_name + ":/" + self.serial_number + ":/" + _name
                _monitoring_name, _selected = self.monitored_sensor(self.get_key(device_values, "monitoring_name"), _sensor_id)
                sensor.append(_monitoring_name)
                sensor.append(self.get_key(device_values, "type"))
                sensor.append(_selected)
                sensor.append(_sensor_id)
                self.sensors_table.append(sensor)


    # deprecated find sensor list in struct
    """
    def find_sensors(self):
        try:
            logger.debug(self.struct["date"])
        except Exception as e:
            logger.debug("No date")
        for sensor_type in self.sensors:
            self.sensors_conf[sensor_type] = {}
            logger.debug(sensor_type + ":")
            try:
                self.cross_devices_list(sensor_type)
            except Exception as e:
                logger.debug(sensor_type + " error")

    def cross_devices_list(self, sensor_type):
        """"""
        for device in self.struct["devices"]:
            if device["device_name"] != "GLOBAL" and device["device_type"] == "meteo" and device["valid"] == "yes":
                self.cros_sensor_list(device, sensor_type)

    def cros_sensor_list(self, device, sensor_type):
        device_id = device["device_name"] + "/" + device["serial_number"]
        for sensor in device["device_values"]:
            if sensor["name"] == sensor_type:
                self.sensors_conf[sensor_type][device_id] = sensor["value"]
                logger.debug("-- " + device_id + " : " + str(sensor["value"]))
    """