Arduino PubNub UUID - arduino

I tried setting up an Arduino which publishes some messages to a NodeJaS server, but I cannot get a publisher name out of it. I searched the docs and found nothing really useful. I set an UUID before the PubNub begin with PubNub.set_uuid(uuid);, but it had no effect. The application just returns an undefined. How can I set this up?
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
// Replace these with your WiFi network settings
const char* ssid = "SSID"; //replace this with your WiFi network name
const char* password = "PW"; //replace this with your WiFi network password
const static char pubkey[] = "KEY"; // your publish key
const static char subkey[] = "KEY"; // your subscribe key
const static char channel[] = "test"; // channel to use
const static char uuid[] = "temp-sens"; // Unique Device UUID
void setup()
{
delay(1000);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println();
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
PubNub.set_uuid(uuid);
PubNub.begin(pubkey, subkey);
Serial.println("PubNub set up");
Serial.println("success!");
Serial.print("IP Address is: ");
Serial.println(WiFi.localIP());
}
void loop() {
WiFiClient *client;
char msg[] = "\"Yo!\"";
client = PubNub.publish(channel, msg);
if (!client) {
Serial.println("publishing error");
delay(1000);
return;
}
if (PubNub.get_last_http_status_code_class() != PubNub::http_scc_success) {
Serial.print("Got HTTP status code error from PubNub, class: ");
Serial.print(PubNub.get_last_http_status_code_class(), DEC);
}
while (client->available()) {
Serial.write(client->read());
}
client->stop();
Serial.println("---");
}

PubNub Publisher UUID in Received Message
I believe your requirement is to receive the publisher's UUID in the message that is received by the subscriber. This is only possible with latest 4.x versions of the PubNub SDK as they implement a new pub/sub API that provides the publisher's UUID as additional data in the delivered message, but not in the actual message content.
For example, if you were to use PubNub JavaScript SDK, you can get the publisher key's value from the message event.
Here is a sample message event JSON payload (do not confuse message event with the message key inside of the message event):
{
"channel": "ch1",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "ch1",
"timetoken": "15215690220119777",
"publisher": "cv1",
"message": {
"msg": "hello"
}
}
That timetoken is the actual publish timetoken which is made its debut in 4.x PubNub SDKs.
The Arduino SDK is an older SDK and does not implement the newest pub/sub APIs that include this information. As a workaround, you can include the publisher's UUID inside of the message content that you publish.

Related

Arduino: CORRUPT HEAP while running this sketch on ESP32

I've modified the WiFiClientSecure example, that comes with ESP32 core, to save the WiFiClientSecure object in a user-defined class Fetch as its property, then return Fetch object from a function, only to retrieve the WiFiClientSecure object from the fetch object by reading the property.
/*
Wifi secure connection example for ESP32
Running on TLS 1.2 using mbedTLS
2017 - Evandro Copercini - Apache 2.0 License.
*/
#include <WiFiClientSecure.h>
const char* ssid = "Mi Fimilia"; // your network SSID (name of wifi network)
const char* password = "muhsamali"; // your network password
const char* server = "www.howsmyssl.com"; // Server URL
// www.howsmyssl.com root certificate authority, to verify the server
// change it to your server root CA
// SHA1 fingerprint is broken now!
const char* test_root_ca= \
"-----BEGIN CERTIFICATE-----\n\
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n\
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n\
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n\
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n\
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n\
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n\
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n\
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n\
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n\
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n\
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n\
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n\
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n\
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n\
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n\
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n\
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n\
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n\
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n\
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n\
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n\
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n\
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n\
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n\
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n\
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n\
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n\
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n\
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n\
-----END CERTIFICATE-----";
// You can use x.509 client certificates if you want
//const char* test_client_key = ""; //to verify the client
//const char* test_client_cert = ""; //to verify the client
class Fetch {
private:
WiFiClientSecure _client;
public:
Fetch(WiFiClientSecure client) : _client(client) {}
WiFiClientSecure getWiFiClientSecure() { return _client; }
};
Fetch getFetch() {
WiFiClientSecure client;
Fetch fetch(client);
return fetch;
}
void setup() {
Fetch fetch = getFetch();
WiFiClientSecure client = fetch.getWiFiClientSecure();
//Initialize serial and wait for port to open:
Serial.begin(115200);
delay(100);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
// attempt to connect to Wifi network:
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
// wait 1 second for re-trying
delay(1000);
}
Serial.print("Connected to ");
Serial.println(ssid);
client.setCACert(test_root_ca);
//client.setCertificate(test_client_key); // for client verification
//client.setPrivateKey(test_client_cert); // for client verification
Serial.println("\nStarting connection to server...");
if (!client.connect(server, 443))
Serial.println("Connection failed!");
else {
Serial.println("Connected to server!");
// Make a HTTP request:
client.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
client.println("Host: www.howsmyssl.com");
client.println("Connection: close");
client.println();
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
client.stop();
}
}
void loop() {
// do nothing
}
This may look like some coding acrobatics but I need this to implement a library that I'm working on. As my understanding goes, WiFiClientSecure is being saved and retrieved by copy. Then why the Heap corruption?

