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
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.
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.
Step 4: We write action value into a buffer by using “writeNumber” function.
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:
After success adding, we will publish message with command value in option parameter such as:
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.
Now, we can get action value directly from packet variable in “on message” callback