First thing’s first, we have to install Node.js and Node Package Manager (npm). This can be done with the following commands:
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash - sudo apt-get install -y nodejs
Once this is done, we can install the MQTT package, we will be using this later.
sudo npm install mqtt --save
Now we will need to set a MQTT broker, this can be done using a free account from CloudMQTT.
Your overview should look something like this.
This allows us to publish and subscribe to topics over this broker.
To do this, we use the mosquitto service which is installed with the following command:
sudo apt-get install mosquitto-clients
We can subscribe to topics sent over the Websocket UI using the mosquittio_sub service
mosquitto_sub -h mXX.cloudmqtt.com -p 16095 -v -t '#' -u xxxxxxxx -P 'XXXXXXXXXXXX'
Note that your port number may be different!
I have posted a message using CloudMQTT, as seen below:
This will appear in your terminal which is running mosquitto_sub
Alternatively, we can publish messages to topics using the Terminal with the mosquitto_pub command:
mosquitto_pub -h mXX.cloudmqtt.com -p 16095 -t 'TEST_TOPIC' -u xxxxxxxx -P XXXXXXXXX -m 'FromTerminal'
Received messages can also be viewed using the Websocket UI.
Finally, we will publish/subscribe using the mqtt package we installed earlier. I have pasted some sample code below.
var mqtt = require('mqtt') var options = { port: 16095, clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8), username: "xxxxxxxx", password: "XXXXXXXXX", }; var client = mqtt.connect('mqtt://m21.cloudmqtt.com', options) client.on('connect', function() { // When connected // subscribe to a topic client.subscribe('topic1/test', function() { // when a message arrives, do something with it client.on('message', function(topic, message, packet) { console.log("Received '" + message + "' on '" + topic + "'"); }); }); // publish a message to a topic client.publish('topic1/test', 'IoT test message', function() { console.log("Message is published"); //client.end(); // Close the connection when published }); });
This will publish the message “IoT test message” which you can view using the same steps above.