Paho for Python – Writing Better Code

Preface

My project for the Internet of Holoday lights was based around our living room which was not very livable. It was a mess and with the upcoming holidays I wanted to set the living room in such a way that it would be suitable for entertaining guests. Additionally I wanted to accomplish the above mentioned in such a way that the holiday lighting becomes part of the living room and I don’t need to remove it after the holidays. Hence the concept of Dynamic Living-room Lighting.

In the previous posts, I have review the YUN and the infineon shield and have presented an overview of the project system. I also setup the place for the lighting with some homemade arts and crafts and give a preview of the system setup. I explained the Library I made for the Infineon Shield as well as the implementation for the MoodLights and made them Dynamic. I also made a XMAS Tree with LEDs and some stuff. I connected them to the YUN and made the control for the Xmas Tree Dynamic and static. It is now integrated into the OpenHAB interface and the YUN works as a relay. I have made the minions dance using a DIY approach and connected them to an RPi. I also wrote a python script to get mentions on twitter and play music while controlling the minions. I also showed you the final build but not yet a video.

In this post, I go back to the minions and make them learn MQTT.

The problem

paho_logo

The basic issue I had failed to address was the fact that I had used a simple script to read tweets and make the minions giggle. I wanted there to be a way to trigger the minion dance via my web interface which is built on top of OpenHAB. There are a couple of ways to do this like remotely invoking a bash script etc but I thought since its MQTT time, why not? Hence I started looking at Paho for Python and this post turned into a tutorial for implementing MQTT Communication in a simple project. Lets see what we can do.

The Design

Now I come from a single threaded microcontroller world where you do just one thing at a time. If you want to do multiple things, you need to write a simple scheduler using a timer and I have done this for ages. Yes there are a lot of ready solutions out there and some lite RTOS as well, but I like to know my code size before the compiler and hence I have written my bits of schedulers(some times in assembly) for over a decade. Python can do a lot of this stuff on it’s own so it was time to let google guide me. I needed a destination and my version of a design is shown below.

Technical Flow Chart
Technical Flow Chart

Hence its clear that since the MQTT Message can arrive anytime and my minion animation is around 45seconds, I need to get the messages in a separate thread. So how exactly does one do all that?

The Implementation

The implementation is simpler and the code in Template form is given below.
In order to install paho on the RPi, I executed the following commands in succession…

sudo apt-get install python-setuptools
sudo easy_install pip
sudo pip install paho-mqtt

Alternatively, You can…

wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
sudo python get-pip.py
sudo pip install paho-mqtt

Alternatively you can build from source and the instructions are given at https://pypi.python.org/pypi/paho-mqtt I use setuptools in windows as well so the first version was the simplest for me.

Next the actual script. I wrote a template for future projects and it looks like…

#! /usr/bin/python

import paho.mqtt.client as mqtt
import time

#Global Stuff
Flag=0
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
#Tell python to look at the global variable Flag
global Flag
Flag=1
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/TheTopicIWantToListenTo")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+": "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("iot.eclipse.org", 1883, 60)

#Start Loop
client.loop_start()

try:
while True:
    if(Flag==1):
       print 'The Flag was set! Woohoo!'
       Flag=0
    print 'Doing Something Here'
    print 'Sleeping again'
    time.sleep(30)
except:
    print 'I made a boo boo'
finally:
    print 'All Clean up Now'
    client.loop_stop()
    # GPIO.cleanup() anyone?

The code is self explanatory. The try and except and finally are used to execute cleanup code which is a good practice in my mind. This can be used in your next project and I hope it gives the newbies a better place to start.

Conclusion

There are N number of ways to do something and I am still learning. I just wanted to share this little snippet and I hope it is useful. Please feel free to add something to the above if you feel it.

Cheers,
IP

Advertisements

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