Thursday, December 29, 2016

Thingsboard 1.0.2 Minor Release

We are pleased to announce today the availability of Thingsboard 1.0.2, minor release that includes additional widgets, new functionality to copy-paste widgets, usage of shared and server-side attributes in the dashboards and more.

What’s new:

  • Device API improvements
  • Ability to Copy-paste widgets
  • Ability to hide dashboard title
  • Improved layout for mobile devices
  • Ability to use shared and server-side attributes in the dashboards
  • Map widgets: OpenStreetMap route-map widget
  • Bug fixes

Availability

Thingsboard 1.0.2 is available for download via the open source repository hosted on GitHub. To get started with Thingsboard try our Hello World app or watch Getting Started Video. In order to upgrade previous Thingsboard installation follow the upgrade instructions.

End User IoT dashboards

In this video tutorial we cover basic operations with Devices, Customers, and Dashboards.

Friday, December 23, 2016

Facilities monitoring system prototype using Thingsboard

Environmental controls in the office rooms are very important as loss of HVAC can result in significant loss to servers, network gear, employee productivity etc. Few days ago we decided to prototype facilities monitoring system that will be able to cover following use cases:
  • Monitoring of temperature and humidity in different zones of the office building.
  • Processing of collected telemetry with various alerting rules based on zone type: work space, meeting and server rooms.
  • Distribution of collected alarms to assigned facility managers.
  • Visualization of real-time and historical values on the configurable web dashboards.
This article describes development and configuration steps we have done in order to build the PoC. The prototype is open-source and is also based on open-source technologies, so you are able to use it for building commercial products.

Facilities management
Data flow diagram

Devices and Connectivity

We decided to use quite cheap hardware based on ESP8266 and DHT22 sensor. The total cost of each device that includes sensor and connectivity module is approximately 5$. Since this is a prototype, we decided to use MQTT over WiFi and have not discussed other connectivity options.

Server-side infrastructure

The server-side part of the solution will be based on the Thingsboard IoT platform which is 100% open-source and can be deployed both in the cloud, on premises or even on Raspberry Pi 3. The collected data is stored to Cassandra database due to built-in fault-tolerance and scalability. We have recently launched Live Demo instance to simplify getting-started process, so we will use this instance in the tutorial.

Development and Configuration steps

Step 1. Device provisioning

Initial step of the PoC was to provision several devices and their attributes. We’ve decided to support three zone types: work area, meeting and server rooms. We have registered three buildings with four rooms in each. During registration we have populated Zone Id, Zone Type server-side attributes. Note that the server-side device attributes may be used by the processing rules, but are not visible to the device itself.

Server side attributes

Step 2. Flushing the devices

During this step we have flushed firmware update with individual device credentials built-in to the firmware. The firmware code and corresponding instructions are available in links below. We have used code from our previous article without modifications, since all the logic is on the server side.

Please note that steps 1 and 2 may be automated, we’ve developed simple java based application that performs provisioning of the devices and other entities using REST API and also emulates this devices for the live demo purposes.

Step 3. Processing Rules

During this steps we have provisioned rules that analyze temperature and humidity against configurable thresholds based on zone type. For example, acceptable humidity range in server room is between 40% and 60%, however, humidity range for the work zone is from 30% to 70%.

The rules are basically set of logical expression written using javascript syntax. For example, rule for a server room consist of two parts: attribute and telemetry filter. This filters may be combined, but we decided to separate them to simplify the PoC.

Attributes filter body example:
typeof ss.ZoneType !== 'undefined' && ss.ZoneType === 'Server Room'
Telemetry filter body example:
(
typeof temperature !== 'undefined'
&& (temperature <= 10 || temperature >= 25)
)
|| 
(
typeof humidity !== 'undefined'
&& (humidity <= 40 || humidity >= 60)
)
You may notice “null” checks in the filter body. This is basically a good practise, because you may use same server for multiple device applications. Some of them report humidity and temperature, some of them upload other sensor readings and this should not affect rules processing.

