diff --git a/adafruit_minimqtt.py b/adafruit_minimqtt.py index 7b9cd0f..e0f9c3c 100644 --- a/adafruit_minimqtt.py +++ b/adafruit_minimqtt.py @@ -79,6 +79,7 @@ _the_interface = None # pylint: disable=invalid-name _the_sock = None # pylint: disable=invalid-name + class MMQTTException(Exception): """MiniMQTT Exception class.""" @@ -95,10 +96,11 @@ def set_socket(sock, iface=None): global _the_sock # pylint: disable=invalid-name, global-statement _the_sock = sock if iface: - global _the_interface # pylint: disable=invalid-name, global-statement + global _the_interface # pylint: disable=invalid-name, global-statement _the_interface = iface _the_sock.set_interface(iface) + class MQTT: """MQTT Client for CircuitPython :param str broker: MQTT Broker URL or IP Address. @@ -114,14 +116,22 @@ class MQTT: """ # pylint: disable=too-many-arguments,too-many-instance-attributes, not-callable, invalid-name, no-member - def __init__(self, broker, port=None, username=None, - password=None, client_id=None, - is_ssl=True, log=False, keep_alive=60): + def __init__( + self, + broker, + port=None, + username=None, + password=None, + client_id=None, + is_ssl=True, + log=False, + keep_alive=60, + ): self._sock = None # broker - try: # set broker IP + try: # set broker IP self.broker = _the_interface.unpretty_ip(broker) - except ValueError: # set broker URL + except ValueError: # set broker URL self.broker = broker # port/ssl self.port = MQTT_TCP_PORT @@ -230,20 +240,26 @@ def connect(self, clean_session=True): self.broker, port = self.broker.split(":", 1) port = int(port) - addr = _the_sock.getaddrinfo(self.broker, self.port, 0, _the_sock.SOCK_STREAM)[0] + addr = _the_sock.getaddrinfo(self.broker, self.port, 0, _the_sock.SOCK_STREAM)[ + 0 + ] self._sock = _the_sock.socket(addr[0], addr[1], addr[2]) self._sock.settimeout(15) if self.port == 8883: try: if self.logger is not None: - self.logger.debug('Attempting to establish secure MQTT connection...') + self.logger.debug( + "Attempting to establish secure MQTT connection..." + ) self._sock.connect((self.broker, self.port), _the_interface.TLS_MODE) except RuntimeError as e: raise MMQTTException("Invalid broker address defined.", e) else: try: if self.logger is not None: - self.logger.debug('Attempting to establish insecure MQTT connection...') + self.logger.debug( + "Attempting to establish insecure MQTT connection..." + ) self._sock.connect(addr[-1], TCP_MODE) except RuntimeError as e: raise MMQTTException("Invalid broker address defined.", e) @@ -386,9 +402,9 @@ def publish(self, topic, msg, retain=False, qos=0): raise MMQTTException("Publish topic can not contain wildcards.") # check msg/qos kwargs if msg is None: - raise MMQTTException('Message can not be None.') + raise MMQTTException("Message can not be None.") if isinstance(msg, (int, float)): - msg = str(msg).encode('ascii') + msg = str(msg).encode("ascii") elif isinstance(msg, str): msg = str(msg).encode("utf-8") else: @@ -628,8 +644,10 @@ def loop(self): if current_time - self._timestamp >= self.keep_alive: # Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server if self.logger is not None: - self.logger.debug('KeepAlive period elapsed - \ - requesting a PINGRESP from the server...') + self.logger.debug( + "KeepAlive period elapsed - \ + requesting a PINGRESP from the server..." + ) self.ping() self._timestamp = 0 self._sock.settimeout(0.1) @@ -699,10 +717,10 @@ def _check_topic(topic): raise MMQTTException("Topic may not be NoneType") # [MQTT-4.7.3-1] if not topic: - raise MMQTTException('Topic may not be empty.') + raise MMQTTException("Topic may not be empty.") # [MQTT-4.7.3-3] - if len(topic.encode('utf-8')) > MQTT_TOPIC_LENGTH_LIMIT: - raise MMQTTException('Topic length is too large.') + if len(topic.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT: + raise MMQTTException("Topic length is too large.") @staticmethod def _check_qos(qos_level): diff --git a/docs/conf.py b/docs/conf.py index 052c191..8b5279f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -37,18 +37,18 @@ master_doc = "index" # General information about the project. -project = u"Adafruit MiniMQTT Library" -copyright = u"2019 Brent Rubell" -author = u"Brent Rubell" +project = "Adafruit MiniMQTT Library" +copyright = "2019 Brent Rubell" +author = "Brent Rubell" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u"1.0" +version = "1.0" # The full version, including alpha/beta/rc tags. -release = u"1.0" +release = "1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -139,7 +139,7 @@ ( master_doc, "AdafruitMiniMQTTLibrary.tex", - u"AdafruitMiniMQTT Library Documentation", + "AdafruitMiniMQTT Library Documentation", author, "manual", ), @@ -153,7 +153,7 @@ ( master_doc, "AdafruitMiniMQTTlibrary", - u"Adafruit MiniMQTT Library Documentation", + "Adafruit MiniMQTT Library Documentation", [author], 1, ) @@ -168,7 +168,7 @@ ( master_doc, "AdafruitMiniMQTTLibrary", - u"Adafruit MiniMQTT Library Documentation", + "Adafruit MiniMQTT Library Documentation", author, "AdafruitMiniMQTTLibrary", "One line description of project.", diff --git a/examples/minimqtt_adafruitio_eth.py b/examples/minimqtt_adafruitio_eth.py index e993f42..f0e8b12 100755 --- a/examples/minimqtt_adafruitio_eth.py +++ b/examples/minimqtt_adafruitio_eth.py @@ -27,10 +27,10 @@ ### Feeds ### # Setup a feed named 'photocell' for publishing to a feed -photocell_feed = secrets['aio_username'] + '/feeds/photocell' +photocell_feed = secrets["aio_username"] + "/feeds/photocell" # Setup a feed named 'onoff' for subscribing to changes -onoff_feed = secrets['aio_username'] + '/feeds/onoff' +onoff_feed = secrets["aio_username"] + "/feeds/onoff" ### Code ### @@ -39,20 +39,20 @@ def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. - print('Connected to Adafruit IO! Listening for topic changes on %s' % onoff_feed) + print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) # Subscribe to all changes on the onoff_feed. client.subscribe(onoff_feed) def disconnected(client, userdata, rc): # This method is called when the client is disconnected - print('Disconnected from Adafruit IO!') + print("Disconnected from Adafruit IO!") def message(client, topic, message): # This method is called when a topic the client is subscribed to # has a new message. - print('New message on topic {0}: {1}'.format(topic, message)) + print("New message on topic {0}: {1}".format(topic, message)) # Initialize MQTT interface with the ethernet interface @@ -60,9 +60,11 @@ def message(client, topic, message): # Set up a MiniMQTT Client # NOTE: We'll need to connect insecurely for ethernet configurations. -mqtt_client = MQTT.MQTT(broker = 'http://io.adafruit.com', - username = secrets['aio_username'], - password = secrets['aio_key']) +mqtt_client = MQTT.MQTT( + broker="http://io.adafruit.com", + username=secrets["aio_username"], + password=secrets["aio_key"], +) # Setup the callback methods above mqtt_client.on_connect = connected @@ -70,7 +72,7 @@ def message(client, topic, message): mqtt_client.on_message = message # Connect the client to the MQTT broker. -print('Connecting to Adafruit IO...') +print("Connecting to Adafruit IO...") mqtt_client.connect() photocell_val = 0 @@ -79,8 +81,8 @@ def message(client, topic, message): mqtt_client.loop() # Send a new message - print('Sending photocell value: %d...' % photocell_val) + print("Sending photocell value: %d..." % photocell_val) mqtt_client.publish(photocell_feed, photocell_val) - print('Sent!') + print("Sent!") photocell_val += 1 time.sleep(5) diff --git a/examples/minimqtt_adafruitio_wifi.py b/examples/minimqtt_adafruitio_wifi.py index 3163bc5..20d0ff0 100644 --- a/examples/minimqtt_adafruitio_wifi.py +++ b/examples/minimqtt_adafruitio_wifi.py @@ -88,9 +88,11 @@ def message(client, topic, message): MQTT.set_socket(socket, esp) # Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT(broker='http://io.adafruit.com', - username=secrets['aio_username'], - password=secrets['aio_key']) +mqtt_client = MQTT.MQTT( + broker="http://io.adafruit.com", + username=secrets["aio_username"], + password=secrets["aio_key"], +) # Setup the callback methods above mqtt_client.on_connect = connected diff --git a/examples/minimqtt_certificate.py b/examples/minimqtt_certificate.py index 5fe5c3e..758fb76 100644 --- a/examples/minimqtt_certificate.py +++ b/examples/minimqtt_certificate.py @@ -110,9 +110,9 @@ def publish(client, userdata, topic, pid): MQTT.set_socket(socket, esp) # Set up a MiniMQTT Client -client = MQTT.MQTT(broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass']) +client = MQTT.MQTT( + broker=secrets["broker"], username=secrets["user"], password=secrets["pass"] +) # Connect callback handlers to client client.on_connect = connect diff --git a/examples/minimqtt_pub_sub_blocking.py b/examples/minimqtt_pub_sub_blocking.py index bea26d0..f088da4 100644 --- a/examples/minimqtt_pub_sub_blocking.py +++ b/examples/minimqtt_pub_sub_blocking.py @@ -86,9 +86,9 @@ def message(client, topic, message): MQTT.set_socket(socket, esp) # Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT(broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass']) +mqtt_client = MQTT.MQTT( + broker=secrets["broker"], username=secrets["user"], password=secrets["pass"] +) # Setup the callback methods above mqtt_client.on_connect = connected @@ -96,7 +96,7 @@ def message(client, topic, message): mqtt_client.on_message = message # Connect the client to the MQTT broker. -print('Connecting to MQTT broker...') +print("Connecting to MQTT broker...") mqtt_client.connect() # Start a blocking message loop... diff --git a/examples/minimqtt_pub_sub_nonblocking.py b/examples/minimqtt_pub_sub_nonblocking.py index 154901d..5c1ce04 100644 --- a/examples/minimqtt_pub_sub_nonblocking.py +++ b/examples/minimqtt_pub_sub_nonblocking.py @@ -83,9 +83,9 @@ def message(client, topic, message): MQTT.set_socket(socket, esp) # Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT(broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass']) +mqtt_client = MQTT.MQTT( + broker=secrets["broker"], username=secrets["user"], password=secrets["pass"] +) # Setup the callback methods above mqtt_client.on_connect = connected diff --git a/examples/minimqtt_pub_sub_pyportal.py b/examples/minimqtt_pub_sub_pyportal.py index 95b0ec9..3fd3bbc 100644 --- a/examples/minimqtt_pub_sub_pyportal.py +++ b/examples/minimqtt_pub_sub_pyportal.py @@ -16,11 +16,10 @@ raise # pylint: disable=protected-access -wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp, - secrets, None) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp, secrets, None) # ------------- MQTT Topic Setup ------------- # -mqtt_topic = 'test/topic' +mqtt_topic = "test/topic" ### Code ### # Define callback methods which are called when events occur @@ -28,12 +27,14 @@ def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. - print('Subscribing to %s' % (mqtt_topic)) + print("Subscribing to %s" % (mqtt_topic)) client.subscribe(mqtt_topic) + def disconnected(client, userdata, rc): # This method is called when the client is disconnected - print('Disconnected from MQTT Broker!') + print("Disconnected from MQTT Broker!") + def message(client, topic, message): """Method callled when a client's subscribed feed has a new @@ -41,7 +42,8 @@ def message(client, topic, message): :param str topic: The topic of the feed with a new value. :param str message: The new value """ - print('New message on topic {0}: {1}'.format(topic, message)) + print("New message on topic {0}: {1}".format(topic, message)) + # Connect to WiFi print("Connecting to WiFi...") @@ -53,10 +55,12 @@ def message(client, topic, message): MQTT.set_socket(socket, pyportal._esp) # Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT(broker=secrets['broker'], - username=secrets['user'], - password=secrets['pass'], - is_ssl=False) +mqtt_client = MQTT.MQTT( + broker=secrets["broker"], + username=secrets["user"], + password=secrets["pass"], + is_ssl=False, +) # Setup the callback methods above mqtt_client.on_connect = connected @@ -72,7 +76,7 @@ def message(client, topic, message): mqtt_client.loop() # Send a new message - print('Sending photocell value: %d' % photocell_val) + print("Sending photocell value: %d" % photocell_val) mqtt_client.publish(mqtt_topic, photocell_val) photocell_val += 1 time.sleep(1) diff --git a/examples/minimqtt_simpletest.py b/examples/minimqtt_simpletest.py index 987b484..c07f51a 100644 --- a/examples/minimqtt_simpletest.py +++ b/examples/minimqtt_simpletest.py @@ -95,9 +95,9 @@ def publish(client, userdata, topic, pid): MQTT.set_socket(socket, esp) # Set up a MiniMQTT Client -client = MQTT.MQTT(broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass']) +client = MQTT.MQTT( + broker=secrets["broker"], username=secrets["user"], password=secrets["pass"] +) # Connect callback handlers to client client.on_connect = connect diff --git a/examples/minimqtt_simpletest_eth.py b/examples/minimqtt_simpletest_eth.py index d24441d..2d1f5d9 100644 --- a/examples/minimqtt_simpletest_eth.py +++ b/examples/minimqtt_simpletest_eth.py @@ -22,7 +22,7 @@ # MQTT Topic # Use this topic if you'd like to connect to a standard MQTT broker -mqtt_topic = 'test/topic' +mqtt_topic = "test/topic" # Adafruit IO-style Topic # Use this topic if you'd like to connect to io.adafruit.com @@ -35,33 +35,38 @@ def connect(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. - print('Connected to MQTT Broker!') - print('Flags: {0}\n RC: {1}'.format(flags, rc)) + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + def disconnect(client, userdata, rc): # This method is called when the client disconnects # from the broker. - print('Disconnected from MQTT Broker!') + print("Disconnected from MQTT Broker!") + def subscribe(client, userdata, topic, granted_qos): # This method is called when the client subscribes to a new feed. - print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos)) + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + def unsubscribe(client, userdata, topic, pid): # This method is called when the client unsubscribes from a feed. - print('Unsubscribed from {0} with PID {1}'.format(topic, pid)) + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + def publish(client, userdata, topic, pid): # This method is called when the client publishes data to a feed. - print('Published to {0} with PID {1}'.format(topic, pid)) + print("Published to {0} with PID {1}".format(topic, pid)) + # Initialize MQTT interface with the ethernet interface MQTT.set_socket(socket, eth) # Set up a MiniMQTT Client -client = MQTT.MQTT(broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass']) +client = MQTT.MQTT( + broker=secrets["broker"], username=secrets["user"], password=secrets["pass"] +) # Connect callback handlers to client client.on_connect = connect @@ -70,17 +75,17 @@ def publish(client, userdata, topic, pid): client.on_unsubscribe = unsubscribe client.on_publish = publish -print('Attempting to connect to %s'%client.broker) +print("Attempting to connect to %s" % client.broker) client.connect() -print('Subscribing to %s'%mqtt_topic) +print("Subscribing to %s" % mqtt_topic) client.subscribe(mqtt_topic) -print('Publishing to %s'%mqtt_topic) -client.publish(mqtt_topic, 'Hello Broker!') +print("Publishing to %s" % mqtt_topic) +client.publish(mqtt_topic, "Hello Broker!") -print('Unsubscribing from %s'%mqtt_topic) +print("Unsubscribing from %s" % mqtt_topic) client.unsubscribe(mqtt_topic) -print('Disconnecting from %s'%client.broker) +print("Disconnecting from %s" % client.broker) client.disconnect()