Exemple #1
0
 def loop_forever(self):
     while True:
         try:
             if not self.__running:
                 self.connect(self.__bacnet_server)
                 setting: AppSetting = current_app.config[
                     AppSetting.FLASK_KEY]
                 if setting.mqtt.enabled:
                     mqtt_client = MqttClient()
                     while not mqtt_client.status():
                         logger.warning(
                             "MQTT is not connected, waiting for MQTT connection successful..."
                         )
                         time.sleep(self.config.attempt_reconnect_secs)
                     self.sync_stack()
                     self.__running = True
                 else:
                     self.sync_stack()
                     self.__running = True
             time.sleep(2)
         except Exception as e:
             logger.error(e)
             logger.warning(
                 "BACnet is not connected, waiting for BACnet server connection..."
             )
             time.sleep(self.config.attempt_reconnect_secs)
Exemple #2
0
    def __decode_device(data: str):
        if data and MqttClient().config and MqttClient().config.publish_raw:
            MqttClient().publish_raw(data)
        if data and DecoderBase.check_payload_len(data):
            logger.debug("payload: {} length: {}".format(data, len(data)))
            device_id = DecoderFactory.get_id(data)

            if DeviceRegistry().get_device(device_id) is None:
                logger.warning('Sensor not in registry: {}'.format(device_id))
                return

            device = DeviceModel.find_by_id(device_id)
            decoder = DecoderFactory.get_decoder(data, device.device_model)
            if decoder is None:
                logger.warning(f'No decoder found for device model {device.device_model}... Continuing')

            payload = decoder.decode()
            logger.debug('Sensor payload: {}'.format(payload))
            is_updated_any: bool = False
            if payload is not None:
                points = device.points
                for key in payload:
                    for point in points:
                        if key == point.device_point_name:
                            point_store = point.point_store
                            point_store.value_original = float(payload[key])
                            is_updated_any: bool = point.update_point_value(point.point_store) or is_updated_any
                if is_updated_any:
                    device.update_mqtt()
        elif data:
            logger.debug("Raw serial: {}".format(data))
Exemple #3
0
    def emit(self, record):
        from src.mqtt import MqttClient

        if MqttClient().config and MqttClient().config.publish_debug:
            try:
                msg = self.format(record)
                MqttClient().publish_debug(msg)
            except Exception as e:
                MqttClient().publish_debug(str(e))
Exemple #4
0
 def add_point(self, point: BACnetPointModel, _update_point_store=True):
     [priority_array,
      present_value] = default_values(point.priority_array_write,
                                      point.relinquish_default)
     if point.use_next_available_address:
         point.address = BACnetPointModel.get_next_available_address(
             point.address)
     object_identifier = create_object_identifier(point.object_type.name,
                                                  point.address)
     if point.object_type.name == "analogOutput":
         register_object_type(AnalogOutputCmdObject)
         p = AnalogOutputFeedbackObject(
             profileName=point.uuid,
             objectIdentifier=(point.object_type.name, point.address),
             objectName=point.object_name,
             relinquishDefault=point.relinquish_default,
             presentValue=present_value,
             priorityArray=priority_array,
             eventState=point.event_state.name,
             statusFlags=StatusFlags(),
             units=EngineeringUnits(point.units.name),
             description=point.description,
             outOfService=False,
         )
         self.__bacnet.add_object(p)
         self.__registry[object_identifier] = p
     elif point.object_type.name == "analogValue":
         register_object_type(AnalogValueCmdObject)
         p = AnalogValueFeedbackObject(
             profileName=point.uuid,
             objectIdentifier=(point.object_type.name, point.address),
             objectName=point.object_name,
             relinquishDefault=point.relinquish_default,
             presentValue=present_value,
             priorityArray=priority_array,
             eventState=point.event_state.name,
             statusFlags=StatusFlags(),
             units=EngineeringUnits(point.units.name),
             description=point.description,
             outOfService=False,
         )
         self.__bacnet.add_object(p)
         self.__registry[object_identifier] = p
     if _update_point_store:  # make it so on start of app not to update the point store
         update_point_store(point.uuid, present_value)
     setting: AppSetting = current_app.config[AppSetting.FLASK_KEY]
     if setting.mqtt.enabled:
         priority = get_highest_priority_field(point.priority_array_write)
         mqtt_client = MqttClient()
         mqtt_client.publish_value(
             ('ao', object_identifier, point.object_name), present_value,
             priority)
Exemple #5
0
 def republish(self):
     logger.info(f"Called MQTT republish")
     while not MqttClient().status():
         logger.warning('Waiting for MQTT connection to be connected...')
         thread.sleep(2)
     self._publish_devices()
     logger.info(f"Finished MQTT republish")
Exemple #6
0
 def update_mqtt(self):
     output: dict = {}
     for point in self.points:
         output[point.device_point_name] = point.point_store.value
     logger.debug(f'Publish payload: {json.dumps(output)}')
     MqttClient().publish_value((self.device_id, self.name),
                                json.dumps(output))
