element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Members
    Members
    • Benefits of Membership
    • Achievement Levels
    • Members Area
    • Personal Blogs
    • Feedback and Support
    • What's New on element14
  • Learn
    Learn
    • Learning Center
    • eBooks
    • STEM Academy
    • Webinars, Training and Events
    • More
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • More
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • More
  • Products
    Products
    • Arduino
    • Dev Tools
    • Manufacturers
    • Raspberry Pi
    • RoadTests & Reviews
    • Avnet Boards Community
    • More
  • Store
    Store
    • Visit Your Store
    • Choose Another Store
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
Pi IoT
  • Challenges & Projects
  • Design Challenges
  • Pi IoT
  • More
  • Cancel
Pi IoT
Blog [PiIoT#02] : Setting up MQTT broker with WebSockets
  • Blog
  • Forum
  • Documents
  • Events
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Blog Post Actions
  • Subscribe by email
  • More
  • Cancel
  • Share
  • Subscribe by email
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: vish
  • Date Created: 25 Jun 2016 1:02 PM Date Created
  • Views 142 views
  • Likes 4 likes
  • Comments 3 comments
  • mqtt
  • vish_piiot
  • piiot
  • eclipse-paho
  • raspberry pi
  • paho
  • piiot challenge
  • mosquitto
Related
Recommended

[PiIoT#02] : Setting up MQTT broker with WebSockets

vish
vish
25 Jun 2016

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

We are set to build mosquitto

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

 

<< Prev | Index | Next >>

Attachments:
index.html.zip
Anonymous

Top Comments

  • DAB
    DAB over 5 years ago +2

    Nice detailed blog.

     

    One of these days I hope to get up to speed on this type of programming.

     

    DAB

  • vish
    vish over 5 years ago in reply to Former Member

    First of all you are not using any websockets feature for this - so problem is more basic in nature.

     

    Why you have to put -h 127.0.0.1? I think even with out that it shoudl work.

    Anyway I suggest this discussion: https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=97422

     

    Don't forget to post your updates

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • Former Member
    Former Member over 5 years ago

    im getting problem following exact steps x(

     

    mosquitto_pub -h 127.0.0.1 -t "/TestMessages" -m "This is from rpp"

    Error: Connection refused

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • DAB
    DAB over 5 years ago

    Nice detailed blog.

     

    One of these days I hope to get up to speed on this type of programming.

     

    DAB

    • Cancel
    • Up +2 Down
    • Reply
    • More
    • Cancel
Element14

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2022 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • Facebook
  • Twitter
  • linkedin
  • YouTube