akenza.io
Search…
How to integrate an Arduino device via MQTT on akenza
In this tutorial you will learn how to integrate an Arduino device via MQTT on akenza
MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT) and one of the protocols supported by akenza.
It is designed as an extremely lightweight publish/subscribe messaging protocol that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth. MQTT is used in a wide variety of industries. By using a combination of MQTT and API functionalities, akenza enables you to automatically create Digital Twins for your devices. Akenza runs an open-source MQTT broker from Eclipse Mosquitto.
In order to proceed in this tutorial, you need an Arduino Board capable to connect to the Internet. In our example, we use an Arduino Uno WiFi Rev2. To directly connect your device via MQTT with akenza, you can easily implement it with a Python script. Find out more about MQTT connectivity here.

1. Connect the Arduino device via MQTT on akenza

1.1 Creating a secret

In order to safely communicate with akenza, a secret needs to be generated that has to be provided in the topic structure of the uplink request.
This step has to be performed for all devices with the same connection parameters, which you want to connect. Each device will be uniquely identified by a specific ID accordingly. A secret will be generated after the creation of the MQTT device connector on the Data Flow.

1.1.1 Setting up an MQTT Device Connector on akenza

Go to Data Flow in the menu and select Create Data Flow.
Choose MQTT as a device connector. As Device Type, select Passthrough, in order to receive data in the same format as sent from your MQTT device.
Choose one or multiple Output Connectors of your choice. There are several options to choose from. In this tutorial, we choose the Akenza DB. Find out more about Output Connectors.
Data Flow with MQTT Device Connector

1.2 Create an MQTT device on akenza

To create a new MQTT device, select Create Device within the menu of the Asset Inventory. Add a device name and optionally a description, Asset Tags, and Custom Fields. Select your created MQTT- Data Flow and click Proceed.
Create a new MQTT device
Generate a random ID for this device by clicking Generate ID. Finish the process by clicking on the button Create Device. Your device will be now displayed on the Asset Inventory Overview.

1.3 Set up the Arduino device

As a next step, the Arduino device has to be now configured to send data to the MQTT Broker of akenza. Go to Asset Inventory and use the filter to search for your device. Open the device detail page by selecting your device. Within API-Configuration, all the required information is available to set up the device as an MQTT- client.
API configuration on device detail page

2. Configure the Arduino device

2.1 Set up the WiFi Connection

To have the Arduino Uno Wifi able to connect to WiFi we used the WiFiNINA library, available in the Library Manager of Arduino IDE.

2.1.1 Manage Username and Password

In order to manage Username and Password, we have created an additional header file called arduino_secrets.h
1
#define SECRET_SSID "<your username>"
2
#define SECRET_PASS "<your password>"
Copied!

2.1.2 WiFi connection code

The code to connect Arduino to WiFi is reported as below:
1
#include <WiFiNINA.h>
2
#include "arduino_secrets.h"
3
4
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
5
char ssid[] = SECRET_SSID; // your network SSID (name)
6
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
7
8
WiFiClient wifiClient;
9
10
void setup() {
11
//Initialize serial and wait for port to open:
12
Serial.begin(9600);
13
while (!Serial) {
14
; // wait for serial port to connect. Needed for native USB port only
15
}
16
17
// attempt to connect to Wifi network:
18
Serial.print("Attempting to connect to WPA SSID: ");
19
Serial.println(ssid);
20
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
21
// failed, retry
22
Serial.print(".");
23
delay(5000);
24
}
25
26
Serial.println("You're connected to the network");
27
Serial.println();
28
}
29
30
void loop()
31
{}
Copied!

2.2 Set up the MQTT Connection to akenza

For security reasons akenza only supports authenticated connections via MQTT. For this, we have chosen as library PubSubClient to manage our MQTT connection. This enables us to use username and password in our connection string.
1
#include <PubSubClient.h>
2
3
//MQTTClient mqttClient(WiFiClient);
4
5
char host[] = "mqtt.akenza.io";
6
char clientid[] = "Arduino";
7
char username[] = "<copy from Akenza Device Api configuration>";
8
char password[] = "<copy from Akenza Device Api configuration>";
9
char outTopic[] = "<copy from Akenza Device Api configuration>";
10
11
PubSubClient client(host, 1883, callback, wifiClient);
12
13
void setup() {
14
if (client.connect(host, username, password)) {
15
Serial.print("Connected to ");
16
Serial.println(host);
17
Serial.println();
18
19
boolean r = client.subscribe(outTopic);
20
Serial.print("Subscribed to ");
21
Serial.println(outTopic);
22
Serial.println();
23
}
24
else {
25
// connection failed
26
// mqttClient.state() will provide more information
27
// on why it failed.
28
Serial.print("Connection failed: ");
29
Serial.println(client.state());
30
Serial.println();
31
}
32
}
Copied!

2.3 Create a JSON message

