Skip to content
ImagineWorld

Communicating with Edge Devices across Long Distances Using LoRa

node_idnode-book_edge-computing-systems-with-kubernetes_chapter-12-communicating-with-edge-devices-across-long-distances-using
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleCommunicating with Edge Devices across Long Distances Using LoRa
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Communicating with Edge Devices across Long Distances Using LoRa

Section titled “Chapter 12 — Communicating with Edge Devices across Long Distances Using LoRa”

Long Range (LoRa) is a wireless protocol that you can use to receive and send data over long distances using low-powered devices. You can use these edge devices with solar panels or other sources of energy. Sometimes, your edge devices use batteries and are not connected to a common power source like we often find in our houses. When you are crafting edge systems, you could use edge devices using sensors that you have to configure. You could use prototype hardware platforms such as Arduino or devices such as ESP32 microcontrollers or a Raspberry Pi. These devices support LoRa modules to bring communication capabilities to your device, which is crucial for sending and receiving data from devices. In this chapter, we are going to explore how to take advantage of the LoRa wireless protocol to send or receive data from long distances. We will continue expanding the options for monitoring edge devices as in the previous chapter but now using the LoRa wireless protocol.

In this chapter, we’re going to cover the following main topics:

  • LoRa wireless protocol and edge computing
  • Deploying MySQL to store sensor data
  • Deploying a service to store sensor data in a MySQL database
  • Programming the ESP32 microcontroller to send sensor data
  • Programming the ESP32 microcontroller to receive sensor data
  • Visualizing data from ESP32 microcontrollers using MySQL and Grafana

To deploy our databases in this chapter, you will need the following:

  • A single or multi-node K3s cluster that can use ARM devices with MetalLB and Longhorn storage installed. This example will be tested using a Raspberry Pi 4B with 4 GB of RAM and using Ubuntu 20.04 or later for ARM 64-bit.
  • A Kubernetes cluster hosted in your public cloud provider (AWS, Azure, GCP) or your private cloud.
  • 2 ESP32 microcontrollers with the LoRa module installed. We are using the Heltec ESP32 + Lora v2 model; one to send and the other to receive data.
  • Arduino IDE installed on your Mac. You can use Windows since it’s pretty similar to configure, and it is also more stable when working with hardware.
  • A USB 2.0 A-Male to Micro B cable for programming your ESP32 devices.
  • A Keyes DHT11 sensor or similar connected to your edge device to read temperature and humidity.
  • kubectl configured to be used in your local machine for your Kubernetes cloud cluster or your K3s cluster to avoid using the --kubeconfig parameter.
  • Clone the GitHub repository at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch12 if you want to run the YAML configurations using kubectl apply instead of copying the code from this book. Take a look at the code directory for Arduino source codes for Heltec devices and the yaml directory for YAML configurations. These are located inside the ch12 directory.

Now, let’s understand how our scenario of using LoRa devices, Prometheus, and Grafana is going to work.

LoRa refers to a radio modulation technique for long distances, and together with LoRaWAN, it defines a network protocol that can be used to interconnect devices. LoRaWAN is also a network architecture that uses a start-of-start topology in which the gateway relays messages between edge devices. LoRa uses three popular frequencies: 433, 868, and 915. 433 is sometimes used outdoors. 868 is used in Europe and 915 is used in America. LoRaWAN has gateway devices that can connect LoRa networks to the internet. LoRa is designed for low power, which is why LoRa is used for applications in IoT to interconnect devices across long distances.

As we know, the goal of edge computing is to process data near the source. Therefore, LoRa allows us to implement edge computing and interconnect devices for long distances without using a lot of energy. Some use cases include agriculture, buildings, supply chain, logistics, geo localization applications, and more. Some common devices that support LoRa are Heltec ESP32 devices, which are designed for low power consumption. We are going to focus on configuring a Heltec ESP32 device with LoRa support in this chapter.

To start our use case implementation of using LoRa on the tiny edge to interact with a far edge Kubernetes cluster, let’s explore the following diagram:

Figure 12.1 – Monitoring with ESP32 devices and LoRaWAN

