NEQTO Docs
  • Languages iconEnglish
    • 日本語
  • Docs
  • API
  • FAQ

›neqto.js

Getting Started

  • NEQTO Hello World!
  • Tutorial Step 1. NEQTO Console Setting
  • Tutorial Step 2. Device Settings & Launching Service (NEQTO Bridge)
  • Tutorial Step 2. Device Settings & Launching Service (STM32 Discovery)
  • Tutorial Step 2. Device Settings & Launching Service (SPRESENSE)
  • Tutorial Step 3. Application development using scripts

NEQTO

  • NEQTO Account Registration
  • Sub-accounts
  • API Usage
  • NEQTO CloudSync for GCP
  • NEQTO Engine Firmware List
  • Support Guidelines

NEQTO Console

  • Introduction
  • Fundamentals
  • Administrative Actions
  • Device Management
  • Linux-based Device Management
  • Batch Registration
  • Scripts
  • Actions and Contacts
  • View Data from the Console
  • NEQTO Apps

    • About NEQTO Apps
    • NEQTO Infinitypool
    • NEQTO Insights
    • NEQTO Custodia
    • NEQTO Flow
  • Machine Driver
  • Recommended Browsers
  • Billing Information

SPRESENSE

    Hardware Specifications

    • 01. About Spresense

    Software Specifications

    • 01. Operational Flow
    • 02. Initial Installation
    • 03. Spresense Wi-Fi Initial Setup
    • 04. Spresense LTE-M Initial Setup
    • 05. Debug Log Acquisition
    • 06. System LED Indications
    • 07. Event Messages
    • 08. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. GPIO
    • 12. UART
    • 13. SPI
    • 14. I2C
    • 15. ADC
    • 16. GNSS
    • 17. Camera
    • 18. Utils
    • 19. nqSpresense
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi
    • 24. nqLte

STM32 Discovery

    Hardware Specifications

    • 01. About STM32 Discovery Kit (B-L4S5I-IOT01A)

    Software Specifications

    • 01. Operational Flow
    • 02. Initial Installation
    • 03. STM32 Discovery Wi-Fi Initial Setup
    • 04. Debug Log Acquisition
    • 05. System LED Indications
    • 06. Event Messages
    • 07. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. UserSW
    • 12. GPIO
    • 13. UART
    • 14. SPI
    • 15. I2C
    • 16. ADC
    • 18. Utils
    • 19. nqDiscovery
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi

NEQTO Bridge

    Hardware Specifications

    • 01. NEQTO Bridge Module
    • 02. NEQTO Bridge Wi-Fi Module
    • 03. NEQTO Bridge LTE-1 Module
    • 04. NEQTO Bridge LTE-M/NB Module
    • 05. NEQTO Bridge IO Board
    • 06. NEQTO Bridge Digital IO Board
    • 07. NEQTO Bridge Connector Board

    Software Specifications

    • 01. Operational Flow
    • 02. NEQTO Bridge Wi-Fi Module Initial Setup
    • 03. NEQTO Bridge LTE Module Initial Setup
    • 04. Debug Log Acquisition
    • 05. System LED Indications
    • 06. Event Messages
    • 07. Updating Firmware

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. Sleep
    • 10. RTC
    • 11. UserSW
    • 12. GPIO
    • 13. UART
    • 14. SPI
    • 15. I2C
    • 16. ADC
    • 17. BLE
    • 18. Utils
    • 19. nqBridge
    • 20. nqService
    • 21. nqMqtt
    • 22. nqFOTA
    • 23. nqWiFi
    • 24. nqLte
    • 25. nqLAN
    • 26. nqEx

Linux-based device

    Software Specifications

    • 01. System Requirements
    • 02. Installation
    • 03. Software Configurations
    • 04. Operational Flow
    • 05. Debug Log Acquisition
    • 06. Event Messages
    • 07. Updating Software

    neqto.js

    • 01. About neqto.js
    • 02. Log
    • 03. Timers
    • 04. HTTP
    • 05. HTTPS
    • 06. MQTT
    • 07. Secure
    • 08. Storage
    • 09. RTC
    • 10. UNIXSocket
    • 11. FileSystem
    • 12. SubProcess
    • 13. Utils
    • 14. nqLinux
    • 15. nqService
    • 16. nqMqtt
    • 17. nqFOTA
    • 18. nqLAN

