Recent Changes - Search:

edit SideBar

Mqtt

The webSocket module is a JavaScript module that supports MQTT client interfaces. This is mainly intended to be compatible with the MQTT.js module. As other optional modules in Node.js, we need to call the require() function to use this module as follows.

var mqtt = require('mqtt');

To use the MQTT client, we need to instantiate it first as in the code below.

client = mqtt.createClient(1883, 'localhost', {clientId: 'subscriber'});
  • createClient(port, host, opts): Create an instance of an MQTT client. Default values are 1833 for port, 'localhost' for host, and {} for opts.

The client instance requires callback functions to handle events that happen when the MQTT connection is established between the client and the broker server, a message arrives from the publisher, or an error occurs. Here are member methods of the MQTT client, including the method that registers event handlers.

  • start(): Start connection between the client and the broker server.
  • subscribe(topic, opts): Subscribe a topic using the given maximum QoS level. Start getting messages on the topic.
  • unsubscribe(topic): Unsubscribe a topic. Stop getting messages on the topic.
  • publish(topic, message, opts, callback): Publish an MQTT message to subscribers listening to the topic.

// TODO: callback is not supported yet, will be implemented later (it may need another way to call callbacks other than EventEmitter.)

  • end(): Disconnect from the broker server and close (i.e. return all allocated resources of) the client.
  • on(event, func): Add a callback function to the MQTT client. Here is the list of events which can be handled by the MQTT client.
    • 'connect', function(): triggered when the client is connected to the broker server.
    • 'message', function(topic, message): triggered when a message arrives from the publisher.
    • 'close', function(): triggered when the connection with the broker server is closed.
    • 'error', function(err): triggered when the connection with the broker server is refused.
    • 'published', function (): triggered when the pubhlish complets (for QoS >= 1);

See Also


Back to Optional JavaScript Modules

Edit - History - Print - Recent Changes - Search
Page last modified on September 13, 2017, at 11:10 pm