Skip to content

Commit bd24155

Browse files
authored
Merge pull request #27 from adafruit/black-update
Black reformatting with Python 3 target.
2 parents bd6c634 + 7e79640 commit bd24155

10 files changed

+109
-78
lines changed

adafruit_minimqtt.py

+34-16
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
_the_interface = None # pylint: disable=invalid-name
8080
_the_sock = None # pylint: disable=invalid-name
8181

82+
8283
class MMQTTException(Exception):
8384
"""MiniMQTT Exception class."""
8485

@@ -95,10 +96,11 @@ def set_socket(sock, iface=None):
9596
global _the_sock # pylint: disable=invalid-name, global-statement
9697
_the_sock = sock
9798
if iface:
98-
global _the_interface # pylint: disable=invalid-name, global-statement
99+
global _the_interface # pylint: disable=invalid-name, global-statement
99100
_the_interface = iface
100101
_the_sock.set_interface(iface)
101102

103+
102104
class MQTT:
103105
"""MQTT Client for CircuitPython
104106
:param str broker: MQTT Broker URL or IP Address.
@@ -114,14 +116,22 @@ class MQTT:
114116
"""
115117

116118
# pylint: disable=too-many-arguments,too-many-instance-attributes, not-callable, invalid-name, no-member
117-
def __init__(self, broker, port=None, username=None,
118-
password=None, client_id=None,
119-
is_ssl=True, log=False, keep_alive=60):
119+
def __init__(
120+
self,
121+
broker,
122+
port=None,
123+
username=None,
124+
password=None,
125+
client_id=None,
126+
is_ssl=True,
127+
log=False,
128+
keep_alive=60,
129+
):
120130
self._sock = None
121131
# broker
122-
try: # set broker IP
132+
try: # set broker IP
123133
self.broker = _the_interface.unpretty_ip(broker)
124-
except ValueError: # set broker URL
134+
except ValueError: # set broker URL
125135
self.broker = broker
126136
# port/ssl
127137
self.port = MQTT_TCP_PORT
@@ -230,20 +240,26 @@ def connect(self, clean_session=True):
230240
self.broker, port = self.broker.split(":", 1)
231241
port = int(port)
232242

