Thursday, March 28, 2024
How ToIoT HardwaresIoT PlatformsRaspberry PiTutorials/DIY

Raspberry Pi with ThingsBoard IoT Platform

In this tutorial, we controlled a LED using Raspberry Pi with Thingsboard. Today lot of IoT platforms available. Thingsboard one of most popular IoT platform.

What is ThingsBoard ?

ThingsBoard is an open-source IoT platform for data collection, processing, visualization, and device management. It enables device connectivity via industry standard IoT protocols – MQTT, CoAP and HTTP and supports both cloud and on-premises deployments. ThingsBoard combines scalability, fault-tolerance and performance so you will never lose your data.

Features

Real-Time IoT Dashboards – ThingsBoard allows you to create rich IoT Dashboards for data visualization and remote device control in real-time. More than 30 customizable widgets allows you to build end-user custom dashboards for most IoT use-cases.

IoT Rule Engine – ThingsBoard allows you to create complex Rule Chains to process data from your devices and match your application specific use cases.

Telemetry Data Collection – Collect and store telemetry data in reliable way, surviving network and hardware failures. Access collected data using customizable web dashboards or server-side APIs.

Multi-tenancy – Support multi-tenant installations out-of-the-box. Single tenant may have multiple tenant administrators and millions of devices and customers.

Data Visualization – Provides 30+ configurable widgets out-of-the-box and ability to create your own widgets using built-in editor. Built-in line-charts, digital and analog gauges, maps and much more.

Horizontal scalability – Amount of supported server-side requests and devices increase linearly as new thingsboard servers are added in clustering mode. No downtime, server restarts or application errors.

Fault-tolerance – All thingsboard servers are identical. No master-workers or hot standby. Node failure is automatically detected. Failed nodes can be replaced without downtime. Persisted data is replicated using reliable NoSQL database.

Device Management – Provides ability to register and manage devices. Allows to monitor client-side and provision server-side device attributes. Provides API for server-side applications to send RPC commands to devices and vice-versa.

Security – Supports transport encryption for both MQTT and HTTP(s) protocols. Supports device authentication and device credentials management.

Asset Management – Provides ability to register and manage assets. Allows to provision server-side asset attributes and monitor related alarms. Ability to build hierarchy of entities using relations.

Customization and Integration – Extend default platform functionality using customizable rule chains, widgets and transport implementations. In addition to MQTT, CoAP and HTTP support, ThingsBoard users can use their own transport implementations or customize behaviour of existing protocols.

Alarms Management – Provides ability to create and manage alarms related to your entities: devices, assets, customers, etc. Allows real-time alarms monitoring and alarms propagation to related entities hierarchy. Raise alarms on device disconnect or inactivity events.

100% Open-source – ThingsBoard is licensed under Apache License 2.0, so you can use any it in your commercial products for free. You can even host it as a SaaS or PaaS solution.

Microservices or Monolithic – Supports monolithic deployment for getting started or small environments. Provides ability to upgrade to microservices for high availability and horizontal scalability.

SQL, NoSQL and Hybrid database – Supports various database options and ability to choose where to store main entities and where to store telemetry data.

Architecture of ThingsBoard

ThingsBoard is designed to be:

  • scalable: horizontally scalable platform, build using leading open-source technologies.
  • fault-tolerant: no single-point-of-failure, every node in the cluster is identical.
  • robust and efficient: single server node can handle tens or even hundreds thousands of devices depending on use-case. ThingsBoard cluster can handle millions of devices.
  • customizable: adding new functionality is easy with customizable widgets and rule engine nodes.
  • durable: never lose your data.

Raspberry Pi with ThingsBoard IoT Platform

Now, for controlling the LED using ThingsBoard we will be using paho-mqtt library to establish a connection between Thingsboard platform and Raspberry Pi.

Recommended:

Components Required

  • Raspberry Pi
  • LED
  • Breadboard
  • 250-ohm Resistor
  • Jumper wires

Circuit Diagram

Raspberry Pi with ThingsBoard IoT Platform

Thingsboard Account Setup

Go to https://demo.thingsboard.io/signup to sign up on ThingsBoard.

After signing up, click on devices in the left corner of home screen and select Raspberry Pi Demo Device.

After that click on ‘Copy Access Token’ to copy the Token as it will be used in the python code.

After device setup, now create a dashboard on ThingsBoard for Raspberry Pi GPIO. For that click on ‘Dashboard’ and download the demo dashboard given for Rapsberry Pi by clicking on ‘Raspberry Pi GPIO Demo Dashboard’.

Now, raspberry pi dashboard for ThingsBoard is ready to use.

Programming Code Explanation of Raspberry Pi for ThingsBoard

First, install the MQTT library for the raspberry pi, by using the below command:

sudo pip install paho-mqtt

Then mention the libraries that need to be included at the beginning of the python code:

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

Next command will use for details about of ThingsBoard. Enter the access token that you copied from Thingsboard.

THINGSBOARD_HOST = 'demo.thingsboard.io'
ACCESS_TOKEN = 'Your Access Token'

Below commands are used to send a message to the client when gets connected.

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)

These commands will be used to print the response and receive the GPIO status 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':
………………………….
………………………….

Now to connect with 1883 port below code is used,

client.connect(THINGSBOARD_HOST, 1883, 60)

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

Testing LED Control from ThingsBoard using Pi

Make a new file using the below command then paste the code given at the end for controlling LED using ThingsBoard and Raspberry Pi.

Sudo nano gpio.py

Now, paste the code into the above created file and run this file using the below command:

Python gpio.py

After this navigate to the Thingsboard dashboard and click on GPIO 17 to on/off LED. Response from the server will be printed on Raspberry Pi terminal.

Complete Code

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

THINGSBOARD_HOST = 'demo.thingsboard.io'
ACCESS_TOKEN = 'Your Access Token'

# Set the GPIO as LOW
gpio_state = {11: 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 ThingsBoard using default MQTT port and 60 seconds keepalive interval
client.connect(THINGSBOARD_HOST, 1883, 60)

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

I hope you like this post.  Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

Explore Some more Raspberry Pi Tutorials :

Upvote on Reddit

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

One thought on “Raspberry Pi with ThingsBoard IoT Platform

Leave a Reply

Your email address will not be published. Required fields are marked *