Mar 28, 2015

MQTT + Websocket

Sometime ago I was thinking in study a IoT protocol, looking for some minutes in web I discovered that one of the most popular protocols that're running in nowadays is MQTT. MQTT is a protocol publish-subscribe type very interesting because was created by IBM a long time ago, used in internal communication with servers and clusters, now we use this to integrate many different devices in a flexible network that can be managed where will you're. The protocol works with a simple topology, in this network you need to have a Broker(concentrator), similar to an Access Point, and the Clients or devices.
The Clients can publish or subscribe in Topics, those are managed by the broker. When a client subscribe a topic, he will receive all data published to this topic, and if he want he could publish in whatever topic in the network. It's real simple as I describe, and you can test on your PC in five minutes to confirm, but the best thing about this protocol is your port to TCP/IP stack, imagine that you're on a trip and you forgot to turn off your skip iron, if you have implemented MQTT in your home, you can connect to the internet and publish a simple "turn off" or "off" in a topic called, "iron clothes" now you drive safe without to back home. One of variants of this protocol are the port to WSN (Wireless Sensor Networks) with MQTT-SN, that is the same protocol but in different radios technologies, some ZigBee devices have fully compatible support to communicate with protocol and you can study how to implement in different applications and scenarios. Now I will teach how to install a broker MQTT and communicate him with a webscoket.

1 - First things first is to search for a lightweight/versatile broker, for the moment let's use MOSQUITTO

su #Insert your root password
apt-get install cmake libssl-dev build-essential
cd ~
git clone https://github.com/aignaciors/libwebsockets.git
cd libwebsockets/
mkdir build
cd build
cmake ..
make
make install
cd ~
git clone http://git.eclipse.org/gitroot/mosquitto/org.eclipse.mosquitto.git
cd org.eclipse.mosquitto

Now, open the file config.mk and edit the line "WITH_WEBSOCKETS:=no" change to yes and change "WITH_SRV=yes" to no .After install the pre-reqs. to compile mosquitto broker...
apt-get install uuid-dev xsltproc docbook-xsl
make
make test
make install
ln -s /usr/local/lib/libwebsockets.so.5 /usr/lib/libwebsockets.so.5
/sbin/ldconfig #Update the linker