Technology / Tutorials

Off-The-Shelf Hacker: Putting the MQTT Broker to Work on the CHIP Platform

20 May 2017 3:00am, by

The MQTT messaging protocol is great for physical computing projects and machine-to-machine messaging because it’s independent of the content. You can put whatever you want in a message, without worrying about formatting or internal structure. Message structure is defined, interpreted and acted on at the sending and receiving ends. Messages published to a topic can be interpreted differently, depending on the code you write. One edge-device might interpret a “1” message, as a command to turn on an LED, while a notebook, looking at that same “1” message, on the same topic might light up a green dot on a user’s desktop dashboard.

In this installment of the Off The Shelf Hacker column, we’ll look at using MQTT as the message transport method on a couple of actual devices networked to a data hub based on the CHIP low-cost processor.

Sounds complicated. Fortunately, we can use Python, which runs on nearly all Linux-based systems.

Python and Libraries are Programming Glue

I started writing programs in Python on the Raspberry Pi, long before discovering MQTT, because it was bundled into Raspbian Linux. As it turns out, Python is easily installed on the CHIP and my Xubuntu Linux notebook, too. What’s more, there are Python MQTT libraries for all these platforms.

The Paho project is a popular MQTT library. It’s easily installed on both the Raspberry Pi and the CHIP. I simply used the Synaptic package manager, on the Xubuntu notebook to load the Paho-MQTT library.

First, if you need to put Python on the CHIP or your Xubuntu Linux notebook use the following command line:

sudo apt-get install python

Python has its own package manager, called pip. Just run pip on the Raspberry Pi and the CHIP to install the mqtt library.

sudo pip install paho-mqtt

Once the installation completes, move on to integrating the library into some Python code.

Reading a Push Button on the CHIP

An MQTT broker AND client(s), both as publishers and subscribers, can function happily on the same device. And, it is a powerful tool, considering all the general purpose input/output (GPIO) pins available on devices like the CHIP or Raspberry Pi.

With that in mind, there isn’t much to a simple Python script, that runs on the CHIP, waits for a button push, then publishes a message to the broker (which, in our case is local), under the “mqtt” topic.

import paho.mqtt.client as mqtt
import CHIP_IO.GPIO as GPIO
import time
import os
import paho.mqtt.publish as publish

GPIO.setup("XIO-P0", GPIO.IN)
GPIO.input("XIO-P0")

while True:
    input_state = GPIO.input("XIO-P0")
    if input_state == True:
           time.sleep(.5)
           publish.single("mqtt", 1, hostname="172.20.0.1")

GPIO.cleanup()

First up, the various libraries are imported and initialized in the program.

Next, the GPIO pin for the push button is initialized. The push button was connected between the XIO-P0 pin and ground, on the CHIP’s U14L header. Facing the top side of the CHIP, with the USB port at the top, the pin is on the right-hand double header, left side about 1/3 of the way down.

The “while” loop just sits there looking at the XIO-P0 pin. When it sees a button push, a “1” is published to the “mqtt” topic on the MQTT broker. The CHIP is the broker and MQTT publishing client. Recall that we added standalone access point (AP) capability to the CHIP, last time, thus the one-off 172.20.0.1 IP address. The CHIP’s access point SSID is “dr-torq-1.”

The loop is actually fast enough to capture contact bounce, so I slipped a ½ second delay into the code, to minimize the effect. See if you can find ways to leverage that speed, in other applications.

Also remember that since the MQTT data hub (the CHIP) is a standalone AP, you’ll need to attach to that SSID before you can do anything from another device.

To write and run the Python script, SSH into the CHIP from the Linux notebook.

drtorq-notebook%  ssh chip@172.20.0.1

Once on the CHIP, edit and run the Python script, using the following.

chip%  vi button1.py
chip%  sudo python button1.py

sudo is required because normal users don’t have permission to directly control to the GPIO pins.