This diagram is divided into different layers. You can see how the data flows between the far edge, where LoRa communication is implemented, to the cloud layer. But first, let’s describe the different components of this use case that we want to implement:

  • Tiny edge: In this layer, we are going to find the Heltec ESP32 devices, which you can classify as devices that send or receive data. This device sends data, reads data from the DHT11 sensor, and sends the information in JSON format using the LoRa protocol. The other devices read the information, send it across LoRa, and send it to the cluster on the far edge using a post request in a LAN. You can add as many devices to send data as you want.
  • Far edge: Here, you can find a single or multi-node K3s cluster using ARM devices. This cluster provides the metrics service, which receives data in JSON format from the tiny edge. Once the data is received, the metrics service writes this data to the cloud layer in the MySQL deployment inside a Kubernetes cluster provisioned in the cloud provider. This could be Amazon, GCP, Azure, and so on.
  • Near edge: This layer contains the local router that connects the local network to the internet. Keep in mind that the cluster in the far edge works as a gateway to send data from the LoRa network to the internet.
  • Cloud layer: Here, you can find the Kubernetes cluster, which contains MySQL and Grafana. MySQL stores data coming from your local sensors, while Grafana uses MySQL to create dashboards using your sensor data.

In summary, all your sensor data is coming from ESP32 devices, some equipped with sensors. These devices send and receive data using the LoRa protocol. When a receiver device receives information, it’s transformed into JSON format and then sent to a Kubernetes service located on the far edge. After this service receives this information, it’s forwarded to the cloud layer and stored in a MySQL database. MySQL is used by Grafana to show sensor data collected at the edge in real time. Now, let’s deploy our MySQL databases to store data.

Before you can store data from your devices using LoRa, you must deploy your database. For this, we are going to use MySQL. MySQL is a pretty popular database that you can use to store data from your sensor. The main advantage of using MySQL is that it is well documented, and you can find a lot of examples on the internet. For our deployment, we are going to use a PersistentVolumeClaim and the mysql:8.0.28-oracle image. Even if you decide to deploy your MySQL over the cloud or locally at the edge, you must use a LoadBalancer service so that you have an endpoint for the service that is going to store all sensor data. Our MySQL database will be deployed in the default namespace to simplify the implementation. To deploy our MySQL database, follow these steps:

  1. Create a PersistentVolumeClaim with 5 GB of storage:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
    name: db-pv-claim
    spec:
    accessModes:
    - ReadWriteOnce
    resources:
    requests:
    storage: 5Gi
    EOF

Important Note

Don’t forget to use ConfigMaps and Secrets for a more secure and advanced configuration. You can explore Chapter 10, SQL and NoSQL Databases at the Edge, for more details.

  1. Now, let’s deploy our MySQL database. Our deployment is going to use the previous PersistentVolumeClaim, called db-pv-claim, for this run:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: mysql
    spec:
    selector:
    matchLabels:
    app: mysql
    strategy:
    type: Recreate
    template:
    metadata:
    labels:
    app: mysql
    spec:
    containers:
    - image: mysql:8.0.28-oracle
    name: mysql
    env:
    - name: MYSQL_DATABASE
    value: sensor_data
    - name: MYSQL_USER
    value: lora_mysql
    - name: MYSQL_PASSWORD
    value: lora123-
    - name: MYSQL_ROOT_PASSWORD
    value: lora123-
    ports:
    - containerPort: 3306
    name: mysql
    volumeMounts:
    - name: mysql-persistent-storage
    mountPath: /var/lib/mysql
    volumes:
    - name: mysql-persistent-storage
    persistentVolumeClaim:
    claimName: db-pv-claim
    EOF

In this deployment, we are using some environment variables:

  • MYSQL_DATABASE: Creates an initial database
  • MYSQL_USER: Creates a super admin user for the database defined in MYSQL_DATABASE
  • MYSQL_PASSWORD: Sets a password for the defined user in the MYSQL_USER variable
  • MYSQL_ROOT_PASSWORD: Sets a password for the root user

Important Note

If you are using a multi-node cluster, use the nodeSelector option to prevent issues with the provisioned PersistentVolumeClaim.

  1. Now, we need a ClusterIP service. This will be used inside Grafana to configure this MySQL database as a data source:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    name: mysql
    spec:
    ports:
    - port: 3306
    protocol: TCP
    targetPort: 3306
    selector:
    app: mysql
    type: ClusterIP
    status:
    loadBalancer: {}
    EOF
  2. We also need a LoadBalancer service to expose MySQL. This service will be used to expose MySQL to the outside world. This could be over the internet or using an IP address inside your local network. Regardless, the provisioned load balancer IP address will be used inside your ESP32 devices. These ESP32 devices are going to send information to this endpoint, using our metrics service to finally store sensor data in MySQL. Let’s create this LoadBalancer service:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    name: mysql-lb
    spec:
    ports:
    - port: 3306
    protocol: TCP
    targetPort: 3306
    selector:
    app: mysql
    type: LoadBalancer
    status:
    loadBalancer: {}
    EOF

