element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • 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
  • Settings
Arduino
  • Products
  • More
Arduino
Blog [Dynamic Living-Room Lights] Paho For Python - Writing better code
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: ipv1
  • Date Created: 22 Jan 2015 7:39 AM Date Created
  • Views 693 views
  • Likes 0 likes
  • Comments 0 comments
  • iot_holidaylights
  • ip_iot
  • holiday_mood
Related
Recommended

[Dynamic Living-Room Lights] Paho For Python - Writing better code

ipv1
ipv1
22 Jan 2015

  • Link to previous posts
  • Preface
  • The problem
  • The Design
  • The Implementation
  • Conclusion

 

Link to previous posts

  • [Dynamic Living-room Lights] Description
  • [Dynamic Living-room Lights] Simple System Design
  • [Dynamic Living-Room Lights] The YUN review - When the Penguin Met The Arduino.
  • [Dynamic Living-Room Lights] The Infineon RGB LED Shield Review
  • [Dynamic Living-Room Lights] The Infineon RGB LED Shield -Library!
  • [Dynamic Living-Room Lights] The Lights Teaser Video
  • [Dynamic Living-room Lights] The YUN talks to OpenHAB
  • [Dynamic Living-room Lights] Building the Mood Lights
  • [Dynamic Living Room Lights] The XMAS Tree
  • [Dynamic Living-Room Lights] IoT Holiday Lights Minions
  • [Dynamic Living-Room Lights] The Big Picture - The Final Build

 

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

image

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.

 

dea717c403e0f18fb7852509e3af1332.jpg

 

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

  • Sign in to reply
element14 Community

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 © 2025 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

  • X
  • Facebook
  • linkedin
  • YouTube