openrvdas.logger.writers.mqtt_writer

No module-level documentation available.
 1#!/usr/bin/env python3
 2
 3import logging
 4
 5# Don't barf if they don't have paho mqtt installed. Only complain if
 6# they actually try to use it, below. If it *is* installed, check which
 7# version, so we know how to call it.
 8try:
 9    import paho.mqtt.client as mqtt  # import the client | $ pip installing paho-mqtt is necessary
10    PAHO_ENABLED = True
11
12    # Check which paho version is being used, so we know how to call it.
13    # importlib.metadata is stdlib; the pkg_resources this used to rely on
14    # ships with setuptools, which recent Python versions no longer install
15    # into a venv by default. When it was missing, the ModuleNotFoundError
16    # landed in the handler below and MQTTWriter reported that paho-mqtt
17    # wasn't installed, even though it was.
18    from importlib.metadata import version as _package_version  # noqa: E402
19    PAHO_VERSION = _package_version('paho-mqtt')
20    USE_VERSION_FLAG = int(PAHO_VERSION.split('.')[0]) >= 2
21except ModuleNotFoundError:
22    PAHO_ENABLED = False
23
24from logger.writers.writer import Writer  # noqa: E402
25
26
27class MQTTWriter(Writer):
28    """Write to paho-mqtt broker channel."""
29
30    def __init__(self, broker, channel, client_name=None, qos=0, **kwargs):
31        """
32        Write text records to a paho-mqtt broker channel.
33        ```
34        broker       MQTT broker to connect, broker format[###.###.#.###]
35        channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
36        client_name  Deprecated
37        qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
38
39        ```
40        See /readers/mqtt_reader.py for info on how to start a broker
41        """
42        super().__init__(**kwargs)  # processes 'quiet' and type hints
43
44        if not PAHO_ENABLED:
45            raise ModuleNotFoundError('MQTTReader(): paho-mqtt is not installed. Please '
46                                      'try "pip install paho-mqtt" prior to use.')
47        if qos not in [0, 1, 2]:
48            raise ValueError('MQTTWriter parameter qos must be integer value 0, 1 or 2. '
49                             f'Found type "{type(qos).__name__}", value "{qos}".')
50        self.broker = broker
51        self.channel = channel
52        self.client_name = client_name
53        self.qos = qos
54
55        try:
56            if USE_VERSION_FLAG:
57                self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
58            else:
59                self.client = mqtt.Client()
60
61            self.client.connect(broker)
62            self.client.subscribe(channel)
63
64            self.client.loop_start()
65
66        except mqtt.WebsocketConnectionError as e:
67            logging.error('Unable to connect to broker at %s:%s',
68                          self.broker, self.channel)
69            raise e
70
71    ############################
72    def __del__(self):
73        """Clean up the connection once finished"""
74        self.client.loop_stop()
75        self.client.disconnect()
76
77    ############################
78    def write(self, record: str):
79
80        # See if it's something we can process, and if not, try digesting
81        if not self.can_process_record(record):  # inherited from BaseModule()
82            self.digest_record(record)  # inherited from BaseModule()
83            return
84
85        # If record is not a string, try converting to JSON. If we don't know
86        # how, throw a hail Mary and force it into str format
87        # if not type(record) is str:
88        #  if type(record) in [int, float, bool, list, dict]:
89        #    record = json.dumps(record)
90        #  else:
91        #    record = str(record)
92
93        try:
94            self.client.publish(self.channel, record, self.qos)
95        except mqtt.WebsocketConnectionError as e:
96            logging.error('Unable to connect to broker at %s:%d',
97                          self.broker, self.channel)
98            raise e
class MQTTWriter(logger.writers.writer.Writer):
28class MQTTWriter(Writer):
29    """Write to paho-mqtt broker channel."""
30
31    def __init__(self, broker, channel, client_name=None, qos=0, **kwargs):
32        """
33        Write text records to a paho-mqtt broker channel.
34        ```
35        broker       MQTT broker to connect, broker format[###.###.#.###]
36        channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
37        client_name  Deprecated
38        qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
39
40        ```
41        See /readers/mqtt_reader.py for info on how to start a broker
42        """
43        super().__init__(**kwargs)  # processes 'quiet' and type hints
44
45        if not PAHO_ENABLED:
46            raise ModuleNotFoundError('MQTTReader(): paho-mqtt is not installed. Please '
47                                      'try "pip install paho-mqtt" prior to use.')
48        if qos not in [0, 1, 2]:
49            raise ValueError('MQTTWriter parameter qos must be integer value 0, 1 or 2. '
50                             f'Found type "{type(qos).__name__}", value "{qos}".')
51        self.broker = broker
52        self.channel = channel
53        self.client_name = client_name
54        self.qos = qos
55
56        try:
57            if USE_VERSION_FLAG:
58                self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
59            else:
60                self.client = mqtt.Client()
61
62            self.client.connect(broker)
63            self.client.subscribe(channel)
64
65            self.client.loop_start()
66
67        except mqtt.WebsocketConnectionError as e:
68            logging.error('Unable to connect to broker at %s:%s',
69                          self.broker, self.channel)
70            raise e
71
72    ############################
73    def __del__(self):
74        """Clean up the connection once finished"""
75        self.client.loop_stop()
76        self.client.disconnect()
77
78    ############################
79    def write(self, record: str):
80
81        # See if it's something we can process, and if not, try digesting
82        if not self.can_process_record(record):  # inherited from BaseModule()
83            self.digest_record(record)  # inherited from BaseModule()
84            return
85
86        # If record is not a string, try converting to JSON. If we don't know
87        # how, throw a hail Mary and force it into str format
88        # if not type(record) is str:
89        #  if type(record) in [int, float, bool, list, dict]:
90        #    record = json.dumps(record)
91        #  else:
92        #    record = str(record)
93
94        try:
95            self.client.publish(self.channel, record, self.qos)
96        except mqtt.WebsocketConnectionError as e:
97            logging.error('Unable to connect to broker at %s:%d',
98                          self.broker, self.channel)
99            raise e

