Skip to content

Commit

Permalink
Merge pull request adafruit#27 from adafruit/black-update
Browse files Browse the repository at this point in the history
Black reformatting with Python 3 target.
  • Loading branch information
dhalbert authored Apr 10, 2020
2 parents b03485e + 6cdd2d5 commit 2f97b43
Show file tree
Hide file tree
Showing 10 changed files with 109 additions and 78 deletions.
50 changes: 34 additions & 16 deletions adafruit_minimqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
_the_interface = None # pylint: disable=invalid-name
_the_sock = None # pylint: disable=invalid-name


class MMQTTException(Exception):
"""MiniMQTT Exception class."""

Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
16 changes: 8 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -139,7 +139,7 @@
(
master_doc,
"AdafruitMiniMQTTLibrary.tex",
u"AdafruitMiniMQTT Library Documentation",
"AdafruitMiniMQTT Library Documentation",
author,
"manual",
),
Expand All @@ -153,7 +153,7 @@
(
master_doc,
"AdafruitMiniMQTTlibrary",
u"Adafruit MiniMQTT Library Documentation",
"Adafruit MiniMQTT Library Documentation",
[author],
1,
)
Expand All @@ -168,7 +168,7 @@
(
master_doc,
"AdafruitMiniMQTTLibrary",
u"Adafruit MiniMQTT Library Documentation",
"Adafruit MiniMQTT Library Documentation",
author,
"AdafruitMiniMQTTLibrary",
"One line description of project.",
Expand Down
24 changes: 13 additions & 11 deletions examples/minimqtt_adafruitio_eth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ###

Expand All @@ -39,38 +39,40 @@
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
MQTT.set_socket(socket, eth)

# 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
mqtt_client.on_disconnect = disconnected
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
Expand All @@ -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)
8 changes: 5 additions & 3 deletions examples/minimqtt_adafruitio_wifi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions examples/minimqtt_certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions examples/minimqtt_pub_sub_blocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,17 @@ 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
mqtt_client.on_disconnect = disconnected
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...
Expand Down
6 changes: 3 additions & 3 deletions examples/minimqtt_pub_sub_nonblocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 15 additions & 11 deletions examples/minimqtt_pub_sub_pyportal.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,34 @@
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
# pylint: disable=unused-argument, redefined-outer-name
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
value.
: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...")
Expand All @@ -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
Expand All @@ -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)
6 changes: 3 additions & 3 deletions examples/minimqtt_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

0 comments on commit 2f97b43

Please sign in to comment.