Connect Arduino + ESP8266 to Azure IoT Hub Device via X509 certificate

I have hard times finding a solution, or writing my own, where I can connect ESP8266 with Azure IoT Hub Device via X509 certificate. Currently, I can connect using the symmetric key connection to my device, but I have devices that I want to authenticate with X509 certificate.
I found a solution, but is for Arduino Nano 33 IoT, which is probably using another chip and it has encryption slot.
I am trying to do this using the Azure IoT SDK C library, but without much success. Here is a code that is using Mqtt and WiFiClientSecure plus BearSSL in order to connect via certificate. Unfortunately, the only solution that I found was to generate ECCX09 certificate with a chip that have encryption and to just use the thumbprint. Here is my try to use the certificate:
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
// C99 libraries
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <cstdlib>
// Libraries for MQTT client, WiFi connection and SAS-token generation.
#include <ESP8266WiFi.h>
#include <ArduinoBearSSL.h>
#include <ArduinoMqttClient.h>
// Additional sample headers
#include "secrets.h"
// Utility macros and defines
#define LED_PIN 2
// Translate iot_configs.h defines into variables used by the sample
static const char* ssid = SECRET_WIFI_SSID;
static const char* password = SECRET_WIFI_PASS;
static const char* host = SECRET_BROKER;
static const String device_id = SECRET_DEVICE_ID;
// Memory allocated for the sample's variables and structures.
static WiFiClientSecure wifi_client;
static BearSSLClient ssl_client(wifi_client);
static MqttClient mqtt_client(ssl_client);
// Auxiliary functions
static void connectToWiFi()
{
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to WIFI SSID ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("WiFi connected, IP address: ");
Serial.println(WiFi.localIP());
}
/*
* Establishses connection with the MQTT Broker (IoT Hub)
* Some errors you may receive:
* -- (-.2) Either a connectivity error or an error in the url of the broker
* -- (-.5) Check credentials - has the SAS Token expired? Do you have the right connection string copied into arduino_secrets?
*/
void connectToMQTT() {
Serial.print("Attempting to MQTT broker: ");
Serial.print(host);
Serial.println(" ");
while (!mqtt_client.connect(host, 8883)) {
// failed, retry
Serial.print(".");
Serial.println(mqtt_client.connectError());
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqtt_client.subscribe("devices/" + device_id + "/messages/devicebound/#");
}
unsigned long getTime() {
// get the current time from the WiFi module
// return WiFi.getTime();
return time(NULL);
}
static void establishConnection()
{
// Set the username to "<broker>/<device id>/?api-version=2018-06-30"
String username;
// Set the client id used for MQTT as the device id
mqtt_client.setId(device_id);
username += host;
username += "/";
username += device_id;
username += "/api-version=2018-06-30";
mqtt_client.setUsernamePassword(username, "");
if(WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
if (!mqtt_client.connected()) {
// MQTT client is disconnected, connect
connectToMQTT();
}
}
// Arduino setup and loop main functions.
void setup()
{
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Serial.begin(9600);
// Set the X.509 certificate
// ssl_client.setEccCert(CLIENT_CERT);
ssl_client.setEccSlot(0, CLIENT_CERT);
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(getTime);
establishConnection();
}
void loop() {}
This fails on setting the Certificate and to use the ecc slot 0, because I am using ESP8266 that does not have cryptography in it (or at least I do not know). I saw in the library that there is another method in the BearSSL - void setEccCert(br_x509_certificate cert); , but I do not know how to initialize br_x509_certificate (here is the ref).
I decided to try something else, too, reading the certificate with SPIFFS, then adding to WiFiClientSecure. Unfortunately, I cannot load the private key to make client connection.
#include "FS.h" // File system commands to access files stored on flash memory
#include <ESP8266WiFi.h> // WiFi Client to connect to the internet
#include <PubSubClient.h> // MQTT Client to connect to AWS IoT Core
#include <NTPClient.h> // Network Time Protocol Client, used to validate certificates
#include <WiFiUdp.h> // UDP to communicate with the NTP server
#include "secrets.h"
// Utility macros and defines
#define NTP_SERVERS "pool.ntp.org", "time.nist.gov"
// Translate secrets.h defines into variables used by the sample
static const char* ssid = SECRET_WIFI_SSID;
static const char* password = SECRET_WIFI_PASS;
static const char* iot_hub_broker = SECRET_BROKER;
// callback function that will be called when the device receive a message
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// Memory allocated client variables
static WiFiUDP ntp_UDP;
static NTPClient time_client(ntp_UDP, "pool.ntp.org");
static WiFiClientSecure esp_client;
static PubSubClient mqtt_client(iot_hub_broker, 8883, callback, esp_client);
// Auxiliary functions
static void configureX509CertificateConnection() {
time_client.begin();
while(!time_client.update()) {
time_client.forceUpdate();
}
esp_client.setX509Time(time_client.getEpochTime());
Serial.println("Time client and ESP client are set up.");
// Attempt to mount the file system
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}
// Load certificate file from file system
File cert = SPIFFS.open("temperature-sensor-1-all.pem", "r");
if (!cert) {
Serial.println("Failed to open certificate from file system");
} else {
Serial.println("Successfully opened certificate file");
}
// Load private key file from file system
File private_key = SPIFFS.open("/temperature-sensor-1-private.pem", "r");
if (!private_key) {
Serial.println("Failed to open private key from file system");
}
else {
Serial.println("Successfully opened private key file");
}
delay(1000);
// Load private key to client connection
if (esp_client.loadPrivateKey(private_key)) {
Serial.println("Private key loaded to client connection");
}
else {
Serial.println("Private key not loaded to client connection");
}
}
static void connectToWiFi() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected, IP address: ");
Serial.println(WiFi.localIP());
}
/*
* Establishses connection with the MQTT Broker (IoT Hub)
* Some errors you may receive:
* -- (-.2) Either a connectivity error or an error in the url of the broker
* -- (-.5) Check credentials - has the SAS Token expired? Do you have the right connection string copied into arduino_secrets?
*/
void connectToMQTT() {
}
static void establishConnection() {
if (WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
configureX509CertificateConnection();
}
// Arduino setup and loop main functions.
void setup() {
pinMode(2, OUTPUT);
digitalWrite(2, HIGH);
Serial.begin(115200);
establishConnection();
}
void loop() {}
I will be happy to find a solution, because I am in a hurry for my thesis.
P.S. I have it up and running on Raspberry Pi, but I have to make some experiments using the Arduino and ESP8266.
P.S.2. I am using Arduino with Atmega328P with integrated ESP8266 chip, but working only with the ESP8266. Additionally, I am using Arduino IDE 1.8.19 and installed the Azure IoT SDK C library (and some other required ones).
P.S.3. Additionally, I could find X509 certificate sample, but it is using the Paho Mqtt Client and I am not able reproduce it on Arduino.

Universal Telegram Bot library doesn't work with Arduino nano 33 iot but it doesn't show an error

I've tried for the first time the example echobot using an arduino nano 33 iot and the classical arduino ide.
I have created a bot using botfather.
I have uploaded the code of the example on the board.
The serial monitor tells me that it's connected to the wifi and shows me the SSID the IP address and the signal strenght but when I try to write something using the telegram bot, nothing happens: I don't receive the echo message in the bot chat.
Can anybody help me?
This is the code:
/*******************************************************************
A telegram bot for your WifiNINA devices that responds
with whatever message you send it.
Parts:
Arduino Nano 33 IOT - https://store.arduino.cc/arduino-nano-33-iot
If you find what I do useful and would like to support me,
please consider becoming a sponsor on Github
https://github.com/sponsors/witnessmenow/
Written by Brian Lough
YouTube: https://www.youtube.com/brianlough
Tindie: https://www.tindie.com/stores/brianlough/
Twitter: https://twitter.com/witnessmenow
*******************************************************************/
// ----------------------------
// Standard Libraries
// ----------------------------
#include <SPI.h>
// ----------------------------
// Additional Libraries - each one of these will need to be installed.
// ----------------------------
#include <WiFiNINA.h>
// Library for using network deatures of the official Arudino
// Wifi Boards (MKR WiFi 1010, Nano 33 IOT etc)
// Search for "nina" in the Arduino Library Manager
// https://github.com/arduino-libraries/WiFiNINA
#include <UniversalTelegramBot.h>
// Library for connecting to Telegram
// Search for "Telegram" in the Arduino Library Manager
// Install the "Universal Telegram" one by Brian Lough
// https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>
// Library used for parsing Json from the API responses
// Search for "Arduino Json" in the Arduino Library manager
// https://github.com/bblanchon/ArduinoJson
// Wifi network station credentials
char ssid[] = "SSID"; // your network SSID (name)
char password[] = "password"; // your network password
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
const unsigned long BOT_MTBS = 1000; // mean time between scan messages
int status = WL_IDLE_STATUS;
WiFiSSLClient client;
UniversalTelegramBot bot(BOT_TOKEN, client);
unsigned long bot_lasttime; // last time messages' scan has been done
void handleNewMessages(int numNewMessages)
{
for (int i = 0; i < numNewMessages; i++)
{
bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
}
}
void printWiFiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void setup()
{
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv < "1.0.0") {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, password);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWiFiStatus();
}
void loop()
{
if (millis() - bot_lasttime > BOT_MTBS)
{
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages)
{
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
bot_lasttime = millis();
}
}
You need to add the Telegram root certificate to the Wifi Module.
Use the Wifi101/WifiNINA Firmware updater.
Refer here
https://support.arduino.cc/hc/en-us/articles/360016119219-How-to-add-certificates-to-Wifi-Nina-Wifi-101-Modules-