neqto.js Libraries

  • About neqto.js Libraries
  • UART

    • GM65 Barcode Reader
    • SRF Ultrasonic Range Finder - Serial Mode

    I2C

    • HTS221 v2 Temperature and Humidity Sensor
    • LIS2DW12 v2 Accelerometer
    • SRF Ultrasonic Range Finder - I2C Mode
    • [Archive] HTS221 Temperature and Humidity Sensor
    • [Archive] LIS2DW12 Accelerometer

    Utils

    • RTC Alarm Synchronized Scheduler

    Integration

    • AWS S3 v2
    • AWS IoT Core v2
    • Azure IoT v2
    • GCP IoT Core
    • [Archive] AWS S3
    • [Archive] AWS IoT Core

neqto.js Snippets

  • About neqto.js Snippets
  • DataDog
  • Dropbox
  • Google Sheets
  • InfluxDB
  • Oracle Cloud Object Storage
  • Salesforce
  • SAP Cloud Platform Internet of Things
  • Splunk
  • Niagara

Release Notes

  • NEQTO Console Updates
  • NEQTO Firmware (Bridge Wi-Fi/LTE Module) Releases
  • NEQTO Firmware (STM32 Discovery Wi-Fi) Releases
  • NEQTO Firmware (Spresense Wi-Fi/LTE-M) Releases
  • NEQTO Engine for Linux Releases

06. MQTT

The mqtt object is a built-in object that provides MQTT client functionality.

Functional overview:

  • Provides the MQTT client function.
  • Supports MQTT v3.1.1 and v3.1.
  • Supports TLS.
  • Supports server and client authentication.

Limitations:

  • The number of MQTT session resources that can be used is 1.



mqtt Global Object

Methods()/PropertiesSummaryVersionNote
mqtt.connect()Starts an MQTT connection.01.00.00+A {Client} instance is generated.
mqtt.set()Sets the information used for the connection.01.00.00+



Details

mqtt.connect(url[,options])

Starts an MQTT connection.
Generates a {Client} instance.

NameTypeM/OSummaryNote
urlstringmandatoryBroker URL
URL is specified in [protocol]://[hostname]:[port] format.
The maximum number of characters is 255 bytes.

protocol
Specify ’mqtt’ or ’mqtts’.
hostname
Domain name or IP address of the MQTT Broker
port
Port number
Specify a decimal digit string.
The default value is 1883.

The TLS CA certificate can be set with mqtt.set().
optionsObjectoptionalMQTT connection options
Refer to options for details.
return{Client}, undefined-{Client} : Generated {Client}
undefined : {Client} generate failed due to invalid arguments or insufficient resources.

options

NameTypeM/OSummaryNote
keepalivenumberoptionalKeep-alive time [s]
0: Invalid
Range: 0 - 2,147,483,647
Default: 60
clientIdstringoptionalMQTT client id
Range: 1 - 127 bytes of single-byte alphanumeric characters
Default: 'mqttjs_' + 8 random decimal digits
protocolIdstringoptionalProtocol id
Default: MQTT
protocolVersionnumberoptionalMQTT protocol version
4: MQTT v3.1.1
3: MQTT v3.1
When setting to 3, set protocolId to ’MQIsdp’.
Default: 4
reconnectPeriodnumberoptionalTime to wait to reconnect when disconnected [ms]
Range: 0 - 10000
Default: 1000
connectTimeoutnumberoptionalConnection timeout (wait for CONNACK) [ms]
Range: 0 - 2,147,483,647
Default: 30000
usernamestringoptionalUsername
Set if broker requires username.
Range: 1 - 511 bytes of single-byte alphanumeric characters (Version 01.00.00+)
Range: 1 - 127 bytes of single-byte alphanumeric characters (Previous Versions)
Default: None
passwordstringoptionalPassword
Set if broker requires password.
Range: 1 - 511 bytes of single-byte alphanumeric characters (Version 01.00.00+)
Range: 1 - 159 bytes of single-byte alphanumeric characters (Previous Versions)
Default: None
reconnectCountnumberoptionalNumber of automatic reconnection retries
If set to 0, automatic reconnection is disabled.
0: Invalid
1855: Infinite times
Range: 0 - 999, 1855
Default: 0

This is a sample that specifies a user name and password and starts a connection to foo.bar.

var mqttOpt = {
    clientId: 'testClientId',
    username: 'foo',
    password: 'bar',
    keepalive: 300
};
var client = mqtt.connect('mqtt://foo.bar',mqttOpt);

mqtt.set(name[,arg])

Sets the information used for a connection.

NameTypeM/OSummaryNote
namestringmandatorySetting name
Names that can be used are: ssl.ca, ssl.cert, ssl.key
argstringoptionalSetting information
returnundefined--

mqtt.set(’ssl.ca’,certificate);

Sets the CA certificate used for the MQTTS connection.

NameTypeM/OSummaryNote
’ssl.ca’stringmandatoryName for setting CA certificate
certificatestringoptionalSet the CA certificate used for the MQTTS connection.
If omitted, the CA certificate settings are released.
returnundefined--

Set as follows:
Use \n for line feed code.

var sslCa = '-----BEGIN CERTIFICATE-----\n' + 
'(...ContentOmission...)\n' + 
//...Omit...
'(...ContentOmission...)\n' + 
'-----END CERTIFICATE-----';

mqtt.set('ssl.ca', sslCa);

mqtt.set(’ssl.cert’,certificate);

Sets the client certificate used for the MQTTS connection.
If not set, client authentication is disabled.

NameTypeM/OSummaryNote
’ssl.cert’stringmandatoryName for setting client certificate
certificatestringoptionalSet the client certificate used for the MQTTS connection.
If omitted, the client certificate settings are released.
returnundefined--

mqtt.set(’ssl.key’,clientkey);

Sets the client private key used for the MQTTS connection.
If not set, client authentication is disabled.

NameTypeM/OSummaryNote
’ssl.key’stringmandatoryName for setting client private key
clientkeystringoptionalSet the client private key used for the MQTTS connection.
If omitted, the client private key settings are released.
returnundefined--

If you want to connect MQTTS using client authentication, set as follows:

var sslCa = '-----BEGIN CERTIFICATE-----\n(...ContentOmission...)\n-----END CERTIFICATE-----';
var sslClientCa  = '-----BEGIN CERTIFICATE-----\n(...ContentOmission...)\n-----END CERTIFICATE-----';
var sslClientKey = '-----BEGIN PRIVATE KEY-----\n(...ContentOmission...)\n-----END PRIVATE KEY-----';
mqtt.set('ssl.ca', sslCa);
mqtt.set('ssl.cert', sslClientCa);
mqtt.set('ssl.key', sslClientKey);



{Client}

Methods()/PropertiesSummaryVersionNote
.on()Registers an event handler.01.00.00+
.publish()Publishes a message to a topic.01.00.00+
.subscribe()Subscribes to a topic.01.00.00+
.unsubscribe()Unsubscribes from a topic.01.00.00+
.end()Disconnects MQTT and exit.01.00.00+
.reconnect()Initiates an MQTT reconnection.01.00.00+
.isConnected()Gets MQTT connection status.01.00.00+
.isReconnecting()Gets the status of MQTT when reconnecting.01.00.00+
.canPublish()Gets the status of whether the MQTT message can be published.01.00.00+
.get()Gets information related to the given argument.01.00.00+



Details

.on(event,callback)

Registers an event handler.

NameTypeM/OSummaryNote
eventstringmandatoryEvent name
Names that can be used are: connect, reconnect, close, error, end, message
callback()functionmandatoryExecutes callback processing when an event occurs.
returnundefined--

event : ’connect’

Executes callback when MQTT connection and reconnection are successful.
The arguments for the callback are as follows:

ArgumentsTypeSummaryNote
connackObjectconnack is the content of the recieved connack packet.
This argument is not mandatory.

event : ’reconnect’

Executes callback when MQTT reconnection is started.

event : ’close’

Executes callback when MQTT is disconnected.

event : ’error’

Executes callback when an error occurs or the MQTT connection fails.
The arguments for the callback are as follows:

ArgumentsTypeSummaryNote
err{MqttError}Error information