Now that MySQL is running, we have to create a table to store sensor data. To do so, follow these steps:

  1. Create a MySQL CLI client to run some commands to create the table where data will be stored:
    $ kubectl run client -it --rm --image=mysql:8.0.28-oracle -- bash

Once you are inside, run the following command. This will ask you for a password. Use lora123- as your password:

$ mysql -u lora_mysql -h mysql -p

The prompt will change to something similar to mysql>.

  1. Create the metric table and include the device, temperature_c, temperature_f, humidity, and time fields:
    use sensor_data;
    CREATE TABLE metric (device INT NOT NULL,temperature_c DECIMAL(4,2),temperature_f DECIMAL(4,2) NOT NULL,humidity DECIMAL(4,2) NOT NULL, time DATETIME NOT NULL);

First, we must select the sensor_data database to create the table inside using the use command. Then, we must create the table metric using the CREATE TABLE command. We configure it so that each field has to have values. We use DECIMAL(4,2), which means 4-2 = 2 integer numbers and 2 decimals. We store data using the format used by the now() MySQL function as MONTH/DAY/YEAR HOUR:MINUTE:SECOND.

Here is a small explanation of what each field contains:

  • device: This represents the number of the ESP32 Lora device that sends sensor data. This could be a number greater than 0.
  • temperature_c: This is the temperature measured in Celsius.
  • temperature_f: This is the temperature measured in Fahrenheit.
  • humidity: Ambient humidity, measured as a percentage.
  1. Exit the MySQL client using the quit command inside MySQL.
  2. Exit the client using the exit command. After exiting, the pod will be deleted.
  3. Get the MySQL IP address provisioned in the LoadBalancer service. To do so, run the following commands:
    $ MYSQL_IP="$(kubectl get svc mysql-lb -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"
    $ echo $MYSQL_IP

The echo command is going to show the IP address of your MySQL.

Now that our MySQL database has been deployed and is ready to be used, let’s deploy our metrics application on the far edge to store data in this MySQL database.

Deploying a service to store sensor data in a MySQL database

Section titled “Deploying a service to store sensor data in a MySQL database”

For this scenario, we need to deploy a service to store data in the previously deployed MySQL. We are going to call this metrics. The metrics service contains the following code:

from flask import Flask, request
import mysql.connector
import os
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'It works'
def insert(data):
conn = mysql.connector.connect(
host=os.environ['HOST'],
user=os.environ['MYSQL_USER'],
password=os.environ['MYSQL_PASSWORD'],
database=os.environ['MYSQL_DATABASE']
)
cursor = conn.cursor()
sql = "INSERT INTO metric "+\
"(device,temperature_c,"+\
"temperature_f,humidity,time) "+\
"VALUES (%s,%s,%s,%s,now());"
val = (data["d"],data["t"],data["t_f"],data["h"])
cursor.execute(sql,val)
conn.commit()
cursor.close()
conn.close()
@app.route('/device',methods = ['POST'])
def device():
data = request.json
print(data)
#Process data in some way
t_farenheit = float(data["t"])*(9/5)+32
data["t_f"] = t_farenheit
insert(data)
return "processed"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000, debug=True)

This code has two endpoints:

  • /: This is only a test URL.
  • /device: This gets data from POST requests and writes it to MySQL by calling the insert function.

It also uses the insert(data) function to insert the data into the MySQL deployed in the cloud layer. This function takes the data coming from LoRaWAN and recalculates the temperature in Fahrenheit. Once stored, the data returns the process word.

This script also uses the following environment variables:

  • HOST: Defines the IP address where MySQL is listening
  • MYSQL_USER: The user to connect to the database
  • MYSQL_PASSWORD: The password used to connect to the database
  • MYSQL_DATABASE: The database name where metrics is going to store data

Our deployment in Kubernetes must have these variables set to work properly, without errors.

Important Note

You can check the code on how to build a container based on this example at https://github.com/sergioarmgpl/containers/tree/main/metric.

Now that we’ve looked at the code of the metrics service, let’s deploy metrics to start storing sensor data in this database. For this, follow these steps:

  1. Deploy our metrics application so that it’s running:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    creationTimestamp: null
    labels:
    app: metrics
    name: metrics
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: metrics
    strategy: {}
    template:
    metadata:
    creationTimestamp: null
    labels:
    app: metrics
    spec:
    containers:
    - image: sergioarmgpl/metric
    name: metric
    env:
    - name: HOST
    value: "192.168.0.240"
    - name: MYSQL_USER
    value: "lora_mysql"
    - name: MYSQL_PASSWORD
    value: "lora123-"
    - name: MYSQL_DATABASE
    value: "sensor_data"
    resources: {}
    status: {}
    EOF

