openrvdas.logger.readers.mqtt_reader

No module-level documentation available.
  1#!/usr/bin/env python3
  2
  3import logging
  4import random
  5import string
  6import time
  7from queue import Queue
  8
  9# Don't barf if they don't have redis installed. Only complain if
 10# they actually try to use it, below
 11try:
 12    import paho.mqtt.client as mqtt  # import the client | $ pip installing paho-mqtt is necessary
 13    PAHO_ENABLED = True
 14
 15    # Check which paho version is being used, so we know how to call it.
 16    # importlib.metadata is stdlib; the pkg_resources this used to rely on
 17    # ships with setuptools, which recent Python versions no longer install
 18    # into a venv by default. When it was missing, the ModuleNotFoundError
 19    # landed in the handler below and MQTTReader reported that paho-mqtt
 20    # wasn't installed, even though it was.
 21    from importlib.metadata import version as _package_version  # noqa: E402
 22    PAHO_VERSION = _package_version('paho-mqtt')
 23    USE_VERSION_FLAG = int(PAHO_VERSION.split('.')[0]) >= 2
 24except ModuleNotFoundError:
 25    PAHO_ENABLED = False
 26
 27from logger.readers.reader import Reader  # noqa: E402
 28
 29
 30################################################################################
 31class MQTTReader(Reader):
 32    """
 33    Read messages from an mqtt broker
 34    """
 35
 36    def __init__(self, broker, channel, client_name=None,
 37                 port=1883, clean_start=None,
 38                 qos=0, return_as_bytes=False,
 39                 reconnect=True, reconnect_delay=1, max_reconnect_delay=60,
 40                 **kwargs):
 41        """
 42        Read text records from the channel subscription.
 43        ```
 44
 45        broker       MQTT broker to connect, broker format[###.###.#.#]
 46        channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
 47        client_name  Prefix used for `client_id` when connecting to broker.  The `client_id`
 48                     must be unique for each broker connection, so a random string will be
 49                     appended to the provided `client_name`.  If None, a random ID is
 50                     generated for you.
 51        port         broker port, typically 1883
 52        clean_start  Request new session on first connection. Options: True, False,
 53                       or the default of mqtt.MQTT_CLEAN_START_FIRST_ONLY
 54        qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
 55        return_as_bytes
 56                     If true, return message in bytes, otherwise convert to str
 57        reconnect    If True (the default), log a warning and try to reconnect when the
 58                     connection to the broker drops. If False, a dropped connection is
 59                     logged and read() returns None, signalling end of input, so the
 60                     logger stops rather than silently receiving nothing.
 61        reconnect_delay
 62                     Seconds to wait before the first reconnection attempt. The delay
 63                     doubles with each failed attempt, up to max_reconnect_delay.
 64        max_reconnect_delay
 65                     Ceiling, in seconds, for the reconnection backoff.
 66        ```
 67        Instructions on how to start an MQTT broker:
 68
 69        1. First install the Mosquitto Broker :
 70            ```
 71            sudo apt-get update
 72            sudo apt-get install mosquitto
 73            sudo apt-get install mosquitto-clients
 74            ```
 75        2. The mosquitto service starts automatically when downloaded but use :
 76            ```
 77            sudo service mosquitto start
 78            sudo service mosquitto stop
 79            ```
 80            to start and stop the service.
 81
 82        3. To test the install use:
 83            ```
 84            netstat -at
 85            ```
 86            and you should see the MQTT broker which is the port 1883
 87
 88        4. In order to manually subscribe to a client use :
 89            ```
 90            mosquitto_sub -t "example/topic"
 91            ```
 92            and publish a message by using
 93            ```
 94            mosquitto_pub -m "published message" -t "certain/channel"
 95            ```
 96        5. Mosquitto uses a configuration file "mosquitto.conf" which you can
 97           find in /etc/mosquitto 	folder
 98
 99        ```
100        """
101        if not PAHO_ENABLED:
102            raise ModuleNotFoundError('MQTTReader(): paho-mqtt is not installed. Please '
103                                      'try "pip install paho-mqtt" prior to use.')
104        if qos not in [0, 1, 2]:
105            raise ValueError('MQTTReader parameter qos must be integer value 0, 1 or 2. '
106                             f'Found type "{type(qos).__name__}", value "{qos}".')
107
108        # Let's build it!
109        super().__init__(**kwargs)
110
111        def on_connect(client, userdata, flags, rc, properties=None):
112            logging.info(f'Connected With Result Code: {rc}')
113            self.connected = True
114            # Subscribe here rather than once at startup: a broker that has
115            # dropped us forgets our subscriptions, so every (re)connection
116            # has to ask for them again.
117            client.subscribe(self.channel, qos=self.qos)
118
119        def on_disconnect(client, userdata, *args):
120            """Note that we lost the broker.
121
122            The callback signature differs between paho versions:
123              paho 1.x: (client, userdata, rc[, properties])
124              paho 2.x: (client, userdata, disconnect_flags, reason_code, properties)
125            In both, the interesting value is why we were disconnected.
126            """
127            if USE_VERSION_FLAG:
128                reason = args[1] if len(args) > 1 else None
129            else:
130                reason = args[0] if args else None
131            self.connected = False
132            logging.warning('MQTTReader lost connection to broker %s:%d, channel %s: %s',
133                            self.broker, self.port, self.channel, reason)
134
135        def on_message(client, userdata, message):
136            self.queue.put(message)
137
138        self.broker = broker
139        self.channel = channel
140        if client_name:
141            # If user supplied `client_name`, append random chars to it to
142            # attempt to ensure we have a unique `client_id`.
143            rand_id = ''.join(random.choices(string.ascii_lowercase+string.digits, k=6))
144            self.client_id = f'{client_name}-{rand_id}'
145        else:
146            # If None is specified, the underlying mqtt library generates a
147            # unique id for you.
148            self.client_id = None
149        self.port = port
150        if clean_start is None:
151            clean_start = mqtt.MQTT_CLEAN_START_FIRST_ONLY
152        self.clean_start = clean_start
153        self.qos = qos
154        self.return_as_bytes = return_as_bytes
155        self.reconnect = reconnect
156        self.reconnect_delay = reconnect_delay
157        self.max_reconnect_delay = max_reconnect_delay
158        self.connected = False
159        self.queue = Queue()
160
161        try:
162            if USE_VERSION_FLAG:
163                self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, self.client_id)
164            else:
165                self.client = mqtt.Client(self.client_id)
166
167            self.client.on_connect = on_connect
168            self.client.on_disconnect = on_disconnect
169            self.client.on_message = on_message
170
171            # Subscription happens in on_connect, so it is re-established on
172            # every reconnection rather than only on the first connection.
173            if USE_VERSION_FLAG:
174                self.client.connect(broker, port)
175            else:
176                self.client.connect(broker, port, clean_start=clean_start)
177
178        except (mqtt.WebsocketConnectionError, ConnectionRefusedError) as e:
179            logging.error(f'Unable to connect to broker at {broker}:{port} {channel}')
180            raise e
181
182    ############################
183    def _reconnect(self, rc):
184        """Try to reconnect to the broker, backing off between attempts.
185
186        Returns True once reconnected. Blocks until it succeeds, so a broker
187        that is down for a while stalls the logger rather than killing it.
188        """
189        delay = self.reconnect_delay
190        attempt = 0
191        while True:
192            attempt += 1
193            try:
194                self.client.reconnect()
195                logging.warning('MQTTReader reconnected to broker %s:%d, channel %s '
196                                'after %d attempt(s)',
197                                self.broker, self.port, self.channel, attempt)
198                return True
199            except (OSError, mqtt.WebsocketConnectionError) as e:
200                # First failure at warning so it's visible; the rest at info so
201                # a long outage doesn't flood the logs.
202                log = logging.warning if attempt == 1 else logging.info
203                log('MQTTReader reconnect to %s:%d failed (attempt %d): %s. '
204                    'Retrying in %g seconds.',
205                    self.broker, self.port, attempt, e, delay)
206                time.sleep(delay)
207                delay = min(delay * 2, self.max_reconnect_delay)
208
209    ############################
210    def read(self):
211        while True:
212            try:
213                rc = self.client.loop()
214                while not self.queue.empty():
215                    message = self.queue.get()
216                    if message is None:
217                        continue
218                    logging.debug('Got message "%s"', message.payload)
219                    if self.return_as_bytes:
220                        return message.payload
221                    else:
222                        return str(message.payload, 'utf-8')
223
224                # client.loop() returns non-zero when the network loop has
225                # failed - typically because the broker has gone away. Ignoring
226                # it means spinning here forever, silently returning nothing,
227                # which is the symptom reported in issue #578.
228                if rc != mqtt.MQTT_ERR_SUCCESS:
229                    if self.reconnect:
230                        self._reconnect(rc)
231                    else:
232                        logging.warning('MQTTReader connection to broker %s:%d lost '
233                                        '(rc %s) and reconnect is disabled; '
234                                        'returning EOF.',
235                                        self.broker, self.port, rc)
236                        return None
237            except KeyboardInterrupt:
238                self.client.disconnect()
239                exit(0)
class MQTTReader(logger.readers.reader.Reader):
 32class MQTTReader(Reader):
 33    """
 34    Read messages from an mqtt broker
 35    """
 36
 37    def __init__(self, broker, channel, client_name=None,
 38                 port=1883, clean_start=None,
 39                 qos=0, return_as_bytes=False,
 40                 reconnect=True, reconnect_delay=1, max_reconnect_delay=60,
 41                 **kwargs):
 42        """
 43        Read text records from the channel subscription.
 44        ```
 45
 46        broker       MQTT broker to connect, broker format[###.###.#.#]
 47        channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
 48        client_name  Prefix used for `client_id` when connecting to broker.  The `client_id`
 49                     must be unique for each broker connection, so a random string will be
 50                     appended to the provided `client_name`.  If None, a random ID is
 51                     generated for you.
 52        port         broker port, typically 1883
 53        clean_start  Request new session on first connection. Options: True, False,
 54                       or the default of mqtt.MQTT_CLEAN_START_FIRST_ONLY
 55        qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
 56        return_as_bytes
 57                     If true, return message in bytes, otherwise convert to str
 58        reconnect    If True (the default), log a warning and try to reconnect when the
 59                     connection to the broker drops. If False, a dropped connection is
 60                     logged and read() returns None, signalling end of input, so the
 61                     logger stops rather than silently receiving nothing.
 62        reconnect_delay
 63                     Seconds to wait before the first reconnection attempt. The delay
 64                     doubles with each failed attempt, up to max_reconnect_delay.
 65        max_reconnect_delay
 66                     Ceiling, in seconds, for the reconnection backoff.
 67        ```
 68        Instructions on how to start an MQTT broker:
 69
 70        1. First install the Mosquitto Broker :
 71            ```
 72            sudo apt-get update
 73            sudo apt-get install mosquitto
 74            sudo apt-get install mosquitto-clients
 75            ```
 76        2. The mosquitto service starts automatically when downloaded but use :
 77            ```
 78            sudo service mosquitto start
 79            sudo service mosquitto stop
 80            ```
 81            to start and stop the service.
 82
 83        3. To test the install use:
 84            ```
 85            netstat -at
 86            ```
 87            and you should see the MQTT broker which is the port 1883
 88
 89        4. In order to manually subscribe to a client use :
 90            ```
 91            mosquitto_sub -t "example/topic"
 92            ```
 93            and publish a message by using
 94            ```
 95            mosquitto_pub -m "published message" -t "certain/channel"
 96            ```
 97        5. Mosquitto uses a configuration file "mosquitto.conf" which you can
 98           find in /etc/mosquitto 	folder
 99
100        ```
101        """
102        if not PAHO_ENABLED:
103            raise ModuleNotFoundError('MQTTReader(): paho-mqtt is not installed. Please '
104                                      'try "pip install paho-mqtt" prior to use.')
105        if qos not in [0, 1, 2]:
106            raise ValueError('MQTTReader parameter qos must be integer value 0, 1 or 2. '
107                             f'Found type "{type(qos).__name__}", value "{qos}".')
108
109        # Let's build it!
110        super().__init__(**kwargs)
111
112        def on_connect(client, userdata, flags, rc, properties=None):
113            logging.info(f'Connected With Result Code: {rc}')
114            self.connected = True
115            # Subscribe here rather than once at startup: a broker that has
116            # dropped us forgets our subscriptions, so every (re)connection
117            # has to ask for them again.
118            client.subscribe(self.channel, qos=self.qos)
119
120        def on_disconnect(client, userdata, *args):
121            """Note that we lost the broker.
122
123            The callback signature differs between paho versions:
124              paho 1.x: (client, userdata, rc[, properties])
125              paho 2.x: (client, userdata, disconnect_flags, reason_code, properties)
126            In both, the interesting value is why we were disconnected.
127            """
128            if USE_VERSION_FLAG:
129                reason = args[1] if len(args) > 1 else None
130            else:
131                reason = args[0] if args else None
132            self.connected = False
133            logging.warning('MQTTReader lost connection to broker %s:%d, channel %s: %s',
134                            self.broker, self.port, self.channel, reason)
135
136        def on_message(client, userdata, message):
137            self.queue.put(message)
138
139        self.broker = broker
140        self.channel = channel
141        if client_name:
142            # If user supplied `client_name`, append random chars to it to
143            # attempt to ensure we have a unique `client_id`.
144            rand_id = ''.join(random.choices(string.ascii_lowercase+string.digits, k=6))
145            self.client_id = f'{client_name}-{rand_id}'
146        else:
147            # If None is specified, the underlying mqtt library generates a
148            # unique id for you.
149            self.client_id = None
150        self.port = port
151        if clean_start is None:
152            clean_start = mqtt.MQTT_CLEAN_START_FIRST_ONLY
153        self.clean_start = clean_start
154        self.qos = qos
155        self.return_as_bytes = return_as_bytes
156        self.reconnect = reconnect
157        self.reconnect_delay = reconnect_delay
158        self.max_reconnect_delay = max_reconnect_delay
159        self.connected = False
160        self.queue = Queue()
161
162        try:
163            if USE_VERSION_FLAG:
164                self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, self.client_id)
165            else:
166                self.client = mqtt.Client(self.client_id)
167
168            self.client.on_connect = on_connect
169            self.client.on_disconnect = on_disconnect
170            self.client.on_message = on_message
171
172            # Subscription happens in on_connect, so it is re-established on
173            # every reconnection rather than only on the first connection.
174            if USE_VERSION_FLAG:
175                self.client.connect(broker, port)
176            else:
177                self.client.connect(broker, port, clean_start=clean_start)
178
179        except (mqtt.WebsocketConnectionError, ConnectionRefusedError) as e:
180            logging.error(f'Unable to connect to broker at {broker}:{port} {channel}')
181            raise e
182
183    ############################
184    def _reconnect(self, rc):
185        """Try to reconnect to the broker, backing off between attempts.
186
187        Returns True once reconnected. Blocks until it succeeds, so a broker
188        that is down for a while stalls the logger rather than killing it.
189        """
190        delay = self.reconnect_delay
191        attempt = 0
192        while True:
193            attempt += 1
194            try:
195                self.client.reconnect()
196                logging.warning('MQTTReader reconnected to broker %s:%d, channel %s '
197                                'after %d attempt(s)',
198                                self.broker, self.port, self.channel, attempt)
199                return True
200            except (OSError, mqtt.WebsocketConnectionError) as e:
201                # First failure at warning so it's visible; the rest at info so
202                # a long outage doesn't flood the logs.
203                log = logging.warning if attempt == 1 else logging.info
204                log('MQTTReader reconnect to %s:%d failed (attempt %d): %s. '
205                    'Retrying in %g seconds.',
206                    self.broker, self.port, attempt, e, delay)
207                time.sleep(delay)
208                delay = min(delay * 2, self.max_reconnect_delay)
209
210    ############################
211    def read(self):
212        while True:
213            try:
214                rc = self.client.loop()
215                while not self.queue.empty():
216                    message = self.queue.get()
217                    if message is None:
218                        continue
219                    logging.debug('Got message "%s"', message.payload)
220                    if self.return_as_bytes:
221                        return message.payload
222                    else:
223                        return str(message.payload, 'utf-8')
224
225                # client.loop() returns non-zero when the network loop has
226                # failed - typically because the broker has gone away. Ignoring
227                # it means spinning here forever, silently returning nothing,
228                # which is the symptom reported in issue #578.
229                if rc != mqtt.MQTT_ERR_SUCCESS:
230                    if self.reconnect:
231                        self._reconnect(rc)
232                    else:
233                        logging.warning('MQTTReader connection to broker %s:%d lost '
234                                        '(rc %s) and reconnect is disabled; '
235                                        'returning EOF.',
236                                        self.broker, self.port, rc)
237                        return None
238            except KeyboardInterrupt:
239                self.client.disconnect()
240                exit(0)

