Introduction: Raspberry Pi GPIO Control Over MQTT Using Thingsboard

The video above demonstrates the final result of this instructable.

You will learn how to control GPIO of your Raspberry Pi device using Thingsboard web UI. We will observe GPIO control using LEDs connected to the pins. The purpose of this application is to demonstrate Thingsboard RPC capabilities. Raspberry Pi will use simple application written in Python that will connect to Thingsboard server via MQTT and listen to RPC commands. Current GPIO state and GPIO control widget is visualized using built-in customizable dashboard.

Thingsboard is an open-source server-side platform that allows you to monitor and control IoT devices. It is free for both personal and commercial usage and you can deploy it anywhere. If this is your first experience with the platform I recommend to review what-is-thingsboard page and getting-started guide.

Step 1: Prerequisites & Wiring Schema

Server setup

You will need access to Thingsboard server. Use either Live Demo or Installation Guide to install Thingsboard.

List of hardware and pinouts

  • Raspberry Pi - we will use Raspberry Pi 3 Model B but you can use any other model.
  • Leds and corresponding resistors
  • female-to-male jumper wires

Wiring schema

Since our application will allow to control state of all available GPIO pins, we recommend to attach some LEDs to those pins for visibility. You can use this basic schema that is attached to this step. You may also add a resistor for each LED. In out case this was not necessary.

Step 2: Programming the Raspberry Pi

MQTT library installation

The following command will install MQTT Python library:

$ sudo pip install paho-mqtt

Application source code

Our application consists of single python script that is well commented. The source code is available here.

You will need to modify THINGSBOARD_HOST constant to match your Thingsboard server installation IP address or hostname. Use “” if you are using live demo server.
The value of ACCESS_TOKEN constant corresponds to sample Raspberry Pi device in pre-provisioned demo data. If you are using live demo server - get the access token for pre-provisioned “Raspberry Pi Demo Device”.

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


# We assume that all GPIOs are LOW gpio_state = {7: False, 11: False, 12: False, 13: False, 15: False, 16: False, 18: False, 22: False, 29: False, 31: False, 32: False, 33: False, 35: False, 36: False, 37: False, 38: False, 40: False}

# The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, rc): print('Connected with result code ' + str(rc)) # Subscribing to receive RPC requests client.subscribe('v1/devices/me/rpc/request/+') # Sending current GPIO status client.publish('v1/devices/me/attributes', get_gpio_status(), 1)

# The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print 'Topic: ' + msg.topic + '\nMessage: ' + str(msg.payload) # Decode JSON request data = json.loads(msg.payload) # Check request method if data['method'] == 'getGpioStatus': # Reply with GPIO status client.publish(msg.topic.replace('request', 'response'), get_gpio_status(), 1) elif data['method'] == 'setGpioStatus': # Update GPIO status and reply set_gpio_status(data['params']['pin'], data['params']['enabled']) client.publish(msg.topic.replace('request', 'response'), get_gpio_status(), 1) client.publish('v1/devices/me/attributes', get_gpio_status(), 1)

def get_gpio_status(): # Encode GPIOs state to json return json.dumps(gpio_state)

def set_gpio_status(pin, status): # Output GPIOs state GPIO.output(pin, GPIO.HIGH if status else GPIO.LOW) # Update GPIOs state gpio_state[pin] = status

# Using board GPIO layout GPIO.setmode(GPIO.BOARD) for pin in gpio_state: # Set output mode for all GPIO pins GPIO.setup(pin, GPIO.OUT)

client = mqtt.Client() # Register connect callback client.on_connect = on_connect # Registed publish message callback client.on_message = on_message # Set access token client.username_pw_set(ACCESS_TOKEN) # Connect to Thingsboard using default MQTT port and 60 seconds keepalive interval client.connect(THINGSBOARD_HOST, 1883, 60)

try: client.loop_forever() except KeyboardInterrupt: GPIO.cleanup()

Running the application

This simple command will launch the application:


Step 3: Data Visualization

In order to simplify this instructable we have included “Raspberry PI GPIO Demo Dashboard” to the demo data that is available in each thingboard installation. Of course, you can modify this dashboard: tune, add, delete widgets, etc. You can access this dashboard by logging in as a tenant administrator.

In case of local installation:

  • login:
  • password: tenant

In case of live-demo server:

  • login: your live-demo username (email)
  • password: your live-demo password

See live-demo page for more details how to get your account.

Once logged in, open Dashboards->Raspberry PI GPIO Demo Dashboard page. You should observe demo dashboard with GPIO control and status panel for your device. Now you can switch status of GPIOs using control panel. As a result you will see LEDs status change on device and on the status panel.