In this deployment, we are using the following values for the environment variables:

  • HOST: This is the IP address of the LoadBalancer service that was created for our MySQL – that is, 192.168.0.240. This will be the IP address that was returned in the last step of the previous section.
  • MYSQL_USER: The MySQL user. In this case, this is lora_mysql.
  • MYSQL_PASSWORD: The password for lora_mysql. In this case, this is lora123-.
  • MYSQL_DATABASE: The name of the MySQL database where sensor data will be stored. In this case, this is sensor_data.

Important Note

You can customize all these values to fit your needs. Remember that you can use ConfigMaps or Secrets to secure your deployments. We are using hard-coded values just to simplify the implementation. Check out Chapter 10, SQL and NoSQL Databases at the Edge, for this kind of configuration.

  1. Now, let’s create our LoadBalancer service for the metrics deployment. The provisioned IP address will be hard-coded inside the code of our ESP32 devices. To create the service, run the following code:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    name: metrics
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: metrics
    type: LoadBalancer
    status:
    loadBalancer: {}
    EOF
  2. To obtain the provisioned IP address from the metrics service, run the following commands:
    $ METRICS_IP="$(kubectl get svc metrics -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"
    $ echo METRICS_IP

The echo command will show the IP address of our metrics application. Take note of this value since it will be used to program our ESP32 devices. Let’s assume that this value is 192.168.0.241 for this scenario.

Now that we have deployed our metrics service on the far edge, let’s configure our ESP32 devices so that they can send and receive data.

Programming the ESP32 microcontroller to send sensor data

Section titled “Programming the ESP32 microcontroller to send sensor data”

ESP32 is a low-cost, low-power microcontroller chip and the successor of the ESP8266 microcontroller. In this chapter, we will be using the Heltec ESP32 + LoRa, which is an ESP32 microcontroller plus the capability to use the LoRa wireless protocol. This microcontroller can also send and receive data using the LoRa wireless protocol using the integrated SX1276 chip in this Heltec dashboard.

Before configuring our device, we have to do the following:

  1. Connect the DHT11 sensor to the Heltec ESP32 + LoRa device.
  2. Install the USB to UART bridge driver.
  3. Install and configure Arduino IDE to program the Heltec ESP32 + LoRa device.
  4. Flash the Heltec ESP32 + Lora device.

So, let’s get started by connecting a DHT11 sensor to our Heltec ESP32 + Lora device.

Configuring Heltec ESP32 + LoRa to read DHT11 sensor data

Section titled “Configuring Heltec ESP32 + LoRa to read DHT11 sensor data”

Heltec devices are often used for IoT, and ESP32 is a very popular device for IoT and LoRa implementations. You can find the official documentation for Heltec devices at https://heltec-automation-docs.readthedocs.io/en/latest. For our LoRa implementation, we are going to use the following diagram:

Figure 12.2 – Heltec ESP32 reading data from the DHT11 schema

To connect your Heltec ESP32 to your DHT11 sensor, follow these steps. This is the sender device:

  1. Connect your LoRa antenna. This could affect the transmission range if the antenna is not connected.
  2. Connect your power source to the USB connection. You must use a USB 2.0 A-Male to Micro B cable.
  3. Connect your PIN 17 with a wire to the S input in the DHT11 sensor.
  4. Connect the GND (ground) to the G input in the DHT11 sensor.
  5. Connect one of the 3V3 volt outputs to the V input in the DHT11 sensor.

For your receiver device, just follow these steps:

  1. Connect your LoRa antenna.
  2. Connect your power source to the USB connection as your sender device.

Important Note

Remember that you have to use a power source supply or a battery that gives you 3.5 or 5 volts. To learn more, check out https://heltec-automation-docs.readthedocs.io/en/latest/esp32/index.html.

With that, your sender and receiver devices are ready to upload some code. Now, let’s install all the software that we need to upload some code into our devices.

When installing the generic SiLabs CP210X driver that installs support for the USB to UART bridge, this driver is going to recognize your device on your computer. In this way, your Heltec device can connect to the computer and interact with Arduino IDE using serial communication.

To install this driver, you can visit the following link for detailed instructions: https://heltec-automation-docs.readthedocs.io/en/latest/general/establish_serial_connection.html. There, you can find the latest documentation to install the driver on Windows and Mac.

These instructions consist of downloading various drivers:

You must follow the wizard to install them, depending on your system. Once you have installed the driver, you can connect your device to your system and check if it was detected. For Mac, you can execute the following command:

$ ls /dev | grep cu | grep 'usbserial\|UART'

You will see an output similar to the following:

cu.SLAB_USBtoUART
cu.usbserial-0001

This means that your device was detected. Some common problems may occur where your device can’t be recognized. This will be because of the cable that you are using; try to find a cable in an optimal condition for your computer to detect the device.

For Windows, you will see that your device appears in the Hardware manager in the part of ports. Then, the device will appear like so:

  • Silicon Labs CP210X USB to UART bridge (COM3)

This means that your Heltec device was detected successfully.

Now that your system recognizes the device, it’s time to install Arduino IDE to upload some code inside your Heltec device.

Arduino IDE is a piece of software that you can use to upload code to your boards. In this case, we are using a board designed by Heltec, which is the one we called the Heltec device. To start using Arduino IDE, follow these steps:

  1. Download Arduino IDE by going to https://www.arduino.cc/en/software. This will depend on which operating system are you using. You can choose between Windows, Linux, or Mac. In this chapter, we are going to cover just Mac. We will use Arduino 1.8.19.

Important Note

You can also follow the official page of Heltec, which explains how to install the Heltec driver and Arduino IDE for Windows and Mac. The quick start link is https://heltec-automation-docs.readthedocs.io/en/latest/esp32/quick_start.html.

  1. Open Arduino IDE by clicking on its icon on your desktop or inside Launchpad on Mac.
  2. Click File | Preferences and paste https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series/releases/download/0.0.5/package_heltec_esp32_index.json inside the Additional Boards Manager URLs field. Then, click OK. The new ESP32 board will be loaded in Arduino IDE:

Figure 12.3 – Configuring Preferences to use the Heltec ESP32 device

  1. Now, go to Tools | Board | Boards Manager:

Figure 12.4 – The Boards Manager menu

  1. Search for heltec in the new pop-up dialog, then click Install to install it:

Figure 12.5 – Searching for heltec on Boards Manager

You will see something similar to the following:

Figure 12.6 – Heltec board installed via Boards Manager

  1. Now, select the board by going to Tools | Board | Heltec ESP32 Arduino and select WiFi LoRa 32(V2):

Figure 12.7 – Setting WiFi LoRa 32(V2) as the default board

  1. Now, repeat this process by going to Tools | Manage Libraries, searching for the DHT sensor library from Adafruit, and choosing Heltec ESP32 Dev-Boards. Make sure you install it.

With that, our Arduino IDE is ready to be used. Now, let’s learn about some configurations that you will need in case of errors.

Troubleshooting Arduino IDE when using Heltec ESP32 + LoRa

Section titled “Troubleshooting Arduino IDE when using Heltec ESP32 + LoRa”

macOS has some challenges, depending on your Mac version, but you can fix them.

One is the esptool Python library. To fix it, follow these steps:

  1. Copy your current esptool.py file inside the tools folder. The command will look as follows:
    $ cp /Users/<YOUR_USER>/Library/Arduino15/packages/Heltec-esp32/hardware/esp32/<X.X.X> /tools/esptool.py /Users/ <YOUR_USER> /Library/Arduino15/packages/Heltec-esp32/tools/esptool_py/<X.X.X>/
  2. Change the permissions for the esptool.py file:
    $ chmod +x esptool.py

Run the esptool.py file:

$ ./esptool.py
  1. Sometimes, you have to install the serial library if the previous command returns an error. For this, you have several options. One is to install the library from scratch by going to https://github.com/pyserial/pyserial/releases. In this case, we are using version 3.4. For this run, the following commands:
    $ wget https://github.com/pyserial/pyserial/archive/refs/tags/v3.4.zip
    $ sudo python setup.py install
  2. Then, try again if the ./esptool.py command returns errors.
  3. Depending on which Python version is installed on your computer, you can try this other alternative:
    $ sudo pip install pyserial or
    $ sudo pip3 install pyserial
  4. The last alternative is to use easy_install to install the pyserial library. To do so, run the following command:
    $ sudo easy_install pyserial

Important Note

macOS Monterrey deletes Python 2.7 by default, so you have to install this Python version. You could stay with Python 3, but you have to open Arduino IDE with the open /Applications/Arduino.app command. You can find a more detailed way to fix these problems by watching the following video: https://www.youtube.com/watch?v=zkyoghpT8_U.

Another problem to fix, depending on your Arduino version, is that Heltec installs its Wi-Fi library. So, when you try to compile and upload the program, sometimes, you will see some errors. To avoid these errors, you have two options:

  1. Uninstall the default Arduino Wi-Fi library by going to Tools | Manage libraries. Then, find the Wi-Fi library from Arduino and uninstall it.
  2. Remove or rename the default Arduino Wi-Fi library folder by using the following commands:
    $ cd /Applications/Arduino.app/Contents/Java/libraries
    $ mv libraries/WiFi

