Skip to content

Commit 055b8e9

Browse files
committed
use NullHandler by default
fixes #146
1 parent 52c52c3 commit 055b8e9

File tree

2 files changed

+52
-66
lines changed

2 files changed

+52
-66
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 51 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@
3131
import struct
3232
import time
3333
from random import randint
34+
35+
import adafruit_logging as logging
3436
from micropython import const
37+
3538
from .matcher import MQTTMatcher
3639

3740
__version__ = "0.0.0+auto.0"
@@ -182,7 +185,7 @@ def __init__(
182185
self._msg_size_lim = MQTT_MSG_SZ_LIM
183186
self._pid = 0
184187
self._timestamp = 0
185-
self.logger = None
188+
self._init_logger()
186189

187190
self.broker = broker
188191
self._username = username
@@ -259,9 +262,9 @@ def _get_connect_socket(self, host, port, *, timeout=1):
259262
"ssl_context must be set before using adafruit_mqtt for secure MQTT."
260263
)
261264

262-
if self.logger is not None and port == MQTT_TLS_PORT:
265+
if port == MQTT_TLS_PORT:
263266
self.logger.info(f"Establishing a SECURE SSL connection to {host}:{port}")
264-
elif self.logger is not None:
267+
else:
265268
self.logger.info(f"Establishing an INSECURE connection to {host}:{port}")
266269

