IoT Hub
IoT Hub Documentation
Guides > Hardware samples > Raspberry Pi > Raspberry Pi GPIO control over MQTT using IoT Hub
Getting Started Documentation
API FAQ

On this page

Raspberry Pi GPIO control over MQTT using IoT Hub

Introduction

IoT Hub 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 we recommend to review what-is-iothub page and getting-started guide.

This sample application will allow you to control GPIO of your Raspberry Pi device using IoT Hub web UI. We will observe GPIO control using Led connected to one of the pins. The purpose of this application is to demonstrate IoT Hub RPC capabilities.

Raspberry Pi will use simple application written in Python that will connect to IoT Hub server via MQTT and listen to RPC commands. Current GPIO state and GPIO control widget is visualized using built-in customizable dashboard.

The video below demonstrates the final result of this tutorial.





Prerequisites

You will need to have IoT Hub server up and running. The easiest way is to use Live Demo server.

The alternative option is to install IoT Hub using Installation Guide. Windows users should follow this guide. Linux users that have docker installed should execute the following commands:

1
2
3
4
5
mkdir -p ~/.mytb-data && sudo chown -R 799:799 ~/.mytb-data
mkdir -p ~/.mytb-logs && sudo chown -R 799:799 ~/.mytb-logs
docker run -it -p 9090:9090 -p 7070:7070 -p 1883:1883 -p 5683-5688:5683-5688/udp -v ~/.mytb-data:/data \
-v ~/.mytb-logs:/var/log/thingsboard --name mytb --restart always thingsboard/tb-postgres

These commands install IoT Hub and load demo data and accounts.

IoT Hub UI will be available using the URL: http://localhost:8080. You may use username tenant@thingsboard.org and password tenant. More info about demo accounts is available here.

List of hardware and pinouts

  • Raspberry Pi - we will use Raspberry Pi 3 Model B but you can use any other model.

  • Led and corresponding resistor

  • 2 female-to-male jumper wires

Wiring schema

Since our application will allow controlling the state of all available GPIO pins, we recommend attaching some LEDs to those pins for visibility. You can use this basic instruction or another one to wire some LEDs.

Programming the Raspberry Pi

MQTT library installation

The following command will install MQTT Python library:

1
sudo pip install paho-mqtt

Application source code

Our application consists of a single python script that is well documented. You will need to modify THINGSBOARD_HOST constant to match your IoT Hub server installation IP address or hostname. Use “iothub.magenta.at” 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”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json

THINGSBOARD_HOST = 'YOUR_THINGSBOARD_IP_OR_HOSTNAME'
ACCESS_TOKEN = 'RASPBERRY_PI_DEMO_TOKEN'

# 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, *extra_params):
    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 IoT Hub 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:

1
python gpio.py

Data visualization

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

  • login: tenant@thingsboard.org
  • password: tenant

in case of local IoT Hub installation.

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 the device and on the status panel.

Below is the screenshot of the “Raspberry PI GPIO Demo Dashboard”.

image

See Also

Browse other samples or explore guides related to main IoT Hub features:

Your feedback

Don’t hesitate to star IoT Hub on github to help us spread the word. If you have any questions about this sample - post it on the issues.

Next steps

  • Getting started guides - These guides provide quick overview of main IoT Hub features. Designed to be completed in 15-30 minutes.