IPWorks IoT 2020 Python Edition

Questions / Feedback?

MQTTSN Class

Properties   Methods   Events   Configuration Settings   Errors  

A lightweight, fully-featured MQTT-SN client implementation.

Syntax

class ipworksiot.MQTTSN

Remarks

The MQTTSN class provides a lightweight, fully-featured MQTT-SN (MQTT for Sensor Networks) client implementation over UDP.

Connecting

Connecting to a gateway is easy; in the simplest case, set the client_id property and call the connect method, passing it the gateway's hostname and port number.

When connecting to an MQTT gateway, the class sends the following information:

Refer to clean_session for more information about MQTT sessions; refer to will_topic, will_message, WillQOS and WillRetain for more information about MQTT Wills.

Basic Connection Example

mqttsn1.ClientId = "testClient";
mqttsn1.CleanSession = true;
mqttsn1.KeepAliveInterval = 30;
mqttsn1.WillTopic = "wills/" + mqttsn1.ClientId;
mqttsn1.WillMessage = mqttsn1.ClientId + " was disconnected ungracefully!";
mqttsn1.Connect(host, port);

Topic Subscriptions

The subscribe and unsubscribe methods are used to subscribe to and unsubscribe from topics.

When subscribing, pass the topic name or id, topic id type and QoS level. Topic filters may contain wildcards in order to match multiple topics on the server. If a topic name is specified, the SubscribedTopicId configuration setting will contain the assigned id for the topic.

Subscribe Examples

String fullTopicName = "full/topic/name";
mqttsn1.Subscribe(fullTopicName, 0, 2); // subscribe with topic name
int assignedTopicId = mqttsn1.Config("SubscribedTopicId"); // map id to topic name used

mqttsn1.Subscribe(fullTopicName+"/#", 0, 2) // topic name with wildcard; SubscribedTopicId will be 0
mqttsn1.OnTopicId += (s,e) => { // will fire before messages matching the wildcard are sent to the client
  int topicId = e.TopicId;
  String topicName = e.TopicName;
  // establish mapping between these
};

mqttsn1.Subscribe("aa", 2, 2); // subscribe with short topic name; no need for registration

After subscribing to topics, any messages received on that topic will cause the on_message_in event to fire. Refer to on_message_in for more information about processing steps for inbound messages.

When unsubscribing, pass the topic id or exact topic name used to subscribe.

Unsubscribe Examples

String fullTopicName = "full/topic/name";
mqtt1.Unsubscribe(fullTopicName, 0); // unsubscribe from topic name

mqtt1.Unsubscribe(fullTopicName+"/#", 0); // must use full topic filter if includes wildcard; can't unsubscribe from individual topics included in the filter

mqtt1.Unsubscribe("aa", 2); // unsubscribe from short topic

Refer to subscribe and unsubscribe for more information about subscriptions and topic names.

Publishing Messages

To publish messages to topics, use the publish_message and publish_data methods.

publish_message is used to publish a message with a string payload, while publish_data is used to publish a message with a raw data payload. Both also accept the topic id to publish to, the topic id type and a QoS level at which to publish.

Publish Examples

// Publish string messages
int id = mqttsn1.RegisterTopic("topic/name"); // must register topic names that are not short or pre-defined
mqttsn1.PublishMessage(id, 0, 2, "hello"); // publish message with registered topic name

mqttsn1.PublishMessage("aa", 2, 2, "hello"); // publish message with short topic name

// Publish a raw data message.
byte[] picture = ...;
mqtt1.PublishData(id, 0, 2, picture);

Refer to publish_data and publish_message for more information about message publishing as well as topic names.

Sleeping

To save battery, clients may enter a sleep state in which their messages will be buffered for them. To manage sleeping, use start_sleep and stop_sleep. To receive all buffered messages then return to sleep, use fetch_messages.

If the client exceeds the sleep duration passed to start_sleep without waking or sending any packets, it will be considered lost and will disconnect.

Sleep Examples

mqttsn1.StartSleep(8); // sleep for 8 seconds
// ... wait for 5 seconds
mqttsn1.FetchMessages(); // MessageIn will fire for each message buffered during that time
// ... wait for 5 more seconds (ok because <8 seconds since last packet sent)
mqttsn1.StopSleep();

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

clean_sessionDetermines whether a clean session is used once connected.
client_idA string that uniquely identifies this instance of the class to the server.
connectedTriggers a connection or disconnection.
keep_alive_intervalThe maximum period of inactivity the gateway should allow between receiving messages from the client.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
local_portThe UDP port in the local host where UDPPort binds.
remote_hostThe address of the remote host. Domain names are resolved to IP addresses.
remote_portThe UDP port in the remote host.
timeoutA timeout for the class.
will_messageThe message that the server should publish in the event of an ungraceful disconnection.
will_topicThe topic that the server should publish the WillMessage to in the event of an ungraceful disconnection.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

configSets or retrieves a configuration setting.
connectConnects to the MQTTSN Gateway.
disconnectDisconnect from the MQTTSN Gateway.
discover_gatewayBroadcast a SEARCHGW message to network clients and gateways.
do_eventsProcesses events from the internal message queue.
fetch_messagesReceive currently buffered messages and return to sleep.
pingSend a PINGREQ message to the gateway to reset the Keep Alive interval and ensure the gateway's liveliness.
publish_dataPublishes a message with a raw data payload.
publish_messagePublishes a message with a string payload.
register_topicRegister a topic name. Returns the topic id mapped to the newly registered topic name.
resetReset the class.
send_discover_responseAsynchronously respond to a SEARCHGW message received from a peer.
start_sleepEnter sleep state for the specified duration.
stop_sleepEnter active state, ending the sleep period.
subscribeSubscribes the class to the specified topic.
unsubscribeUnsubscribes the class from the specified topic.
update_will_messageUpdate the will message stored in session state data by the server.
update_will_topicUpdate the will topic, will QoS and will retain flag stored in session state data by the server.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_connectedFired after a MQTTSN connection completes (or fails).
on_disconnectedFired when a MQTTSN connection is closed.
on_discover_requestFired when the class receives a SEARCHGW packet from another client.
on_errorInformation about errors during data delivery.
on_gateway_infoFired when the class receives a GWINFO or ADVERTISE packet.
on_logFires once for each log message.
on_message_inFired when an incoming message has been received and/or fully acknowledged.
on_topic_infoFired when the client receives a REGISTER packet from the gateway assigning a topic id to a topic name.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

ConnectionTimeoutHow long to wait for a connection attempt to succeed.
DuplicateWhether to set the Duplicate flag when publishing a message.
LogLevelThe level of detail that is logged.
PingTimeoutLength of time to wait for a PINGRESP packet.
RetainWhether to set the Retain flag when publishing a message.
SubscribedTopicIdTopic id assigned by the gateway when a topic name is used in a SUBSCRIBE message.
SubscribeDUPWhether to set the Duplicate flag when subscribe to a topic.
WillQOSThe QoS value to use for the Will message.
WillRetainWhether the server should retain the Will message after publishing it.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks IoT 2020 Python Edition - Version 20.0 [Build 8265]