Important Note

On Windows, the installation is smooth, so you won’t have to fix this kind of issue.

Now, it is time to upload some code to your devices using Arduino IDE.

Uploading code to the ESP32 microcontroller to send sensor data

Section titled “Uploading code to the ESP32 microcontroller to send sensor data”

Now, let’s upload our code to our Heltec devices. Let’s start with the sender device. This device is going to capture data from the DHT11 sensor and send it to the receiver device using the LoRa wireless protocol. Let’s create a new file by going to File | New. By default, you will see something similar to the following:

void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}

Now, replace it with the following code:

#include "heltec.h"
#define BAND 915E6
#include "DHT.h"
#define DHTPIN 17
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
#define DEVICE 1
#define DELAY 3000
void setup()
{
Heltec.begin(false,true,true,true,BAND);
Serial.begin(9600);
LoRa.setSyncWord(0xF3);
Serial.println("LoRa started");
dht.begin();
}
void sendTH()
{
String values = "";
LoRa.beginPacket();
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println(F("Failed to get data from sensor"));
return;
}
String hS = (String)h;
String tS = (String)t;
String dS = (String)DEVICE;
values = "{\"t\":"+tS+",\"h\":"+hS+",\"d\":"+dS+"}";
Serial.println(values);
LoRa.print(values);
LoRa.endPacket();
}
void loop()
{
delay(DELAY);
sendTH();
}

Let’s look at the preceding code in more detail:

  • heltec.h: We import the library to use the ESP32 + LoRa device. With this, you can use the Wi-Fi and LoRa wireless protocol.
  • DHT.h: We import the library to read data from the DHT11 sensor.
  • BAND: We set the band to use to connect the devices. For Europe, you have to use a value of 868E6, while for America, you have to use 915E6.
  • DHTPIN: This is a constant value that we use to set the PIN that’s used to read data in our ESP32 device. In this case, we are using pin 17. Keep in mind that the pin to use has to support digital information.
  • DHTTYPE: This defines the type of sensor. The library that we are using supports the DHT11 and DHT12 sensors.
  • DEVICE: This is the device number that is sending data. You must change this value every time you upload the code on a device, just to identify each device using a number.
  • DELAY: This is the time to wait until sending the next sensor measure data.
  • setup(): This function does an initial configuration for the Heltec device and sets the network ID for LoRa using 0xF3 – that is, the network ID for our devices. This value must be set between 0 and 0xFF.
  • sendTH(): This function captures and sends the sensor data with the LoRa Wi-Fi protocol in the {"t":26.2,"h":35.5,"d":1} format, where t is the temperature in Celsius, h is the humidity in percentages, and d is the device number.
  • loop(): This function runs as a loop and calls sendTH() to capture and send sensor data using LoRa.

Important Note

You can find the source code of the sender and receiver device at https://github.com/PacktPublishing/Edge-Computing-Systems-with-Kubernetes/tree/main/ch12/code/arduino.

In summary, first, we set all the constant values to configure how to read data from the DHT11 sensor and send data using LoRa. Then, the setup is called to prepare reading data from the sensor and the initial configuration for LoRa. Finally, loop() runs as a loop that calls sendTH(), which sends and receives data. Once you have your device with this code, just turn it on to send data. To stop sending data, you must power off the device.

Pay attention to the lines that contain the Serial.println command. This command prints information using the serial port. You can troubleshoot what is happening in your device using Arduino when your device is powered with your USB port from your laptop by opening Tools | Serial Monitor. Doing this will show all the Serial.println outputs inside the window:

Figure 12.8 – Monitoring with Heltec ESP32 devices in Arduino

Important Note

To connect your device to macOS, you need a USB A-to-USB C adaptor. If you need a power source with at least 5 volts, you can also use a battery bank instead of connecting the device to a laptop or a computer.

Now that your Heltec sender device is working, you can start uploading the code for the receiver device.

Programming the ESP32 microcontroller to receive sensor data

Section titled “Programming the ESP32 microcontroller to receive sensor data”

Now, we have to configure our Heltec ESP32 device to receive the sensor data and send it to the far edge cluster by doing a request across the wireless network. To start, we must create another file by clicking File | New and replacing the default content with the following code:

