From a59436eb575b361d4cdb7b0084c99d3ee21b6481 Mon Sep 17 00:00:00 2001 From: dherrada Date: Thu, 12 Mar 2020 19:18:37 -0400 Subject: [PATCH] Ran black, updated to pylint 2.x --- .github/workflows/build.yml | 2 +- adafruit_minimqtt.py | 236 ++++++++++++++--------- docs/conf.py | 112 ++++++----- examples/minimqtt_adafruitio_wifi.py | 34 ++-- examples/minimqtt_certificate.py | 51 +++-- examples/minimqtt_pub_sub_blocking.py | 27 ++- examples/minimqtt_pub_sub_nonblocking.py | 29 +-- examples/minimqtt_simpletest.py | 47 +++-- setup.py | 52 ++--- 9 files changed, 341 insertions(+), 249 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint diff --git a/adafruit_minimqtt.py b/adafruit_minimqtt.py index e900f5f..e189a77 100644 --- a/adafruit_minimqtt.py +++ b/adafruit_minimqtt.py @@ -58,25 +58,30 @@ TLS_MODE = const(2) # MQTT Commands -MQTT_PINGREQ = b'\xc0\0' -MQTT_PINGRESP = const(0xd0) -MQTT_SUB = b'\x82' -MQTT_UNSUB = b'\xA2' -MQTT_PUB = bytearray(b'\x30\0') +MQTT_PINGREQ = b"\xc0\0" +MQTT_PINGRESP = const(0xD0) +MQTT_SUB = b"\x82" +MQTT_UNSUB = b"\xA2" +MQTT_PUB = bytearray(b"\x30\0") # Variable CONNECT header [MQTT 3.1.2] MQTT_VAR_HEADER = bytearray(b"\x04MQTT\x04\x02\0\0") -MQTT_DISCONNECT = b'\xe0\0' +MQTT_DISCONNECT = b"\xe0\0" + +CONNACK_ERRORS = { + const(0x01): "Connection Refused - Incorrect Protocol Version", + const(0x02): "Connection Refused - ID Rejected", + const(0x03): "Connection Refused - Server unavailable", + const(0x04): "Connection Refused - Incorrect username/password", + const(0x05): "Connection Refused - Unauthorized", +} -CONNACK_ERRORS = {const(0x01) : 'Connection Refused - Incorrect Protocol Version', - const(0x02) : 'Connection Refused - ID Rejected', - const(0x03) : 'Connection Refused - Server unavailable', - const(0x04) : 'Connection Refused - Incorrect username/password', - const(0x05) : 'Connection Refused - Unauthorized'} class MMQTTException(Exception): """MiniMQTT Exception class.""" + # pylint: disable=unnecessary-pass - #pass + # pass + class MQTT: """MQTT Client for CircuitPython @@ -91,21 +96,32 @@ class MQTT: :param bool log: Attaches a logger to the MQTT client, defaults to logging level INFO. :param int keep_alive: KeepAlive interval between the broker and the MiniMQTT client. """ + # pylint: disable=too-many-arguments,too-many-instance-attributes, not-callable, invalid-name, no-member - def __init__(self, socket, broker, port=None, username=None, - password=None, network_manager=None, client_id=None, - is_ssl=True, log=False, keep_alive=60): + def __init__( + self, + socket, + broker, + port=None, + username=None, + password=None, + network_manager=None, + client_id=None, + is_ssl=True, + log=False, + keep_alive=60, + ): # network management self._socket = socket network_manager_type = str(type(network_manager)) - if 'ESPSPI_WiFiManager' in network_manager_type: + if "ESPSPI_WiFiManager" in network_manager_type: self._wifi = network_manager else: raise TypeError("This library requires a NetworkManager object.") # broker - try: # set broker IP + try: # set broker IP self.broker = self._wifi.esp.unpretty_ip(broker) - except ValueError: # set broker URL + except ValueError: # set broker URL self.broker = broker # port/ssl self.port = MQTT_TCP_PORT @@ -117,24 +133,28 @@ def __init__(self, socket, broker, port=None, username=None, self.user = username # [MQTT-3.1.3.5] self.password = password - if self.password is not None and len(password.encode('utf-8')) > MQTT_TOPIC_LENGTH_LIMIT: - raise MMQTTException('Password length is too large.') + if ( + self.password is not None + and len(password.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT + ): + raise MMQTTException("Password length is too large.") if client_id is not None: # user-defined client_id MAY allow client_id's > 23 bytes or # non-alpha-numeric characters self.client_id = client_id else: # assign a unique client_id - self.client_id = 'cpy{0}{1}'.format(randint(0, int(time.monotonic()*100)%1000), - randint(0, 99)) + self.client_id = "cpy{0}{1}".format( + randint(0, int(time.monotonic() * 100) % 1000), randint(0, 99) + ) # generated client_id's enforce spec.'s length rules if len(self.client_id) > 23 or not self.client_id: - raise ValueError('MQTT Client ID must be between 1 and 23 bytes') + raise ValueError("MQTT Client ID must be between 1 and 23 bytes") self.keep_alive = keep_alive self.user_data = None self.logger = None if log is True: - self.logger = logging.getLogger('log') + self.logger = logging.getLogger("log") self.logger.setLevel(logging.INFO) self._sock = None self._is_connected = False @@ -172,11 +192,13 @@ def last_will(self, topic=None, message=None, qos=0, retain=False): :param bool retain: Specifies if the message is to be retained when it is published. """ if self._is_connected: - raise MMQTTException('Last Will should be defined before connect() is called.') + raise MMQTTException( + "Last Will should be defined before connect() is called." + ) if qos < 0 or qos > 2: raise MMQTTException("Invalid QoS level, must be between 0 and 2.") if self.logger is not None: - self.logger.debug('Setting last will properties') + self.logger.debug("Setting last will properties") self._lw_qos = qos self._lw_topic = topic self._lw_msg = message @@ -189,13 +211,15 @@ def connect(self, clean_session=True): """ self._set_interface() if self.logger is not None: - self.logger.debug('Creating new socket') + self.logger.debug("Creating new socket") self._sock = self._socket.socket() self._sock.settimeout(10) 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), TLS_MODE) except RuntimeError: raise MMQTTException("Invalid broker address defined.") @@ -206,8 +230,10 @@ def connect(self, clean_session=True): addr = (self.broker, self.port) try: if self.logger is not None: - self.logger.debug('Attempting to establish insecure MQTT connection...') - #self._sock.connect((self.broker, self.port), TCP_MODE) + self.logger.debug( + "Attempting to establish insecure MQTT connection..." + ) + # self._sock.connect((self.broker, self.port), TCP_MODE) self._sock.connect(addr, TCP_MODE) except RuntimeError as e: raise MMQTTException("Invalid broker address defined.", e) @@ -236,7 +262,7 @@ def connect(self, clean_session=True): # Remaining length calculation large_rel_length = False - if remaining_length > 0x7f: + if remaining_length > 0x7F: large_rel_length = True # Calculate Remaining Length [2.2.3] while remaining_length > 0: @@ -253,9 +279,10 @@ def connect(self, clean_session=True): fixed_header.append(0x00) if self.logger is not None: - self.logger.debug('Sending CONNECT to broker') - self.logger.debug('Fixed Header: {}\nVariable Header: {}'.format(fixed_header, - var_header)) + self.logger.debug("Sending CONNECT to broker") + self.logger.debug( + "Fixed Header: {}\nVariable Header: {}".format(fixed_header, var_header) + ) self._sock.send(fixed_header) self._sock.send(var_header) # [MQTT-3.1.3-4] @@ -270,7 +297,7 @@ def connect(self, clean_session=True): self._send_str(self.user) self._send_str(self.password) if self.logger is not None: - self.logger.debug('Receiving CONNACK packet from broker') + self.logger.debug("Receiving CONNACK packet from broker") while True: op = self._wait_for_msg() if op == 32: @@ -289,10 +316,10 @@ def disconnect(self): """ self.is_connected() if self.logger is not None: - self.logger.debug('Sending DISCONNECT packet to broker') + self.logger.debug("Sending DISCONNECT packet to broker") self._sock.send(MQTT_DISCONNECT) if self.logger is not None: - self.logger.debug('Closing socket') + self.logger.debug("Closing socket") self._sock.close() self._is_connected = False self._subscribed_topics = None @@ -305,16 +332,16 @@ def ping(self): """ self.is_connected() if self.logger is not None: - self.logger.debug('Sending PINGREQ') + self.logger.debug("Sending PINGREQ") self._sock.send(MQTT_PINGREQ) if self.logger is not None: - self.logger.debug('Checking PINGRESP') + self.logger.debug("Checking PINGRESP") while True: op = self._wait_for_msg(0.5) if op == 208: ping_resp = self._sock.recv(2) if ping_resp[0] != 0x00: - raise MMQTTException('PINGRESP not returned from broker.') + raise MMQTTException("PINGRESP not returned from broker.") return # pylint: disable=too-many-branches, too-many-statements @@ -345,19 +372,19 @@ def publish(self, topic, msg, retain=False, qos=0): """ self.is_connected() self._check_topic(topic) - if '+' in topic or '#' in topic: - raise MMQTTException('Publish topic can not contain wildcards.') + if "+" in topic or "#" in topic: + raise MMQTTException("Publish topic can not contain wildcards.") # check msg/qos kwargs if msg is None: - raise MMQTTException('Message can not be None.') - elif isinstance(msg, (int, float)): - msg = str(msg).encode('ascii') + raise MMQTTException("Message can not be None.") + if isinstance(msg, (int, float)): + msg = str(msg).encode("ascii") elif isinstance(msg, str): - msg = str(msg).encode('utf-8') + msg = str(msg).encode("utf-8") else: - raise MMQTTException('Invalid message data type.') + raise MMQTTException("Invalid message data type.") if len(msg) > MQTT_MSG_MAX_SZ: - raise MMQTTException('Message size larger than %db.'%MQTT_MSG_MAX_SZ) + raise MMQTTException("Message size larger than %db." % MQTT_MSG_MAX_SZ) self._check_qos(qos) pkt = MQTT_PUB pkt[0] |= qos << 1 | retain @@ -366,14 +393,18 @@ def publish(self, topic, msg, retain=False, qos=0): sz += 2 assert sz < 2097152 i = 1 - while sz > 0x7f: - pkt[i] = (sz & 0x7f) | 0x80 + while sz > 0x7F: + pkt[i] = (sz & 0x7F) | 0x80 sz >>= 7 i += 1 pkt[i] = sz if self.logger is not None: - self.logger.debug('Sending PUBLISH\nTopic: {0}\nMsg: {1}\ - \nQoS: {2}\nRetain? {3}'.format(topic, msg, qos, retain)) + self.logger.debug( + "Sending PUBLISH\nTopic: {0}\nMsg: {1}\ + \nQoS: {2}\nRetain? {3}".format( + topic, msg, qos, retain + ) + ) self._sock.send(pkt) self._send_str(topic) if qos == 0: @@ -387,7 +418,7 @@ def publish(self, topic, msg, retain=False, qos=0): if self.on_publish is not None: self.on_publish(self, self.user_data, topic, pid) if self.logger is not None: - self.logger.debug('Sending PUBACK') + self.logger.debug("Sending PUBACK") self._sock.send(msg) if qos == 1: while True: @@ -454,19 +485,19 @@ def subscribe(self, topic, qos=0): # Assemble packet packet_length = 2 + (2 * len(topics)) + (1 * len(topics)) packet_length += sum(len(topic) for topic, qos in topics) - packet_length_byte = packet_length.to_bytes(1, 'big') + packet_length_byte = packet_length.to_bytes(1, "big") self._pid += 1 - packet_id_bytes = self._pid.to_bytes(2, 'big') + packet_id_bytes = self._pid.to_bytes(2, "big") # Packet with variable and fixed headers packet = MQTT_SUB + packet_length_byte + packet_id_bytes # attaching topic and QOS level to the packet for t, q in topics: - topic_size = len(t).to_bytes(2, 'big') - qos_byte = q.to_bytes(1, 'big') + topic_size = len(t).to_bytes(2, "big") + qos_byte = q.to_bytes(1, "big") packet += topic_size + t + qos_byte if self.logger is not None: for t, q in topics: - self.logger.debug('SUBSCRIBING to topic {0} with QoS {1}'.format(t, q)) + self.logger.debug("SUBSCRIBING to topic {0} with QoS {1}".format(t, q)) self._sock.send(packet) while True: op = self._wait_for_msg() @@ -474,7 +505,7 @@ def subscribe(self, topic, qos=0): rc = self._sock.recv(4) assert rc[1] == packet[2] and rc[2] == packet[3] if rc[3] == 0x80: - raise MMQTTException('SUBACK Failure!') + raise MMQTTException("SUBACK Failure!") for t, q in topics: if self.on_subscribe is not None: self.on_subscribe(self, self.user_data, t, q) @@ -508,30 +539,35 @@ def unsubscribe(self, topic): topics.append((t)) for t in topics: if t not in self._subscribed_topics: - raise MMQTTException('Topic must be subscribed to before attempting unsubscribe.') + raise MMQTTException( + "Topic must be subscribed to before attempting unsubscribe." + ) # Assemble packet packet_length = 2 + (2 * len(topics)) packet_length += sum(len(topic) for topic in topics) - packet_length_byte = packet_length.to_bytes(1, 'big') + packet_length_byte = packet_length.to_bytes(1, "big") self._pid += 1 - packet_id_bytes = self._pid.to_bytes(2, 'big') + packet_id_bytes = self._pid.to_bytes(2, "big") packet = MQTT_UNSUB + packet_length_byte + packet_id_bytes for t in topics: - topic_size = len(t).to_bytes(2, 'big') + topic_size = len(t).to_bytes(2, "big") packet += topic_size + t if self.logger is not None: for t in topics: - self.logger.debug('UNSUBSCRIBING from topic {0}.'.format(t)) + self.logger.debug("UNSUBSCRIBING from topic {0}.".format(t)) self._sock.send(packet) if self.logger is not None: - self.logger.debug('Waiting for UNSUBACK...') + self.logger.debug("Waiting for UNSUBACK...") while True: op = self._wait_for_msg() if op == 176: return_code = self._sock.recv(3) assert return_code[0] == 0x02 # [MQTT-3.32] - assert return_code[1] == packet_id_bytes[0] and return_code[2] == packet_id_bytes[1] + assert ( + return_code[1] == packet_id_bytes[0] + and return_code[2] == packet_id_bytes[1] + ) for t in topics: if self.on_unsubscribe is not None: self.on_unsubscribe(self, self.user_data, t, self._pid) @@ -550,7 +586,11 @@ def is_wifi_connected(self): @property def is_sock_connected(self): """Returns if the socket is connected.""" - return self.is_wifi_connected and self._sock and self._wifi.esp.socket_connected(self._sock._socknum) + return ( + self.is_wifi_connected + and self._sock + and self._wifi.esp.socket_connected(self._sock._socknum) + ) def reconnect_socket(self): """Re-establishes the socket's connection with the MQTT broker. @@ -561,7 +601,9 @@ def reconnect_socket(self): self.reconnect() except RuntimeError as err: if self.logger is not None: - self.logger.debug('Failed to reconnect with MQTT Broker, retrying...', err) + self.logger.debug( + "Failed to reconnect with MQTT Broker, retrying...", err + ) time.sleep(1) self.reconnect_socket() @@ -571,11 +613,11 @@ def reconnect_wifi(self): while not self.is_wifi_connected: try: if self.logger is not None: - self.logger.debug('Connecting to WiFi AP...') + self.logger.debug("Connecting to WiFi AP...") self._wifi.connect() except (RuntimeError, ValueError): if self.logger is not None: - self.logger.debug('Failed to reset WiFi module, retrying...') + self.logger.debug("Failed to reset WiFi module, retrying...") time.sleep(1) # we just reconnected, is the socket still connected? if not self.is_sock_connected: @@ -586,13 +628,15 @@ def reconnect(self, resub_topics=True): :param bool resub_topics: Resubscribe to previously subscribed topics. """ if self.logger is not None: - self.logger.debug('Attempting to reconnect with MQTT broker') + self.logger.debug("Attempting to reconnect with MQTT broker") self.connect() if self.logger is not None: - self.logger.debug('Reconnected with broker') + self.logger.debug("Reconnected with broker") if resub_topics: if self.logger is not None: - self.logger.debug('Attempting to resubscribe to previously subscribed topics.') + self.logger.debug( + "Attempting to resubscribe to previously subscribed topics." + ) while self._subscribed_topics: feed = self._subscribed_topics.pop() self.subscribe(feed) @@ -629,7 +673,9 @@ 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) @@ -647,13 +693,13 @@ def _wait_for_msg(self, timeout=30): sz = self._sock.recv(1)[0] assert sz == 0 return None - if res[0] & 0xf0 != 0x30: + if res[0] & 0xF0 != 0x30: return res[0] sz = self._recv_len() topic_len = self._sock.recv(2) topic_len = (topic_len[0] << 8) | topic_len[1] topic = self._sock.recv(topic_len) - topic = str(topic, 'utf-8') + topic = str(topic, "utf-8") sz -= topic_len + 2 if res[0] & 0x06: pid = self._sock.recv(2) @@ -661,7 +707,7 @@ def _wait_for_msg(self, timeout=30): sz -= 0x02 msg = self._sock.recv(sz) if self.on_message is not None: - self.on_message(self, topic, str(msg, 'utf-8')) + self.on_message(self, topic, str(msg, "utf-8")) if res[0] & 0x06 == 0x02: pkt = bytearray(b"\x40\x02\0\0") struct.pack_into("!H", pkt, 2, pid) @@ -675,7 +721,7 @@ def _recv_len(self): sh = 0 while True: b = self._sock.recv(1)[0] - n |= (b & 0x7f) << sh + n |= (b & 0x7F) << sh if not b & 0x80: return n sh += 7 @@ -686,7 +732,7 @@ def _send_str(self, string): """ self._sock.send(struct.pack("!H", len(string))) if isinstance(string, str): - self._sock.send(str.encode(string, 'utf-8')) + self._sock.send(str.encode(string, "utf-8")) else: self._sock.send(string) @@ -696,13 +742,13 @@ def _check_topic(topic): :param str topic: Topic identifier """ if topic is None: - raise MMQTTException('Topic may not be NoneType') + raise MMQTTException("Topic may not be NoneType") # [MQTT-4.7.3-1] - elif not topic: - raise MMQTTException('Topic may not be empty.') + if not topic: + raise MMQTTException("Topic may not be empty.") # [MQTT-4.7.3-3] - elif 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): @@ -711,9 +757,9 @@ def _check_qos(qos_level): """ if isinstance(qos_level, int): if qos_level < 0 or qos_level > 2: - raise MMQTTException('QoS must be between 1 and 2.') + raise MMQTTException("QoS must be between 1 and 2.") else: - raise MMQTTException('QoS must be an integer.') + raise MMQTTException("QoS must be an integer.") def _set_interface(self): """Sets a desired network hardware interface. @@ -723,7 +769,7 @@ def _set_interface(self): if self._wifi: self._socket.set_interface(self._wifi.esp) else: - raise TypeError('Network Manager Required.') + raise TypeError("Network Manager Required.") def is_connected(self): """Returns MQTT client session status as True if connected, raises @@ -747,7 +793,7 @@ def mqtt_msg(self, msg_size): self._msg_size_lim = msg_size # Logging - def attach_logger(self, logger_name='log'): + def attach_logger(self, logger_name="log"): """Initializes and attaches a logger to the MQTTClient. :param str logger_name: Name of the logger instance """ @@ -759,14 +805,16 @@ def set_logger_level(self, log_level): :param string log_level: Level of logging to output to the REPL. """ if self.logger is None: - raise MMQTTException('No logger attached - did you create it during initialization?') - if log_level == 'DEBUG': + raise MMQTTException( + "No logger attached - did you create it during initialization?" + ) + if log_level == "DEBUG": self.logger.setLevel(logging.DEBUG) - elif log_level == 'INFO': + elif log_level == "INFO": self.logger.setLevel(logging.INFO) - elif log_level == 'WARNING': + elif log_level == "WARNING": self.logger.setLevel(logging.WARNING) - elif log_level == 'ERROR': + elif log_level == "ERROR": self.logger.setLevel(logging.CRITICIAL) else: - raise MMQTTException('Incorrect logging level provided!') + raise MMQTTException("Incorrect logging level provided!") diff --git a/docs/conf.py b/docs/conf.py index 0fd26d6..052c191 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,10 +11,10 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # Uncomment the below if you use native CircuitPython modules such as @@ -22,29 +23,32 @@ autodoc_mock_imports = ["micropython", "microcontroller", "random", "adafruit_logging"] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit MiniMQTT Library' -copyright = u'2019 Brent Rubell' -author = u'Brent Rubell' +project = u"Adafruit MiniMQTT Library" +copyright = u"2019 Brent Rubell" +author = u"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 = u"1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = u"1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -56,7 +60,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -68,7 +72,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -83,59 +87,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitMinimqttLibrarydoc' +htmlhelp_basename = "AdafruitMinimqttLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitMiniMQTTLibrary.tex', u'AdafruitMiniMQTT Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitMiniMQTTLibrary.tex", + u"AdafruitMiniMQTT Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -143,8 +150,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitMiniMQTTlibrary', u'Adafruit MiniMQTT Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitMiniMQTTlibrary", + u"Adafruit MiniMQTT Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -153,7 +165,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitMiniMQTTLibrary', u'Adafruit MiniMQTT Library Documentation', - author, 'AdafruitMiniMQTTLibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitMiniMQTTLibrary", + u"Adafruit MiniMQTT Library Documentation", + author, + "AdafruitMiniMQTTLibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/minimqtt_adafruitio_wifi.py b/examples/minimqtt_adafruitio_wifi.py index 47f2a1c..41c12bc 100644 --- a/examples/minimqtt_adafruitio_wifi.py +++ b/examples/minimqtt_adafruitio_wifi.py @@ -34,7 +34,8 @@ esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -44,16 +45,15 @@ # GREEN_LED = PWMOut.PWMOut(esp, 27) # BLUE_LED = PWMOut.PWMOut(esp, 25) # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) -wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( - esp, secrets, status_light) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) ### 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 ### @@ -62,31 +62,33 @@ 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)) # Connect to WiFi wifi.connect() # Set up a MiniMQTT Client -mqtt_client = MQTT(socket, - broker='io.adafruit.com', - username=secrets['aio_username'], - password=secrets['aio_key'], - network_manager=wifi) +mqtt_client = MQTT( + socket, + broker="io.adafruit.com", + username=secrets["aio_username"], + password=secrets["aio_key"], + network_manager=wifi, +) # Setup the callback methods above mqtt_client.on_connect = connected @@ -94,7 +96,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 @@ -103,8 +105,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(1) diff --git a/examples/minimqtt_certificate.py b/examples/minimqtt_certificate.py index 471e176..05c257c 100644 --- a/examples/minimqtt_certificate.py +++ b/examples/minimqtt_certificate.py @@ -30,7 +30,9 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -46,7 +48,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 @@ -59,31 +61,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)) + # Get certificate and private key from a certificates.py file try: from certificates import DEVICE_CERT, DEVICE_KEY except ImportError: - print("Certificate and private key data is kept in certificates.py, please add them there!") + print( + "Certificate and private key data is kept in certificates.py, please add them there!" + ) raise # Set Device Certificate @@ -96,11 +105,13 @@ def publish(client, userdata, topic, pid): wifi.connect() # Set up a MiniMQTT Client -client = MQTT(socket, - broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass'], - network_manager = wifi) +client = MQTT( + socket, + broker=secrets["broker"], + username=secrets["user"], + password=secrets["pass"], + network_manager=wifi, +) # Connect callback handlers to client client.on_connect = connect @@ -109,17 +120,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() diff --git a/examples/minimqtt_pub_sub_blocking.py b/examples/minimqtt_pub_sub_blocking.py index 5831466..1b4a7d5 100644 --- a/examples/minimqtt_pub_sub_blocking.py +++ b/examples/minimqtt_pub_sub_blocking.py @@ -31,7 +31,9 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -46,7 +48,7 @@ ### Adafruit IO Setup ### # Setup a feed named `testfeed` for publishing. -default_topic = secrets['user']+'/feeds/testfeed' +default_topic = secrets["user"] + "/feeds/testfeed" ### Code ### @@ -55,13 +57,15 @@ def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. - print('Connected to MQTT broker! Listening for topic changes on %s'%default_topic) + print("Connected to MQTT broker! Listening for topic changes on %s" % default_topic) # Subscribe to all changes on the default_topic feed. client.subscribe(default_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 @@ -69,17 +73,20 @@ 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 wifi.connect() # Set up a MiniMQTT Client -mqtt_client = MQTT(socket, - broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass'], - network_manager = wifi) +mqtt_client = MQTT( + socket, + broker=secrets["broker"], + username=secrets["user"], + password=secrets["pass"], + network_manager=wifi, +) # Setup the callback methods above mqtt_client.on_connect = connected diff --git a/examples/minimqtt_pub_sub_nonblocking.py b/examples/minimqtt_pub_sub_nonblocking.py index fdde9a7..1a920c2 100644 --- a/examples/minimqtt_pub_sub_nonblocking.py +++ b/examples/minimqtt_pub_sub_nonblocking.py @@ -30,7 +30,9 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -45,7 +47,7 @@ ### Adafruit IO Setup ### # Setup a feed named `testfeed` for publishing. -default_topic = secrets['user']+'/feeds/testfeed' +default_topic = secrets["user"] + "/feeds/testfeed" ### Code ### # Define callback methods which are called when events occur @@ -53,13 +55,15 @@ def connected(client, userdata, flags, rc): # This function will be called when the client is connected # successfully to the broker. - print('Connected to MQTT broker! Listening for topic changes on %s'%default_topic) + print("Connected to MQTT broker! Listening for topic changes on %s" % default_topic) # Subscribe to all changes on the default_topic feed. client.subscribe(default_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 @@ -67,17 +71,20 @@ 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 wifi.connect() # Set up a MiniMQTT Client -mqtt_client = MQTT(socket, - broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass'], - network_manager = wifi) +mqtt_client = MQTT( + socket, + broker=secrets["broker"], + username=secrets["user"], + password=secrets["pass"], + network_manager=wifi, +) # Setup the callback methods above mqtt_client.on_connect = connected @@ -93,7 +100,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(default_topic, photocell_val) photocell_val += 1 time.sleep(0.5) diff --git a/examples/minimqtt_simpletest.py b/examples/minimqtt_simpletest.py index a600c69..43b9f86 100644 --- a/examples/minimqtt_simpletest.py +++ b/examples/minimqtt_simpletest.py @@ -30,7 +30,9 @@ spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" -status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED @@ -46,7 +48,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 @@ -59,35 +61,42 @@ 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)) + # Connect to WiFi wifi.connect() # Set up a MiniMQTT Client -client = MQTT(socket, - broker = secrets['broker'], - username = secrets['user'], - password = secrets['pass'], - network_manager = wifi) +client = MQTT( + socket, + broker=secrets["broker"], + username=secrets["user"], + password=secrets["pass"], + network_manager=wifi, +) # Connect callback handlers to client client.on_connect = connect @@ -96,17 +105,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() diff --git a/setup.py b/setup.py index c0efb71..adada48 100644 --- a/setup.py +++ b/setup.py @@ -6,6 +6,7 @@ """ from setuptools import setup, find_packages + # To use a consistent encoding from codecs import open from os import path @@ -13,51 +14,40 @@ here = path.abspath(path.dirname(__file__)) # Get the long description from the README file -with open(path.join(here, 'README.rst'), encoding='utf-8') as f: +with open(path.join(here, "README.rst"), encoding="utf-8") as f: long_description = f.read() setup( - name='adafruit-circuitpython-minimqtt', - + name="adafruit-circuitpython-minimqtt", use_scm_version=True, - setup_requires=['setuptools_scm'], - - description='MQTT client library for CircuitPython', + setup_requires=["setuptools_scm"], + description="MQTT client library for CircuitPython", long_description=long_description, - long_description_content_type='text/x-rst', - + long_description_content_type="text/x-rst", # The project's main homepage. - url='https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT', - + url="https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT", # Author details - author='Adafruit Industries', - author_email='circuitpython@adafruit.com', - - install_requires=[ - 'Adafruit-Blinka' - ], - + author="Adafruit Industries", + author_email="circuitpython@adafruit.com", + install_requires=["Adafruit-Blinka"], # Choose your license - license='MIT', - + license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Topic :: System :: Hardware', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", ], - # What does your project relate to? - keywords='adafruit blinka circuitpython micropython minimqtt mqtt, client, socket', - + keywords="adafruit blinka circuitpython micropython minimqtt mqtt, client, socket", # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # CHANGE `py_modules=['...']` TO `packages=['...']` - py_modules=['adafruit_minimqtt'], + py_modules=["adafruit_minimqtt"], )