IoT Bytes

Bits and Bytes of IoT

MQTT over WebSockets

Pradeep Singh | 11th Jan 2017

websocket-logo

MQTT is a lightweight publish/subscribe messaging protocol which suits best for low power sensors. Whereas, WebSocket is a transport layer protocol, designed to be TCP for the Web. It (WebSocket) provides full-duplex communication channels over a single TCP connection between Client and Server.

Bringing these two protocols together can open an ocean of possibilities in the world of IoT. Imagine a HTML page that can display live sensor data without refreshing or polling Web Server periodically. Sounds interesting?

Most of the MQTT Brokers now support WebSocket communication; which means all you need to do is write Client side code and leverage MQTT Broker to cover everything else.

mqtt_over_websockets

Let’s try to a write a simple HTML 5 Web Page that can send and recieve MQTT messages over WebSocket.

MQTT Broker:

If you have a local MQTT Broker that supports WebSockets; feel free to use it. Otherwise, there are several Cloud based MQTT Brokers which can be used for testing purpose. Here in this article we are going to use HiveMQ Public MQTT Broker (For more details on this please visit http://www.hivemq.com/try-out/).

Following is the WebSocket URL for HiveMQ Test Server –

ws://broker.hivemq.com:8000/mqtt

JavaScript based MQTT Client:

Instead of writing complete JavaScript framework for MQTT Client you can simply use Paho. It provides an open-source client implementation of MQTT messaging protocol.

You can download Paho JavaScript Client from following link –

https://projects.eclipse.org/projects/technology.paho/downloads

You may include Minified Paho JavaScript Client into your HTML Page from following CDN Link –

https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js

Web Page (The Code):

I have written a sample WebPage that can be used for testing MQTT over WebSockets. You can download HTML code from GitHub Repository Octocat. You can run this code directly on your machine. Make sure your internet connection is working in case you want to use cloud based MQTT Broker (such as HiveMQ – ws://broker.hivemq.com:8000/mqtt).

Following diagram shows a simplified view of information flow between this sample HTML Page and MQTT Broker.

mqtt_webpage

Quick Demo:

Feel free to tweak the code and use it in your IoT projects.  Cheers!!!


References:

Paho JavaScript Documentation

HiveMQ Test Instance

WebSockets Protocol RFC 6455

MQTT Org

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: