Skip to content

Commit 7468a09

Browse files
committed
use NullHandler by default
fixes #146
1 parent 75cc3b2 commit 7468a09

File tree

2 files changed

+53
-68
lines changed

2 files changed

+53
-68
lines changed

adafruit_minimqtt/adafruit_minimqtt.py

Lines changed: 52 additions & 68 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"
@@ -186,7 +189,7 @@ def __init__(
186189
self._msg_size_lim = MQTT_MSG_SZ_LIM
187190
self._pid = 0
188191
self._timestamp = 0
189-
self.logger = None
192+
self._init_logger()
190193

191194
self._reconnect_attempt = 0
192195
self._reconnect_timeout = float(0)
@@ -270,9 +273,9 @@ def _get_connect_socket(self, host, port, *, timeout=1):
270273
"ssl_context must be set before using adafruit_mqtt for secure MQTT."
271274
)
272275

273-
if self.logger is not None and port == MQTT_TLS_PORT:
276+
if port == MQTT_TLS_PORT:
274277
self.logger.info(f"Establishing a SECURE SSL connection to {host}:{port}")
275-
elif self.logger is not None:
278+
else:
276279
self.logger.info(f"Establishing an INSECURE connection to {host}:{port}")
277280

278281
addr_info = self._socket_pool.getaddrinfo(
@@ -352,8 +355,7 @@ def will_set(self, topic=None, payload=None, qos=0, retain=False):
352355
:param bool retain: Specifies if the payload is to be retained when
353356
it is published.
354357
"""
355-
if self.logger is not None:
356-
self.logger.debug("Setting last will properties")
358+
self.logger.debug("Setting last will properties")
357359
self._valid_qos(qos)
358360
if self._is_connected:
359361
raise MMQTTException("Last Will should only be called before connect().")
@@ -502,8 +504,7 @@ def _connect(self, clean_session=True, host=None, port=None, keep_alive=None):
502504
if keep_alive:
503505
self.keep_alive = keep_alive
504506

505-
if self.logger is not None:
506-
self.logger.debug("Attempting to establish MQTT connection...")
507+
self.logger.debug("Attempting to establish MQTT connection...")
507508

508509
if self._reconnect_attempt > 0:
509510
if self.logger is not None:
@@ -565,11 +566,9 @@ def _connect(self, clean_session=True, host=None, port=None, keep_alive=None):
565566
fixed_header.append(remaining_length)
566567
fixed_header.append(0x00)
567568

568-
if self.logger is not None:
569-
self.logger.debug("Sending CONNECT packet to broker...")
570-
self.logger.debug(
571-
"Fixed Header: %s\nVariable Header: %s", fixed_header, var_header
572-
)
569+
self.logger.debug("Sending CONNECT to broker...")
570+
self.logger.debug(f"Fixed Header: {fixed_header}")
571+
self.logger.debug(f"Variable Header: {var_header}")
573572
self._sock.send(fixed_header)
574573
self._sock.send(var_header)
575574
# [MQTT-3.1.3-4]
@@ -581,8 +580,7 @@ def _connect(self, clean_session=True, host=None, port=None, keep_alive=None):
581580
if self._username is not None:
582581
self._send_str(self._username)
583582
self._send_str(self._password)
584-
if self.logger is not None:
585-
self.logger.debug("Receiving CONNACK packet from broker")
583+
self.logger.debug("Receiving CONNACK packet from broker")
586584
stamp = time.monotonic()
587585
while True:
588586
op = self._wait_for_msg()
@@ -607,15 +605,12 @@ def _connect(self, clean_session=True, host=None, port=None, keep_alive=None):
607605
def disconnect(self):
608606
"""Disconnects the MiniMQTT client from the MQTT broker."""
609607
self._connected()
610-
if self.logger is not None:
611-
self.logger.debug("Sending DISCONNECT packet to broker")
608+
self.logger.debug("Sending DISCONNECT packet to broker")
612609
try:
613610
self._sock.send(MQTT_DISCONNECT)
614611
except RuntimeError as e:
615-
if self.logger is not None:
616-
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
617-
if self.logger is not None:
618-
self.logger.debug("Closing socket")
612+
self.logger.warning(f"Unable to send DISCONNECT packet: {e}")
613+
self.logger.debug("Closing socket")
619614
self._sock.close()
620615
self._is_connected = False
621616
self._subscribed_topics = []
@@ -628,8 +623,7 @@ def ping(self):
628623
Returns response codes of any messages received while waiting for PINGRESP.
629624
"""
630625
self._connected()
631-
if self.logger is not None:
632-
self.logger.debug("Sending PINGREQ")
626+
self.logger.debug("Sending PINGREQ")
633627
self._sock.send(MQTT_PINGREQ)
634628
ping_timeout = self.keep_alive
635629
stamp = time.monotonic()
@@ -699,15 +693,14 @@ def publish(self, topic, msg, retain=False, qos=0):
699693
else:
700694
pub_hdr_fixed.append(remaining_length)
701695

702-
if self.logger is not None:
703-
self.logger.debug(
704-
"Sending PUBLISH\nTopic: %s\nMsg: %s\
705-
\nQoS: %d\nRetain? %r",
706-
topic,
707-
msg,
708-
qos,
709-
retain,
710-
)
696+
self.logger.debug(
697+
"Sending PUBLISH\nTopic: %s\nMsg: %s\
698+
\nQoS: %d\nRetain? %r",
699+
topic,
700+
msg,
701+
qos,
702+
retain,
703+
)
711704
self._sock.send(pub_hdr_fixed)
712705
self._sock.send(pub_hdr_var)
713706
self._sock.send(msg)
@@ -777,9 +770,8 @@ def subscribe(self, topic, qos=0):
777770
topic_size = len(t.encode("utf-8")).to_bytes(2, "big")
778771
qos_byte = q.to_bytes(1, "big")
779772
packet += topic_size + t.encode() + qos_byte
780-
if self.logger is not None:
781-
for t, q in topics:
782-
self.logger.debug("SUBSCRIBING to topic %s with QoS %d", t, q)
773+
for t, q in topics:
774+
self.logger.debug("SUBSCRIBING to topic %s with QoS %d", t, q)
783775
self._sock.send(packet)
784776
stamp = time.monotonic()
785777
while True:
@@ -831,12 +823,10 @@ def unsubscribe(self, topic):
831823
for t in topics:
832824
topic_size = len(t.encode("utf-8")).to_bytes(2, "big")
833825
packet += topic_size + t.encode()
834-
if self.logger is not None:
835-
for t in topics:
836-
self.logger.debug("UNSUBSCRIBING from topic %s", t)
826+
for t in topics:
827+
self.logger.debug("UNSUBSCRIBING from topic %s", t)
837828
self._sock.send(packet)
838-
if self.logger is not None:
839-
self.logger.debug("Waiting for UNSUBACK...")
829+
self.logger.debug("Waiting for UNSUBACK...")
840830
while True:
841831
stamp = time.monotonic()
842832
op = self._wait_for_msg()
@@ -909,17 +899,13 @@ def reconnect(self, resub_topics=True):
909899
910900
"""
911901

912-
if self.logger is not None:
913-
self.logger.debug("Attempting to reconnect with MQTT broker")
914-
915-
ret = self.connect()
916-
if self.logger is not None:
917-
self.logger.debug("Reconnected with broker")
902+
self.logger.debug("Attempting to reconnect with MQTT broker")
903+
self.connect()
904+
self.logger.debug("Reconnected with broker")
918905
if resub_topics:
919-
if self.logger is not None:
920-
self.logger.debug(
921-
"Attempting to resubscribe to previously subscribed topics."
922-
)
906+
self.logger.debug(
907+
"Attempting to resubscribe to previously subscribed topics."
908+
)
923909
subscribed_topics = self._subscribed_topics.copy()
924910
self._subscribed_topics = []
925911
while subscribed_topics:
@@ -938,16 +924,16 @@ def loop(self, timeout=0):
938924
939925
"""
940926

927+
self.logger.debug(f"waiting for messages for {timeout} seconds")
941928
if self._timestamp == 0:
942929
self._timestamp = time.monotonic()
943930
current_time = time.monotonic()
944931
if current_time - self._timestamp >= self.keep_alive:
945932
self._timestamp = 0
946933
# Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server
947-
if self.logger is not None:
948-
self.logger.debug(
949-
"KeepAlive period elapsed - requesting a PINGRESP from the server..."
950-
)
934+
self.logger.debug(
935+
"KeepAlive period elapsed - requesting a PINGRESP from the server..."
936+
)
951937
rcs = self.ping()
952938
return rcs
953939

@@ -960,10 +946,9 @@ def loop(self, timeout=0):
960946
if rc is None:
961947
break
962948
if time.monotonic() - stamp > self._recv_timeout:
963-
if self.logger is not None:
964-
self.logger.debug(
965-
f"Loop timed out, message queue not empty after {self._recv_timeout}s"
966-
)
949+
self.logger.debug(
950+
f"Loop timed out, message queue not empty after {self._recv_timeout}s"
951+
)
967952
break
968953
rcs.append(rc)
969954

@@ -996,8 +981,7 @@ def _wait_for_msg(self, timeout=0.1):
996981
# If we get here, it means that there is nothing to be received
997982
return None
998983
if res[0] & MQTT_PKT_TYPE_MASK == MQTT_PINGRESP:
999-
if self.logger is not None:
1000-
self.logger.debug("Got PINGRESP")
984+
self.logger.debug("Got PINGRESP")
1001985
sz = self._sock_exact_recv(1)[0]
1002986
if sz != 0x00:
1003987
raise MMQTTException(f"Unexpected PINGRESP returned from broker: {sz}.")
@@ -1029,10 +1013,7 @@ def _wait_for_msg(self, timeout=0.1):
10291013
# read message contents
10301014
raw_msg = self._sock_exact_recv(sz)
10311015
msg = raw_msg if self._use_binary_mode else str(raw_msg, "utf-8")
1032-
if self.logger is not None:
1033-
self.logger.debug(
1034-
"Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg
1035-
)
1016+
self.logger.debug("Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg)
10361017
self._handle_on_message(self, topic, msg)
10371018
if res[0] & 0x06 == 0x02:
10381019
pkt = bytearray(b"\x40\x02\0\0")
@@ -1101,8 +1082,7 @@ def _sock_exact_recv(self, bufsize):
11011082
# This will timeout with socket timeout (not keepalive timeout)
11021083
rc = self._sock.recv(bufsize)
11031084
if not rc:
1104-
if self.logger is not None:
1105-
self.logger.debug("_sock_exact_recv timeout")
1085+
self.logger.debug("_sock_exact_recv timeout")
11061086
# If no bytes waiting, raise same exception as socketpool
11071087
raise OSError(errno.ETIMEDOUT)
11081088
# If any bytes waiting, try to read them all,
@@ -1187,13 +1167,17 @@ def enable_logger(self, log_pkg, log_level=20, logger_name="log"):
11871167
:return logger object
11881168
11891169
"""
1170+
# pylint: disable=attribute-defined-outside-init
11901171
self.logger = log_pkg.getLogger(logger_name)
11911172
self.logger.setLevel(log_level)
11921173

11931174
return self.logger
11941175

11951176
def disable_logger(self):
11961177
"""Disables logging."""
1197-
if not self.logger:
1198-
raise MMQTTException("Can not disable logger, no logger found.")
1199-
self.logger = None
1178+
self._init_logger()
1179+
1180+
def _init_logger(self):
1181+
"""Initializes logger to use NullHandler, i.e. no logging will be done."""
1182+
self.logger = logging.getLogger("")
1183+
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)