267270
addr_info = self._socket_pool.getaddrinfo(
@@ -343,8 +346,7 @@ def will_set(self, topic=None, payload=None, qos=0, retain=False):
343346
:param bool retain: Specifies if the payload is to be retained when
344347
it is published.
345348
"""
346-
if self.logger is not None:
347-
self.logger.debug("Setting last will properties")
349+
self.logger.debug("Setting last will properties")
348350
self._valid_qos(qos)
349351
if self._is_connected:
350352
raise MMQTTException("Last Will should only be called before connect().")
@@ -435,8 +437,7 @@ def connect(self, clean_session=True, host=None, port=None, keep_alive=None):
435437
if keep_alive:
436438
self.keep_alive = keep_alive
437439

438-
if self.logger is not None:
439-
self.logger.debug("Attempting to establish MQTT connection...")
440+
self.logger.debug("Attempting to establish MQTT connection...")
440441

441442
# Get a new socket
442443
self._sock = self._get_connect_socket(
@@ -491,11 +492,9 @@ def connect(self, clean_session=True, host=None, port=None, keep_alive=None):
491492
fixed_header.append(remaining_length)
492493
fixed_header.append(0x00)
493494

494-
if self.logger is not None:
495-
self.logger.debug("Sending CONNECT to broker...")
496-
self.logger.debug(
497-
"Fixed Header: %s\nVariable Header: %s", fixed_header, var_header
498-
)
495+
self.logger.debug("Sending CONNECT to broker...")
496+
self.logger.debug(f"Fixed Header: {fixed_header}")
497+
self.logger.debug(f"Variable Header: {var_header}")
499498
self._sock.send(fixed_header)
500499
self._sock.send(var_header)
501500
# [MQTT-3.1.3-4]
@@ -507,8 +506,7 @@ def connect(self, clean_session=True, host=None, port=None, keep_alive=None):
507506
if self._username is not None:
508507
self._send_str(self._username)
509508
self._send_str(self._password)
510-
if self.logger is not None:
511-
self.logger.debug("Receiving CONNACK packet from broker")
509+
self.logger.debug("Receiving CONNACK packet from broker")
512510
stamp = time.monotonic()
513511
while True:
514512
op = self._wait_for_msg()
@@ -532,15 +530,12 @@ def connect(self, clean_session=True, host=None, port=None, keep_alive=None):
532530
def disconnect(self):
533531
"""Disconnects the MiniMQTT client from the MQTT broker."""
534532
self._connected()
535-
if self.logger is not None:
536-
self.logger.debug("Sending DISCONNECT packet to broker")
533+
self.logger.debug("Sending DISCONNECT packet to broker")
537534
try:
538535
self._sock.send(MQTT_DISCONNECT)
539536
except RuntimeError as e:
540-
if self.logger is not None:
541-
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
542-
if self.logger is not None:
543-
self.logger.debug("Closing socket")
537+
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
538+
self.logger.debug("Closing socket")
544539
self._sock.close()
545540
self._is_connected = False
546541
self._subscribed_topics = []
@@ -553,8 +548,7 @@ def ping(self):
553548
Returns response codes of any messages received while waiting for PINGRESP.
554549
"""
555550
self._connected()
556-
if self.logger is not None:
557-
self.logger.debug("Sending PINGREQ")
551+
self.logger.debug("Sending PINGREQ")
558552
self._sock.send(MQTT_PINGREQ)
559553
ping_timeout = self.keep_alive
560554
stamp = time.monotonic()
@@ -624,15 +618,14 @@ def publish(self, topic, msg, retain=False, qos=0):
624618
else:
625619
pub_hdr_fixed.append(remaining_length)
626620

627-
if self.logger is not None:
628-
self.logger.debug(
629-
"Sending PUBLISH\nTopic: %s\nMsg: %s\
630-
\nQoS: %d\nRetain? %r",
631-
topic,
632-
msg,
633-
qos,
634-
retain,
635-
)
621+
self.logger.debug(
622+
"Sending PUBLISH\nTopic: %s\nMsg: %s\
623+
\nQoS: %d\nRetain? %r",
624+
topic,
625+
msg,
626+
qos,
627+
retain,
628+
)
636629
self._sock.send(pub_hdr_fixed)
637630
self._sock.send(pub_hdr_var)
638631
self._sock.send(msg)
@@ -702,9 +695,8 @@ def subscribe(self, topic, qos=0):
702695
topic_size = len(t.encode("utf-8")).to_bytes(2, "big")
703696
qos_byte = q.to_bytes(1, "big")
704697
packet += topic_size + t.encode() + qos_byte
705-
if self.logger is not None:
706-
for t, q in topics:
707-
self.logger.debug("SUBSCRIBING to topic %s with QoS %d", t, q)
698+
for t, q in topics:
699+
self.logger.debug("SUBSCRIBING to topic %s with QoS %d", t, q)
708700
self._sock.send(packet)
709701
stamp = time.monotonic()
710702
while True:
@@ -756,12 +748,10 @@ def unsubscribe(self, topic):
756748
for t in topics:
757749
topic_size = len(t.encode("utf-8")).to_bytes(2, "big")
758750
packet += topic_size + t.encode()
759-
if self.logger is not None:
760-
for t in topics:
761-
self.logger.debug("UNSUBSCRIBING from topic %s", t)
751+
for t in topics:
752+
self.logger.debug("UNSUBSCRIBING from topic %s", t)
762753
self._sock.send(packet)
763-
if self.logger is not None:
764-
self.logger.debug("Waiting for UNSUBACK...")
754+
self.logger.debug("Waiting for UNSUBACK...")
765755
while True:
766756
stamp = time.monotonic()
767757
op = self._wait_for_msg()
@@ -788,16 +778,13 @@ def reconnect(self, resub_topics=True):
788778
:param bool resub_topics: Resubscribe to previously subscribed topics.
789779
790780
"""
791-
if self.logger is not None:
792-
self.logger.debug("Attempting to reconnect with MQTT broker")
781+
self.logger.debug("Attempting to reconnect with MQTT broker")
793782
self.connect()
794-
if self.logger is not None:
795-
self.logger.debug("Reconnected with broker")
783+
self.logger.debug("Reconnected with broker")
796784
if resub_topics:
797-
if self.logger is not None:
798-
self.logger.debug(
799-
"Attempting to resubscribe to previously subscribed topics."
800-
)
785+
self.logger.debug(
786+
"Attempting to resubscribe to previously subscribed topics."
787+
)
801788
subscribed_topics = self._subscribed_topics.copy()
802789
self._subscribed_topics = []
803790
while subscribed_topics:
@@ -814,16 +801,16 @@ def loop(self, timeout=0):
814801
815802
"""
816803

804+
self.logger.debug(f"waiting for messages for {timeout} seconds")
817805
if self._timestamp == 0:
818806
self._timestamp = time.monotonic()
819807
current_time = time.monotonic()
820808
if current_time - self._timestamp >= self.keep_alive:
821809
self._timestamp = 0
822810
# Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server
823-
if self.logger is not None:
824-
self.logger.debug(
825-
"KeepAlive period elapsed - requesting a PINGRESP from the server..."
826-
)
811+
self.logger.debug(
812+
"KeepAlive period elapsed - requesting a PINGRESP from the server..."
813+
)
827814
rcs = self.ping()
828815
return rcs
829816

@@ -836,10 +823,9 @@ def loop(self, timeout=0):
836823
if rc is None:
837824
break
838825
if time.monotonic() - stamp > self._recv_timeout:
839-
if self.logger is not None:
840-
self.logger.debug(
841-
f"Loop timed out, message queue not empty after {self._recv_timeout}s"
842-
)
826+
self.logger.debug(
827+
f"Loop timed out, message queue not empty after {self._recv_timeout}s"
828+
)
843829
break
844830
rcs.append(rc)
845831

@@ -872,8 +858,7 @@ def _wait_for_msg(self, timeout=0.1):
872858
# If we get here, it means that there is nothing to be received
873859
return None
874860
if res[0] & MQTT_PKT_TYPE_MASK == MQTT_PINGRESP:
875-
if self.logger is not None:
876-
self.logger.debug("Got PINGRESP")
861+
self.logger.debug("Got PINGRESP")
877862
sz = self._sock_exact_recv(1)[0]
878863
if sz != 0x00:
879864
raise MMQTTException(f"Unexpected PINGRESP returned from broker: {sz}.")
@@ -905,10 +890,7 @@ def _wait_for_msg(self, timeout=0.1):
905890
# read message contents
906891
raw_msg = self._sock_exact_recv(sz)
907892
msg = raw_msg if self._use_binary_mode else str(raw_msg, "utf-8")
908-
if self.logger is not None:
909-
self.logger.debug(
910-
"Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg
911-
)
893+
self.logger.debug("Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg)
912894
self._handle_on_message(self, topic, msg)
913895
if res[0] & 0x06 == 0x02:
914896
pkt = bytearray(b"\x40\x02\0\0")
@@ -977,8 +959,7 @@ def _sock_exact_recv(self, bufsize):
977959
# This will timeout with socket timeout (not keepalive timeout)
978960
rc = self._sock.recv(bufsize)
979961
if not rc:
980-
if self.logger is not None:
981-
self.logger.debug("_sock_exact_recv timeout")
962+
self.logger.debug("_sock_exact_recv timeout")
982963
# If no bytes waiting, raise same exception as socketpool
983964
raise OSError(errno.ETIMEDOUT)
984965
# If any bytes waiting, try to read them all,
@@ -1063,13 +1044,17 @@ def enable_logger(self, log_pkg, log_level=20, logger_name="log"):
10631044
:return logger object
10641045
10651046
"""
1047+
# pylint: disable=attribute-defined-outside-init
10661048
self.logger = log_pkg.getLogger(logger_name)
10671049
self.logger.setLevel(log_level)
10681050

10691051
return self.logger
10701052

10711053
def disable_logger(self):
10721054
"""Disables logging."""
1073-
if not self.logger:
1074-
raise MMQTTException("Can not disable logger, no logger found.")
1075-
self.logger = None
1055+
self._init_logger()
1056+
1057+
def _init_logger(self):
1058+
"""Initializes logger to use NullHandler, i.e. no logging will be done."""
1059+
self.logger = logging.getLogger("")
1060+
self.logger.addHandler(logging.NullHandler())

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@
33
# SPDX-License-Identifier: Unlicense
44

55
Adafruit-Blinka
6+
adafruit-circuitpython-logging

0 commit comments

Comments
 (0)