Read messages from an mqtt broker

MQTTReader( broker, channel, client_name=None, port=1883, clean_start=None, qos=0, return_as_bytes=False, reconnect=True, reconnect_delay=1, max_reconnect_delay=60, **kwargs)
 37    def __init__(self, broker, channel, client_name=None,
 38                 port=1883, clean_start=None,
 39                 qos=0, return_as_bytes=False,
 40                 reconnect=True, reconnect_delay=1, max_reconnect_delay=60,
 41                 **kwargs):
 42        """
 43        Read text records from the channel subscription.
 44        ```
 45
 46        broker       MQTT broker to connect, broker format[###.###.#.#]
 47        channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
 48        client_name  Prefix used for `client_id` when connecting to broker.  The `client_id`
 49                     must be unique for each broker connection, so a random string will be
 50                     appended to the provided `client_name`.  If None, a random ID is
 51                     generated for you.
 52        port         broker port, typically 1883
 53        clean_start  Request new session on first connection. Options: True, False,
 54                       or the default of mqtt.MQTT_CLEAN_START_FIRST_ONLY
 55        qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
 56        return_as_bytes
 57                     If true, return message in bytes, otherwise convert to str
 58        reconnect    If True (the default), log a warning and try to reconnect when the
 59                     connection to the broker drops. If False, a dropped connection is
 60                     logged and read() returns None, signalling end of input, so the
 61                     logger stops rather than silently receiving nothing.
 62        reconnect_delay
 63                     Seconds to wait before the first reconnection attempt. The delay
 64                     doubles with each failed attempt, up to max_reconnect_delay.
 65        max_reconnect_delay
 66                     Ceiling, in seconds, for the reconnection backoff.
 67        ```
 68        Instructions on how to start an MQTT broker:
 69
 70        1. First install the Mosquitto Broker :
 71            ```
 72            sudo apt-get update
 73            sudo apt-get install mosquitto
 74            sudo apt-get install mosquitto-clients
 75            ```
 76        2. The mosquitto service starts automatically when downloaded but use :
 77            ```
 78            sudo service mosquitto start
 79            sudo service mosquitto stop
 80            ```
 81            to start and stop the service.
 82
 83        3. To test the install use:
 84            ```
 85            netstat -at
 86            ```
 87            and you should see the MQTT broker which is the port 1883
 88
 89        4. In order to manually subscribe to a client use :
 90            ```
 91            mosquitto_sub -t "example/topic"
 92            ```
 93            and publish a message by using
 94            ```
 95            mosquitto_pub -m "published message" -t "certain/channel"
 96            ```
 97        5. Mosquitto uses a configuration file "mosquitto.conf" which you can
 98           find in /etc/mosquitto 	folder
 99
100        ```
101        """
102        if not PAHO_ENABLED:
103            raise ModuleNotFoundError('MQTTReader(): paho-mqtt is not installed. Please '
104                                      'try "pip install paho-mqtt" prior to use.')
105        if qos not in [0, 1, 2]:
106            raise ValueError('MQTTReader parameter qos must be integer value 0, 1 or 2. '
107                             f'Found type "{type(qos).__name__}", value "{qos}".')
108
109        # Let's build it!
110        super().__init__(**kwargs)
111
112        def on_connect(client, userdata, flags, rc, properties=None):
113            logging.info(f'Connected With Result Code: {rc}')
114            self.connected = True
115            # Subscribe here rather than once at startup: a broker that has
116            # dropped us forgets our subscriptions, so every (re)connection
117            # has to ask for them again.
118            client.subscribe(self.channel, qos=self.qos)
119
120        def on_disconnect(client, userdata, *args):
121            """Note that we lost the broker.
122
123            The callback signature differs between paho versions:
124              paho 1.x: (client, userdata, rc[, properties])
125              paho 2.x: (client, userdata, disconnect_flags, reason_code, properties)
126            In both, the interesting value is why we were disconnected.
127            """
128            if USE_VERSION_FLAG:
129                reason = args[1] if len(args) > 1 else None
130            else:
131                reason = args[0] if args else None
132            self.connected = False
133            logging.warning('MQTTReader lost connection to broker %s:%d, channel %s: %s',
134                            self.broker, self.port, self.channel, reason)
135
136        def on_message(client, userdata, message):
137            self.queue.put(message)
138
139        self.broker = broker
140        self.channel = channel
141        if client_name:
142            # If user supplied `client_name`, append random chars to it to
143            # attempt to ensure we have a unique `client_id`.
144            rand_id = ''.join(random.choices(string.ascii_lowercase+string.digits, k=6))
145            self.client_id = f'{client_name}-{rand_id}'
146        else:
147            # If None is specified, the underlying mqtt library generates a
148            # unique id for you.
149            self.client_id = None
150        self.port = port
151        if clean_start is None:
152            clean_start = mqtt.MQTT_CLEAN_START_FIRST_ONLY
153        self.clean_start = clean_start
154        self.qos = qos
155        self.return_as_bytes = return_as_bytes
156        self.reconnect = reconnect
157        self.reconnect_delay = reconnect_delay
158        self.max_reconnect_delay = max_reconnect_delay
159        self.connected = False
160        self.queue = Queue()
161
162        try:
163            if USE_VERSION_FLAG:
164                self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, self.client_id)
165            else:
166                self.client = mqtt.Client(self.client_id)
167
168            self.client.on_connect = on_connect
169            self.client.on_disconnect = on_disconnect
170            self.client.on_message = on_message
171
172            # Subscription happens in on_connect, so it is re-established on
173            # every reconnection rather than only on the first connection.
174            if USE_VERSION_FLAG:
175                self.client.connect(broker, port)
176            else:
177                self.client.connect(broker, port, clean_start=clean_start)
178
179        except (mqtt.WebsocketConnectionError, ConnectionRefusedError) as e:
180            logging.error(f'Unable to connect to broker at {broker}:{port} {channel}')
181            raise e