233-
addr = _the_sock.getaddrinfo(self.broker, self.port, 0, _the_sock.SOCK_STREAM)[0]
243+
addr = _the_sock.getaddrinfo(self.broker, self.port, 0, _the_sock.SOCK_STREAM)[
244+
0
245+
]
234246
self._sock = _the_sock.socket(addr[0], addr[1], addr[2])
235247
self._sock.settimeout(15)
236248
if self.port == 8883:
237249
try:
238250
if self.logger is not None:
239-
self.logger.debug('Attempting to establish secure MQTT connection...')
251+
self.logger.debug(
252+
"Attempting to establish secure MQTT connection..."
253+
)
240254
self._sock.connect((self.broker, self.port), _the_interface.TLS_MODE)
241255
except RuntimeError as e:
242256
raise MMQTTException("Invalid broker address defined.", e)
243257
else:
244258
try:
245259
if self.logger is not None:
246-
self.logger.debug('Attempting to establish insecure MQTT connection...')
260+
self.logger.debug(
261+
"Attempting to establish insecure MQTT connection..."
262+
)
247263
self._sock.connect(addr[-1], TCP_MODE)
248264
except RuntimeError as e:
249265
raise MMQTTException("Invalid broker address defined.", e)
@@ -386,9 +402,9 @@ def publish(self, topic, msg, retain=False, qos=0):
386402
raise MMQTTException("Publish topic can not contain wildcards.")
387403
# check msg/qos kwargs
388404
if msg is None:
389-
raise MMQTTException('Message can not be None.')
405+
raise MMQTTException("Message can not be None.")
390406
if isinstance(msg, (int, float)):
391-
msg = str(msg).encode('ascii')
407+
msg = str(msg).encode("ascii")
392408
elif isinstance(msg, str):
393409
msg = str(msg).encode("utf-8")
394410
else:
@@ -628,8 +644,10 @@ def loop(self):
628644
if current_time - self._timestamp >= self.keep_alive:
629645
# Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server
630646
if self.logger is not None:
631-
self.logger.debug('KeepAlive period elapsed - \
632-
requesting a PINGRESP from the server...')
647+
self.logger.debug(
648+
"KeepAlive period elapsed - \
649+
requesting a PINGRESP from the server..."
650+
)
633651
self.ping()
634652
self._timestamp = 0
635653
self._sock.settimeout(0.1)
@@ -699,10 +717,10 @@ def _check_topic(topic):
699717
raise MMQTTException("Topic may not be NoneType")
700718
# [MQTT-4.7.3-1]
701719
if not topic:
702-
raise MMQTTException('Topic may not be empty.')
720+
raise MMQTTException("Topic may not be empty.")
703721
# [MQTT-4.7.3-3]
704-
if len(topic.encode('utf-8')) > MQTT_TOPIC_LENGTH_LIMIT:
705-
raise MMQTTException('Topic length is too large.')
722+
if len(topic.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT:
723+
raise MMQTTException("Topic length is too large.")
706724

707725
@staticmethod
708726
def _check_qos(qos_level):

docs/conf.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -37,18 +37,18 @@
3737
master_doc = "index"
3838

3939
# General information about the project.
40-
project = u"Adafruit MiniMQTT Library"
41-
copyright = u"2019 Brent Rubell"
42-
author = u"Brent Rubell"
40+
project = "Adafruit MiniMQTT Library"
41+
copyright = "2019 Brent Rubell"
42+
author = "Brent Rubell"
4343

4444
# The version info for the project you're documenting, acts as replacement for
4545
# |version| and |release|, also used in various other places throughout the
4646
# built documents.
4747
#
4848
# The short X.Y version.
49-
version = u"1.0"
49+
version = "1.0"
5050
# The full version, including alpha/beta/rc tags.
51-
release = u"1.0"
51+
release = "1.0"
5252

5353
# The language for content autogenerated by Sphinx. Refer to documentation
5454
# for a list of supported languages.
@@ -139,7 +139,7 @@
139139
(
140140
master_doc,
141141
"AdafruitMiniMQTTLibrary.tex",
142-
u"AdafruitMiniMQTT Library Documentation",
142+
"AdafruitMiniMQTT Library Documentation",
143143
author,
144144
"manual",
145145
),
@@ -153,7 +153,7 @@
153153
(
154154
master_doc,
155155
"AdafruitMiniMQTTlibrary",
156-
u"Adafruit MiniMQTT Library Documentation",
156+
"Adafruit MiniMQTT Library Documentation",
157157
[author],
158158
1,
159159
)
@@ -168,7 +168,7 @@
168168
(
169169
master_doc,
170170
"AdafruitMiniMQTTLibrary",
171-
u"Adafruit MiniMQTT Library Documentation",
171+
"Adafruit MiniMQTT Library Documentation",
172172
author,
173173
"AdafruitMiniMQTTLibrary",
174174
"One line description of project.",

examples/minimqtt_adafruitio_eth.py

+13-11
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@
2727
### Feeds ###
2828

2929
# Setup a feed named 'photocell' for publishing to a feed
30-
photocell_feed = secrets['aio_username'] + '/feeds/photocell'
30+
photocell_feed = secrets["aio_username"] + "/feeds/photocell"
3131

3232
# Setup a feed named 'onoff' for subscribing to changes
33-
onoff_feed = secrets['aio_username'] + '/feeds/onoff'
33+
onoff_feed = secrets["aio_username"] + "/feeds/onoff"
3434

3535
### Code ###
3636

@@ -39,38 +39,40 @@
3939
def connected(client, userdata, flags, rc):
4040
# This function will be called when the client is connected
4141
# successfully to the broker.
42-
print('Connected to Adafruit IO! Listening for topic changes on %s' % onoff_feed)
42+
print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed)
4343
# Subscribe to all changes on the onoff_feed.
4444
client.subscribe(onoff_feed)
4545

4646

4747
def disconnected(client, userdata, rc):
4848
# This method is called when the client is disconnected
49-
print('Disconnected from Adafruit IO!')
49+
print("Disconnected from Adafruit IO!")
5050

5151

5252
def message(client, topic, message):
5353
# This method is called when a topic the client is subscribed to
5454
# has a new message.
55-
print('New message on topic {0}: {1}'.format(topic, message))
55+
print("New message on topic {0}: {1}".format(topic, message))
5656

5757

5858
# Initialize MQTT interface with the ethernet interface
5959
MQTT.set_socket(socket, eth)
6060

6161
# Set up a MiniMQTT Client
6262
# NOTE: We'll need to connect insecurely for ethernet configurations.
63-
mqtt_client = MQTT.MQTT(broker = 'http://io.adafruit.com',
64-
username = secrets['aio_username'],
65-
password = secrets['aio_key'])
63+
mqtt_client = MQTT.MQTT(
64+
broker="http://io.adafruit.com",
65+
username=secrets["aio_username"],
66+
password=secrets["aio_key"],
67+
)
6668

6769
# Setup the callback methods above
6870
mqtt_client.on_connect = connected
6971
mqtt_client.on_disconnect = disconnected
7072
mqtt_client.on_message = message
7173

7274
# Connect the client to the MQTT broker.
73-
print('Connecting to Adafruit IO...')
75+
print("Connecting to Adafruit IO...")
7476
mqtt_client.connect()
7577

7678
photocell_val = 0
@@ -79,8 +81,8 @@ def message(client, topic, message):
7981
mqtt_client.loop()
8082

8183
# Send a new message
82-
print('Sending photocell value: %d...' % photocell_val)
84+
print("Sending photocell value: %d..." % photocell_val)
8385
mqtt_client.publish(photocell_feed, photocell_val)
84-
print('Sent!')
86+
print("Sent!")
8587
photocell_val += 1
8688
time.sleep(5)

examples/minimqtt_adafruitio_wifi.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,11 @@ def message(client, topic, message):
8888
MQTT.set_socket(socket, esp)
8989

9090
# Set up a MiniMQTT Client
91-
mqtt_client = MQTT.MQTT(broker='http://io.adafruit.com',
92-
username=secrets['aio_username'],
93-
password=secrets['aio_key'])
91+
mqtt_client = MQTT.MQTT(
92+
broker="http://io.adafruit.com",
93+
username=secrets["aio_username"],
94+
password=secrets["aio_key"],
95+
)
9496

9597
# Setup the callback methods above
9698
mqtt_client.on_connect = connected

examples/minimqtt_certificate.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,9 @@ def publish(client, userdata, topic, pid):
110110
MQTT.set_socket(socket, esp)
111111

112112
# Set up a MiniMQTT Client
113-
client = MQTT.MQTT(broker = secrets['broker'],
114-
username = secrets['user'],
115-
password = secrets['pass'])
113+
client = MQTT.MQTT(
114+
broker=secrets["broker"], username=secrets["user"], password=secrets["pass"]
115+
)
116116

117117
# Connect callback handlers to client
118118
client.on_connect = connect

examples/minimqtt_pub_sub_blocking.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -86,17 +86,17 @@ def message(client, topic, message):
8686
MQTT.set_socket(socket, esp)
8787

8888
# Set up a MiniMQTT Client
89-
mqtt_client = MQTT.MQTT(broker = secrets['broker'],
90-
username = secrets['user'],
91-
password = secrets['pass'])
89+
mqtt_client = MQTT.MQTT(
90+
broker=secrets["broker"], username=secrets["user"], password=secrets["pass"]
91+
)
9292

9393
# Setup the callback methods above
9494
mqtt_client.on_connect = connected
9595
mqtt_client.on_disconnect = disconnected
9696
mqtt_client.on_message = message
9797

9898
# Connect the client to the MQTT broker.
99-
print('Connecting to MQTT broker...')
99+
print("Connecting to MQTT broker...")
100100
mqtt_client.connect()
101101

102102
# Start a blocking message loop...

examples/minimqtt_pub_sub_nonblocking.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,9 @@ def message(client, topic, message):
8383
MQTT.set_socket(socket, esp)
8484

8585
# Set up a MiniMQTT Client
86-
mqtt_client = MQTT.MQTT(broker = secrets['broker'],
87-
username = secrets['user'],
88-
password = secrets['pass'])
86+
mqtt_client = MQTT.MQTT(
87+
broker=secrets["broker"], username=secrets["user"], password=secrets["pass"]
88+
)
8989

9090
# Setup the callback methods above
9191
mqtt_client.on_connect = connected

examples/minimqtt_pub_sub_pyportal.py

+15-11
Original file line numberDiff line numberDiff line change
@@ -16,32 +16,34 @@
1616
raise
1717

1818
# pylint: disable=protected-access
19-
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp,
20-
secrets, None)
19+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp, secrets, None)
2120