Connecting and adding Arduino MKR NBIoT 1500 board to the cloud server

I tried connecting the Arduino MKR NBIoT 1500 board to the Azure IoT Hub but wasn't successful. The board was able to connect to the cellular network and I tried to connect to Azure IoT Hub using MQTT but getting an error “-2”. I have also tried Google IoT and AWS IoT core and I'm still having the same error. I would appreciate if anyone could give me a feedback on what to do to be able to solve the problem. Thank you
Azure IoT Hub NB
This sketch securely connects to an Azure IoT Hub using MQTT over NB IoT/LTE Cat M1.
It uses a private key stored in the ATECC508A and a self signed public
certificate for SSL/TLS authetication.
It publishes a message every 5 seconds to "devices/{deviceId}/messages/events/" topic
and subscribes to messages on the "devices/{deviceId}/messages/devicebound/#"
topic.
The circuit:
- MKR NB 1500 board
- Antenna
- SIM card with a data plan
- LiPo battery
The following tutorial on Arduino Project Hub can be used
to setup your Azure account and the MKR board:
https://create.arduino.cc/projecthub/Arduino_Genuino/securely-connecting-an-arduino-nb-1500-to-azure-iot-hub-af6470
This example code is in the public domain.
*/
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <MKRNB.h>
#include "arduino_secrets.h"
/////// Enter your sensitive data in arduino_secrets.h
const char pinnumber[] = SECRET_PINNUMBER;
const char broker[] = SECRET_BROKER;
String deviceId = SECRET_DEVICE_ID;
NB nbAccess=true;
GPRS gprs;
NBClient nbClient; // Used for the TCP socket connection
BearSSLClient sslClient(nbClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient mqttClient(sslClient);
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
while (!Serial);
if (!ECCX08.begin()) {
Serial.println("No ECCX08 present!");
while (1);
}
// reconstruct the self signed cert
ECCX08SelfSignedCert.beginReconstruction(0, 8);
ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
ECCX08SelfSignedCert.endReconstruction();
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(getTime);
// Set the ECCX08 slot to use for the private key
// and the accompanying public certificate for it
sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());
// Set the client id used for MQTT as the device id
mqttClient.setId(deviceId);
// Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
String username;
username += broker;
username += "/";
username += deviceId;
username += "/api-version=2018-06-30";
mqttClient.setUsernamePassword(username, "");
// Set the message callback, this function is
// called when the MQTTClient receives a message
mqttClient.onMessage(onMessageReceived);
}
void loop() {
if (nbAccess.status() != NB_READY || gprs.status() != GPRS_READY) {
connectNB();
}
if (!mqttClient.connected()) {
// MQTT client is disconnected, connect
connectMQTT();
}
// poll for new MQTT messages and send keep alives
mqttClient.poll();
// publish a message roughly every 5 seconds.
if (millis() - lastMillis > 5000) {
lastMillis = millis();
publishMessage();
}
}
unsigned long getTime() {
// get the current time from the cellular module
return nbAccess.getTime();
//return 1583929365;
}
void connectNB() {
Serial.println("Attempting to connect to the cellular network");
while ((nbAccess.begin(pinnumber) != NB_READY) ||
(gprs.attachGPRS() != GPRS_READY)) {
// failed, retry
Serial.print(".");
delay(1000);
}
Serial.println("You're connected to the cellular network");
Serial.println();
}
void connectMQTT() {
Serial.print("Attempting to MQTT broker: ");
Serial.print(broker);
Serial.println(" ");
while (!mqttClient.connect(broker, 8883)) {
// failed, retry
Serial.print(".");
Serial.println(mqttClient.connectError());
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqttClient.subscribe("devices/" + deviceId + "/messages/devicebound/#");
}
void publishMessage() {
Serial.println("Publishing message");
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("devices/" + deviceId + "/messages/events/");
mqttClient.print("hello ");
mqttClient.print(millis());
mqttClient.endMessage();
}
void onMessageReceived(int messageSize) {
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available()) {
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}
// NB settings
#define SECRET_PINNUMBER ""
// Fill in the hostname of your Azure IoT Hub broker
#define SECRET_BROKER "ArduinoProjectHub.azure-devices.net"
// Fill in the device id
#define SECRET_DEVICE_ID "MKRNB1500"

How to connect esp_mqtt library to thingsboard.io?

I am trying to publish sensor data using esp_mqtt library to thingsboard.io dashboard. But the connection between the library and thingsboard is not getting established. I am using esp8266 nodeMCU v2 and platformIO
Here is the link to the esp_mqtt library documentation.
https://github.com/tuanpmt/esp_mqtt/blob/master/README.md
Here is the code snippet :
#include <ESP8266WiFi.h>
#include <MQTT.h>
#define CLIENT_ID "client1"
#define TOPIC "v1/devices/me/telemetry"
#define TOKEN "access token"
MQTT myMqtt(CLIENT_ID,"localhost",1883);
const char* ssid = "ssid";
const char* password = "password";
void setup() {
Serial.begin(115200);
delay(1000);
setup_wifi();
Serial.println("Connecting to MQTT server");
// setup callbacks
myMqtt.onConnected(myConnectedCb);
myMqtt.onDisconnected(myDisconnectedCb);
myMqtt.onPublished(myPublishedCb);
myMqtt.onData(myDataCb);
Serial.println("connect mqtt...");
myMqtt.setClientId(CLIENT_ID);
myMqtt.setUserPwd(TOKEN,"");
myMqtt.connect();
Serial.println("subscribe to topic...");
myMqtt.subscribe(TOPIC);
delay(10);
}
void loop() {
float value = analogRead(A0);
String temp=String(value);
// publish value to topic
String payload = "{";
//payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"temperature\":"; payload += temp;
payload += "}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
//String(attributes);
boolean result = myMqtt.publish("v1/devices
/me/telemetry",attributes,100,1,0);
delay(1000);
}
You are trying to connect to localhost unless you are running a broker on the ESP8266 this is never going to work.
You need to know what the host name of thingsboard.io's broker is and replace localhost with that value. The port number may also need changing.
I'm also guessing the clientid may need to be something a little more unique than client1

Resources