Write to paho-mqtt broker channel.

MQTTWriter(broker, channel, client_name=None, qos=0, **kwargs)
31    def __init__(self, broker, channel, client_name=None, qos=0, **kwargs):
32        """
33        Write text records to a paho-mqtt broker channel.
34        ```
35        broker       MQTT broker to connect, broker format[###.###.#.###]
36        channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
37        client_name  Deprecated
38        qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
39
40        ```
41        See /readers/mqtt_reader.py for info on how to start a broker
42        """
43        super().__init__(**kwargs)  # processes 'quiet' and type hints
44
45        if not PAHO_ENABLED:
46            raise ModuleNotFoundError('MQTTReader(): paho-mqtt is not installed. Please '
47                                      'try "pip install paho-mqtt" prior to use.')
48        if qos not in [0, 1, 2]:
49            raise ValueError('MQTTWriter parameter qos must be integer value 0, 1 or 2. '
50                             f'Found type "{type(qos).__name__}", value "{qos}".')
51        self.broker = broker
52        self.channel = channel
53        self.client_name = client_name
54        self.qos = qos
55
56        try:
57            if USE_VERSION_FLAG:
58                self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
59            else:
60                self.client = mqtt.Client()
61
62            self.client.connect(broker)
63            self.client.subscribe(channel)
64
65            self.client.loop_start()
66
67        except mqtt.WebsocketConnectionError as e:
68            logging.error('Unable to connect to broker at %s:%s',
69                          self.broker, self.channel)
70            raise e

Write text records to a paho-mqtt broker channel.

broker       MQTT broker to connect, broker format[###.###.#.###]
channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
client_name  Deprecated
qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once

See /readers/mqtt_reader.py for info on how to start a broker

broker
channel
client_name
qos
def write(self, record: str):
79    def write(self, record: str):
80
81        # See if it's something we can process, and if not, try digesting
82        if not self.can_process_record(record):  # inherited from BaseModule()
83            self.digest_record(record)  # inherited from BaseModule()
84            return
85
86        # If record is not a string, try converting to JSON. If we don't know
87        # how, throw a hail Mary and force it into str format
88        # if not type(record) is str:
89        #  if type(record) in [int, float, bool, list, dict]:
90        #    record = json.dumps(record)
91        #  else:
92        #    record = str(record)
93
94        try:
95            self.client.publish(self.channel, record, self.qos)
96        except mqtt.WebsocketConnectionError as e:
97            logging.error('Unable to connect to broker at %s:%d',
98                          self.broker, self.channel)
99            raise e

Core method - write a record that we've been passed.