Read text records from the channel subscription.


broker       MQTT broker to connect, broker format[###.###.#.#]
channel      MQTT channel to read from, channel format[@broker/path_of_subscripton]
client_name  Prefix used for `client_id` when connecting to broker.  The `client_id`
             must be unique for each broker connection, so a random string will be
             appended to the provided `client_name`.  If None, a random ID is
             generated for you.
port         broker port, typically 1883
clean_start  Request new session on first connection. Options: True, False,
               or the default of mqtt.MQTT_CLEAN_START_FIRST_ONLY
qos          Quality of service: 0 = at most once, 1 = at least once, 2 = exactly once
return_as_bytes
             If true, return message in bytes, otherwise convert to str
reconnect    If True (the default), log a warning and try to reconnect when the
             connection to the broker drops. If False, a dropped connection is
             logged and read() returns None, signalling end of input, so the
             logger stops rather than silently receiving nothing.
reconnect_delay
             Seconds to wait before the first reconnection attempt. The delay
             doubles with each failed attempt, up to max_reconnect_delay.
max_reconnect_delay
             Ceiling, in seconds, for the reconnection backoff.

Instructions on how to start an MQTT broker:

  1. First install the Mosquitto Broker :

    sudo apt-get update
    sudo apt-get install mosquitto
    sudo apt-get install mosquitto-clients
    
  2. The mosquitto service starts automatically when downloaded but use :

    sudo service mosquitto start
    sudo service mosquitto stop
    

    to start and stop the service.

  3. To test the install use:

    netstat -at
    

    and you should see the MQTT broker which is the port 1883

  4. In order to manually subscribe to a client use :

    mosquitto_sub -t "example/topic"
    

    and publish a message by using

    mosquitto_pub -m "published message" -t "certain/channel"
    
  5. Mosquitto uses a configuration file "mosquitto.conf" which you can find in /etc/mosquitto folder

```

broker
channel
port
clean_start
qos
return_as_bytes
reconnect
reconnect_delay
max_reconnect_delay
connected
queue
def read(self):
211    def read(self):
212        while True:
213            try:
214                rc = self.client.loop()
215                while not self.queue.empty():
216                    message = self.queue.get()
217                    if message is None:
218                        continue
219                    logging.debug('Got message "%s"', message.payload)
220                    if self.return_as_bytes:
221                        return message.payload
222                    else:
223                        return str(message.payload, 'utf-8')
224
225                # client.loop() returns non-zero when the network loop has
226                # failed - typically because the broker has gone away. Ignoring
227                # it means spinning here forever, silently returning nothing,
228                # which is the symptom reported in issue #578.
229                if rc != mqtt.MQTT_ERR_SUCCESS:
230                    if self.reconnect:
231                        self._reconnect(rc)
232                    else:
233                        logging.warning('MQTTReader connection to broker %s:%d lost '
234                                        '(rc %s) and reconnect is disabled; '
235                                        'returning EOF.',
236                                        self.broker, self.port, rc)
237                        return None
238            except KeyboardInterrupt:
239                self.client.disconnect()
240                exit(0)

read() should return None when there are no more records.