Akenza accepts messages in JSON format for MQTT connections. To build up a well-formed JSON object, we make use of the ArduinoJson library.
1
#include <ArduinoJson.h>
2
3
void loop()
4
{
5
StaticJsonDocument<256> doc;
6
doc["Temperature"] = 22;
7
doc["Humidity"] = 68;
8
doc["Light"] = 96;
9
10
// Add an array
11
JsonArray data = doc.createNestedArray("data");
12
data.add(48);
13
data.add(2.3);
14
15
char out[128];
16
int b =serializeJson(doc, out);
17
Serial.print("publishing bytes = ");
18
Serial.println(b,DEC);
19
20
boolean rc = client.publish(outTopic, out);
21
22
// The above line prints:
23
// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
24
delay(5000);
25
client.loop();
26
}
Copied!

2.4 Final result

Now you have all the elements needed to set up your code on Arduino and stream data via MQTT to akenza.
The final code is reported as below:
1
#include <SPI.h>
2
#include <PubSubClient.h>
3
#include <WiFiNINA.h>
4
#include <ArduinoJson.h>
5
6
#include "arduino_secrets.h"
7
8
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
9
char ssid[] = SECRET_SSID; // your network SSID (name)
10
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
11
12
char host[] = "mqtt.akenza.io";
13
char clientid[] = "Arduino";
14
char username[] = "0783ddd64683f579";
15
char password[] = "bd604gmgit0x7kilc8puok3g2rxsldl2";
16
char outTopic[] = "/up/bd604gmgit0x7kilc8puok3g2rxsldl2/id/99E77F4ECC728656";
17
18
//set interval for sending messages (milliseconds)
19
const long interval = 8000;
20
unsigned long previousMillis = 0;
21
22
int count = 0;
23
24
//receive data
25
void callback(char* topic, byte* payload, unsigned int length) {
26
27
char str[length+1];
28
Serial.print("Message arrived [");
29
Serial.print(topic);
30
Serial.print("] ");
31
int i=0;
32
33
for (i=0;i<length;i++) {
34
Serial.print((char)payload[i]);
35
str[i]=(char)payload[i];
36
}
37
38
str[i] = 0; // Null termination
39
Serial.println();
40
41
StaticJsonDocument <256> doc;
42
deserializeJson(doc,payload);
43
44
// deserializeJson(doc,str); can use string instead of payload
45
const char* sensor = doc["sensor"];
46
long time = doc["time"];
47
float latitude = doc["data"][0];
48
float longitude = doc["data"][1];
49
50
Serial.println("latitude =");
51
Serial.println(latitude,2);
52
Serial.println(sensor);
53
54
}
55
56
WiFiClient wifiClient;
57
PubSubClient client(host, 1883, callback, wifiClient);
58
59
void setup() {
60
//Initialize serial and wait for port to open:
61
Serial.begin(9600);
62
while (!Serial) {
63
; // wait for serial port to connect. Needed for native USB port only
64
}
65
66
// attempt to connect to Wifi network:
67
Serial.print("Attempting to connect to WPA SSID: ");
68
Serial.println(ssid);
69
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
70
// failed, retry
71
Serial.print(".");
72
delay(5000);
73
}
74
75
Serial.println("You're connected to the network");
76
Serial.println();
77
78
if (client.connect(host, username, password)) {
79
Serial.print("Connected to ");
80
Serial.println(host);
81
Serial.println();
82
83
boolean r = client.subscribe(outTopic);
84
Serial.print("Subscribed to ");
85
Serial.println(outTopic);
86
Serial.println();
87
}
88
else {
89
// connection failed
90
Serial.println("Connection failed ");
91
Serial.println(client.state());
92
Serial.println();
93
}
94
}
95
96
void loop()
97
{
98
StaticJsonDocument<256> doc;
99
doc["Temperature"] = 22;
100
doc["Humidity"] = 68;
101
doc["Light"] = 96;
102
103
// Add an array
104
JsonArray data = doc.createNestedArray("data");
105
data.add(48);
106
data.add(2.3);
107
108
char out[128];
109
int b =serializeJson(doc, out);
110
Serial.print("publishing bytes = ");
111
Serial.println(b,DEC);
112
113
boolean rc = client.publish(outTopic, out);
114
115
// The above line prints:
116
// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}
117
delay(5000);
118
client.loop();
119
}
Copied!

3. Visualize and manage your data on akenza

Akenza automatically decodes the received JSON and visualizes data received from the Arduino device. Incoming data can be viewed on the Device Detail Page within Message Logs.
Message Logs on Device Detail Page
Incoming data are visualized on Data Overview as Device Data KPIs and also on the History chart.
Device Data KPIs & History Chart on Device Detail Page
Further data processing and visualization options can now be applied to your individual use case. For example:
ArduinoJson: Efficient JSON serialization for embedded C++
ArduinoJson
PubSubClient - Arduino Reference
WiFiNINA - Arduino Reference
Arduino -Sending and Receiving JSON Data over MQTT
|
ArduinoJson - Arduino Reference
Last modified 2mo ago