Step 4. Alarms distribution

At this step we have configured email plugin to distribute data using SendGrid mail service and provisioned rule action to send data to the configured mail address. Rule action consists of several templates that allow flexible configuration of email topic, body and adress list based on substitution of device attributes and telemetry values. For example, following email body template:
[$date.get('yyyy-MM-dd HH:mm:ss')] $ss.get('ZoneId') HVAC malfunction detected. 
Temperature - $temperature.valueAsString (°C). 
Humidity - $humidity.valueAsString (%)!
Will be evaluated to the following email body
[2016-12-22 15:06:09] Server Room C HVAC malfunction detected. 
Temperature – 45.0 (°C).
Humidity – 70.0 (%)!
The evaluation and template syntax is based on Velocity engine.

Step 5. Data visualization

At this step we provisioned several dashboards to visualize the data. We will describe them below.

Map dashboard

This dashboard shows multiple buildings on the map with their short status available in the tooltip. You can use links in the tooltips to navigate to Floor Plan and Historical Data dashboards.

Map Dashboard

Floor Plan dashboard

This dashboard uses static background image with the floor plan. We have placed widgets that show temperature and humidity in each room that is being monitored.

Floor Plan

Historical dashboard

This dashboard shows last minute of sensor readings that are reported each second.

Historical Data

Live Demo

In order to demonstrate this PoC in action you need to do two simple steps:
  1. Sign-up or login to the live demo instance and save your login and password.
  2. Download and launch device emulator using this link.
java -jar facilities-monitoring.jar demo.thingsboard.io
Once started, the emulator will ask you for your live demo login and password. This information will be used to get the JWT token and execute REST API calls in order to:
  1. provision demo devices.
  2. create rules and dashboards.
  3. start emulation of the temperature and humidity sensor data for provisioned devices using MQTT.

Conclusion

This prototype was written by two engineers literally in one day. Most of the time was spent on the client-side code (Arduino sketch for real device and emulator). The server-side part of the prototype has zero coding and was all about configuration of the rules, plugins and dashboards.

This demonstrates how easy is to prototype and build IoT solutions using Thingsboard. Of course, there is certain learning curve that you need to pass, but we hope that this article and other docs will help you to do this.

Thursday, December 22, 2016

Thingsboard 1.0.1 Minor Release

We are pleased to announce today the availability of Thingsboard 1.0.1, minor release that includes additional widgets and functionality to set background on dashboard.

What’s new:

  • Label widget
  • Route Map widget
  • Ability to set background on dashboard
  • Bug-fixing

Availability

Thingsboard 1.0.1 is available for download via the open source repository hosted on GitHub. To get started with Thingsboard try our Hello World app.

Wednesday, December 21, 2016

Raspberry Pi GPIO control over MQTT using Thingsboard

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

This sample application will allow you to control GPIO of your Raspberry Pi device using Thingsboard web UI. We will observe GPIO control using Led connected to one of 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.

The video below demonstrates the final result of this tutorial.





Prerequisites

You will need to Thingsboard server up and running. 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.

  • Led and corresponding resistor

  • 2 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 instruction or another one to wire some LEDs.

Programming the Raspberry Pi

MQTT library installation

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. You will need to modify THINGSBOARD_HOST constant to match your Thingsboard server installation IP address or hostname. Use “demo.thingsboard.io” 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”.

resources/gpio.py
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):
    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:

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 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. Use

in case of local Thingsboard 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 device and on the status panel.

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

image

Next steps

Browse other samples or explore guides related to main Thingsboard features:

Alarms based on sensor readings

This tutorial will demonstrate how to configure Rule that will generate Alarm when certain device reports temperature or humidity that exceeds certain thresholds.

Lets assume that we have devices that are able to report humidity and temperature values. We have one device per room (zone) in the building or other facility and we want to specify different rules based on zone type.