#include "heltec.h"
#include "WiFi.h"
#include <HTTPClient.h>
#define BAND 915E6
#define METRICS_IP "192.168.0.241"
void setup()
{
Heltec.begin(false, true, true, true, BAND);
Serial.begin(9600);
LoRa.setSyncWord(0xF3);
Serial.println("LoRa started");
WIFISetUp();
}
void WIFISetUp(void)
{
WiFi.disconnect(true);
delay(100);
WiFi.mode(WIFI_STA);
WiFi.setAutoConnect(true);
WiFi.begin("NET_NAME","PASSWORD");
delay(100);
byte count = 0;
while(WiFi.status() != WL_CONNECTED && count < 10)
{
count ++;
delay(500);
Serial.println("Connecting...");
}
if(WiFi.status() == WL_CONNECTED)
Serial.println("Connected OK");
else
Serial.println("Failed");
}
void callURL(String data)
{
String postData = data;
Serial.println("Sending: " + postData);
WiFiClient client;
HTTPClient http;
http.begin(client, "http://"+((String)METRICS_IP)+":3000/device");
http.addHeader("Content-Type","application/json");
int httpResponseCode = http.POST(postData);
Serial.println("HTTP Response code xyz: "+(String)httpResponseCode);
http.end();
}
void loop()
{
onReceive(LoRa.parsePacket());
}
void onReceive(int packetSize)
{
String incoming = "";
if (packetSize == 0) return;
while (LoRa.available())
incoming += (char)LoRa.read();
Serial.println("Received: " + incoming);
callURL(incoming);
}

Let’s understand the code a little bit:

  • Heltec.h, WiFi.h, HTTPClient.h: These are the libraries that we are using for the receiver. Heltec.h is used to send data with LoRa, WiFi.h is the Wi-Fi Heltec library to connect to the wireless network, and HTTPClient.h is used to send a request to our far edge server with the sensor data.
  • BAND: Here, we set the same band that’s used in the sender device.
  • METRICS_IP: This is the IP address of the metrics service in your cluster. To get this value, go to the Deploying a service to store sensor data in a MySQL database section. Replace this value before uploading the code to your device.
  • setup(): Here, we configure the Heltec device to receive data from the same LoRa network defined by setSyncWord. It also configures the Wi-Fi connection.
  • WIFISetUp(void): Here, we configure the Wi-Fi connection. To do so, you must replace NET_NAME with your network name and PASSWORD with the necessary password to access your connection.
  • callURL(String data): This calls the metrics service in your cluster. The URL to access it will be something like http://METRICS_IP:3000/device, but this function automatically generates this URL using the value of the METRICS_IP constant.
  • onReceive(int packetSize): This receives information that’s been sent to the configured network using the LoRa protocol and then sends that information to the metrics service in the far edge cluster using an HTTP POST request.
  • loop(): This function runs as a loop and calls onReceive(int packetSize), which gets LoRa packets that contains sensor data. Then, it sends these to the metrics endpoint in the far edge cluster.

To summarize, first, we configure the device so that we can connect to the same LoRa network. We must also configure the Wi-Fi, which has access to the far edge server. loop() constantly checks if it has received some data to send it to the metrics server in the far edge cluster.

Now, upload the code to your device and turn it on, as we did in the Programming the ESP32 microcontroller to send sensor data section. With that, our devices have been configured, so let’s move to the last step and configure Grafana to show all our data in a dashboard, using the sensor data stored in MySQL.

Visualizing data from ESP32 microcontrollers using MySQL and Grafana

Section titled “Visualizing data from ESP32 microcontrollers using MySQL and Grafana”

Now, let’s finish off our implementation of a real-time temperature and humidity system. For this, we are going to use Grafana to create our reports and MySQL as our source of data to feed the reports. You can deploy this software in Kubernetes in the cloud or a private cloud using a network that can be accessed by your edge clusters. In this section, we are assuming that we are using Kubernetes in the cloud. To start creating our reports, follow these steps:

  1. Create the necessary namespace monitoring:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Namespace
    metadata:
    creationTimestamp: null
    name: monitoring
    spec: {}
    status: {}
    EOF
  2. Create a ConfigMap to create a default data source that contains our MySQL connection:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: grafana-datasources
    namespace: monitoring
    labels:
    grafana_datasource: "true"
    data:
    datasource.yaml: |-
    apiVersion: 1
    datasources:
    - name: sensor_data
    type: mysql
    url: mysql.default.svc
    access: proxy
    database: sensor_data
    user: lora_mysql
    secureJsonData:
    password: lora123-
    isDefault: true
    EOF

This will be the default data source configured in your grafana deployment.

Important Note

