IPWorks IoT 2020 JavaScript Edition

Questions / Feedback?


Properties   Methods   Events   Configuration Settings   Errors  

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




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


Connecting to a gateway is easy; in the simplest case, set the ClientId 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 CleanSession for more information about MQTT sessions; refer to WillTopic, WillMessage, 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 MessageIn event to fire. Refer to MessageIn 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 PublishMessage and PublishData methods.

PublishMessage is used to publish a message with a string payload, while PublishData 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 PublishData and PublishMessage for more information about message publishing as well as topic names.


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

If the client exceeds the sleep duration passed to StartSleep 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)

Property List

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

CleanSessionDetermines whether a clean session is used once connected.
ClientIdA string that uniquely identifies this instance of the class to the server.
ConnectedTriggers a connection or disconnection.
KeepAliveIntervalThe maximum period of inactivity the gateway should allow between receiving messages from the client.
LocalHostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
LocalPortThe UDP port in the local host where UDPPort binds.
RemoteHostThe address of the remote host. Domain names are resolved to IP addresses.
RemotePortThe UDP port in the remote host.
TimeoutA timeout for the class.
WillMessageThe message that the server should publish in the event of an ungraceful disconnection.
WillTopicThe 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.
DiscoverGatewayBroadcast a SEARCHGW message to network clients and gateways.
DoEventsProcesses events from the internal message queue.
FetchMessagesReceive 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.
PublishDataPublishes a message with a raw data payload.
PublishMessagePublishes a message with a string payload.
RegisterTopicRegister a topic name. Returns the topic id mapped to the newly registered topic name.
ResetReset the class.
SendDiscoverResponseAsynchronously respond to a SEARCHGW message received from a peer.
StartSleepEnter sleep state for the specified duration.
StopSleepEnter active state, ending the sleep period.
SubscribeSubscribes the class to the specified topic.
UnsubscribeUnsubscribes the class from the specified topic.
UpdateWillMessageUpdate the will message stored in session state data by the server.
UpdateWillTopicUpdate 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.

ConnectedFired after a MQTTSN connection completes (or fails).
DisconnectedFired when a MQTTSN connection is closed.
DiscoverRequestFired when the class receives a SEARCHGW packet from another client.
ErrorInformation about errors during data delivery.
GatewayInfoFired when the class receives a GWINFO or ADVERTISE packet.
LogFires once for each log message.
MessageInFired when an incoming message has been received and/or fully acknowledged.
TopicInfoFired 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.
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 JavaScript Edition - Version 20.0 [Build 8265]