event : ’end’

Executes callback processing when .end() processing is started.

event : ’message’

Executes callback when a publish message received.
The arguments for the callback are as follows:

ArgumentsTypeSummary                                                 Note
topicstringThe topic of the received publish
messagestring, ArrayBufferThe message of the received publish
A string of up to 380 bytes.
If the maximum number of bytes is exceeded, the message is discarded.
The ArrayBuffer type is supported from Version 01.03.00 or later. Specify the type with the bin option of .subscribe().

.publish(topic,message[,options][,callback])

Publishes a message to a topic.

NameTypeM/OSummaryNote
topicstringmandatoryTopic name
Topic name can be up to 127 bytes of alphanumeric characters and the symbols /, *, and #.
messagestring, ArrayBuffermandatoryThe message to publish
If the message to be published is more than 2500 bytes, an argument error occurs and the callback process of .on('error') is executed.
The ArrayBuffer type is supported from Version 01.03.00 or later.
optionsObjectoptionalPublish options
qos : {number}
QoS level
Range: 0, 1, 2
Default: 0
retain : {boolean}
Retain flag
Default: false
dup : {boolean}
Duplicate flag
Default: false
Refer to the MQTT specifications for details such as QoS parameters. (http://mqtt.org/)
callback(err)functionoptionalExecute the callback process when the publish process is completed.
err : {MqttError}
Error information
When err.code is 0, it means success.
returnundefined, {MqttError}-{MqttError} : If the request is not accepted due to an illegal argument error, disconnection, etc., {MqttError} is returned. (Version 02.00.00+)

Note: If the next .publish() is performed before the current .publish() callback, the latter .publish() may be discarded. Before performing a .publish(), it is recommended to check whether the callback of the previous .publish() has been executed, or check whether publishing is possible with .canPublish().

.subscribe(topic[,options][,callback])

Subscribes to a topic.
Up to 5 topics can be subscribed to.

NameTypeM/OSummaryNote
topicstringmandatoryTopic name
Topic name can be up to 127 bytes of alphanumeric characters and the symbols /, *, and #.
optionsObjectoptionalSubscribe options
qos : {number}
QoS level
Range: 0, 1, 2
Default: 0
bin : {boolean} (Version 01.03.00+)
Specifies the type of the 'message' argument of message event.
true: ArrayBuffer
false: string
Default: false
callback(err)functionoptionalExecute the callback process when the subscribe process is completed.
err : {MqttError}
Error information
An err.code value of 0 means success.
returnundefined, {MqttError}-{MqttError} : If the request is not accepted due to an illegal argument error, disconnection, etc., {MqttError} is returned. (Version 02.00.00+)

.unsubscribe(topic[,callback])

Unsubscribes from a topic.

NameTypeM/OSummaryNote
topicstringmandatoryTopic name
Topic name can be up to 127 bytes of alphanumeric characters and the symbols /, *, and #.
callback(err)functionoptionalExecute the callback process when the unsubscribe process is completed.
err : {MqttError}
Error information
An err.code value of 0 means success.
returnundefined, {MqttError}-{MqttError} : If the request is not accepted due to an illegal argument error, disconnection, etc., {MqttError} is returned. (Version 02.00.00+)

.end([,callback])

Disconnects MQTT and exit.
It may take some time before the MQTT session resource is released.
If you want to connect MQTT again, you need to wait until MQTT session resource is released.
Please refer to Sample Code.

NameTypeM/OSummaryNote
callback()functionoptionalExecutes callback processing when releasing MQTT session resources.
returnundefined--

.reconnect()

Initiates an MQTT reconnection.

NameTypeM/OSummaryNote
returnundefined--

.isConnected()

Gets MQTT connection status.

NameTypeM/OSummaryNote
returnboolean-MQTT connection status
true: MQTT connected
false: Not connected

.isReconnecting()

Gets the status of MQTT when reconnecting.

NameTypeM/OSummaryNote
returnboolean-MQTT reconnecting status
true: MQTT reconnecting
false: Not reconnecting

.canPublish()

Gets the status of whether the MQTT message can be published.

NameTypeM/OSummaryNote
returnboolean-Whether the MQTT message can be published
true: Can publish
false: Cannot publish

.get(name)

Gets information related to the given argument.

NameTypeM/OSummaryNote
namestringmandatoryThe name of the information to be obtained
The name that can be used is errnoConnect.
returnnumber, undefined-number : Acquired information
undefined : When information cannot be obtained

.get(’errnoConnect’)

Gets the connection error number.

NameTypeM/OSummaryNote
’errnoConnect’stringmandatoryName to get connection error number
returnnumber-Refer to errnoConnect table for connection error number details.



Appendix

{MqttError}

Methods()/PropertiesTypeSummaryNote
.codenumberError code
Refer to mqtt errors table for error code details.
.messagestringError contents
Refer to mqtt errors table for error content details.

mqtt errors table

The following is the error code table.
"✓" indicates the callback to be notified. (xx.xx.xx) is the supported FW version.

.code.messageNote.on('error',cb).publish(cb).subscribe(cb).unsubscribe(cb)
0OKNo error✓✓✓
1Connection failedConnection (reconnection) failure✓
10Illegal argumentInvalid argument error✓✓ (02.00.00+)✓ (02.00.00+)✓ (02.00.00+)
11Disconnected *Disconnect error✓✓✓
12Publish failedPublish failed✓ (02.00.00+)✓
13Subscribe failedSubscribe failed✓ (02.00.00+)✓
14Unsubscribe failedUnsubscribe failed✓ (02.00.00+)✓
255Other errorOther errors✓

* Notified when publish()/subscribe()/unsubscribe() is executed while unconnected.

errnoConnect table

The following is the connection error code table.

errnoConnectSummaryNote
0OKNo error
1Unacceptable protocol versionProtocol version not supported
2Identifier rejectedIdentifier rejection
3Server unavailableServer unavailable
4Bad user name or passwordInvalid username or password
5Not authorizedPermission error
6Connection failedOther errors (mainly network errors)
7SSL/TLS errorTLS related errors
OthersReservedReserved



Object Usage Examples

Sample 1

This is a sample MQTT connection.
Starts a 10-second period timer, transmits and receives.

var client = mqtt.connect('mqtt://foo.bar');
if(!client) {
    print('Failed to create mqtt instance');
} else {
    client.on('connect', function(connack) {
        print('CONNECTED');
        client.subscribe('foo_topic/device01');
    });
    client.on('error', function(err) {
        print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
        if(1 == err.code) { //Connection failed
            client.reconnect();
        }
        //TODO: Error handling
    });
    client.on('close', function() {
        print("DISCONNECTED");
        client.reconnect();
    });
    client.on('message', function(topic, message) {
        print('TOPIC: ' + topic + ' MESSAGE: ' + message);
        //TODO: Message handling
    });
}
var tmobj = setInterval(function() {
    if(!client) {
    } else {
        if(client.isConnected()) {
            var dummyBatteryLevel = 10;
            if(10 >= dummyBatteryLevel) {
                client.publish( 'bar_topic/device01',
                                'Battery level : '
                                 + dummyBatteryLevel.toString()
                                 + '%');
            }
        } else {
            print('Skipped');
        }
    }
}, 10000);

Sample 2

This is a sample MQTTS connection.
Starts a 10-second period timer, transmits and receives.

var sslCa = '-----BEGIN CERTIFICATE-----\n(...ContentOmission...)\n-----END CERTIFICATE-----';
mqtt.set('ssl.ca', sslCa);

var client = mqtt.connect('mqtts://foo.bar:8883');
if(!client) {
    print('Failed to create mqtt instance');
} else {
    client.on('connect', function(connack) {
        print('CONNECTED');
        client.subscribe('foo_topic/device01');
    });
    client.on('error', function(err) {
        print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
        if(1 == err.code) { //Connection failed
            client.reconnect();
        }
        //TODO: Error handling
    });
    client.on('close', function() {
        print("DISCONNECTED");
        client.reconnect();
    });
    client.on('message', function(topic, message) {
        print('TOPIC: ' + topic + ' MESSAGE: ' + message);
        //TODO: Message handling
    });
}
var tmobj = setInterval(function() {
    if(!client) {
    } else {
        if(client.isConnected()) {
            var dummyBatteryLevel = 10;
            if(10 >= dummyBatteryLevel) {
                client.publish( 'bar_topic/device01',
                                'Battery level : '
                                 + dummyBatteryLevel.toString()
                                 + '%');
            }
        } else {
            print('Skipped');
        }
    }
}, 10000);

Sample 3

This is a sample MQTTS connection using client authentication.
Starts a 10-second period timer, transmits and receives.

var sslCa = '-----BEGIN CERTIFICATE-----\n(...ContentOmission...)\n-----END CERTIFICATE-----';
var sslClientCert = '-----BEGIN CERTIFICATE-----\n(...ContentOmission...)\n-----END CERTIFICATE-----';
var sslClientKey = '-----BEGIN PRIVATE KEY-----\n(...ContentOmission...)\n-----END PRIVATE KEY-----';
mqtt.set('ssl.ca', sslCa);
mqtt.set('ssl.cert', sslClientCert);
mqtt.set('ssl.key', sslClientKey);

var mqttClientId = 'foo';
var mqttUser = 'foo';
var mqttPass = 'foobar';
var mqttOpt = {clientId:mqttClientId, username:mqttUser, password:mqttPass, reconnectCount:1855};

var client = mqtt.connect('mqtts://foo.bar:8883', mqttOpt);
if(!client) {
    print('Failed to create mqtt instance');
} else {
    client.on('connect', function(connack) {
        print('CONNECTED');
        client.subscribe('foo_topic/device01');
    });
    client.on('error', function(err) {
        print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
        if(1 == err.code) { //Connection failed
            client.reconnect();
        }
        //TODO: Error handling
    });
    client.on('close', function() {
        print("DISCONNECTED");
        client.reconnect();
    });
    client.on('message', function(topic, message) {
        print('TOPIC: ' + topic + ' MESSAGE: ' + message);
        //TODO: Message handling
    });
}
var tmobj = setInterval(function() {
    if(!client) {
    } else {
        if(client.isConnected()) {
            var dummyBatteryLevel = 10;
            if(10 >= dummyBatteryLevel) {
                client.publish( 'bar_topic/device01',
                                'Battery level : '
                                 + dummyBatteryLevel.toString()
                                 + '%');
            }
        } else {
            print('Skipped');
        }
    }
}, 10000);

Sample 4

This sample repeats the start and end of MQTT connection.
If you do mqtt.connect() immediately after exiting with .end(), mqtt.connect() may fail because MQTT resources have not been released yet. In that case, wait a while and try the connection again.

var mqttUrl = 'mqtt://foo.bar:1883';
var mqttc = undefined;
var endEv = 0;

var to = setInterval(function() {
    print('end event');
    endEv = 1;
}, 30000);

while(1) {
    if(!mqttc) {
        mqttc = mqtt.connect(mqttUrl, {reconnectCount:1855});
        if(!mqttc) {
            print('Waiting for mqtt resource release');
            setTimeout(200).wait();
            continue;
        }
        mqttc.on('connect', function(connack) {
            print('CONNECTED');
        });
        //  ...Omitted: Registers an event handler.
    }
    //  ...Omitted: mqtt communication processing.
    if(1 == endEv) {
        endEv = 0;
        print('ABORT');
        mqttc.end();
        mqttc = undefined;
        continue;
    }
}

Sample 5

This is a sample to connect MQTT with automatic reconnection enabled.
After connection, loopback test of transmission and reception is performed.

var client = mqtt.connect('mqtt://foo.bar:1883', {reconnectCount: 1855});
if(!client) {
    throw 'Failed to create mqtt instance';
}

client.on('error', function(err) {
    print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
    //TODO: Error handling
});
client.on('message', function(topic, message) {
    print('TOPIC: ' + topic + ' MESSAGE: ' + message);
    //TODO: Message handling
});
client.on('connect', function() {
    print('CONNECTED');
    client.subscribe('testtopic/subtopic/#', { qos: 1 }, function(err) {
        if(err.code > 0) {
            print('MQTT SUBSCRIBE ERROR', err.code);
            //TODO: Error handling
        }
    });
    client.subscribe('shadowtopic/#', { qos: 1 }, function(err) {
        if(err.code > 0) {
            print('MQTT SUBSCRIBE ERROR', err.code);
            //TODO: Error handling
        }
    });
});

setInterval(function() {
    if (client.canPublish()) {
        var body = JSON.stringify({ "message" : "dummy" });
        client.publish('testtopic/subtopic/dummy', body, { qos: 1 }, function(err) {
            if(err.code == 0) {
                print('Publish OK');
            } else {
                print('Publish failed');
                //TODO: Error handling
            }
        });
    } else {
        print('Cannot publish');
    }
}, 15000);

Sample 6

This is a sample to manually reconnect MQTT.
If the reconnects fail consecutively, release the instance and recreate it.

var mqttUrl = 'mqtt://foo.bar:1883';
var reconnectAttempts = 0;
var maxReconnectAttempts = 24;

var registerEventHandlers = function() {
    if(!client) {
        return;
    }
    client.on('error', function(err) {
        print('ERROR: ' + err.code + ' ERRNO: ' + client.get('errnoConnect'));
        if (err.code == 1) { //Connection failed
            if (reconnectAttempts++ < maxReconnectAttempts) {
                print('reconnectAttempts:', reconnectAttempts);
                client.reconnect();
            } else {
                print('ABORT');
                reconnectAttempts = 0;
                client.end(); //Release mqtt instance
                client = undefined;
            }
        }
    });
    client.on('message', function(topic, message) {
        print('TOPIC: ' + topic + ' MESSAGE: ' + message);
        //TODO: Message handling
    });
    client.on('close', function() {
        print("DISCONNECTED");
        client.reconnect();
    });
    client.on('connect', function() {
        reconnectAttempts = 0;
        print("CONNECTED");
        client.subscribe("foo_topic/device01/#", { qos: 1 }, function(err) {
            if(err.code > 0) {
                print("MQTT SUBSCRIBE ERROR", err.code);
                //TODO: Error handling
            }
        });
    });
}

var client = mqtt.connect(mqttUrl);
if(!client) {
    throw 'Failed to create mqtt instance';
}

registerEventHandlers();

setInterval(function() {
    if(!client) {
        print('mqtt instance recreate');
        client = mqtt.connect(mqttUrl);
        registerEventHandlers();
    }
    if(client && client.canPublish()) {
        var body = JSON.stringify({ "message" : "dummy" });
        client.publish("foo_topic/device01/dummy", body, { qos: 1 }, function(err) {
            if(err.code == 0) {
                print('Publish OK');
            } else {
                print('Publish failed');
                //TODO: Error handling
            }
        });
    }
}, 15000);



Updated: 2022-06-03
← 05. HTTPS07. Secure →
  • mqtt Global Object
  • Details
    • mqtt.connect(url[,options])
    • options
    • mqtt.set(name[,arg])
    • mqtt.set(’ssl.ca’,certificate);
    • mqtt.set(’ssl.cert’,certificate);
    • mqtt.set(’ssl.key’,clientkey);
  • {Client}
  • Details
    • .on(event,callback)
    • event : ’connect’
    • event : ’reconnect’
    • event : ’close’
    • event : ’error’
    • event : ’end’
    • event : ’message’
    • .publish(topic,message[,options][,callback])
    • .subscribe(topic[,options][,callback])
    • .unsubscribe(topic[,callback])
    • .end([,callback])
    • .reconnect()
    • .isConnected()
    • .isReconnecting()
    • .canPublish()
    • .get(name)
    • .get(’errnoConnect’)
  • Appendix
  • {MqttError}
    • mqtt errors table
    • errnoConnect table
  • Object Usage Examples
    • Sample 1
    • Sample 2
    • Sample 3
    • Sample 4
    • Sample 5
    • Sample 6
AboutNewsProductsFAQPrivacy Policy}
NEQTO Console
IntroductionFundamentalsAdministrative ActionsDevice Management NEQTO Apps
NEQTO Bridge
NEQTO Bridge ModuleNEQTO Bridge Wi-Fi ModuleNEQTO Bridge LTE-1 ModuleError Logging Event Messages
API Documentation
API UsageGlobal APIRegional APIAPI Terms of Service
Jigsaw, Inc.
© 2023 JIG-SAW INC.