Exemple #7
0
    def get(cls):
        up_time = get_up_time()
        up_min = up_time / 60
        up_min = "{:.2f}".format(up_min)
        up_hour = up_time / 3600
        up_hour = "{:.2f}".format(up_hour)
        from src import AppSetting
        setting: AppSetting = current_app.config[AppSetting.FLASK_KEY]
        deployment_mode = 'production' if setting.prod else 'development'

        return {
            'version': get_version(),
            'up_time_date': up_time_date,
            'up_min': up_min,
            'up_hour': up_hour,
            'deployment_mode': deployment_mode,
            'bacnet': {
                'enabled': setting.bacnet.enabled,
                'status': BACServer().status(),
                'use_pre_set_ethernet_interface':
                setting.bacnet.enable_ip_by_nic_name,
                'pre_set_ethernet_interface': setting.bacnet.ip_by_nic_name,
                'default_point_cov': setting.bacnet.default_point_cov
            },
            'mqtt': {
                'enabled': setting.mqtt.enabled,
                'status': MqttClient().status()
            }
        }
Exemple #8
0
 def check_feedback(self, old_value, new_value):
     priority_array = self._dict_contents().get('priorityArray')
     serialized_priority_array = serialize_priority_array(priority_array)
     with self.__app_context():
         priority_array_updated = PriorityArrayModel.filter_by_point_uuid(self.profileName).update(
             serialized_priority_array)
         update_point_store(self.profileName, new_value)
         setting: AppSetting = current_app.config[AppSetting.FLASK_KEY]
         if setting.mqtt.publish_value:
             object_identifier = create_object_identifier(self.objectIdentifier[0], self.objectIdentifier[1])
             present_value = self.presentValue
             if isinstance(present_value, Real):
                 present_value = float(present_value.value)
             elif type(present_value) is float:
                 present_value = float(present_value)
             priority = get_highest_priority_field(priority_array_updated)
             mqtt_client = MqttClient()
             mqtt_client.publish_value(('ao', object_identifier, self.objectName), present_value, priority)
Exemple #9
0
    def __start(self):
        self.__register_devices()
        self.__serial_driver = NetworkModel.create_network(self.__config)
        while True:
            self.__check_and_set_restart()
            if not self.__connect_serial():
                time.sleep(5)
                continue

            try:
                if MqttClient().config.enabled:
                    time.sleep(1)  # time for mqtt client to connect
                    while not MqttClient().status():
                        logger.warning("MQTT not connected. Waiting for MQTT connection successful...")
                        time.sleep(MqttClient().config.attempt_reconnect_secs)
                    logger.info("MQTT client connected. Resuming...")
            except Exception as e:
                self.__connection = None
                logger.error("Error: {}".format(str(e)))
                continue

            self.__read_serial_loop()
Exemple #10
0
    def run():
        from src.bacnet_server import BACServer
        from src.mqtt import MqttClient
        setting: AppSetting = current_app.config[AppSetting.FLASK_KEY]
        logger.info("Running Background Task...")
        if setting.mqtt.enabled:
            MqttClient().start(setting.mqtt)

        if setting.bacnet.enabled:
            FlaskThread(target=BACServer().start_bac,
                        daemon=True,
                        kwargs={
                            'config': setting.bacnet
                        }).start()

        Background.sync_on_start()
Exemple #11
0
    def run():
        from src.lora import SerialConnectionListener
        from src.mqtt import MqttClient
        setting: AppSetting = current_app.config[AppSetting.FLASK_KEY]
        logger.info("Running Background Task...")
        if setting.mqtt.enabled:
            MqttClient().start(setting.mqtt)

        if setting.serial.enabled:
            FlaskThread(target=SerialConnectionListener().start, daemon=True,
                        kwargs={'config': setting.serial}).start()

        Background.sync_on_start()

        if setting.mqtt.enabled:
            from .services.mqtt_republish import MqttRepublish
            FlaskThread(target=MqttRepublish().republish, daemon=True).start()
Exemple #12
0
 def get(cls):
     up_time = get_up_time()
     up_min = up_time / 60
     up_min = round(up_min, 2)
     up_min = str(up_min)
     up_hour = up_time / 3600
     up_hour = round(up_hour, 2)
     up_hour = str(up_hour)
     from src import AppSetting
     setting: AppSetting = current_app.config[AppSetting.FLASK_KEY]
     return {
         'version': get_version(),
         'up_time_date': up_time_date,
         'up_min': up_min,
         'up_hour': up_hour,
         'serial': {
             'enabled': setting.mqtt.enabled,
             'status': SerialConnectionListener().status()
         },
         'mqtt': {
             'enabled': setting.mqtt.enabled,
             'status': MqttClient().status()
         }
     }
Exemple #13
0
from src import MqttSetting
from src.mqtt import MqttClient

if __name__ == '__main__':
    MqttClient().start(MqttSetting(), loop_forever=False)
    print(MqttClient().make_topic((MqttClient().config.topic, ) +
                                  ("id", "name")))