In last blog, I discussed how to create dashboards for data monitoring using freeboard. In this post, I will use freeboard to display the data acquired from sense hat. In my PiIoT architecture, I want to create a distributed system, I will be creating a separate script for reading sensor values from sense hat and publish it to an MQTT broker. MQTT is a widely used IoT protocol for communication between the nodes in a network. For more info on MQTT, read this blog. Script handling the dashboard can subscribe to this and update the display. This way, I will be able to attach sense hat to one node and display the data to the display attached to another rpi where the dashboard script is running. In this post, I wil cover the steps to install Mosquitto with websockets in raspberry pi.
Installing Mosquitto with websockets
Installing Mosquitto broker is fairly simple if you don't want websockets functionality. Websockets allows MQTT clients running in web browsers to communicate with the broker. Since I'm going to write some of my scripts in nodejs and is expecting some client functionality in web browser, I need an installation with WebSockets enabled.
First step is to keep the system up to date
sudo apt-get update sudo apt-get upgrade
Now go on to install the dependencies:
sudo apt-get install libssl-dev cmake libc-ares-dev uuid-dev daemon
Next, clone libwebsockets library to a convenient location:
cd ~/Downloads wget https://github.com/warmcat/libwebsockets/archive/v1.3-chrome37-firefox30.tar.gz tar -xvf v1.3-chrome37-firefox30.tar.gz
Build libwebsockets:
cd v1.3-chrome37-firefox30/ mkdir build cd build cmake ./.. make sudo make install sudo ln -s /usr/local/lib/libwebsockets.so.4.0.0 /usr/lib/libwebsockets.so.4.0.0 sudo ldconfig
Now, download latest version of mosquitto and unzip:
cd ~/Downloads wget http://mosquitto.org/files/source/mosquitto-1.4.tar.gz tar -xvf mosquitto-1.4.tar.gz cd mosquitto-1.4
Open 'config.mk' file and enable websockets for build by replacing
# Build with websockets support on the broker. WITH_WEBSOCKETS:=no
with
# Build with websockets support on the broker. WITH_WEBSOCKETS:=yes
make sudo make install
If everything goes fine, now Mosquitto with websockets is installed in raspberry pi.
Now we need to create a config file tell mosquitto which ports to listen and which protocols to handle:
sudo cp /etc/mosquitto/mosquitto.conf.example /etc/mosquitto/mosquitto.conf
Now edit the contents and add as follows:
listener 1883 # Under default listner listener 9001 # Under additional listeners protocol websockets# # Under additional listeners
Testing the installation
To check the installation, I'm going to host a simple webpage which listens to a particular topic from broker and updates it to the screen. I'm going to use a modified version of the nodejs server used in last blog post to host the webpage. We also need to download the client library in js to the same folder.
Create a new folder:
cd ~/Documents mkdir mqtt-wss-test cd mqtt-wss-test wget https://raw.githubusercontent.com/eclipse/paho.mqtt.javascript/master/src/mqttws31.js touch server.js touch index.html
Open 'server.js' and put in this contents:
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), mime = require("mime") port = process.argv[2] || 8888; http.createServer( function(request, response) { var uri = url.parse(request.url).pathname; var filename = path.join(process.cwd(), uri ); // console.log( "New Request: \n" + // " URI : " + uri + "\n" + // " file: " + filename + "\n" ); fs.exists( filename, function(exists) { if( !exists ) { response.writeHead( 404, {"Content-Type": "text/plain"} ); response.write( "404 Not Found\n" ); response.end(); return; } if ( fs.statSync(filename).isDirectory() ) { filename += '/index.html'; } fs.readFile( filename, "binary", function(err, file ) { if(err) { response.writeHead( 500, {"Content-Type": "text/plain"} ); response.write( err + "\n" ); response.end(); return; } response.writeHead( 200, {"Content-Type": mime.lookup(filename)} ); response.write( file, "binary" ); response.end(); }); }); }).listen( parseInt(port,10) ); console.log( "Server running as PORT " + port + "\nPress CTRL + C to stop" );
Now edit 'index.html' and put these contents:
<html> <head> <script src="mqttws31.js"></script> <title> MQTT WSS Test Page </title> </head> <body> <div id="status"> Connecting to broker... </div> <div id="messages"> </div> </body> <script> // Create a client instance client = new Paho.MQTT.Client( '192.168.1.54', Number(9001), "clientId-"+ Math.random()); // set callback handlers client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived; // connect the client client.connect({ onSuccess:onConnect }); // called when the client connects function onConnect() { // Once a connection has been made, make a subscription and send a message. var status = document.getElementById( "status" ); console.log("onConnect"); status.innerHTML = "Connected to broker"; client.subscribe("/TestMessages"); message = new Paho.MQTT.Message("Hello MQTT :)"); message.destinationName = "/TestMessages"; client.send(message); } // called when the client loses its connection function onConnectionLost(responseObject) { if (responseObject.errorCode !== 0) { var status = document.getElementById( "status" ); console.log( "onConnectionLost: "+responseObject.errorMessage ); status.innerHTML = "Connection Lost : "+responseObject.errorMessage; } } // called when a message arrives function onMessageArrived(message) { var status = document.getElementById("messages"); console.log("New message: "+message.payloadString); var currentdate = new Date(); status.innerHTML = status.innerHTML + currentdate.getDate() + "-" + (currentdate.getMonth()+1) + "-" + currentdate.getFullYear() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds() + ": " + message.payloadString + "<br/>"; } </script> </html>
Here, change the IP address of broker to your Pi's IP in line 16. Save both the files.
Now start mosquitto with:
mosquitto -c /etc/mosquitto/mosquitto.conf
And you will be seeing something simillar to:
1466857348: mosquitto version 1.4 (build date 2016-06-25 17:26:05+0530) starting 1466857348: Config loaded from /etc/mosquitto/mosquitto.conf. 1466857348: Opening ipv4 listen socket on port 1883. 1466857348: Opening ipv6 listen socket on port 1883. 1466857348: Opening websockets listen socket on port 9001.
Also start the nodejs server:
nodejs server.js
Go to your web browser and goto http://<Pi's IP>:8888. you will be able to see that the client from your web browser is connecting to boker running at Pi and publishing a Hello message.
Go to pi's terminal and type:
mosquitto_pub -t "/TestMessages" -m "This is from rpi"
You should be able to see this message in your web browser now.
If everything works fine, you have a successful installation of Mosquito with Websockets
An alternate script to which connects to a mosquitto's public server is attached.
Happy Hacking
- vish
Top Comments