def run(self):
        self.__create_connection()
        tag_names = [self.rule['var_name']]
        self.conn.send(MonitorMessage(tag_names))
        while True:
            try:
                if self.conn.poll():
                    result = self.conn.recv()
                    if isinstance(result, UnknownPlcTagException):
                        raise UnknownPlcTagException(result)
                    elif isinstance(result, TerminateMessage):
                        logger.info("Terminating monitoring of '{}'.".format(
                            self.rule['var_name']))
                        break
                    elif isinstance(result, MonitorResponseMessage):
                        if self.rule['predicate'] == Predicates.MAXVAL:
                            if int(result.value) > self.rule['value']:
                                logger.warning(
                                    "ALERT! '{}' tag [{}={}] exceeds max value of {}."
                                    .format(self.rule['plc'].name,
                                            self.rule['var_name'],
                                            result.value, self.rule['value']))
                    else:
                        logger.error("Received unexpected message type '%s'.",
                                     type(result))
            except EOFError:
                logger.exception("Received EOF.")
                break
            except UnknownPlcTagException:
                logger.exception("Unknown PLC Tag.")

        self.conn.close()
    def run(self):
        self.__create_connection()
        tag_names = [self.rule['plc_var']]
        self.conn.send(MonitorMessage(tag_names))
        while True:
            try:
                result = self.conn.recv()
                if isinstance(result, UnknownPlcTagException):
                    raise UnknownPlcTagException(result)
                elif isinstance(result, TerminateMessage):
                    logger.info("Terminating monitoring of '{}'.".format(
                        self.rule['plc_var']))
                    break
                elif isinstance(result, MonitorResponseMessage):
                    if self.rule['predicate'] == Predicates.EQUALS:
                        for var in self.rule['hmi'].vars:
                            warn = False
                            if var['name'] == self.rule['hmi_var']:
                                if type(var['value']) is int:
                                    if var['value'] != int(result.value):
                                        warn = True
                                elif type(var['value']) is bool:
                                    if var['value'] != (result.value
                                                        == 'True'):
                                        warn = True
                                if warn:
                                    logger.warning(
                                        "ALERT! '{}' tag [{}={}] does not equal '{}' tag [{}={}]."
                                        .format(self.rule['hmi'].name,
                                                var['name'], var['value'],
                                                self.rule['plc'].name,
                                                self.rule['plc_var'],
                                                result.value))
                else:
                    logger.error("Received unexpected message type '%s'.",
                                 type(result))
            except EOFError:
                logger.exception("Received EOF.")
                break
            except UnknownPlcTagException:
                logger.exception("Unknown PLC Tag.")

        self.conn.close()
Example #3
0
 def __monitor(self):
     self.__create_connection()
     self.conn.send(MonitorMessage(self.motor.plc_vars_map.keys()))
Example #4
0
        def run(self):
            self.__create_connection()
            tag_names = []
            # If motor is none, all PLC tags should be monitored
            if self.motor is None:
                self.conn.send(GetAllTagNamesMessage())
            else:
                tag_names = self.motor.plc_vars_map.keys()
                self.conn.send(MonitorMessage(tag_names))
            while True:
                try:
                    result = self.conn.recv()
                    if isinstance(result, UnknownPlcTagException):
                        raise UnknownPlcTagException(result)
                    elif isinstance(result, TerminateMessage):
                        logger.info("Terminating monitoring of '{}'.".format(
                            ', '.join(tag_names)))
                        break
                    elif isinstance(result, GetAllTagNamesResponseMessage):
                        tag_names = result.tag_names
                        # Recreate connection before sending new message
                        self.listener_ready = False
                        self.__create_connection()
                        self.conn.send(MonitorMessage(tag_names))
                    elif isinstance(result, MonitorResponseMessage):
                        dev_name = None
                        # First check if we are currently monitoring a PLC or motor
                        if self.motor is None:
                            # We are monitoring a PLC
                            if self.plc_name in device_to_client_map:
                                dev_name = self.plc_name
                        else:
                            if self.motor.name in device_to_client_map:
                                dev_name = self.motor.name
                                # We have to alter the name of the result set, as we are receiving PLC tag
                                # changes, yet we have to transmit the motor tag
                                # The 'plc_vars_map' will contain the mapping: {PLC_TAG_NAME: IDX_MOTOR_VARS}
                                idx_motor_var = self.motor.plc_vars_map.get(
                                    result.name)
                                if idx_motor_var is not None:
                                    # Set the correct motor tag name
                                    result.name = self.motor.vars[
                                        idx_motor_var]['name']
                                else:
                                    logger.error(
                                        "Received unknown PLC tag (motor tag map)."
                                    )

                        if dev_name is not None:
                            # logger.info("'%s' variable changed [%s=%s].", dev_name, result.name, result.value)
                            for client in device_to_client_map[dev_name]:
                                client.sendMessage(u"" + json.dumps({
                                    'tag_change': {
                                        'name': result.name,
                                        'value': result.value
                                    }
                                }))
                    else:
                        logger.error("Received unexpected message type '%s'.",
                                     type(result))
                except EOFError:
                    logger.exception("Received EOF.")
                    break
                except UnknownPlcTagException:
                    logger.exception("Unknown PLC Tag.")

            self.conn.close()
Example #5
0
    def run(self):
        self.__create_connection()
        tag_names = []
        # If motor is none, all PLC tags should be monitored
        if self.motor is None:
            self.conn.send(GetAllTagNamesMessage())
        else:
            tag_names = self.motor.plc_vars_map.keys()
            self.conn.send(MonitorMessage(tag_names))
        while not self.stop_event.is_set():
            try:
                if self.conn.poll():
                    result = self.conn.recv()
                    if isinstance(result, UnknownPlcTagException):
                        raise UnknownPlcTagException(result)
                    elif isinstance(result, TerminateMessage):
                        logger.info("Terminating monitoring of '{}'.".format(
                            ', '.join(tag_names)))
                        break
                    elif isinstance(result, GetAllTagNamesResponseMessage):
                        tag_names = result.tag_names
                        # Recreate connection before sending new message
                        self.listener_ready = False
                        self.__create_connection()
                        self.conn.send(MonitorMessage(tag_names))
                    elif isinstance(result, MonitorResponseMessage):
                        # First check if we are currently monitoring a PLC or motor
                        if self.motor is None:
                            dev_name = self.plc_name
                        else:
                            dev_name = self.motor.name
                            # We have to alter the name of the result set, as we are receiving PLC tag
                            # changes, yet we have to transmit the motor tag
                            # The 'plc_vars_map' will contain the mapping: {PLC_TAG_NAME: IDX_MOTOR_VARS}
                            idx_motor_var = self.motor.plc_vars_map.get(
                                result.name)
                            if idx_motor_var is not None:
                                # Set the correct motor tag name
                                result.name = self.motor.vars[idx_motor_var][
                                    'name']
                            else:
                                logger.error(
                                    "Received unknown PLC tag (motor tag map)."
                                )
                        if dev_name is not None:
                            state_logger.info(
                                "[%s] '%s' variable changed [%s=%s].",
                                result.timestamp.strftime(
                                    '%Y-%m-%d %H:%M:%S.%f')[:-3], dev_name,
                                result.name, result.value)
                    else:
                        logger.error("Received unexpected message type '%s'.",
                                     type(result))
            except EOFError:
                logger.exception("Received EOF.")
                break
            except UnknownPlcTagException:
                logger.exception("Unknown PLC Tag.")

        try:
            # Announce to PLC supervisor that we stop monitoring PLC tags
            logger.info("Announcing PLC supervisor to stop monitoring.")
            self.conn.send(StopMonitoringMessage())
        except IOError, e:
            if e.errno == errno.EPIPE:
                pass
            else:
                logger.exception(
                    "Could not announce to PLC supervisor to stop monitoring states for state logging."
                )