You can use a Secret object to secure sensitive data, but we are using ConfigMap to simplify this example.

  1. Deploy Grafana so that it can use the previous ConfigMap by running the following code:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: apps/v1
    kind: Deployment
    metadata:
    name: grafana
    namespace: monitoring
    spec:
    replicas: 1
    selector:
    matchLabels:
    app: grafana
    template:
    metadata:
    name: grafana
    labels:
    app: grafana
    spec:
    containers:
    - name: grafana
    image: grafana/grafana:8.4.4
    ports:
    - name: grafana
    containerPort: 3000
    resources:
    limits:
    memory: "1Gi"
    cpu: "1000m"
    requests:
    memory: 500M
    cpu: "500m"
    volumeMounts:
    - mountPath: /var/lib/grafana
    name: grafana-storage
    - mountPath: /etc/grafana/provisioning/datasources
    name: grafana-datasources
    readOnly: false
    volumes:
    - name: grafana-storage
    emptyDir: {}
    - name: grafana-datasources
    configMap:
    defaultMode: 420
    name: grafana-datasources
    EOF
  2. Let’s create the service to access Grafana:
    $ cat <<EOF | kubectl apply -f -
    apiVersion: v1
    kind: Service
    metadata:
    creationTimestamp: null
    labels:
    app: grafana
    name: grafana
    namespace: monitoring
    spec:
    ports:
    - port: 3000
    protocol: TCP
    targetPort: 3000
    selector:
    app: grafana
    type: ClusterIP
    EOF
  3. Use port-forward to forward the previous Grafana service. This will help us connect to Grafana locally:
    $ kubectl port-forward svc/grafana 3000 -n monitoring --address 0.0.0.0
  4. Go to http://localhost:3000. When the login page appears, use the username admin and password admin and click on the Log in button. After that, you will be you for new credentials:

Figure 12.9 – Grafana login

  1. After logging in, you can check that your default data source is set to MySQL by going to Configuration | Data sources:

Figure 12.10 – Grafana configuration menu

You will see something similar to the following:

Figure 12.11 – sensor_data default data source

  1. Now, click on Create | Dashboard:

Figure 12.12 – Creating a dashboard

Then, click Add a new panel:

Figure 12.13 – Grafana – The Add panel page

  1. Then, configure the new dashboard with the following query and values:
    SELECT
    UNIX_TIMESTAMP(time) AS "time",
    temperature_c AS "Temperature(Celcius)",
    temperature_f AS "Temperature(Farenheit)",
    humidity AS "Humidity(%)"
    FROM metric
    WHERE
    $__timeFilter(time)
    and device=1
    ORDER BY time

You must edit the default query by clicking on the pencil icon. Then, copy the previous query there:

Figure 12.14 – Editing the default MySQL query

We have set Title to Device 1 Sensor Data here. The new dashboard will look like this:

Figure 12.15 – The New dashboard/Edit Panel window

After changing the query if data is available, you will see a graph with three lines – one representing the temperature in Celsius, another representing the temperature in Fahrenheit, and the humidity as a percentage. Remember to set the dashboard to visualize the proper range of data – for example, to show data from the last 5 minutes – and refresh the dashboard every 5 seconds.

  1. After that, save your dashboard by clicking on the Save button.

Important Note

Check out Chapter 11, Monitoring the Edge with Prometheus and Grafana, for more details about customizing your dashboard.

  1. Finally, your dashboard will look as follows:

Figure 12.16 – ESP32 monitoring dashboard in Grafana

At this point, you are visualizing the data from your Heltec devices to send and receive data. This device interacts with your far edge cluster. If you chose to deploy Grafana and MySQL on the cloud, this scenario is also interacting with the cloud layer. All these components interact with each other to do their job. Remember that this is a simple implementation that you can extend to your own. Now, let’s summarize what we have learned in this chapter.

In this chapter, we explored how to implement an edge computing system by using LoRa devices to send and receive sensor data. Finally, we implemented a dashboard using MySQL and Grafana. In this way, the LoRa wireless protocol represents a way to implement lower-cost systems that need to transmit information close to the edge. Therefore, LoRa is a common choice as a transmission protocol for edge devices and IoT applications. In the next chapter, we are going to use a GPS module to extend the range of communication and databases to implement geolocation applications.

Here are a few questions to validate your new knowledge:

  • What are the uses and advantages of using the LoRa wireless protocol?
  • What is LoRaWAN?
  • How can I use a Heltec ESP32 + LoRa device to send sensor data?
  • How can I use Arduino IDE to program ESP32 devices?
  • How can I create a simple gateway to send data coming from LoRaWAN to LAN?
  • How can I use MySQL and Grafana to create reports?

Please refer to the following references for more information on the topics covered in this chapter: