Skip to content

Commit 003962e

Browse files
authored
Merge pull request #6 from brentru/expose-properties
Exposing attributes used by client libraries
2 parents 25b344a + 35ba546 commit 003962e

File tree

1 file changed

+88
-89
lines changed

1 file changed

+88
-89
lines changed

adafruit_minimqtt.py

Lines changed: 88 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -115,33 +115,32 @@ def __init__(self, socket, broker, port=None, username=None,
115115
if port is not None:
116116
self.port = port
117117
# session identifiers
118-
self._user = username
118+
self.user = username
119119
# [MQTT-3.1.3.5]
120-
self._pass = password
121-
if self._pass is not None and len(password.encode('utf-8')) > MQTT_TOPIC_LENGTH_LIMIT:
120+
self.password = password
121+
if self.password is not None and len(password.encode('utf-8')) > MQTT_TOPIC_LENGTH_LIMIT:
122122
raise MMQTTException('Password length is too large.')
123123
if client_id is not None:
124124
# user-defined client_id MAY allow client_id's > 23 bytes or
125125
# non-alpha-numeric characters
126-
self._client_id = client_id
126+
self.client_id = client_id
127127
else:
128128
# assign a unique client_id
129-
self._client_id = 'cpy{0}{1}'.format(microcontroller.cpu.uid[randint(0, 15)],
130-
randint(0, 9))
129+
self.client_id = 'cpy{0}{1}'.format(microcontroller.cpu.uid[randint(0, 15)],
130+
randint(0, 9))
131131
# generated client_id's enforce spec.'s length rules
132-
if len(self._client_id) > 23 or not self._client_id:
132+
if len(self.client_id) > 23 or not self.client_id:
133133
raise ValueError('MQTT Client ID must be between 1 and 23 bytes')
134-
self._logger = None
134+
self.keep_alive = keep_alive
135+
self.user_data = None
136+
self.logger = None
135137
if log is True:
136-
self._logger = logging.getLogger('log')
137-
self._logger.setLevel(logging.INFO)
138+
self.logger = logging.getLogger('log')
139+
self.logger.setLevel(logging.INFO)
138140
self._sock = None
139141
self._is_connected = False
140142
self._msg_size_lim = MQTT_MSG_SZ_LIM
141-
self.packet_id = 0
142-
self._keep_alive = keep_alive
143143
self._pid = 0
144-
self._user_data = None
145144
self._timestamp = 0
146145
# List of subscribed topics, used for tracking
147146
self._subscribed_topics = []
@@ -177,8 +176,8 @@ def last_will(self, topic=None, message=None, qos=0, retain=False):
177176
raise MMQTTException('Last Will should be defined before connect() is called.')
178177
if qos < 0 or qos > 2:
179178
raise MMQTTException("Invalid QoS level, must be between 0 and 2.")
180-
if self._logger is not None:
181-
self._logger.debug('Setting last will properties')
179+
if self.logger is not None:
180+
self.logger.debug('Setting last will properties')
182181
self._lw_qos = qos
183182
self._lw_topic = topic
184183
self._lw_msg = message
@@ -190,14 +189,14 @@ def connect(self, clean_session=True):
190189
:param bool clean_session: Establishes a persistent session.
191190
"""
192191
self._set_interface()
193-
if self._logger is not None:
194-
self._logger.debug('Creating new socket')
192+
if self.logger is not None:
193+
self.logger.debug('Creating new socket')
195194
self._sock = self._socket.socket()
196195
self._sock.settimeout(10)
197196
if self.port == 8883:
198197
try:
199-
if self._logger is not None:
200-
self._logger.debug('Attempting to establish secure MQTT connection...')
198+
if self.logger is not None:
199+
self.logger.debug('Attempting to establish secure MQTT connection...')
201200
self._sock.connect((self.broker, self.port), TLS_MODE)
202201
except RuntimeError:
203202
raise MMQTTException("Invalid broker address defined.")
@@ -207,8 +206,8 @@ def connect(self, clean_session=True):
207206
else:
208207
addr = (self.broker, self.port)
209208
try:
210-
if self._logger is not None:
211-
self._logger.debug('Attempting to establish insecure MQTT connection...')
209+
if self.logger is not None:
210+
self.logger.debug('Attempting to establish insecure MQTT connection...')
212211
#self._sock.connect((self.broker, self.port), TCP_MODE)
213212
self._sock.connect(addr, TCP_MODE)
214213
except RuntimeError as e:
@@ -223,14 +222,14 @@ def connect(self, clean_session=True):
223222
var_header[6] = clean_session << 1
224223

225224
# Set up variable header and remaining_length
226-
remaining_length = 12 + len(self._client_id)
227-
if self._user is not None:
228-
remaining_length += 2 + len(self._user) + 2 + len(self._pass)
225+
remaining_length = 12 + len(self.client_id)
226+
if self.user is not None:
227+
remaining_length += 2 + len(self.user) + 2 + len(self.password)
229228
var_header[6] |= 0xC0
230-
if self._keep_alive:
231-
assert self._keep_alive < MQTT_TOPIC_LENGTH_LIMIT
232-
var_header[7] |= self._keep_alive >> 8
233-
var_header[8] |= self._keep_alive & 0x00FF
229+
if self.keep_alive:
230+
assert self.keep_alive < MQTT_TOPIC_LENGTH_LIMIT
231+
var_header[7] |= self.keep_alive >> 8
232+
var_header[8] |= self.keep_alive & 0x00FF
234233
if self._lw_topic:
235234
remaining_length += 2 + len(self._lw_topic) + 2 + len(self._lw_msg)
236235
var_header[6] |= 0x4 | (self._lw_qos & 0x1) << 3 | (self._lw_qos & 0x2) << 3
@@ -254,25 +253,25 @@ def connect(self, clean_session=True):
254253
fixed_header.append(remaining_length)
255254
fixed_header.append(0x00)
256255

257-
if self._logger is not None:
258-
self._logger.debug('Sending CONNECT to broker')
259-
self._logger.debug('Fixed Header: {}\nVariable Header: {}'.format(fixed_header,
260-
var_header))
256+
if self.logger is not None:
257+
self.logger.debug('Sending CONNECT to broker')
258+
self.logger.debug('Fixed Header: {}\nVariable Header: {}'.format(fixed_header,
259+
var_header))
261260
self._sock.write(fixed_header)
262261
self._sock.write(var_header)
263262
# [MQTT-3.1.3-4]
264-
self._send_str(self._client_id)
263+
self._send_str(self.client_id)
265264
if self._lw_topic:
266265
# [MQTT-3.1.3-11]
267266
self._send_str(self._lw_topic)
268267
self._send_str(self._lw_msg)
269-
if self._user is None:
270-
self._user = None
268+
if self.user is None:
269+
self.user = None
271270
else:
272-
self._send_str(self._user)
273-
self._send_str(self._pass)
274-
if self._logger is not None:
275-
self._logger.debug('Receiving CONNACK packet from broker')
271+
self._send_str(self.user)
272+
self._send_str(self.password)
273+
if self.logger is not None:
274+
self.logger.debug('Receiving CONNACK packet from broker')
276275
while True:
277276
op = self._wait_for_msg()
278277
if op == 32:
@@ -283,34 +282,34 @@ def connect(self, clean_session=True):
283282
self._is_connected = True
284283
result = rc[0] & 1
285284
if self.on_connect is not None:
286-
self.on_connect(self, self._user_data, result, rc[2])
285+
self.on_connect(self, self.user_data, result, rc[2])
287286
return result
288287

289288
def disconnect(self):
290289
"""Disconnects the MiniMQTT client from the MQTT broker.
291290
"""
292291
self.is_connected()
293-
if self._logger is not None:
294-
self._logger.debug('Sending DISCONNECT packet to broker')
292+
if self.logger is not None:
293+
self.logger.debug('Sending DISCONNECT packet to broker')
295294
self._sock.write(MQTT_DISCONNECT)
296-
if self._logger is not None:
297-
self._logger.debug('Closing socket')
295+
if self.logger is not None:
296+
self.logger.debug('Closing socket')
298297
self._sock.close()
299298
self._is_connected = False
300299
self._subscribed_topics = None
301300
if self.on_disconnect is not None:
302-
self.on_disconnect(self, self._user_data, 0)
301+
self.on_disconnect(self, self.user_data, 0)
303302

304303
def ping(self):
305304
"""Pings the MQTT Broker to confirm if the broker is alive or if
306305
there is an active network connection.
307306
"""
308307
self.is_connected()
309-
if self._logger is not None:
310-
self._logger.debug('Sending PINGREQ')
308+
if self.logger is not None:
309+
self.logger.debug('Sending PINGREQ')
311310
self._sock.write(MQTT_PINGREQ)
312-
if self._logger is not None:
313-
self._logger.debug('Checking PINGRESP')
311+
if self.logger is not None:
312+
self.logger.debug('Checking PINGRESP')
314313
while True:
315314
op = self._wait_for_msg(0.5)
316315
if op == 208:
@@ -373,23 +372,23 @@ def publish(self, topic, msg, retain=False, qos=0):
373372
sz >>= 7
374373
i += 1
375374
pkt[i] = sz
376-
if self._logger is not None:
377-
self._logger.debug('Sending PUBLISH\nTopic: {0}\nMsg: {1}\
375+
if self.logger is not None:
376+
self.logger.debug('Sending PUBLISH\nTopic: {0}\nMsg: {1}\
378377
\nQoS: {2}\nRetain? {3}'.format(topic, msg, qos, retain))
379378
self._sock.write(pkt)
380379
self._send_str(topic)
381380
if qos == 0:
382381
if self.on_publish is not None:
383-
self.on_publish(self, self._user_data, topic, self._pid)
382+
self.on_publish(self, self.user_data, topic, self._pid)
384383
if qos > 0:
385384
self._pid += 1
386385
pid = self._pid
387386
struct.pack_into("!H", pkt, 0, pid)
388387
self._sock.write(pkt)
389388
if self.on_publish is not None:
390-
self.on_publish(self, self._user_data, topic, pid)
391-
if self._logger is not None:
392-
self._logger.debug('Sending PUBACK')
389+
self.on_publish(self, self.user_data, topic, pid)
390+
if self.logger is not None:
391+
self.logger.debug('Sending PUBACK')
393392
self._sock.write(msg)
394393
if qos == 1:
395394
while True:
@@ -401,12 +400,12 @@ def publish(self, topic, msg, retain=False, qos=0):
401400
rcv_pid = rcv_pid[0] << 0x08 | rcv_pid[1]
402401
if pid == rcv_pid:
403402
if self.on_publish is not None:
404-
self.on_publish(self, self._user_data, topic, rcv_pid)
403+
self.on_publish(self, self.user_data, topic, rcv_pid)
405404
return
406405
elif qos == 2:
407406
assert 0
408407
if self.on_publish is not None:
409-
self.on_publish(self, self._user_data, topic, rcv_pid)
408+
self.on_publish(self, self.user_data, topic, rcv_pid)
410409

411410
def subscribe(self, topic, qos=0):
412411
"""Subscribes to a topic on the MQTT Broker.
@@ -466,9 +465,9 @@ def subscribe(self, topic, qos=0):
466465
topic_size = len(t).to_bytes(2, 'big')
467466
qos_byte = q.to_bytes(1, 'big')
468467
packet += topic_size + t + qos_byte
469-
if self._logger is not None:
468+
if self.logger is not None:
470469
for t, q in topics:
471-
self._logger.debug('SUBSCRIBING to topic {0} with QoS {1}'.format(t, q))
470+
self.logger.debug('SUBSCRIBING to topic {0} with QoS {1}'.format(t, q))
472471
self._sock.write(packet)
473472
while True:
474473
op = self._wait_for_msg()
@@ -479,7 +478,7 @@ def subscribe(self, topic, qos=0):
479478
raise MMQTTException('SUBACK Failure!')
480479
for t, q in topics:
481480
if self.on_subscribe is not None:
482-
self.on_subscribe(self, self._user_data, t, q)
481+
self.on_subscribe(self, self.user_data, t, q)
483482
self._subscribed_topics.append(t)
484483
return
485484

@@ -521,12 +520,12 @@ def unsubscribe(self, topic):
521520
for t in topics:
522521
topic_size = len(t).to_bytes(2, 'big')
523522
packet += topic_size + t
524-
if self._logger is not None:
523+
if self.logger is not None:
525524
for t in topics:
526-
self._logger.debug('UNSUBSCRIBING from topic {0}.'.format(t))
525+
self.logger.debug('UNSUBSCRIBING from topic {0}.'.format(t))
527526
self._sock.write(packet)
528-
if self._logger is not None:
529-
self._logger.debug('Waiting for UNSUBACK...')
527+
if self.logger is not None:
528+
self.logger.debug('Waiting for UNSUBACK...')
530529
while True:
531530
op = self._wait_for_msg()
532531
if op == 176:
@@ -536,7 +535,7 @@ def unsubscribe(self, topic):
536535
assert return_code[1] == packet_id_bytes[0] and return_code[2] == packet_id_bytes[1]
537536
for t in topics:
538537
if self.on_unsubscribe is not None:
539-
self.on_unsubscribe(self, self._user_data, t, self._pid)
538+
self.on_unsubscribe(self, self.user_data, t, self._pid)
540539
self._subscribed_topics.remove(t)
541540
return
542541

@@ -558,12 +557,12 @@ def reconnect_socket(self):
558557
"""Re-establishes the socket's connection with the MQTT broker.
559558
"""
560559
try:
561-
if self._logger is not None:
562-
self._logger.debug("Attempting to reconnect with MQTT Broker...")
560+
if self.logger is not None:
561+
self.logger.debug("Attempting to reconnect with MQTT Broker...")
563562
self.reconnect()
564563
except RuntimeError as err:
565-
if self._logger is not None:
566-
self._logger.debug('Failed to reconnect with MQTT Broker, retrying...', err)
564+
if self.logger is not None:
565+
self.logger.debug('Failed to reconnect with MQTT Broker, retrying...', err)
567566
time.sleep(1)
568567
self.reconnect_socket()
569568

@@ -572,12 +571,12 @@ def reconnect_wifi(self):
572571
"""
573572
while not self.is_wifi_connected:
574573
try:
575-
if self._logger is not None:
576-
self._logger.debug('Connecting to WiFi AP...')
574+
if self.logger is not None:
575+
self.logger.debug('Connecting to WiFi AP...')
577576
self._wifi.connect()
578577
except (RuntimeError, ValueError):
579-
if self._logger is not None:
580-
self._logger.debug('Failed to reset WiFi module, retrying...')
578+
if self.logger is not None:
579+
self.logger.debug('Failed to reset WiFi module, retrying...')
581580
time.sleep(1)
582581
# we just reconnected, is the socket still connected?
583582
if not self.is_sock_connected:
@@ -587,14 +586,14 @@ def reconnect(self, resub_topics=True):
587586
"""Attempts to reconnect to the MQTT broker.
588587
:param bool resub_topics: Resubscribe to previously subscribed topics.
589588
"""
590-
if self._logger is not None:
591-
self._logger.debug('Attempting to reconnect with MQTT broker')
589+
if self.logger is not None:
590+
self.logger.debug('Attempting to reconnect with MQTT broker')
592591
self.connect()
593-
if self._logger is not None:
594-
self._logger.debug('Reconnected with broker')
592+
if self.logger is not None:
593+
self.logger.debug('Reconnected with broker')
595594
if resub_topics:
596-
if self._logger is not None:
597-
self._logger.debug('Attempting to resubscribe to previously subscribed topics.')
595+
if self.logger is not None:
596+
self.logger.debug('Attempting to resubscribe to previously subscribed topics.')
598597
while self._subscribed_topics:
599598
feed = self._subscribed_topics.pop()
600599
self.subscribe(feed)
@@ -628,10 +627,10 @@ def loop(self):
628627
if self._timestamp == 0:
629628
self._timestamp = time.monotonic()
630629
current_time = time.monotonic()
631-
if current_time - self._timestamp >= self._keep_alive:
630+
if current_time - self._timestamp >= self.keep_alive:
632631
# Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server
633-
if self._logger is not None:
634-
self._logger.debug('KeepAlive period elapsed - requesting a PINGRESP from the server...')
632+
if self.logger is not None:
633+
self.logger.debug('KeepAlive period elapsed - requesting a PINGRESP from the server...')
635634
self.ping()
636635
self._timestamp = 0
637636
self._sock.settimeout(0.1)
@@ -753,22 +752,22 @@ def attach_logger(self, logger_name='log'):
753752
"""Initializes and attaches a logger to the MQTTClient.
754753
:param str logger_name: Name of the logger instance
755754
"""
756-
self._logger = logging.getLogger(logger_name)
757-
self._logger.setLevel(logging.INFO)
755+
self.logger = logging.getLogger(logger_name)
756+
self.logger.setLevel(logging.INFO)
758757

759758
def set_logger_level(self, log_level):
760759
"""Sets the level of the logger, if defined during init.
761760
:param string log_level: Level of logging to output to the REPL.
762761
"""
763-
if self._logger is None:
762+
if self.logger is None:
764763
raise MMQTTException('No logger attached - did you create it during initialization?')
765764
if log_level == 'DEBUG':
766-
self._logger.setLevel(logging.DEBUG)
765+
self.logger.setLevel(logging.DEBUG)
767766
elif log_level == 'INFO':
768-
self._logger.setLevel(logging.INFO)
767+
self.logger.setLevel(logging.INFO)
769768
elif log_level == 'WARNING':
770-
self._logger.setLevel(logging.WARNING)
769+
self.logger.setLevel(logging.WARNING)
771770
elif log_level == 'ERROR':
772-
self._logger.setLevel(logging.CRITICIAL)
771+
self.logger.setLevel(logging.CRITICIAL)
773772
else:
774773
raise MMQTTException('Incorrect logging level provided!')

0 commit comments

Comments
 (0)