D.I.Y- Implementing Internet of Things using MQTT

6
2260

Let’s materialize that which we are talking about so much these days. Yes, Internet of Things or IOT has become one giant buzz word in this era. With it’s popularity, it is but natural that the hobbyists like us would want to get the real feel of it. So let’s stop talking for once and make something!

In this article, I will tell you exact steps required to get the basic understanding of how IoT works. Before getting started,we should have following ready:

Pre-requisites:

1.Linux OS (eg. Ubuntu)

2.Linux Machine(eg. Galileo,Beaglebone,etc)

3.Install Paho-MQTT package for Python

https://pypi.python.org/pypi/paho-mqtt

4.Install Mosquitto Broker

Downloads

5.Python

NOTE:

1.This is using locally hosted broker to develop a basic understanding of MQTT.

2.If you don’t have the above mentioned boards or any other, your laptop/desktop will do.

A little insight into the elements involved in IoT implementation using MQTT:

When we say MQTT we are talking about a client-broker model similar to client-server model except that here clients can assume roles of sender as well as receiver. Publish and subscribe are the terms used for this. There can be N number of clients and all of them can be either publishers or subscribers or both. Broker is program running on either local machine (as will be demonstrated in this article) or on some cloud. Broker receives the data from clients, stores it under “directories” called topics and push this data to the clients who subscribe it.

In Action!

IMG_20150930_194811

I will run python script on Intel Galileo board which “publishes” sensor data to the Mosquitto broker running on my laptop. How do we run Mosquitto? In my case, it automatically starts as soon as my Wi-Fi turns on.

Selection_019

The Mosquitto broker runs automatically on Ubuntu.

Selection_035

I run the code for subscription on my laptop and all the sensor data can be seen on the screen.

Selection_018

One very important thing is TOPIC. Topic is just like the address where a particular data is to be published/subscribed to. This way, the elements (client as well as broker) keep the track of all the data transaction. We use wildcards like “#” and “+” to subscribe/publish data using some condition. ”#” means all the data below this hierarchy is to be considered. ”+” is single level hierarchy.

By running following command, one can see the data being published/subscribed to the broker. This is useful in debugging.

~$mosquitto_sub -t ‘room/#’ -v

mosquitto_subCode:

#Do the indentation yourself

#Subscribe client(Laptop):

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
#This is in response to the connect called from the client
def on_connect(client, userdata, flags, rc): #——————– (3) called after CONNACK
print(“Connected with result code “+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(“room/#”)

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg): #———————–(4)
print(msg.topic+” “+str(msg.payload))
print(“\n”)

client = mqtt.Client() #————————-(1)
client.on_connect = on_connect
client.on_message = on_message

client.connect(“local host address”,1883, 60) #—————(2)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

Publish client(Galileo):

#Take care of indentation yourself.

import paho.mqtt.client as mqtt
import sys
import time
import os
################code for ADC read in Galileo##########
# This part is optional for those who do not have Galileo board.
# They can simply skip to the next part of the code below.
# You can publish any constant value/string.
def basic_setup():
try:
#export adc pins
adc0export = open(“/sys/class/gpio/export”,”w”)
adc0export.write(“48”)
adc1export = open(“/sys/class/gpio/export”,”w”)
adc1export.write(“50”)
adc0export.close()
adc1export.close()
except IOError:
print “INFO : ADC0 already exists,skipping export.”
print “INFO : ADC1 already exists,skipping export.”
try:
#set adc direction as input
fp1 = open(“/sys/class/gpio/gpio48/direction”,”w”)
fp3 = open(“/sys/class/gpio/gpio50/direction”,”w”)
fp1.write(“in”)
fp3.write(“in”)
fp3.close()
fp1.close()
except IOError:
print “!!”

def write_temp():
try:
#read the temperature sensor value
fp2 = open(“/sys/bus/iio/devices/iio:device0/in_voltage0_raw”,”$
val = int(fp2.read())
val1 = (50*val)/4096
return str(val1) + ” ” +”degrees”
fp2.close()
except IOError:
print “!”
def write_light():
try:
#read the light sensor value
fp4 = open(“/sys/bus/iio/devices/iio:device0/in_voltage1_raw”,”$
val_l = int(fp4.read())
return val_l
fp4.close()
except IOError:
print “#”

basic_setup()
####################################################################

client = mqtt.Client()
client.connect(“local host address”, 1883, 60)

while True:
client.publish(“room/temp”,write_temp()) #publish the temperature
client.publish(“room/light”,write_light()) #publish the light value
time.sleep(1)

That’s all people! This is just one small implementation. There can be many more use cases of MQTT. You can come up with your own implementation, with any other language. Go explore the world of IoT and revert back with new ideas, suggestions or queries.

D.I.Y -how you can programme IBM Bluemix with Python . 

6 COMMENTS

        • I have not yet tried building my own broker.I think it will be difficult because mosquitto broker for an instance is light weight inherently.There should be other constraints as well so making your own broker is a complex task according to me but I am in no position to be able to answer beyond this.You can search about this and if you get a solution,feel free to share it with us. 🙂

          • It is quite easy to create your own broker. The issues I am having is SSL encrypted connections, all of my devices I have built operate on the local network publishing and receiving to a gateway I have built, the gateway is encrypted with SSL and is the only publicly accessible device, however I need the gateway (which is the broker) to communicate through to my webserver via MQTT to receive commands for the other devices from a GUI so have to get the SSL part sorted asap. Here is my project page:

LEAVE A REPLY

Please enter your comment!
Please enter your name here