Assumptions

We assume you have already configured email plugin that will distribute generated alarms to recepients. You can follow previous tutorial to do this.

How it works?

We will provision simple rule that filters incoming data using:

  • “Message type” filter to react on telemetry data.
  • “Device Attributes” filter to process data from device that has certain room type as a server side attribute.
  • “Device Telemetry” filter to detect humidity and temperature values that are out of pre-configured range.

Device provisioning

Let’s create a Device and provision certain server-side attributes: ZoneId and ZoneType.

Step 1. Create Device

Navigate to devices page and click on big red “+” button. Populate device name and description and click “Add” button.

image

Step 2. Provision ZoneID and ZoneType attributes

Open device card that you have created. Navigate to “Attributes” tab and select “Server” attributes scope.

image

Click on the highlighted “+” button. Add two attributes “ZoneId” and “ZoneType” as shown below. We will use them later in the rule filters.

image image

Rule configuration

Step 3. Create “Server Room Monitoring” Rule

Navigate to rules page and click on big red “+” button. Populate rule name and description first.

image

Our rule will contain three filters as described in “how it works” section.

Step 4. Message type filter

Add filter based on message type (see image below).

image

Step 5. Attributes filter

Add filter based on the server-side attributes (see image below).

typeof ss.ZoneType !== 'undefined' && ss.ZoneType === 'Server Room'

image

Step 6. Telemetry filter

(
    typeof temperature !== 'undefined' 
    && (temperature <= 10 || temperature >= 25)
)
|| 
(
    typeof humidity !== 'undefined' 
    && (humidity <= 40 || humidity >= 60)
)

Add filter based on the sensor reading (see image below).

image

Step 7. Alarm Processor

Let’s add simple processor that will generate and save alarm to the database based on templates below.

Alarm ID:

[$date.get('yyyy-MM-dd HH:mm')] $ss.get('ZoneId') HVAC malfunction detected!

Alarm Body:

[$date.get('yyyy-MM-dd HH:mm:ss')] $ss.get('ZoneId') HVAC malfunction detected. 
Temperature - $temperature.valueAsString (°C). 
Humidity - $humidity.valueAsString (%)!

image

NOTE Alarm Id is a unique identifier. If there will be multiple events that match filters, alarms will be de-duplicated based on the Alarm Id. Email will be sent once per alarm.

In our case we use timestamp that is truncated to minutes to make sure that we will send email once per minute or less frequently.

Step 8. Rule Action

Select “SendGrid Email Plugin” from previous tutorial and click on “Create” button. Don’t forget to replace “[email protected]” with your mail address.

image

Step 9. Save and Activate Rule

Once rule is saved successfully, don’t forget to activate it by clicking on “Activate” button (see image below).

image

Dry run

Let’s check our configuration by publishing some telemetry data. We will use access token from the device that we have created on the first step.

mosquitto_pub -d -h "demo.thingsboard.io" -t "v1/devices/me/telemetry" -u "$YOUR_ACCESS_TOKEN" -m "{'temperature':42, 'humidity':74}"

Troubleshooting

If you have configured something wrong, you should see errors logged on the corresponding tab:

image

If there is no error in the rule, but you can’t see the email - check errors in the target plugin.

Email Plugin Configuration

In this short tutorial we will explain how to configure Email Plugin to distribute alarms to recepients via email. We will use Live Demo Thignsboard server and SendGrid SMTP API in this tutorial. The Email plugin implementation is based on Java Mail and may be easily configured to other mail servers.

SMTP server parameters

Step 1. Get your SendGrid account.

We assume you have SendGrid account. You can sign-up for trial using this link.

Step 2. Configure SMTP Relay

Once logged in open SMTP relay configuration page. Follow instructions on the page to get the API Key. Save the API key somewhere.

Plugin Configuration

Step 3. Login to Live Demo server

Login to Live Demo server using Tenant Administrator account (the one that you created during sign-up).

