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:
- The values of the client_id, clean_session, and keep_alive_interval properties.
- The values of the will_topic and will_message properties and the WillRetain and WillQOS configuration settings.
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_session | Determines whether a clean session is used once connected. |
client_id | A string that uniquely identifies this instance of the class to the server. |
connected | Triggers a connection or disconnection. |
keep_alive_interval | The maximum period of inactivity the gateway should allow between receiving messages from the client. |
local_host | The name of the local host or user-assigned IP interface through which connections are initiated or accepted. |
local_port | The UDP port in the local host where UDPPort binds. |
remote_host | The address of the remote host. Domain names are resolved to IP addresses. |
remote_port | The UDP port in the remote host. |
timeout | A timeout for the class. |
will_message | The message that the server should publish in the event of an ungraceful disconnection. |
will_topic | The 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.
config | Sets or retrieves a configuration setting. |
connect | Connects to the MQTTSN Gateway. |
disconnect | Disconnect from the MQTTSN Gateway. |
discover_gateway | Broadcast a SEARCHGW message to network clients and gateways. |
do_events | Processes events from the internal message queue. |
fetch_messages | Receive currently buffered messages and return to sleep. |
ping | Send a PINGREQ message to the gateway to reset the Keep Alive interval and ensure the gateway's liveliness. |
publish_data | Publishes a message with a raw data payload. |
publish_message | Publishes a message with a string payload. |
register_topic | Register a topic name. Returns the topic id mapped to the newly registered topic name. |
reset | Reset the class. |
send_discover_response | Asynchronously respond to a SEARCHGW message received from a peer. |
start_sleep | Enter sleep state for the specified duration. |
stop_sleep | Enter active state, ending the sleep period. |
subscribe | Subscribes the class to the specified topic. |
unsubscribe | Unsubscribes the class from the specified topic. |
update_will_message | Update the will message stored in session state data by the server. |
update_will_topic | Update 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_connected | Fired after a MQTTSN connection completes (or fails). |
on_disconnected | Fired when a MQTTSN connection is closed. |
on_discover_request | Fired when the class receives a SEARCHGW packet from another client. |
on_error | Information about errors during data delivery. |
on_gateway_info | Fired when the class receives a GWINFO or ADVERTISE packet. |
on_log | Fires once for each log message. |
on_message_in | Fired when an incoming message has been received and/or fully acknowledged. |
on_topic_info | Fired 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.
ConnectionTimeout | How long to wait for a connection attempt to succeed. |
Duplicate | Whether to set the Duplicate flag when publishing a message. |
LogLevel | The level of detail that is logged. |
PingTimeout | Length of time to wait for a PINGRESP packet. |
Retain | Whether to set the Retain flag when publishing a message. |
SubscribedTopicId | Topic id assigned by the gateway when a topic name is used in a SUBSCRIBE message. |
SubscribeDUP | Whether to set the Duplicate flag when subscribe to a topic. |
WillQOS | The QoS value to use for the Will message. |
WillRetain | Whether the server should retain the Will message after publishing it. |
BuildInfo | Information about the product's build. |
CodePage | The system code page used for Unicode to Multibyte translations. |
LicenseInfo | Information about the current license. |
ProcessIdleEvents | Whether the class uses its internal event loop to process events when the main thread is idle. |
SelectWaitMillis | The length of time in milliseconds the class will wait when DoEvents is called if there are no events to process. |
UseInternalSecurityAPI | Tells the class whether or not to use the system security libraries or an internal implementation. |