2221
# ------------- MQTT Topic Setup ------------- #
23-
mqtt_topic = 'test/topic'
22+
mqtt_topic = "test/topic"
2423

2524
### Code ###
2625
# Define callback methods which are called when events occur
2726
# pylint: disable=unused-argument, redefined-outer-name
2827
def connected(client, userdata, flags, rc):
2928
# This function will be called when the client is connected
3029
# successfully to the broker.
31-
print('Subscribing to %s' % (mqtt_topic))
30+
print("Subscribing to %s" % (mqtt_topic))
3231
client.subscribe(mqtt_topic)
3332

33+
3434
def disconnected(client, userdata, rc):
3535
# This method is called when the client is disconnected
36-
print('Disconnected from MQTT Broker!')
36+
print("Disconnected from MQTT Broker!")
37+
3738

3839
def message(client, topic, message):
3940
"""Method callled when a client's subscribed feed has a new
4041
value.
4142
:param str topic: The topic of the feed with a new value.
4243
:param str message: The new value
4344
"""
44-
print('New message on topic {0}: {1}'.format(topic, message))
45+
print("New message on topic {0}: {1}".format(topic, message))
46+
4547

4648
# Connect to WiFi
4749
print("Connecting to WiFi...")
@@ -53,10 +55,12 @@ def message(client, topic, message):
5355
MQTT.set_socket(socket, pyportal._esp)
5456

5557
# Set up a MiniMQTT Client
56-
mqtt_client = MQTT.MQTT(broker=secrets['broker'],
57-
username=secrets['user'],
58-
password=secrets['pass'],
59-
is_ssl=False)
58+
mqtt_client = MQTT.MQTT(
59+
broker=secrets["broker"],
60+
username=secrets["user"],
61+
password=secrets["pass"],
62+
is_ssl=False,
63+
)
6064

6165
# Setup the callback methods above
6266
mqtt_client.on_connect = connected
@@ -72,7 +76,7 @@ def message(client, topic, message):
7276
mqtt_client.loop()
7377

7478
# Send a new message
75-
print('Sending photocell value: %d' % photocell_val)
79+
print("Sending photocell value: %d" % photocell_val)
7680
mqtt_client.publish(mqtt_topic, photocell_val)
7781
photocell_val += 1
7882
time.sleep(1)

examples/minimqtt_simpletest.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,9 @@ def publish(client, userdata, topic, pid):
9595
MQTT.set_socket(socket, esp)
9696

9797
# Set up a MiniMQTT Client
98-
client = MQTT.MQTT(broker = secrets['broker'],
99-
username = secrets['user'],
100-
password = secrets['pass'])
98+
client = MQTT.MQTT(
99+
broker=secrets["broker"], username=secrets["user"], password=secrets["pass"]
100+
)
101101

102102
# Connect callback handlers to client
103103
client.on_connect = connect

0 commit comments

Comments
 (0)