Step 4. Create new Mail Plugin instance

Open Plugins page and click on big red “+” button. Populate plugin name and description.

image

Once you choose the corresponding plugin type, the form will expand. Populate values as shown below. Use API key as a password.

NOTE Since demo instance is hosted on Google Cloud, you need to specify 2525 port. All other SMTP related ports are blocked.

image

Don’t forget to add other mail properties that will force secure connection.

image

Click on “Add” button.

Step 5. Activate new plugin

Once plugin is saved successfully, don’t forget to activate it by clicking on “Activate” button.

image

Next Steps

Explore next tutorial to provision basic rules and generate emails based on sensor readings.

Troubleshooting

Once you configure you plugin and corresponding rules, you may review statistics and events on plugin details page. If you have configured something wrong, you should see errors logged on the corresponding tab:

image

Temperature upload over MQTT using ESP8266 and DHT22 sensor

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

This sample application performs collection of temperature and humidity values produced by DHT22 sensor and further visualization on the real-time web dashboard. Collected data is pushed via MQTT to Thingsboard server for storage and visualization. The purpose of this application is to demonstrate Thingsboard data collection API and visualization capabilities.

The DHT22 sensor is connected to ESP8266. ESP8266 offers a complete and self-contained Wi-Fi networking solution. ESP8266 push data to Thingsboard server via MQTT protocol by using PubSubClient library for Arduino. Data is visualized using built-in customizable dashboard. The application that is running on ESP8266 is written using Arduino SDK which is quite simple and easy to understand.

The video below demonstrates the final result of this tutorial.





Once you complete this sample/tutorial, you will see your sensor data on the following dashboard.

image

Prerequisites

You will need to Thingsboard server up and running. Use either Live Demo or Installation Guide to install Thingsboard.

List of hardware and pinouts

image

image

  • USB to TTL

    image

    image

  • Resistor (between 4.7K and 10K)

  • Breadboard

  • 2 female-to-female jumper wires

  • 10 female-to-male jumper wires

  • 3 male-to-male jumper wire

  • 3.3V power source (for example 2 AA batteries)

Wiring schemes

Programming/flashing schema

ESP8266 Pin USB-TTL Pin
ESP8266 VCC USB-TTL VCC +3.3V
ESP8266 CH_PD USB-TTL VCC +3.3V
ESP8266 GND (-) USB-TTL GND
ESP8266 GPIO 0 USB-TTL GND
ESP8266 RX USB-TTL TX
ESP8266 TX USB-TTL RX
DHT-22 Pin ESP8266 Pin
DHT-22 Data ESP8266 GPIO 2
DHT-22 Pin USB-TTL Pin
DHT-22 VCC USB-TTL VCC +3.3V
DHT-22 GND (-) USB-TTL GND

Finally, place a resistor (between 4.7K and 10K) between pin number 1 and 2 of the DHT sensor.

The following picture summarizes the connections for this project in programming/debug mode:

image

Final schema (Battery Powered)

ESP8266 Pin 3.3V power source
ESP8266 VCC VCC+
ESP8266 CH_PD VCC+
ESP8266 GND (-) VCC-
DHT-22 Pin ESP8266 Pin
DHT-22 Data ESP8266 GPIO 2
DHT-22 Pin 3.3V power source
DHT-22 VCC VCC+
DHT-22 GND (-) VCC-

The final picture:

image

Thingsboard configuration

Note Thingsboard configuration steps are necessary only in case of local Thingsboard installation. If you are using Live Demo instance all entities are pre-configured for your demo account. However, we recommend to review this steps because you will still need to get device access token to send requests to Thingsboard.

Provision your device

This step contains instructions that are necessary to connect your device to Thingsboard.