Check the operation of the push button by subscribing to the “mqtt” topic from the Linux notebook.

drtorq-notebook%  mosquitto_sub -h 172.20.0.1 -t mqtt

Every time the microswitch is pushed, you should see a “1” pop up on the screen.

Next, we’ll tackle the “subscriber” side.

Lighting the “Ozone Tube”

Why gin up new hardware when you can repurpose existing devices, as proof-of-concept prototypes? Be smart and get maximum value from that mountain of parts sitting on your workbench, by recycling projects. A hot topic in the industry right now is how to build hardware, where changing physical computing results only require a software mod.

Of course, the Badge needs to attach to the CHIP AP (dr-torq-1 SSID) and get a 172.20.0.xxx address. I’ll leave that to the reader as a practical networking exercise. We already attached the Linux notebook to the dr-torq-1 SSID. The Pi grabbed the 172.20.0.137 IP address from the CHIP AP, in my case.

drtorq-notebook%  ssh pi@172.20.0.137

Editing and running the “subscribe” (I called it mqtt-sub.py) Python script on the Pi works exactly the same as the “publish” script on the CHIP.

pi%  vi mqtt-sub.py
pi%  sudo python mqtt-sub.py

This Python script reads the MQTT subscription topic (“mqtt”) on the CHIP broker and acts on the message, turning on a green LED.

import time
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO 

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.OUT)

def on_connect(client, userdata, rc):
    print

def on_message(client, userdata, msg):
    if str(msg.payload) == "0":
         GPIO.output(27,False)
    elif str(msg.payload) == "1":
         GPIO.output(27,True)
	 time.sleep(1)
         GPIO.output(27,False)
    else:
         print
	
client = mqtt.Client()
client.connect("172.20.0.1", 1883, 60)
client.subscribe("mqtt")

client.on_connect = on_connect
client.on_message = on_message

client.loop_forever()

Importing the libraries come first. Notice that the GPIO libraries are different between the CHIP and the Raspberry Pi. Multiple libraries exist for the different platforms, although they all function pretty much the same. Pick one, read the docs and you should be able to get it working. I think being familiar with the “process” of using the libraries, regardless of platform, is an extremely valuable skill for the Off-The-Shelf Hacker. Libraries are the way the hardware industry incorporates features, in software.

Next, initialize GPIO pin 27 for output. This pin connects to the green LED in the Badge’s ozone tube.

We then define a little function that checks MQTT messages for a “0,” “1” or another value. If it receives a “0” it turns off the LED. “1” turns it on and any other value prints nothing and takes no action.

Lastly, we connect to the MQTT broker at 172.20.0.1 and loop indefinitely, for any values coming in on topic “mqtt”.

Start the script on the Pi and you should see the green LED light up, every time the microswitch is pushed on the CHIP. Note also, that I added a couple of lines in the code to automatically turn the LED off again after one second. Not much use if you push the button and the LED is already on.

Next Steps

Being able to send and receive messages going from and to, possibly many devices simultaneously is a super power for physical computing systems. We’ve seen how to publish and subscribe through an MQTT broker, to actually control physical behavior.

With this framework, the next step might be to explore controlling motors, servos, steppers and other actuators. Can we do near real-time control? Who knows. Is this setup fast enough to be able to control a robot, remotely, using MQTT messaging? Don’t know about that one either. Would that have any application or even make sense?

And, we haven’t even talked about MQTT oriented dashboards on a connected Linux notebook or even an Android superphone, to display inputs, trends and such on our edge devices. A message might light an LED and at the same time drive a data point on a desktop graph.

We could take any number of different directions.

What capabilities and features would you like to see in a portable, wireless data hub? I’d love to see how Off-The-Shelf Hackers apply this physical computing stack tech to their projects.


A digest of the week’s most important stories & analyses.

View / Add Comments

Please stay on topic and be respectful of others. Review our Terms of Use.