Professional Documents
Culture Documents
A Degree Thesis
Submitted to the Faculty of the
Escola Tècnica d'Enginyeria de Telecomunicació de
Barcelona
Universitat Politècnica de Catalunya
by
Andreu Soler Mascarell
In partial fulfilment
of the requirements for the degree in
TELECOMMUNICATIONS TECHNOLOGIES AND
SERVICES ENGINEERING
But in order to control and monitor them, it is necessary to have control panels and a
platform that performs all the integration.
That is why this project will integrate Node-RED and its own control panel, saving the data
obtained in a database (InfluxDB) and being able to represent them in another type of
visualisation (Grafana). The concept of dockers and the installation involved were also
investigated.
After carrying out multiple proofs of concept, we obtained a very complete device
integration system, at a reduced cost and ideal for adding any smart device we want.
1
Resum
En aquest treball de final de grau ens introduïm en l’ampli món de l’IoT. L’auge d’aquest
concepte i la tecnologia relacionada amb ell fa que tothom vulgui tenir una casa intel·ligent.
Amb aquest propòsit, s’equipen diferents dispositius de control ambiental, interruptors
intel·ligents, llums intel·ligents, panys intel·ligents, etc.
És per això que aquest projecte integrarà Node-RED i el seu propi tauler de control,
guardant les dades obtingudes en una base de dades (InfluxDB) i podent representar-les
en un altre tipus de visualització (Grafana). També es va investigar el concepte de dockers
i la instal·lació que implica.
2
Resumen
En este trabajo de fin de grado, nos introducimos en el amplio mundo IoT. El auge que
está teniendo este concepto y la tecnología relacionada con ella, ocasiona que cualquier
persona quiera tener un hogar inteligente. Para ello, se equipan distintos dispositivos de
monitoreo ambiental, interruptores inteligentes, luces inteligentes, cerraduras inteligentes,
etc.
Pero para poder controlarlos y monitorearlos, es necesario contar con paneles de control
y una plataforma que realice toda la integración.
Es por ello que en este proyecto se realizará una integración con Node-RED y su propio
panel de control, guardando los datos obtenidos en una base de datos (InfluxDB) y
pudiéndolos representar en otro tipo de visualización (Grafana). También se ha indagado
en el concepto de los dockers y la instalación que ello conlleva.
3
Acknowledgements
I would like to express my gratitude to several people. First of all, I want to thank my advisor
Anna Calveras for giving me the opportunity to carry out such an interesting project and
constantly helping me during the development of the project.
Of course, I would like to thank my friends who I have met at university for all the good
times that we have had during these years and that I hope to have many more.
Lastly, I would like to thank my family for trusting me and my decisions throughout all these
years.
4
Revision history and approval record
Name e-mail
5
Table of contents
.
Abstract ............................................................................................................................................. 1
Resum ............................................................................................................................................... 2
Resumen ........................................................................................................................................... 3
Acknowledgements ........................................................................................................................... 4
Revision history and approval record ................................................................................................ 5
Table of contents ............................................................................................................................... 6
List of Figures .................................................................................................................................... 8
List of Tables: .................................................................................................................................. 10
1. Introduction .............................................................................................................................. 11
1.1. Statement of purpose ...................................................................................................... 11
1.2. Requirements and specifications .................................................................................... 11
1.3. Methods and procedures ................................................................................................. 12
1.4. Work plan with tasks, milestones and a Gantt diagram .................................................. 12
1.4.1. Workplan packages ................................................................................................. 12
1.4.2. Milestones................................................................................................................ 15
1.4.3. Gantt Diagram ......................................................................................................... 16
1.5. Deviations from the initial plan and incidences ............................................................... 16
1.6. Final Degree Thesis ........................................................................................................ 17
2. State of the art of the technology used or applied in this thesis: ............................................. 18
2.1. Internet of Things (IoT) .................................................................................................... 18
2.2. MQTT............................................................................................................................... 19
2.3. Node-RED ....................................................................................................................... 19
2.4. NPM ................................................................................................................................. 19
2.5. InfluxDB ........................................................................................................................... 20
2.6. Grafana ............................................................................................................................ 20
2.7. Docker ............................................................................................................................. 21
3. Methodology / project development: ....................................................................................... 22
3.1. Hardware Prototype......................................................................................................... 22
3.1.1. Raspberry Pi ............................................................................................................ 22
3.1.2. ESP32 with BMP280 ............................................................................................... 23
3.1.3. ESP32 with LED ...................................................................................................... 23
3.2. Home Automation Platform Comparison ......................................................................... 24
3.2.1. Introduction .............................................................................................................. 24
3.2.2. IOT Platform ............................................................................................................ 24
6
3.2.3. Platform Comparison ............................................................................................... 25
3.2.4. Final Implementation ............................................................................................... 28
3.3. Proof of Concept without dockers ................................................................................... 29
3.3.1. Install Raspberry Pi OS ........................................................................................... 29
3.3.2. Installing and running Node-RED on Raspberry Pi ................................................. 29
3.3.3. Installing MQTT Broker ............................................................................................ 33
3.3.4. Testing the Proof of Concept ................................................................................... 37
3.3.5. InfluxDB Installation ................................................................................................. 43
3.3.6. Grafana Installation ................................................................................................. 46
3.3.7. Add Influx as a Grafana data source ....................................................................... 47
3.3.8. Configuration of InfluxDB on NodeRED .................................................................. 49
3.3.9. Collecting some data with Grafana ......................................................................... 50
3.4. Dockers for IoT ................................................................................................................ 52
3.4.1. Introduction to Docker ............................................................................................. 52
3.4.2. Benefits of Using Docker ......................................................................................... 52
3.4.3. Why the IoT would use Docker (Benefits concretizing in the use of the IoT) .......... 54
3.5. Proof of Concept with dockers ........................................................................................ 55
3.5.1. Docker Installation ................................................................................................... 55
3.5.2. Docker MQTT Installation ........................................................................................ 57
3.5.3. Docker NodeRED Installation .................................................................................. 60
3.5.4. Docker InfluxDB Installation .................................................................................... 61
3.5.5. Docker Grafana Installation ..................................................................................... 62
3.6. Proof of Concept with other platforms (ThingsBoard CE) ............................................... 63
3.6.1. Install Raspberry Pi OS ........................................................................................... 63
3.6.2. Install Third-Party components (Java 11) ................................................................ 63
3.6.3. Install ThingsBoard Software................................................................................... 63
3.6.4. Install ThingsBoard database (PostgreSQL) ........................................................... 64
3.6.5. ThingsBoard Configuration service ......................................................................... 65
3.6.6. Run script and start ThingsBoard service ............................................................... 66
4. Results ..................................................................................................................................... 68
4.1. Screenshots final design & visualization ......................................................................... 68
4.2. MQTT Broker Tests ......................................................................................................... 71
4.3. Performance .................................................................................................................... 73
4.3.1. Raspberry Pi CPU & Memory Test .......................................................................... 73
4.3.2. Raspberry Pi memory storage ................................................................................. 75
4.3.3. MQTT connections test ........................................................................................... 75
5. Budget ..................................................................................................................................... 78
7
6. Conclusions and future development: ..................................................................................... 80
Bibliography: .................................................................................................................................... 81
Appendices: ..................................................................................................................................... 84
Appendix 1: Raspberry Pi Installation ............................................................................................. 84
Appendix 2: Node-RED Flow .......................................................................................................... 91
Appendix 3: ESP32 & BMP280 code for Node-RED ...................................................................... 92
Appendix 4: ESP32 & LED code for Node-RED ............................................................................. 95
Glossary .......................................................................................................................................... 98
.
List of Figures
Figure 1. Gantt diagram .................................................................................................................. 16
Figure 2. IoT application. Source [38] ............................................................................................. 18
Figure 3. MQTT structure. Source [3].............................................................................................. 19
Figure 4. Grafana example. Source [8] ........................................................................................... 20
Figure 5. Hardware design .............................................................................................................. 22
Figure 6. BMP280 connections ....................................................................................................... 23
Figure 7. LED connections .............................................................................................................. 23
Figure 8. OpenHAB example. Source [13] ...................................................................................... 25
Figure 9. Home Assistant example. Source [13] ............................................................................. 25
Figure 10. ThingsBoard example. Source [13] ................................................................................ 26
Figure 11. Node-RED example. Source [13] ................................................................................... 27
Figure 12. PoC without dockers design........................................................................................... 29
Figure 13. Command: bash node-red ............................................................................................. 30
Figure 14. Node-RED package installation ..................................................................................... 30
Figure 15. Node-RED manage palette (1) ...................................................................................... 31
Figure 16. Node dashboard modules installation (1) ...................................................................... 32
Figure 17. Node modules installation (2)......................................................................................... 32
Figure 18. Node modules installed on pallete ................................................................................. 32
Figure 19. Node-RED dashboard modules ..................................................................................... 33
Figure 20. Node-RED manage palette (2) ...................................................................................... 35
Figure 21. Node dashboard modules installation (2) ...................................................................... 35
Figure 22. MQTT Aedes node-red module ..................................................................................... 35
Figure 23. Configurating Aedes MQTT Broker ................................................................................ 36
Figure 24. MQTT Broker test with Node-RED ................................................................................. 37
Figure 25. Proof of Concept Node-RED flow .................................................................................. 37
Figure 26. Aedes Broker configuration ............................................................................................ 38
8
Figure 27. Inject node configuration ................................................................................................ 38
Figure 28. Function node configuration ........................................................................................... 39
Figure 29. MQTT publish node configuration .................................................................................. 39
Figure 30. MQTT Broker server configuration ................................................................................. 40
Figure 31. MQTT subcribe node configuration ................................................................................ 40
Figure 32. JSON node configuration. .............................................................................................. 41
Figure 33. Node-RED dashboard nodes configuration ................................................................... 41
Figure 34. Node-RED data reception .............................................................................................. 42
Figure 35. Node-RED Dashboard visualization .............................................................................. 42
Figure 36. InfluxDB vs SQLite. Source [22] .................................................................................... 43
Figure 37. Grafana relative time ranges .......................................................................................... 44
Figure 38. Grafana welcome menu ................................................................................................. 47
Figure 39. Influx as a Grfana data source ....................................................................................... 47
Figure 40. InfluxDB ip on Grafana ................................................................................................... 48
Figure 41. InfluxDB Access on Grafana .......................................................................................... 48
Figure 42. InfluxDB node modules .................................................................................................. 49
Figure 43. InfluxDB node configuration ........................................................................................... 49
Figure 44. Node-RED real data reception ....................................................................................... 50
Figure 45. InfluxDB database data .................................................................................................. 50
Figure 46. Grafana dashboard creation (1) ..................................................................................... 50
Figure 47. Grafana dashboard creation (2) ..................................................................................... 51
Figure 48. Grafana dashboard creation (3) ..................................................................................... 51
Figure 49. Command: curl docker ................................................................................................... 55
Figure 50. Verify docker version ...................................................................................................... 56
Figure 51. Upgrade docker package ............................................................................................... 57
Figure 52. Docker pull mosquitto ..................................................................................................... 57
Figure 53. Verify mqtt container is up.............................................................................................. 59
Figure 54. Check mosquitto is running correctly ............................................................................. 59
Figure 55. Configure mqtt user & password .................................................................................... 60
Figure 56. MQTT password encrypted ............................................................................................ 60
Figure 57. Docker pull Node-RED ................................................................................................... 60
Figure 58. Java version installed ..................................................................................................... 63
Figure 59. Verify PostgreSQL is running ......................................................................................... 64
Figure 60. PostgreSQL databases .................................................................................................. 65
Figure 61. ThingsBoard installation script ....................................................................................... 66
Figure 62. Verify ThingsBoard is running ........................................................................................ 66
Figure 63. ThingsBoard welcome menu.......................................................................................... 67
9
Figure 64. ThingsBoard main screen .............................................................................................. 67
Figure 65. Node-RED Dashboard (mobile visualisation) ................................................................ 68
Figure 66. Grafana Real-Time data dashboard (computer format) ................................................. 69
Figure 67. Grafana historical data dashboard (computer format) ................................................... 69
Figure 68. Grafana Real-Time data dashboard (mobile format) ..................................................... 70
Figure 69. Grafana historical data dashboard (mobile format) ....................................................... 70
Figure 70. Execute shell mosquitto container ................................................................................. 71
Figure 71. MQTTBox public broker subscription ............................................................................. 71
Figure 72. MQTTBox publish to public broker ................................................................................. 71
Figure 73. Mosquitto container public broker subscription .............................................................. 72
Figure 74. Mosquitto container local broker publishing ................................................................... 72
Figure 75. MQTTBox local broker subscription ............................................................................... 72
Figure 76. Figure 72. MQTTBox publish to local broker ................................................................. 72
Figure 77. Mosquitto container local broker subscription ................................................................ 73
Figure 78. htop command initalizing the system ............................................................................. 73
Figure 79. htop command with system stabilized (1) ...................................................................... 73
Figure 80. htop command with system stabilized (2) ...................................................................... 74
Figure 81. htop command with Grafana influxdb query .................................................................. 74
Figure 82. Raspberry Pi memory storage ....................................................................................... 75
Figure 83. Mqtt-stresser publishing results: Test condition: client=10, Messages=100 ................. 75
Figure 84. Mqtt-stresser receiving results: Test condition: client=10, Messages=100 ................... 76
Figure 85. Mqtt-bench receiving results: Test condition: client=10, Messages=100 ...................... 76
Figure 86. mqtt-bench command example ...................................................................................... 76
Figure 87. CPU effect of multiple mqtt connections ........................................................................ 77
Figure 88. Raspberry Pi Imager ...................................................................................................... 84
Figure 89. Raspberry Pi OS selection ............................................................................................. 85
Figure 90. Writing OS to SD card .................................................................................................... 85
Figure 91. Localising Raspberry Pi IP ............................................................................................. 87
List of Tables:
Table 1. Workplan packages ........................................................................................................... 15
Table 2. Milestones ......................................................................................................................... 16
Table 3. MQTT comparison. Source[18] ......................................................................................... 34
Table 4. Budget: variable costs ....................................................................................................... 78
Table 5. Budget: wages ................................................................................................................... 79
Table 6. Budget: fixed costs ............................................................................................................ 79
10
1. Introduction
Project specifications:
11
- Operational open-source home automation software.
- Interconnection between sensors and actuators with the platform installed on the
raspberry using standard protocols such as MQTT or HTTP protocols.
- Operational database.
- Operational dashboard
- Alert notification.
- Access via smartphone
12
Major constituent: hardware prototype Sheet 2 of 6
Internal task T3: Receive ESP32 data in real time. WP3 Summary 26/04/2021
Internal task T4: Treat and interpret the data for the
dashboard visualization.
Internal task T5: Alert's notification.
Internal task T6: WP validation.
13
Project: ThingsBoard CE Platform (Proof of WP ref: WP4
Concept)
14
Project: Documentation WP ref: WP6
1.4.2. Milestones
15
WP5 T2 Performance Improvement Docker implementation 31/05/2021 (W16)
In addition, a shorter time had been estimated for the research and implementation of the
docker packaging system, which has taken much longer than expected.
The tasks of the work packages remain the same, although the delivery period has
changed in some of them.
16
What has changed is the priority of the tasks because it has been considered very important
to learn to work with dockers and their implementation in the home automation platform,
rather than carry out an extensive test with an alternative platform.
The unforeseen difficulty with the dockers led to the postponement of the hardware
deployment as a post-deployment test of the dockers, also leaving the ThingsBoard
software as the last point of investigation and installation.
It is considered that the whole installation process should be included in the project
development section as it is an essential part of the project to implement the software
together.
17
2. State of the art of the technology used or applied in this
thesis:
A background, comprehensive review of the literature is required. This is known as the
Review of Literature and should include relevant, recent research that has been done on
the subject matter.
18
2.2. MQTT
MQTT[3] stands for Message Queuing Telemetry Transport. It is a lightweight
messaging protocol for use in cases where clients need a small code footprint and
are connected to unreliable networks or networks with limited bandwidth resources.
It is primarily used for machine-to-machine (M2M) communication or Internet of
Things types of connections.
MQTT runs on top of TCP/IP using a PUSH/SUBSCRIBE topology. In MQTT
architecture, there are two types of systems: clients and brokers. A broker is the
server that the clients communicate with. The broker receives communications from
clients and sends those communications on to other clients. Clients do not
communicate directly with each other, but rather connect to the broker. Each client
may be either a publisher, a subscriber, or both.
2.3. Node-RED
Node-RED[4][5] is a flow-based development tool for visual programming developed
originally by IBM for wiring together hardware devices, APIs and online services as part of
the Internet of Things.
Node-RED provides a web browser-based editor that makes it easy to wire together flows
using the wide range of nodes in the palette that can be deployed to its runtime in a single-
click. Also, you can create your own functions based on JavaScript. Elements of
applications can be saved or shared for re-use. The runtime is built on Node.js and the
flows created in Node-RED are stored using JSON.
2.4. NPM
NPM[6] (originally short for Node Package Manager) is the default package manager for the
JavaScript runtime environment Node.js. It consists of a command line client, also called
npm, and an online database of public and paid-for private packages, called the npm
19
registry. The registry is accessed via the client, and the available packages can be browsed
and searched via the npm website.
2.5. InfluxDB
InfluxDB[7] is an open-source time series database (TSDB) developed by InfluxData. It is
written in Go and optimized for fast, high-availability storage and retrieval of time series
data in fields such as operations monitoring, application metrics, Internet of Things sensor
data, and real-time analytics
2.6. Grafana
Grafana[8] is an open-source solution for running data analytics, pulling up metrics that
make sense of the massive amount of data and to monitor our apps with the help of cool
customizable dashboards.
Grafana connects with every possible data source, commonly referred to as databases
such as Graphite, Prometheus, Influx DB, ElasticSearch, MySQL, PostgreSQL etc.
The tool helps to study, analyse and monitor data over a period of time, technically called
time series analytics.
A big upside of the project is it can be deployed on-prem by organizations which do not
want their data to be streamed over to a vendor cloud for security & other reasons.
Here is a snapshot of a Grafana dashboard example, monitoring different things.
The dashboards contain a gamut of visualization options such as geo maps, heat maps,
histograms, all the variety of charts & graphs which a business typically requires to study
data.
20
2.7. Docker
Docker[9] is an open platform for developing, shipping, and running applications. Docker
enables you to separate your applications from your infrastructure so you can deliver
software quickly (this software packages are called containers). With Docker, you can
manage your infrastructure in the same ways you manage your applications. By taking
advantage of Docker’s methodologies for shipping, testing, and deploying code quickly,
you can significantly reduce the delay between writing code and running it in production.
Containers are isolated from one another and bundle their own software, libraries and
configuration files; they can communicate with each other through well-defined channels.
Because all of the containers share the services of a single operating system kernel, they
use fewer resources than virtual machines.
Note: An extended explanation of Dockers for IoT are added in the Methodology Section.
21
3. Methodology / project development:
3.1.1. Raspberry Pi
The specifications of the Raspberry Pi model that we have used (3 Model B+) are the
following:
22
3.1.2. ESP32 with BMP280
The BMP280 sensor connects with the ESP32 device by making the following junctions:
BMP280 -> ESP32
Pin Vin -> Pin 3.3V
Pin GND -> Pin GND
SCL Pin -> SCL Pin (GIOP 22)
Pin SDA -> Pin SDA (GIOP 21)
SCL and SDA pins are I2C (Inter-Integrated Circuit) pins:
• SCL stands for Serial CLock.
• SDA stands for Serial DAta.
23
3.2. Home Automation Platform Comparison
3.2.1. Introduction
In this project, a proof of concept integrating several sensors and actuators must
be developed, through which it is proposed to generate a low-cost home automation
system that will allow the integration of control panels for data visualization and
interaction with the different sensors. For this, a platform will be required to interpret
the data from the sensors and actuators, represent them graphically, store their
data and alert to unexpected events.
• Control devices
• Store data
• Control Devices
• Display Data
• Run Tests
24
3.2.3. Platform Comparison
To implement it, we have made a comparison between different platforms.
1. OpenHAB
OpenHAB is a home automation platform whose main aim is the integration and
interaction between different home automation technologies and devices.
Main features:
▪ Vendor and technology agnostic
▪ Developed in java
2. Home Assistant
This is a home automation platform running on Phyton 3. Home Assistant tracks
and controls all devices at home.
25
Main features:
▪ Quick and easy installation
▪ Mobile-friendly interface
▪ Set up of rules
3. ThingsBoard
ThingsBoard is an open-source IoT platform that enables rapid development,
management, and scaling of IoT projects. ThingsBoard allows you to manage
devices, collect the information generated, analyse and process data and visualize.
ThingsBoard is licensed under Apache 2.0.
Their goal is to provide the out-of-the-box IoT cloud or on-premises solution that
will enable server-side infrastructure for your IoT applications.
Main features:
With ThingsBoard, you are able to:
• Provision devices, assets and customers, and define relations between them.
• Analyse incoming telemetry and trigger alarms with complex event processing.
• Build work-flows based on a device life-cycle event, REST API event, RPC
request, etc.
26
• Design dynamic and responsive dashboards and present device or asset
telemetry and insights to your customers.
4. Node-RED
Node-RED is a development team created by IBM for IoT devices and is the perfect
companion to a home automation platform such as Home Assistant. At its core, it
allows for easy automation of virtually any connected device or service in an easy-
to-understand visual flow interface composed of nodes and wires.
It provides a browser-based editor that makes it easy to wire together flows using
the wide range of nodes in the palette that can be deployed to its runtime in a single-
click.
27
• The light-weight runtime is built on Node.js, taking full advantage of its event-
driven, non-blocking model.
• An online flow library allows you to share your best flows with the world.
28
3.3. Proof of Concept without dockers
In this initial proof of concept, the main part of the system and the multiple options
that have been raised with the same final purpose, to visualize temperature,
humidity, pressure and altitude data will be detailed. Although with certain
differences, since we have made several designs. Real-time data with Dashboard
Node-RED, data saving in the InfluxDB database and visualization of historical and
real-time data in Grafana[14][15][16].
29
The Node-RED developers provide a script to install Node.js, npm and
Node-RED onto a Raspberry Pi. The script can also be used to upgrade an
existing install when a new release is available.
Running the following command will download and run the script.
The installed script for the Pi also sets it up to run as a service. This means
it can run in the background and be enabled to automatically start on boot.
If you want Node-RED to run when the Pi is turned on, or re-booted, you can
enable the service to autostart by running the command:
sudo systemctl enable nodered.service
30
To disable the service, run the command:
sudo systemctl disable nodered.service
31
• Select the tab "Install", search node-red-dashboard and click to
"install":
32
Figure 19. Node-RED dashboard modules
The following table lists the main characteristics of the two MQTT brokers[18]
that we are comparing:
Broker Description
33
• Aedes replaces Mosca. Mosca is no longer being
developed.
• Aedes is a very simple broker and ideal for small home
network deployments and for learning MQTT.
• Aedes is Node.js based and so requires node.js to be
installed.
• It can also be installed as a node in node-red.
Mosca- • It is not very feature rich when compared to mosquitto but
Aedes
ideal for home automation projects.
• Currently supports v3.1.1
• Runs on Windows and Linux
• Aedes permits a high availability MQTT cluster for the
Internet of Things
• Mosca (Aedes) supports websockets and also SSL. See
Install Aedes Broker on Node-Red
Table 3. MQTT comparison. Source[18]
Summing up, both options are small enough to run on very simple hardware
like the raspberry PI. They are good and sufficient for the use we want to
give them. So, we will prove both of them, Mosquitto for their efficiency and
Aedes because is so easy to install on Node-RED.
We can install the MQTT Aedes[19] node running the following command:
npm install node-red-dashboard
Otherwise, we can install the MQTT Aedes node via Node-RED User
Interface:
• Select the icon at the top right and the option "Manage
palette":
34
Figure 20. Node-RED manage palette (2)
• Click on the install tab and search for aedes, then install it. Allow
to Node-RED for restarting after the installation.
35
3.3.3.3. Configurating Aedes MQTT Broker
Click twice on the node.
The node properties have two tabs: connections and security. and with very
few settings.
The main tab is shown below:
You need to set the ports for standard MQTT and MQTT over websockets if
used.
The standard port for MQTT is the 1883 port and the one for MQTT over
Websockets is the 1884 port.
The security tab contains options for username and password (if needed).
36
3.3.3.5. Testing MQTT Brokers
After both installations and adding an MQTT data receiver node in Node-RED
(explained in the next point), we have carried out connection tests from outside,
such as a windows computer with a broker, with the MQTT Broker of the Raspberry
(both Aedes and Mosquitto).
Note: since both use port 1883 by default, it will not be possible to have both active.
The solution would be to stop or uninstall one of them or run them on different ports.
37
Node Aedes MQTT Broker:
In this node we configure the MQTT Broker:
38
Function node:
msg.payload={
"temperature": parseFloat((Math.random()* (85 - (-40)) + (-40)).toFixed(2)),
"humidity": parseFloat((Math.random()*100).toFixed(2)),
"pressure": parseFloat((Math.random()* ((1110 - 300) + 300)).toFixed(2))
}
return msg;
Finally, we are publishing this JSON to the next MQTT broker and topic:
39
Where the server is configured as follows (adding the broker's username and
password in security tab):
Mqtt subscriber:
40
Json Node (Converts JSON string to Object):
41
Final Test:
Data reception:
Data visualization:
42
3.3.5. InfluxDB Installation
But this is not the most important difference. Much more important is the reading of
the data stored in the database and how these new databases deal with historical
data.
What are typical questions we have for our sensor data?
We are interested in, for example, all data for the last hour, or the last 24 hours?
Or we want to have average temperatures for all days of the previous year?
What is common in all these questions? Time slots are always one part of the
question. Time series databases are optimized for such queries. Of course, you
also can create standard SQL queries to answer those questions, but this involves
a lot of work and you have to write all the different queries yourself. In contrast, for
43
Grafana, is so easy to implement InfluxDB and filtering with the time ranges you
choose, without one line of coding and with big results.
44
Then start the influxdb service and set it to run at boot:
sudo systemctl enable influxdb
sudo systemctl start influxdb
We should now be able to run the influx client with influx and create a user for later
(here I use a single admin user 'pi' for simplicity):
influx
> create database home
> use home
Using database home
> create user pi with password 'passwordhere' with all privileges
> grant all privileges on home to pi
> show users
> exit
You can now exit the Influx client by typing exit.
influx -version
InfluxDB shell version: 1.8.5
45
3.3.6. Grafana Installation
The next step is to install Grafana[23], to view the data that will be entered into the
database.
Install Grafana:
Grafana is now installed, but not yet running. To make sure Grafana starts up even
if the Raspberry Pi is restarted, we need to enable and start the Grafana Systemctl
service.
Grafana is now running on the machine and is accessible from any device on the
local network.
46
Figure 38. Grafana welcome menu
Log in to Grafana with the default username admin, and the default password admin.
Grafana is now running on your Raspberry Pi. If the Raspberry Pi is ever restarted
or turned off, Grafana will start up whenever the machine regains power.
47
As we are running both services on the same Pi, set the URL to localhost and use
the default influx port of 8086:
We then need to add the database, user and password that we set earlier:
Now go ahead and hit “Save & Test” to connect everything together.
48
3.3.8. Configuration of InfluxDB on NodeRED
Install influxdb module[24]:
Go to Manage Palette -> Install and search 'node-red-contrib-influxdb'
Once installed, you can find the following nodes on the left.
Now, we will try to import our random data injected to MQTT topic 'bmp280' and
insert this data to the Influx Database.
49
Figure 44. Node-RED real data reception
Note: if we want to delete some data from this database, we would use the next
command on the shell:
Delete all database:
DELETE FROM table_name WHERE condition
Delete a column:
ALTER TABLE table_name DROP COLUMN column_name
Delete specific data:
DELETE FROM table_name WHERE column_name=specific_data
50
Also, on the right side we find the panel configuration, where we can modify the
axes, the display, the legend, the name, etc.
Finally, we have obtained a graph to visualize the temperature and humidity data
of our virtual sensor:
51
3.4. Dockers for IoT
As can be seen from this diagram, a Docker container includes an application plus
any binaries or libraries that the application requires in order for it to run. The
container runs under the control of Docker, which in turn runs on top of the operating
system.
• Portability
52
Once you have tested your containerized application you can deploy it to any
other system where Docker is running and you can be sure that your
application will perform exactly as it did when you tested it.
• Performance
Although virtual machines are an alternative to containers, the fact that
containers do not contain an operating system (whereas virtual machines
do) means that containers have much smaller footprints than virtual
machines, are faster to create, and quicker to start.
• Agility
The portability and performance benefits offered by containers can help you
make your development process more agile and responsive. Enhancing your
continuous integration and continuous delivery processes to take advantage
of containers and technology such as Enterprise Developer Build Tools for
Windows makes it easier for you to deliver the right software at the right time.
Enterprise Developer Build Tools for Windows is a component of Enterprise
Developer which provides all of the functionality of Enterprise Developer to
enable you to compile, build, and test COBOL code but without the overhead
of an IDE.
• Isolation
A Docker container that contains one of your applications also includes the
relevant versions of any supporting software that your application requires.
If other Docker containers contain applications that require different versions
of the same supporting software, that isn't a problem because the different
Docker containers are totally independent of one other.
This also means that as you move through the various stages of your
development lifecycle, you can have total confidence that an image you
create during development will perform exactly the same as it moves through
testing and potentially to your users.
• Scalability
You can quickly create new containers if demand for your applications
requires them. When using multiple containers, you can take advantage of
a range of container management options. See the Docker documentation
for more information on these options.
53
3.4.3. Why the IoT would use Docker (Benefits concretizing in the use of the IoT)
Containers are well-positioned to address some of the main challenges that
developers face when deploying software to IoT devices:
▪ Minimal hardware resources. Many IoT devices lack powerful computing
and memory resources. Their ability to process software updates is therefore
limited. Containers can help on this front because installing a new container
image does not require much computing power. An IoT device needs simply
to download an image, put it wherever it’s going to live and remove the old
image. Configuration processing is minimal.
54
3.5. Proof of Concept with dockers
This proof of concept only details the differences from installation without dockers.
The software configuration through the graphical interface is detailed in the
previous proof of concept.
A previous installation of the Raspberry Pi Lite is required (Appendix 1). Then you
can proceed to install the dockers[25][26].
All dockers installation has been done with root permissions.
Move on to downloading the installation script and execute the script using the
command:
curl -sSL https://get.docker.com | sh
This installs the required packages for your Raspbian Linux distribution.
The output will tell you which version of Docker is now running on your system.
55
3.5.1.2. Configure Docker
There are a couple of manual steps needed to get the best experience.
Set Docker to auto-start:
sudo systemctl enable docker
You can now reboot the Pi (using the command sudo shutdown -r now), or start
the Docker daemon with:
sudo systemctl start docker
56
The output will display the Docker version along with some additional information.
For system-wide information (including the kernel version, number of containers
and images, and more extended description) run:
docker info
With the following command we would see the containers running on this docker
container (at the moment the container's list is empty):
docker ps
57
3.5.2.2. Create folders for MQTT
Next, create a test file called mosquitto.conf in the newly created subdirectory
mosquitto/config/ and edit the config file:
nano /docker/mosquitto/config/mosquitto.conf
And add the as a minimum set of conf directives.
persistence true
persistence_location /mosquitto/data/
log_dest file /mosquitto/log/mosquitto.log
#password_file /mosquitto/config/pwfile
allow_anonymous true
listener 1883 192.168.0.10
The command to execute the mosquitto container is quite long because we indicate
the directory where to store the persistence files. So, if the running container is
stopped, the files will remain for the next run:
58
Docker run command options:
--name: container identification
-i: We indicate that it will be interactive
-t: Open the TTY
-d: keep the container and current terminal session separate
--restart: the docker will not stop if machine is power off, only if the user stopped
manually
--net: connect a container to a network
-v: Bind mount a volume (host-source:container-dest)
Note: If the error message "Error response from daemon: Conflict. The container
name" / mosquitto "is already in use by container" appears, you must uninstall the
detected docker, using the command sudo docker mosquitto rm -fv / mosquitto
Note: If when running docker ps you notice that the broker status is not up, check
if you already have an active mqtt broker (even if it is not as a docker) and disable
it or change the ports in any of them.
Open the file mosquitto.log from the directory mosquitto/log and check the installed
version of mosquitto:
Execute the shell of the docker mosquitto container to modify the username and
password:
59
docker exec -it mosquitto sh
cd mosquitto/config
mosquitto_passwd -c pwfile pi
60
We will carry out a process similar to that of MQTT, so that the data persists even
if the machine or the docker is restarted. To do this we will generate a directory
inside the 'docker' folder and we will need to ensure that any existing /data directory
has the correct ownership.
After that process, execute the command to run Node-RED Docker:
sudo su
cd /
mkdir /docker/mynodered
mkdir /docker/mynodered/data
We will need to ensure that any existing /data directory has the correct ownership.
This needs to be 1000:1000. This can be forced by the command:
sudo chown -R 1000:1000 /docker/mynodered/data
Execute the command to run the container with the right configuration and
directories:
sudo docker run --name mynodered -itd --restart=unless-stopped -p
1880:1880 -v /docker/mynodered/data:/data nodered/node-red
Now to build this Raspberry Pi IoT project, once the Mosquitto is up and running,
we can install and configure InfluxDB[30]:
docker pull influxdb:1.8.5
mkdir /docker/influxdb
once the installation completes, it is possible to start InfluxDB:
docker run -itd --name influxdb --restart=unless-stopped -p
8086:8086 -v /docker/influxdb:/var/lib/influxdb influxdb:1.8.5
The next step is creating the database and the user that will access this database
First, start the InfluxDB CLI:
docker exec -it influxdb influx
Next, let us create the database and the user:
> create database home
> use home
61
Using database home
> create user pi with password 'passwordhere' with all privileges
> grant all privileges on home to pi
> show users
> exit
With these few lines, we have created a database named home and a user with
username pi and password passwordhere.
62
3.6. Proof of Concept with other platforms (ThingsBoard CE)
The ThingsBoard CE (Community Edition) installation is the 100% open-source and on-
premise version of the ThingsBoard software, with maintenance carried out by the
community itself and without having dependencies on the cloud or maintenance payments.
63
3.6.4. Install ThingsBoard database (PostgreSQL)
Once PostgreSQL is installed you may create a new user or set the password for
the main user. Execute the instructions below to set the password for main
postgresql user:
sudo su - postgres
psql
\password
\q
64
Then, press “Ctrl+D” to return to main user console and connect to the database to
create thingsboard DB:
psql -U postgres -d postgres -h 127.0.0.1 -W
CREATE DATABASE thingsboard;
\l #show databases
\q
65
# Specify partitioning size for timestamp key-value storage. Allowed
values: DAYS, MONTHS, YEARS, INDEFINITE.
export SQL_POSTGRES_TS_KV_PARTITIONING=MONTHS
Also, for slow machines as our system that has 1GB of RAM, add the following line:
# Update ThingsBoard memory usage and restrict it to 256MB in
/etc/thingsboard/conf/thingsboard.conf
66
Once started, you will be able to open Web UI using the following link:
http://localhost:8080/
So now we have our Node-RED alternative platform running:
67
4. Results
This section includes all the results obtained like all dashboards visualization, tests
and performance analysis.
Firstly, the results of dashboards obtained through various tools and accessed from
different devices are visualised.
68
Figure 66. Grafana Real-Time data dashboard (computer format)
69
Figure 68. Grafana Real-Time data dashboard (mobile format)
70
4.2. MQTT Broker Tests
Next, we will try to publish and subscribe with an external broker and with the local
broker.
First, execute the shell of the docker mosquitto container to run the mosquitto_pub
& mosquitto_sub commands:
docker exec -it mosquitto sh
mosquitto_pub -h test.mosquitto.org -t temperature -d -m
"Temperature = 22.5 ºC"
We can check from an app like MQTTBox (Chrome extension)that the written
message is being published:
We can also carry out the opposite process (subscribe in the installed broker and
send from another machine):
71
mosquitto_sub -h test.mosquitto.org -t temperature -d
72
Figure 77. Mosquitto container local broker subscription
4.3. Performance
It can be seen that while the system is booting and all its tasks, the CPU is at a
medium level without becoming saturated.
System stabilized:
73
Figure 80. htop command with system stabilized (2)
InfluxDB query:
At the moment that we go from a request to represent historical data for the whole
day, to represent the data of a full month, the system becomes saturated since a
single request is made to represent a lot of data (this saturation does not reach 1
minute).
74
4.3.2. Raspberry Pi memory storage
This project has been installed and tested on a 16 GB Micro SD memory.
As can be seen, the amount of memory used with a data collection every 10
seconds for a month is very small, also considering the installed software, so it will
take at least a couple of years to fill the memory. (That is calculated without deleting
and averaging old data stored, which can be done with InfluxDB).
Here the results of a scenario with multiple benchmarks (mqtt-stresser & mqtt-
bench )taking 10 clients sending multiple messages (100 msg/client) tested 5 times
and doing the median:
Publishing Throughput
70000
60000
50000
msg/sec
40000
30000
20000
10000
0
Fastest Slowest Median
75
Receiving Throughput
350
300
250
msg/sec
200
150
100
50
0
Fastest Slowest Median
MQTT-BENCH
2000
1500
msg/sec
1000
500
0
Test 1 Test 2 Test 3 Test 4 Test 5 Median
Simulating with the benchmark mqtt-bench, with 10 concurrent MQTT clients, each
one sending 100 messages of 1 KByte each, we see how we could receive
approximately 1000 messages per second, the obtained results are:
76
On the other hand, if we increase the recurring customers to 25, we see how the
number of messages per second is radically reduced to less than half.
The effect of this large number of messages does not cause a large increase in
CPU consumption:
77
5. Budget
The objective of the thesis is a prototype of a home automation installation.
For the development of this project, the approximate costs of the components used,
both hardware and software, have been taken into account, as well as the salary of
the workers and the place where it was developed.
The project has been carried out in a term of 6 months
Variable costs:
Software:
All the software used in this project is open source, so there is no cost to include at
this point.
Hardware:
This section will detail the material used for the installation of the project, as well as
the necessary components for the design.
It is calculated using the annual amortization fee, which takes into account the
residual value (10%) and the approximate years of amortization of each product.
Wages:
78
Employee Salary/hour Total hours (h) Social Project cost (€)
(€/h) Security (%)
Junior
10 480 33,4 6403,2
Engineer
Senior
25 144 33,4 4802,4
Engineer
Table 5. Budget: wages
Fixed costs:
Finally, the use of a coworking space has been considered, which includes all kinds
of supplies, to be able to develop the prototype.
79
6. Conclusions and future development:
This project had one main objective: to create a domestic platform to control and
monitor different types of sensors.
To carry out this task, an investigation of different platforms has been developed to
install through a local server (such as a Raspberry Pi) to facilitate access from the
local network to the visualization and monitoring of data, which can be done from a
browser Web.
After this investigation, it was decided to design our platform from Node-RED since
it has been very interesting due to its block programming, multiple available plugins
and total customization.
Then, once the basic installation was done, improvements were added, such as a
database to store historical data, another type of more complete representation,
packaged by dockers, etc.
In summary, it has been possible to carry out a basic but complete installation of a
domestic platform to monitor household data and actions.
As a future development, there are many things that can be implemented, such as
multiple more sensors, integrations with platforms such as Telegram and Google
Assistant, a display of metrics in real time, among many others. That is the most
interesting thing about the IoT world, which is always in constant growth.
80
Bibliography:
[1] “What Is the Internet of Things (IoT)?” Oracle, www.oracle.com/internet-of-things/what-is-iot.
[2] Suwimon Vongsingthong, and Sucha Smanchat. “Internet Of Things: A Review Of Applications And
Technologies.” 4, vol. 21, Suaranaree University of Technology, 2014, p. Suranaree Journal of Science
www.en.wikipedia.org/wiki/Npm_(software).
[7] InfluxData. “InfluxDB: Purpose-Built Open-Source Time Series Database.” InfluxData, 21 May 2021,
www.influxdata.com.
[8] Shivang. “What Is Grafana? Why Use It? Everything You Should Know About It.” 8bitmen.Com, 13 Aug.
2020, www.8bitmen.com/what-is-grafana-why-use-it-everything-you-should-know-about-it.
[9] Yegulalp, Serdar. “What Is Docker? The Spark for the Container Revolution.” InfoWorld, 19 Apr. 2019,
www.infoworld.com/article/3204171/what-is-docker-the-spark-for-the-container-revolution.html.
[10] Jain, Varul. “Altitude Monitoring with BMP280 Using ESP32 and Node-Red.” Medium, 27 Feb. 2019,
https://medium.com/@varuldcube100/altitude-monitoring-with-bmp280-using-esp32-and-node-red-
35bec7ff5ed2.
[11] Azzola, Francesco. “How to Connect ESP32 to the Smartphone Using Node-RED.” SwA, 22 Feb. 2021,
www.survivingwithandroid.com/connect-esp32-to-smartphone-node-red/.
[12] Santos, Sara. “ESP32 MQTT - Publish BME280 Sensor Readings (Arduino IDE).” Random Nerd Tutorials,
[13] Santos, Sara. “9 Home Automation Open-Source Platforms for Your Projects.” Random Nerd Tutorials, 2
soloelectronicos.com/2020/11/29/instalacion-de-node-red-infuxdb-y-grafana.
[15] Oneguyoneblog. “IoT Server: Mosquitto and Node Red on Raspberry Pi.” One Guy, One Blog, 5 Oct. 2017,
oneguyoneblog.com/2017/06/20/mosquitto-mqtt-node-red-raspberry-pi.
81
[18] Cope, Steve. “MQTT Brokers and Cloud Hosting Guide.” Steve’s Internet Guide, 10 Mar. 2021,
www.steves-internet-guide.com/mqtt-hosting-brokers-and-servers.
contrib-aedes.
[20] Centurio. “How to install InfluxDB and Grafana on a Raspberry Pi 3 – Centurios Blog.” Centurios Blog, 28
[21] “Installing InfluxDB & Grafana on Raspberry Pi.” Simon Hearne, simonhearne.com/2020/pi-influx-grafana.
[22] “#255 Node-Red, InfluxDB, and Grafana Tutorial on a Raspberry Pi.” YouTube, uploaded by Andreas
[25] Simic, Sofija. “How to Install Docker on Raspberry Pi.” Knowledge Base by PhoenixNAP, 11 May 2021,
phoenixnap.com/kb/docker-on-raspberry-pi.
[26] Ellis, Alex. “Get Started with Docker 1.12 on Raspberry Pi.” Alex Ellis’ Blog, 3 Aug. 2017,
blog.alexellis.io/getting-started-with-docker-on-raspberry-pi.
[27] Cooling, Niall. “Running the Eclipse-Mosquitto MQTT Broker in a Docker Container.” Sticky Bits - Powered
docker-container.
[28] “Eclipse MQTT 2.x in Docker + user credentials on Synology.” YouTube, uploaded by BeardedTinker, 17
grafana.com/docs/grafana/latest/administration/configure-docker/#run-grafana-container-using-bind-
mounts.
guide/install/rpi.
[33] Mishra Biswajeeban. “Performance Evaluation of MQTT Broker Servers.” Computational Science and Its
Applications – ICCSA 2018, 2018, Lecture Notes in Computer Science, vol 10963. Springer, Cham.
https://doi-org.recursos.biblioteca.upc.edu/10.1007/978-3-319-95171-3_47
[34] Takanorig. “MQTT-Bench: MQTT Benchmark Tool.” GitHub, 6 Dec. 2015, github.com/takanorig/mqtt-
bench.
82
[36] The Raspberry Pi Foundation. “Raspberry Pi OS” Raspberry Pi, www.raspberrypi.org/software/.
[37] “Download the Free Nmap Security Scanner for Linux/Mac/Windows.” NMAP, nmap.org/download.html.
[38] Boulogeorgos, A.A., Diamantoulakis, P.D., & Karagiannidis, G. (2016). Low Power Wide Area Networks
(LPWANs) for Internet of Things (IoT) Applications: Research Challenges and Future Trends. ArXiv,
abs/1611.07449.
83
Appendices:
Raspberry Pi have developed a graphical SD card writing tool that works on Mac
OS, Ubuntu 18.04 and Windows, and is the easiest option for most users as it will
download the image and install it automatically to the SD card.
84
Figure 89. Raspberry Pi OS selection
You can now insert the SD card into the Raspberry Pi and power it up.
2. Accessing the Raspberry Pi
For the official Raspberry Pi OS, if you need to manually log in, the default user
name is pi, with password raspberry. Remember the default keyboard layout is set
to UK.
You should change the default password straight away to ensure your Raspberry
Pi is secure.
85
2.1. Configuring without HDMI display, Ethernet connection, keyboard and
mouse
Open Rufus and select the SD card on which the Raspbian OS is to be installed.
Select the iso file of the Raspbian OS and click Start. SD card will be formatted
and Raspbian OS will be written on it.
To connect and configure your Raspberry Pi without any connection, you must
first create a file with name ‘ssh’ without any extension and put it in the SD card
folder. This is to enable SSH in Raspberry-Pi. There will be no code in this file.
All files for example in Windows notepad must be saved as ANSI type.
Create a file with name ‘wpa_supplicant.conf’ and put it in the SD card folder.
This file is to enable Raspberry-Pi Wifi adapter to connect to the Wifi with given
credentials. The code present in this file should be:
country=ES
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="yourwifiname"
scan_ssid=1
psk="yourwifipassword"
key_mgmt=WPA-PSK
}
Then you must look the ip that is assignes by using nmap [37] :
nmap -sP -PI -PT <ip address of host>/24
86
To know ip address of the host:
cmd -> ipconfig /all
Then, you can localise the Raspberry Pi IP with nmap and access using ssh
to:
ssh pi@ip
You can change your keyboard layout (for example, to Spanish) with the
following steps:
87
you want to connect to, see the next section on how to list available networks prior
to running raspi-config.
sudo raspi-config
Optionally, network details can also be added to the Raspberry Pi via command
line.
Open the wpa-supplicant configuration file in nano:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Go to the bottom of the file and add the following:
Note that with the latest Buster Raspberry Pi OS release, you must ensure that the
wpa_supplicant.conf file contains the following information at the top:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=<Insert 2 letter ISO 3166-1 country code here>
88
In our example, the configuration file looks like this:
country=ES
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="name_wifi_network_1"
psk="password_wifi_network_1"
id_str="name_1"
}
network={
ssid="name_wifi_network_2"
psk="password_wifi_network_2"
id_str="name_2"
}
Note: If we have some problems to scan for wireless networks, using the command:
sudo iwlist wlan0 scan
If we cannot visualize the wlan0 interface, we apply the following command that will
display all interfaces which are currently available, even if down:
sudo ifconfig -a
So, if now we can visualize the wlan0, it means is down and we will apply the next
command:
If we continue without visualizing the wlan0 interface, we will apply the next
commands, because the system is blocking the interface:
rfkill list all
sudo rfkill unblock all
sudo ip link set wlan0 up
89
Choose Yes
Select Ok
Choose Finish
5. Configure static IP
To facilitate access to the command line a static IP will be configured, which gives
us the possibility of saving our access in the SSH client software.
To configure a static IP, we must edit the /etc/dhcpcd.conf file with the command:
sudo nano /etc/dhcpcd.conf
If we look at the content of the file, we will see some commented lines (they start
with '#') that have an example of static IP configuration:
To create our own static IP address, for example for the WiFi interface (wlan0), we
copy the commented fragment and modify it so that it looks like the following.
interface wlan0
static ip_address=192.168.0.20/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.1
90
Now we restart the Raspberry Pi with the command:
sudo reboot
Finally, we check that, indeed, the assigned IP is the one we have configured by
executing with the command:
ifconfig wlan0
91
tls":"","influxdbVersion":"1.x","url":"http://localhost:8086","rejectUnauthorized":true}
]
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
//https://www.meteo.cat/observacions/xema/dades
#include <PubSubClient.h>
const char* ssid = "your_wifi_network"; // The SSID (name) of the Wi-Fi network you want to connect
to
//Platform server
//Platform port
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
92
delay(10);
Serial.println('\n');
bool status;
// default settings
status = bme.begin(0x76);
if (!status) {
while (1);
Serial.print("Connecting to ");
Serial.print(ssid);
delay(500);
Serial.print('.');
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println('\n');
client.setServer(mqttServer, mqttPort); //configure the PubSubClient with the address and port
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
Serial.println("Client connected");
} else {
Serial.print(client.state());
delay(2000);
lastSend=0;
93
}
void loop() {
if(millis()-lastSend>1000){
getAndSendData();
lastSend=millis();
client.loop();
void getAndSendData()
Serial.print("getAndSendData: ");
float h=bme.readHumidity();
float t=bme.readTemperature();
float a=bme.readAltitude(SEALEVELPRESSURE_HPA);
String temperature=String(t);
String humidity=String(h);
String pressure=String(p);
String altitude=String(a);
Serial.print("Temperature = ");
Serial.print(temperature);
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(pressure);
Serial.println(" hPa");
Serial.print(altitude);
Serial.println(" m");
Serial.print("Humidity = ");
Serial.print(humidity);
Serial.println(" %");
Serial.println();
94
payload += "\"pressure\":"; payload += pressure; payload +=",";
payload += "}";
char telemetry[1000];
Serial.println( telemetry );
Serial.println('\n');
delay(10000);
const char* ssid = "your_wifi_network"; // The SSID (name) of the Wi-Fi network you want to connect
to
const int mqttPort = 1883; // The TCP port of your MQTT Broker
WiFiClient espClient_1; // Define the client that allows us to transmit by WiFi. Must be different
for each MQQT client that you want to connect to a MQTT Broker
PubSubClient client(espClient_1); // Define the MQTT client that will access the MQTT Broker.
Serial.println(topic);
Serial.print("Message:");
95
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
delay(500);
delay(500);
void setup() {
delay(10);
Serial.println('\n');
Serial.print("Connecting to ");
Serial.print(ssid);
delay(500);
Serial.print('.');
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
client.setServer(mqttServer, mqttPort); //configure the PubSubClient with the address and port
while (!client.connected()) { // While mqtt client it's not connected stay at loop
96
if (client.connect("espClient_1", mqttUser, mqttPassword )) { // connect to broker (return true if connect, false
if not)
Serial.println("connected");
if(client.subscribe("alert", 1)){
Serial.println("Subscribed to alert");
} else {
Serial.print(client.state());
delay(2000);
void loop() {
client.loop();
97
Glossary
This section contains alphabetically ordered list of all representative acronyms in
the project and the meaning they stand for.
DB: DataBase
IoT: Internet of Things
JS: JavaScript
JSON: JavaScript Object Notation
MQTT: Message Queuing Telemetry Transport
SSH: Secure SHell
98