@@ -91,9 +91,9 @@ class MMQTTException(Exception):
91
91
92
92
def set_socket (sock , iface = None ):
93
93
"""Helper to set the global socket and optionally set the global network interface.
94
+
94
95
:param sock: socket object.
95
96
:param iface: internet interface object
96
-
97
97
"""
98
98
global _the_sock # pylint: disable=invalid-name, global-statement
99
99
_the_sock = sock
@@ -105,6 +105,7 @@ def set_socket(sock, iface=None):
105
105
106
106
class MQTT :
107
107
"""MQTT Client for CircuitPython
108
+
108
109
:param str broker: MQTT Broker URL or IP Address.
109
110
:param int port: Optional port definition, defaults to 8883.
110
111
:param str username: Username for broker authentication.
@@ -193,19 +194,22 @@ def __exit__(self, exception_type, exception_value, traceback):
193
194
self .deinit ()
194
195
195
196
def deinit (self ):
196
- """De-initializes the MQTT client and disconnects from
197
- the mqtt broker.
198
-
199
- """
197
+ """De-initializes the MQTT client and disconnects from the mqtt broker."""
200
198
self .disconnect ()
201
199
202
200
def will_set (self , topic = None , payload = None , qos = 0 , retain = False ):
203
- """Sets the last will and testament properties. MUST be called before connect().
204
- :param str topic: MQTT Broker topic.
205
- :param str payload: Last will disconnection payload.
206
- :param int qos: Quality of Service level.
207
- :param bool retain: Specifies if the payload is to be retained when it is published.
201
+ """Sets the last will and testament properties. MUST be called before `connect()`.
208
202
203
+ :param str topic: MQTT Broker topic.
204
+ :param int,float,str payload: Last will disconnection payload.
205
+ payloads of type int & float are converted to a string.
206
+ :param int qos: Quality of Service level, defaults to
207
+ zero. Conventional options are ``0`` (send at most once), ``1``
208
+ (send at least once), or ``2`` (send exactly once).
209
+
210
+ .. note:: Only options ``1`` or ``0`` are QoS levels supported by this library.
211
+ :param bool retain: Specifies if the payload is to be retained when
212
+ it is published.
209
213
"""
210
214
if self .logger is not None :
211
215
self .logger .debug ("Setting last will properties" )
@@ -225,18 +229,18 @@ def will_set(self, topic=None, payload=None, qos=0, retain=False):
225
229
226
230
def add_topic_callback (self , mqtt_topic , callback_method ):
227
231
"""Registers a callback_method for a specific MQTT topic.
228
- :param str mqtt_topic: MQTT topic.
229
- :param str callback_method: Name of callback method.
230
232
233
+ :param str mqtt_topic: MQTT topic identifier.
234
+ :param str callback_method: Name of callback method.
231
235
"""
232
236
if mqtt_topic is None or callback_method is None :
233
237
raise ValueError ("MQTT topic and callback method must both be defined." )
234
238
self ._on_message_filtered [mqtt_topic ] = callback_method
235
239
236
240
def remove_topic_callback (self , mqtt_topic ):
237
241
"""Removes a registered callback method.
238
- :param str mqtt_topic: MQTT topic.
239
242
243
+ :param str mqtt_topic: MQTT topic identifier string.
240
244
"""
241
245
if mqtt_topic is None :
242
246
raise ValueError ("MQTT Topic must be defined." )
@@ -249,8 +253,7 @@ def remove_topic_callback(self, mqtt_topic):
249
253
def on_message (self ):
250
254
"""Called when a new message has been received on a subscribed topic.
251
255
252
- Expected method signature is:
253
- on_message(client, topic, message)
256
+ Expected method signature is ``on_message(client, topic, message)``
254
257
"""
255
258
return self ._on_message
256
259
@@ -271,8 +274,8 @@ def _handle_on_message(self, client, topic, message):
271
274
# pylint: disable=too-many-branches, too-many-statements, too-many-locals
272
275
def connect (self , clean_session = True ):
273
276
"""Initiates connection with the MQTT Broker.
274
- :param bool clean_session: Establishes a persistent session.
275
277
278
+ :param bool clean_session: Establishes a persistent session.
276
279
"""
277
280
self ._sock = _the_sock .socket ()
278
281
self ._sock .settimeout (15 )
@@ -411,24 +414,30 @@ def ping(self):
411
414
# pylint: disable=too-many-branches, too-many-statements
412
415
def publish (self , topic , msg , retain = False , qos = 0 ):
413
416
"""Publishes a message to a topic provided.
417
+
414
418
:param str topic: Unique topic identifier.
415
- :param str msg: Data to send to the broker.
416
- :param int msg: Data to send to the broker.
417
- :param float msg: Data to send to the broker.
419
+ :param str,int,float msg: Data to send to the broker.
418
420
:param bool retain: Whether the message is saved by the broker.
419
- :param int qos: Quality of Service level for the message.
421
+ :param int qos: Quality of Service level for the message, defaults to
422
+ zero. Conventional options are ``0`` (send at most once), ``1``
423
+ (send at least once), or ``2`` (send exactly once).
424
+
425
+ .. note:: Only options ``1`` or ``0`` are QoS levels supported by this library.
420
426
421
427
Example of sending an integer, 3, to the broker on topic 'piVal'.
428
+
422
429
.. code-block:: python
423
430
424
431
mqtt_client.publish('topics/piVal', 3)
425
432
426
433
Example of sending a float, 3.14, to the broker on topic 'piVal'.
434
+
427
435
.. code-block:: python
428
436
429
437
mqtt_client.publish('topics/piVal', 3.14)
430
438
431
439
Example of sending a string, 'threepointonefour', to the broker on topic piVal.
440
+
432
441
.. code-block:: python
433
442
434
443
mqtt_client.publish('topics/piVal', 'threepointonefour')
@@ -509,27 +518,38 @@ def publish(self, topic, msg, retain=False, qos=0):
509
518
def subscribe (self , topic , qos = 0 ):
510
519
"""Subscribes to a topic on the MQTT Broker.
511
520
This method can subscribe to one topics or multiple topics.
512
- :param str topic: Unique MQTT topic identifier.
513
- :param int qos: Quality of Service level for the topic, defaults to zero.
514
- :param tuple topic: Tuple containing topic identifier strings and qos level integers.
515
- :param list topic: List of tuples containing topic identifier strings and qos.
521
+
522
+ :param str,tuple,list topic: Unique MQTT topic identifier string. If
523
+ this is a `tuple`, then the tuple should contain topic identifier
524
+ string and qos level integer. If this is a `list`, then each list
525
+ element should be a tuple containing a topic identifier string and
526
+ qos level integer.
527
+ :param int qos: Quality of Service level for the topic, defaults to
528
+ zero. Conventional options are ``0`` (send at most once), ``1``
529
+ (send at least once), or ``2`` (send exactly once).
530
+
531
+ .. note:: Only options ``1`` or ``0`` are QoS levels supported by this library.
516
532
517
533
Example of subscribing a topic string.
534
+
518
535
.. code-block:: python
519
536
520
537
mqtt_client.subscribe('topics/ledState')
521
538
522
539
Example of subscribing to a topic and setting the qos level to 1.
540
+
523
541
.. code-block:: python
524
542
525
543
mqtt_client.subscribe('topics/ledState', 1)
526
544
527
545
Example of subscribing to topic string and setting qos level to 1, as a tuple.
546
+
528
547
.. code-block:: python
529
548
530
549
mqtt_client.subscribe(('topics/ledState', 1))
531
550
532
551
Example of subscribing to multiple topics with different qos levels.
552
+
533
553
.. code-block:: python
534
554
535
555
mqtt_client.subscribe([('topics/ledState', 1), ('topics/servoAngle', 0)])
@@ -583,15 +603,19 @@ def subscribe(self, topic, qos=0):
583
603
584
604
def unsubscribe (self , topic ):
585
605
"""Unsubscribes from a MQTT topic.
586
- :param str topic: Unique MQTT topic identifier.
587
- :param list topic: List of tuples containing topic identifier strings.
606
+
607
+ :param str,list topic: Unique MQTT topic identifier string or a list
608
+ of tuples, where each tuple contains an MQTT topic identier
609
+ string.
588
610
589
611
Example of unsubscribing from a topic string.
612
+
590
613
.. code-block:: python
591
614
592
615
mqtt_client.unsubscribe('topics/ledState')
593
616
594
617
Example of unsubscribing from multiple topics.
618
+
595
619
.. code-block:: python
596
620
597
621
mqtt_client.unsubscribe([('topics/ledState'), ('topics/servoAngle')])
@@ -645,6 +669,7 @@ def unsubscribe(self, topic):
645
669
646
670
def reconnect (self , resub_topics = True ):
647
671
"""Attempts to reconnect to the MQTT broker.
672
+
648
673
:param bool resub_topics: Resubscribe to previously subscribed topics.
649
674
"""
650
675
if self .logger is not None :
@@ -668,11 +693,11 @@ def loop_forever(self):
668
693
method if you want to run a program forever.
669
694
Code below a call to this method will NOT execute.
670
695
671
- NOTE : This method is depreciated and will be removed in the
672
- next major release. Please see examples/minimqtt_pub_sub_blocking.py
673
- for an example of creating a blocking loop which can handle wireless
674
- network events.
675
-
696
+ .. note: : This method is depreciated and will be removed in the
697
+ next major release. Please see
698
+ `examples/minimqtt_pub_sub_blocking.py <examples.html#basic-forever- loop>`_
699
+ for an example of creating a blocking loop which can handle wireless
700
+ network events.
676
701
"""
677
702
while True :
678
703
if self ._sock .connected :
@@ -681,7 +706,6 @@ def loop_forever(self):
681
706
def loop (self ):
682
707
"""Non-blocking message loop. Use this method to
683
708
check incoming subscription messages.
684
-
685
709
"""
686
710
if self ._timestamp == 0 :
687
711
self ._timestamp = time .monotonic ()
@@ -744,6 +768,7 @@ def _recv_len(self):
744
768
745
769
def _send_str (self , string ):
746
770
"""Packs and encodes a string to a socket.
771
+
747
772
:param str string: String to write to the socket.
748
773
"""
749
774
self ._sock .send (struct .pack ("!H" , len (string )))
@@ -755,6 +780,7 @@ def _send_str(self, string):
755
780
@staticmethod
756
781
def _check_topic (topic ):
757
782
"""Checks if topic provided is a valid mqtt topic.
783
+
758
784
:param str topic: Topic identifier
759
785
"""
760
786
if topic is None :
@@ -769,6 +795,7 @@ def _check_topic(topic):
769
795
@staticmethod
770
796
def _check_qos (qos_level ):
771
797
"""Validates the quality of service level.
798
+
772
799
:param int qos_level: Desired QoS level.
773
800
"""
774
801
if isinstance (qos_level , int ):
@@ -789,7 +816,7 @@ def _set_interface(self):
789
816
790
817
def is_connected (self ):
791
818
"""Returns MQTT client session status as True if connected, raises
792
- a MMQTTException if False.
819
+ a ` MMQTTException` if ` False` .
793
820
"""
794
821
if self ._sock is None or self ._is_connected is False :
795
822
raise MMQTTException ("MiniMQTT is not connected." )
@@ -803,6 +830,7 @@ def mqtt_msg(self):
803
830
@mqtt_msg .setter
804
831
def mqtt_msg (self , msg_size ):
805
832
"""Sets the maximum MQTT message payload size.
833
+
806
834
:param int msg_size: Maximum MQTT payload size.
807
835
"""
808
836
if msg_size < MQTT_MSG_MAX_SZ :
@@ -811,14 +839,18 @@ def mqtt_msg(self, msg_size):
811
839
### Logging ###
812
840
def attach_logger (self , logger_name = "log" ):
813
841
"""Initializes and attaches a logger to the MQTTClient.
842
+
814
843
:param str logger_name: Name of the logger instance
815
844
"""
816
845
self .logger = logging .getLogger (logger_name )
817
846
self .logger .setLevel (logging .INFO )
818
847
819
848
def set_logger_level (self , log_level ):
820
849
"""Sets the level of the logger, if defined during init.
821
- :param string log_level: Level of logging to output to the REPL.
850
+
851
+ :param str log_level: Level of logging to output to the REPL.
852
+ Acceptable options are ``DEBUG``, ``INFO``, ``WARNING``, or
853
+ ``ERROR``.
822
854
"""
823
855
if self .logger is None :
824
856
raise MMQTTException (
0 commit comments