Open Thingsboard Web UI (http://localhost:8080) in browser and login as tenant administrator

Goto “Devices” section. Click “+” button and create device with name “ESP8266 Demo Device”.

image

Once device created, open its details and click “Manage credentials”. Copy auto-generated access token from the “Access token” field. Please save this device token. It will be referred to later as $ACCESS_TOKEN.

image

Click “Copy Device ID” in device details to copy your device id to clipboard. Paste your device id to some place, this value will be used in further steps.

Provision your dashboard

This step contains instructions that are necessary to provision new dashboard with map widgets to Thingsboard.

Open “Terminal” and download file containing demo dashboard JSON:

curl -L https://thingsboard.io/docs/samples/esp8266/resources/esp8266_dht_temp_dashboard.json > esp8266_dht_temp_dashboard.json

Update dashboard configuration with your device Id (obtained in previous step) by issuing the following command:

sed -i "s/{DEVICE_ID}/<your device id>/" esp8266_dht_temp_dashboard.json

Obtain JWT token by issuing login POST command:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{"username":"[email protected]", "password":"tenant"}' 'http://localhost:8080/api/auth/login'

You will receive response in the following format:

{"token":"$YOUR_JSON_TOKEN", "refreshToken": "$REFRESH_TOKEN"}

copy $YOUR_JSON_TOKEN to some place. Note that it will be valid for 15 minutes by default.

Execute dashboard upload command:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Authorization: Bearer $YOUR_JSON_TOKEN' -d "@esp8266_dht_temp_dashboard.json" 'http://localhost:8080/api/dashboard'

Programming the ESP8266

Step 1. ESP8266 and Arduino IDE setup.

In order to start programming ESP8266 device you will need Arduino IDE installed and all related software.

Download and install Arduino IDE.

After starting arduino, open from the ‘file’ menu the preferences.

image

Fill in the “Additional board managers URL” this url: http://arduino.esp8266.com/stable/package_esp8266com_index.json

Close the screen by the OK button.

Now we can add the board ESP8266 using the board manager.

Click in the menu tools the menu option Board: “Most likely Arduino UNO”. There you will find the first option “Board Manager”.

Type in the search bar the 3 letters ESP. Locate and click on “esp8266 by ESP8266 Community”. Click on install and wait for a minute to download the board.

image

Note that this tutorial was tested with the “esp8266 by ESP8266 Community” version 2.3.0.

In the menu Tools “Board “Most likely Arduino UNO” three new boards are added.

Select “Generic ESP8266 Module”.

Prepare your hardware according to the Programming/flashing schema. Connect USB-TTL adapter with PC.

Select in the menu Tools, port the corresponding port of the USB-TTL adapter. Open the serial monitor (by pressing CTRL-Shift-M or from the menu Tools). Set the key emulation to “Both NL & CR” and the speed to 115200 baud. This can be set in the bottom of terminal screen.

Step 2. Install Arduino libraries.

Open Arduino IDE and go to Sketch -> Include Library -> Manage Libraries. Find and install the following libraries:

Note that this tutorial was tested with the following versions of the libraries:

  • PubSubClient 2.6
  • Adafruit Unified Sensor 1.0.2
  • DHT sensor library 1.3.0

Step 3. Prepare and upload sketch.

Download and open esp8266-dht-mqtt.ino sketch.

Note You need to edit following constants and variables in the sketch:

  • WIFI_AP - name of your access point
  • WIFI_PASSWORD - access point password
  • TOKEN - the $ACCESS_TOKEN from Thingsboard configuration step.
  • thingsboardServer - Thingsboard HOST/IP address that is accessable within your wifi network. Specify “demo.thingsboard.io” if you are using live demo server.
resources/esp8266-dht-mqtt.ino
#include "DHT.h"
#include <PubSubClient.h>
#include <ESP8266WiFi.h>

#define WIFI_AP "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"

#define TOKEN "ESP8266_DEMO_TOKEN"

// DHT
#define DHTPIN 2
#define DHTTYPE DHT22

char thingsboardServer[] = "YOUR_THINGSBOARD_HOST_OR_IP";

WiFiClient wifiClient;

// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);

PubSubClient client(wifiClient);

int status = WL_IDLE_STATUS;
unsigned long lastSend;

void setup()
{
  Serial.begin(115200);
  dht.begin();
  delay(10);
  InitWiFi();
  client.setServer( thingsboardServer, 1883 );
  lastSend = 0;
}

void loop()
{
  if ( !client.connected() ) {
    reconnect();
  }

  if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds
    getAndSendTemperatureAndHumidityData();
    lastSend = millis();
  }

  client.loop();
}

void getAndSendTemperatureAndHumidityData()
{
  Serial.println("Collecting temperature data.");

  // Reading temperature or humidity takes about 250 milliseconds!
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");

  String temperature = String(t);
  String humidity = String(h);


  // Just debug messages
  Serial.print( "Sending temperature and humidity : [" );
  Serial.print( temperature ); Serial.print( "," );
  Serial.print( humidity );
  Serial.print( "]   -> " );

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"temperature\":"; payload += temperature; payload += ",";
  payload += "\"humidity\":"; payload += humidity;
  payload += "}";

  // Send payload
  char attributes[100];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/devices/me/telemetry", attributes );
  Serial.println( attributes );

}

void InitWiFi()
{
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_AP, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    status = WiFi.status();
    if ( status != WL_CONNECTED) {
      WiFi.begin(WIFI_AP, WIFI_PASSWORD);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("Connected to AP");
    }
    Serial.print("Connecting to Thingsboard node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("ESP8266 Device", TOKEN, NULL) ) {
      Serial.println( "[DONE]" );
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

Connect USB-TTL adapter to PC and select the corresponding port in Arduino IDE. Compile and Upload your sketch to device using “Upload” button.

After application will be uploaded and started it will try to connect to Thingsboard node using mqtt client and upload “temperature” and “humidity” timeseries data once per second.

Autonomous operation

When you have uploaded the sketch, you may remove all the wires required for uploading including USB-TTL adapter and connect your ESP8266 and DHT sensor directly to power source according to the Final wiring schema.

Troubleshooting

In order to perform troubleshooting you should assemble your hardware according to the Programming/flashing schema. Then connect USB-TTL adapter with PC and select port of the USB-TTL adapter in Arduino IDE. Finally open “Serial Monitor” in order to view debug information produced by serial output.

Data visualization

Finally, open Thingsboard Web UI. You can access this dashboard by logging in as a tenant administrator. Use:

in case of local Thingsboard installation.

Go to “Devices” section and locate “ESP8266 Demo Device”, open device details and switch to “Latest telemetry” tab. If all is configured correctly you should be able to see latest values of “temperature” and “humidity” in the table.

image

After, open “Dashboards” section then locate and open “ESP8266 DHT22: Temperature & Humidity Demo Dashboard”. As a result you will see two digital gauges and two time-series charts displaying temperature and humidity level (similar to dashboard image in the introduction).

Next steps

Browse other samples or explore guides related to main Thingsboard features:

Temperature upload over MQTT using Arduino UNO, ESP8266 and DHT22 sensor

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

This sample application performs collection of temperature and humidity values produced by DHT22 sensor and further visualization on the real-time web dashboard. Collected data is pushed via MQTT to Thingsboard server for storage and visualization. The purpose of this application is to demonstrate Thingsboard data collection API and visualization capabilities.

The DHT22 sensor is connected to Arduino UNO. Arduino UNO connects to the WiFi network using ESP8266. Arduino UNO push data to Thingsboard server via MQTT protocol by using PubSubClient library for Arduino. Data is visualized using built-in customizable dashboard. The application that is running on Arduino UNO is written using Arduino SDK which is quite simple and easy to understand.

Once you complete this sample/tutorial, you will see your sensor data on the following dashboard.

image

Prerequisites

You will need to Thingsboard server up and running. Use either Live Demo or Installation Guide to install Thingsboard.

List of hardware and pinouts

image

image

image

  • Resistor (between 4.7K and 10K)

  • Breadboard

  • 2 female-to-female jumper wires

  • 11 female-to-male jumper wires

  • 3 male-to-male jumper wire

ESP8266 Firmware

In the current tutorial WiFiEsp Arduino library is used to connect Arduino board to the internet. This library supports ESP SDK version 1.1.1 and above (AT version 0.25 and above). Please make sure that your ESP8266 has compatible firmware. You can download and flash AT25-SDK112 firmware which is tested in this tutorial.

Please note that serial baud rate of ESP8266 should be set to 9600 by the following AT command:

AT+UART_DEF=9600,8,1,0,0

Wiring schema

Arduino UNO Pin ESP8266 Pin
Arduino UNO 3.3V ESP8266 VCC
Arduino UNO 3.3V ESP8266 CH_PD
Arduino UNO GND ESP8266 GND (-)
Arduino UNO D2 ESP8266 RX
Arduino UNO D3 ESP8266 TX
Arduino UNO Pin DHT-22 Pin
Arduino UNO 5V DHT-22 VCC
Arduino UNO GND DHT-22 GND (-)
Arduino UNO D4 DHT-22 Data

Finally, place a resistor (between 4.7K and 10K) between pin number 1 and 2 of the DHT sensor.

The following picture summarizes the connections for this project:

image

Thingsboard configuration

Note Thingsboard configuration steps are necessary only in case of local Thingsboard installation. If you are using Live Demo instance all entities are pre-configured for your demo account. However, we recommend to review this steps because you will still need to get device access token to send requests to Thingsboard.

Provision your device

This step contains instructions that are necessary to connect your device to Thingsboard.

Open Thingsboard Web UI (http://localhost:8080) in browser and login as tenant administrator

Goto “Devices” section. Click “+” button and create device with name “Arduino UNO Demo Device”.

image

Once device created, open its details and click “Manage credentials”.

Copy auto-generated access token from the “Access token” field. Please save this device token. It will be referred to later as $ACCESS_TOKEN.

image

Click “Copy Device ID” in device details to copy your device id to clipboard. Paste your device id to some place, this value will be used in further steps.

Provision your dashboard

This step contains instructions that are necessary to provision new dashboard with map widgets to Thingsboard.

Open “Terminal” and download file containing demo dashboard JSON:

curl -L https://thingsboard.io/docs/samples/arduino/resources/arduino_dht_temp_dashboard.json > arduino_dht_temp_dashboard.json

Update dashboard configuration with your device Id (obtained in previous step) by issuing the following command:

sed -i "s/{DEVICE_ID}/<your device id>/" arduino_dht_temp_dashboard.json

Obtain JWT token by issuing login POST command:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{"username":"[email protected]", "password":"tenant"}' 'http://localhost:8080/api/auth/login'

You will receive response in the following format:

{"token":"$YOUR_JSON_TOKEN", "refreshToken": "$REFRESH_TOKEN"}

copy $YOUR_JSON_TOKEN to some place. Note that it will be valid for 15 minutes by default.

Execute dashboard upload command:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'X-Authorization: Bearer $YOUR_JSON_TOKEN' -d "@arduino_dht_temp_dashboard.json" 'http://localhost:8080/api/dashboard'

Programming the Arduino UNO device

If you already familiar with basics of Arduino UNO programming using Arduino IDE you can skip the following step and proceed with step 2.

Step 1. Arduino UNO and Arduino IDE setup.

In order to start programming Arduino UNO device you will need Arduino IDE installed and all related software.

Download and install Arduino IDE.

To learn how to connect your Uno board to the computer and upload your first sketch please follow this guide.

Step 2. Install Arduino libraries.

Open Arduino IDE and go to Sketch -> Include Library -> Manage Libraries. Find and install the following libraries:

Note that this tutorial was tested with the following versions of the libraries:

  • PubSubClient 2.6
  • WiFiEsp 2.1.2
  • Adafruit Unified Sensor 1.0.2
  • DHT sensor library 1.3.0

Step 3. Prepare and upload sketch.

Download and open arduino-dht-esp8266-mqtt.ino sketch.

Note You need to edit following constants and variables in the sketch:

  • WIFI_AP - name of your access point
  • WIFI_PASSWORD - access point password
  • TOKEN - the $ACCESS_TOKEN from Thingsboard configuration step.
  • thingsboardServer - Thingsboard HOST/IP address that is accessible within your wifi network. Specify “demo.thingsboard.io” if you are using live demo server.
resources/arduino-dht-esp8266-mqtt.ino
#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include "SoftwareSerial.h"

#define WIFI_AP "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"

#define TOKEN "YOUR_ACCESS_TOKEN"

// DHT
#define DHTPIN 4
#define DHTTYPE DHT22

char thingsboardServer[] = "YOUR_THINGSBOARD_HOST_OR_IP";

// Initialize the Ethernet client object
WiFiEspClient espClient;

// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);

PubSubClient client(espClient);

SoftwareSerial soft(2, 3); // RX, TX

int status = WL_IDLE_STATUS;
unsigned long lastSend;

void setup() {
  // initialize serial for debugging
  Serial.begin(9600);
  dht.begin();
  InitWiFi();
  client.setServer( thingsboardServer, 1883 );
  lastSend = 0;
}

void loop() {
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    while ( status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(WIFI_AP);
      // Connect to WPA/WPA2 network
      status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
      delay(500);
    }
    Serial.println("Connected to AP");
  }

  if ( !client.connected() ) {
    reconnect();
  }

  if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds
    getAndSendTemperatureAndHumidityData();
    lastSend = millis();
  }

  client.loop();
}

void getAndSendTemperatureAndHumidityData()
{
  Serial.println("Collecting temperature data.");

  // Reading temperature or humidity takes about 250 milliseconds!
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");

  String temperature = String(t);
  String humidity = String(h);


  // Just debug messages
  Serial.print( "Sending temperature and humidity : [" );
  Serial.print( temperature ); Serial.print( "," );
  Serial.print( humidity );
  Serial.print( "]   -> " );

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"temperature\":"; payload += temperature; payload += ",";
  payload += "\"humidity\":"; payload += humidity;
  payload += "}";

  // Send payload
  char attributes[100];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/devices/me/telemetry", attributes );
  Serial.println( attributes );
}

void InitWiFi()
{
  // initialize serial for ESP module
  soft.begin(9600);
  // initialize ESP module
  WiFi.init(&soft);
  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(WIFI_AP);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
    delay(500);
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Connecting to Thingsboard node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("Arduino Uno Device", TOKEN, NULL) ) {
      Serial.println( "[DONE]" );
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

Connect your Arduino UNO device via USB cable and select “Arduino/Genuino Uno” port in Arduino IDE. Compile and Upload your sketch to device using “Upload” button.

After application will be uploaded and started it will try to connect to Thingsboard node using mqtt client and upload “temperature” and “humidity” timeseries data once per second.

Troubleshooting

When application is running you can select “Arduino/Genuino Uno” port in Arduino IDE and open “Serial Monitor” in order to view debug information produced by serial output.

Data visualization

Finally, open Thingsboard Web UI. You can access this dashboard by logging in as a tenant administrator. Use

in case of local Thingsboard installation.

Go to “Devices” section and locate “Arduino UNO Demo Device”, open device details and switch to “Latest telemetry” tab. If all is configured correctly you should be able to see latest values of “temperature” and “humidity” in the table.

image

After, open “Dashboards” section then locate and open “Arduino DHT22: Temperature & Humidity Demo Dashboard”. As a result you will see two time-series charts and two digital gauges displaying temperature and humidity level (similar to dashboard image in the introduction).

Next steps

Browse other samples or explore guides related to main Thingsboard features: