Using MQTTS from devices

@alvarolb Can you please help with the following query.
I saw your post at Adding SSL/TLS Support to the ESP8266 – Thinger.io.
I need to use MQTTS protocol between the device and Thinger.io. So if I use the 2.5.0 library will it encrypt the data going to the port 8883 in the server? Can you please share an example client application source that uses MQTTS?

Hi @Sahil_Vakkani ,

In this case, the Thinger.io Arduino library referenced in that post is not necessary, as it will connect to the platform using thinger’s protocol.

In order to connect from a device to Thinger.io using MQTT, you would use a library like PubSubClient, depending on the device and firmware you are using.

To make it secure (MQTTS), just make sure it connects through the port 8883.

You can test the connection from your computer to the platform to make sure your messages are being received. In the documentation you can find a couple of examples.

The MQTT broker from the platform acts as any other broker you can find in any tutorial, so you can just search for your device and how to connect through MQTT and pass thinger’s url, and any other necessary options to the client in your code.

Regards!

Hi,

May I ask why the need of using mqtt if you can use the thinger native library? I guess the case of using mqtt is appropriate if you want to use a developed mqtt capable device, but if you are coding the device, using thinger native library for communication is recommended.

On the other hand, note that the mqtt communication library is from a 3rd party development, so is not supported by thinger, at least at the device end.

Hope this helps.

Thank you for the response.
If just using port 8883 can establish a secure connection, can you please elaborate on how the messages transmitted from device side will be encrypted and Thinger.io will decrypt the received data ?What do I need to do encrypt a message when sending to a server and decrypt a message received from the server?

The communication between the client and the server is done through the TLS protocol, which encrypts the messages exchanged between both. The is not much more to it, you can find an lot of information on the web regarding this protocol, which is the same that HTTPS uses.
I’ll leave a post that explains how the communication is done.
https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/

Hey @Sahil_Vakkani

I’ve tested the following code to connect to an instance of Thinger.io platform. Keep in mind that is developed for an ESP32. If you have an ESP8266 you’ll need to change the at least the WiFi library.

Also I’ve omitted what could be important code just to make a small test, but you can find the example it is based on here.

#include <WiFiClientSecure.h>
#include <PubSubClient.h>


const char* username = "<thinger username>";
const char* clientId = "<device id>";
const char* credentials = "<device credentials>";

const char* ssid     = "<ssid>";
const char* password = "<password>";

const char* server = "<subomain>.aws.thinger.io";

const char* root_ca = \
"-----BEGIN C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\
"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-----\n";

WiFiClientSecure secureClient;

PubSubClient mqttClient(secureClient);

unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup() {
  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);

  secureClient.setCACert(root_ca);

  mqttClient.setServer(server, 8883);

  if (mqttClient.connect(clientId, username, credentials)) {
    Serial.println("connected");
  }
}

void loop() {

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    mqttClient.publish("outTopic", msg);
  }

}

1 Like

Thank you for the reply.
Can you please specify where do I obtain the the CA Certificate and the steps for the same?

Yeah, you have to use the same one from my code, which is just part of the public certificate that identifies the entity that issued the end certificate, and that will make sure the certificate your client obtains from the server is to be trusted.

No additional steps are required.

Hi, I tried using the above example and am getting an error for line:

secureClient.setCACert( root_ca);

It is showing:
no matching function for call to ‘BearSSL::WiFiClientSecure::setCACert(const char*&)’

I am sorry but I am so new at this that I do not know how fix it .Can we please help with the problem??

I would say it is something regarding the declaration of the variable root_ca or how you are calling the function.
The definition of the function is setCACert(const char *rootCA). In your case you seem to be passing a pointer parameter by reference (*&), when it should be only be a pointer (*).

Check the differences between your code and what is in a previous post and if you need further assitance please post your code.

By the way, I believe you a have a freemium account on thinger’s public cloud. Keep in mind that mqtt is no supported in the public platform. It is documented in this section:

Can you please share/ explain the code for esp8266

It would actually be fairly similar to the sketch from the comment above. Also, check the links posted that may give you some ideas and are better documented than my code.

I encourage you to give it a try, and post your code if you get stuck.

Hi @jaimebs , I tried using the code you shared for MQTTS connection with ESP32. But when I try to publish data from ESP32 and subscribe a bucket to the topic, I don’t see the data in my bucket. What would be the issue?

Hi

Did you checked the log? to see if the platform receives the message

Does the uC give some message? does it subscribe to topics and send messages without issues or give some warning?

Yes, I have checked the logs. The logs show that device has been connected. But I don’t see any statements saying writing bucket “bucket name”. The uC is sending temperature values. The bucket is not able to subscribe to the topic. I’ll add a screenshot of the server logs.

Hi @Technically_Nerd ,

Could you also post your code and the configuration from the bucket? I tested my code and could see the data, encoded in base64, in the bucket. At least in my code, the topic has no preceding ‘/’, so in the bucket configuration it should also not have it.

Regards

Sure. Please find the code for ESP32 below. I have also attached a screenshot of the bucket configuration.

#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <AHT10.h>
#include "utilities.h"


const char* username = "";
const char* clientId = "";
const char* credentials = "";

const char* ssid     = "";
const char* password = "";

const char* server = "xyz.aws.thinger.io";

const char* 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+s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NPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" \
"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" \
"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" \
"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" \
"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" \
"-----END CERTIFICATE-----\n";

WiFiClientSecure secureClient;

PubSubClient mqttClient(secureClient);

AHT10 myAHT(0x38);
StaticJsonDocument<512> pub;

int counter, lastIndex, numberOfPieces = 24;
String pieces[24], input;
uint32_t lastReconnectAttempt = 0;
char output[300];

float temp=0;
float humi=0;

void setup() {
  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);

  secureClient.setCACert(root_ca);

  mqttClient.setServer(server, 8883);

  if (mqttClient.connect(clientId, username, credentials)) {
    Serial.println("connected");
  }

  while(myAHT.begin() != true)
   {
    Serial.println("AHT10 Error");
   }
}


void light_sleep(uint32_t sec )
{
  esp_sleep_enable_timer_wakeup(sec * 1000000ULL);
  esp_light_sleep_start();
}

void loop() {

  get_data();

  send_data(temp,humi);
  //delay(60000);
    //mqttClient.loop();
    Serial.printf("End of tests. Enable deep sleep , Will wake up in %d seconds", TIME_TO_SLEEP);

  //Wait moden power off
  light_sleep(5);

  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
  delay(200);
  esp_deep_sleep_start();

  while (1);

}


void send_data(float f,float g)
{
  
  pub["Temperature"]= f;
  pub["Humidity"]= g;
int  x=serializeJson(pub, output);
  Serial.println("bytes=");
  Serial.print(x,DEC);
  boolean rc= mqttClient.publish("test", output);
  if(rc)
  {
    Serial.println("Message Published");
  }
  else
  {
    Serial.println("Failed to Publish");
  }
}

void get_data()
{
  temp = myAHT.readTemperature();
  
    Serial.println("Temperature is:");
    Serial.println(temp);
    delay(500);
    humi = myAHT.readHumidity();
    Serial.println("Humidity is:");
    Serial.println(humi);
    delay(500);

}

I don’t see any apparent issue regarding Thinger. What I don’t know is how the deep sleep is acting and if its able to connect again to the Wifi and to Thinger.

When you can please send also the logs of the platform while the device is sending data.

I would start with my sketch and check if Thinger is able to receive the data, and from that point start developing your solution.

Deep sleep sets ESP into hibernation mode. This saves some battery. I will add a screenshot of server log when my device will connect to Thinger.

@jaimebs @ega @alvarolb Here is a screenshot of the server logs.
#1 When I try to connect ESP32 using MQTTS I don’t see any “writing bucket” in the logs

#2 When I try to connect ESP32 using MQTT I do see “writing bucket:bucket name” in the logs