How to add a new field in Nodejs MQTT library

MQTT.js is an OPEN Open Source Project in order to create a client library for the MQTT protocol, written in JavaScript for node.js and the browser.

We can easily install via command:  npm install mqtt –save. After installation, mqtt module is automatically imported into Node module directory in our project.

Our goal is add a new 2 bytes field into variable header of MQTT public message to transfer command.

Step 1: Open file “generate.js” at ./node_modules/mqtt/node_modules/mqtt-packet, this is java script file is used to generate a MQTT message

1

Step 2: Go to “publish” function in generate.js file. This function is used to generate MQTT publish message. Parameter of publish function a set of option encapsulated in JSON format. We declare a new value named action with value equal action file in parameter.

2

That mean we need to add a new parameter name “action” into publish function.

Step 3: In variable header we have “remain length” field, so we need to recalculate this value to add new field. We add 2 bytes so we need to add 2 into “length” variable.

3

Step 4: We write action value into a buffer by using “writeNumber” function.

4

Step 5: Open “client.js” file at at ./node_modules/mqtt/libs. Go to “MqttClient.prototype.publish” function that is use to publish message, add a new action file into packet variable:

5

After success adding, we will publish message with command value in option parameter such as:

6

The next problem is change MQTT decapsulation process to get action value from incoming publish message.

Step 1: Open file “parser.js” at ./node_modules/mqtt/node_modules/mqtt-packet, this is java script file is used to parse MQTT packet into readable fields.

Step 2: Go to “_parsePublish” function. This function is used to parse publish message into separated fields. We will get action field by using _parseNum() method.

7

Now, we can get action value directly from packet variable in “on message” callback

8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

<span>%d</span> bloggers like this: