Unknown behviour for library Wificlientsecure in ESP32

Hi all,

We are having an issue with the library wificlientsecure and we are using ESP32.

There are two functions in our library:

void HttpDownstreamClient::subscriptionCreate(char* user, char* password, char* URL, char* device_ID, char* context , char* SubName, char* API, char* type_Filter, char* fragments_To_Copy) {


  #if defined(ARDUINO_ARCH_ESP32)
  base64ESP(user, password);
  #else
  base64(user,password)
  #endif

  //Serial.println(_base64);

  StaticJsonDocument<400> root;
  root["context"] = context;
  
  if(context == "mo"){
    if(device_ID != NULL){
  
  JsonObject source  = root.createNestedObject("source");
  source["id"] = device_ID;
  
      }else{
        Serial.println("Please enter the device ID");
        }
    }
  //JsonObject source  = root.createNestedObject("source");
  //source["id"] = device_ID;

  root["subscription"] = SubName;
  
  JsonObject subFilter = root.createNestedObject("subscriptionFilter");
  if (*type_Filter != NULL) {
    subFilter["typeFilter"] = type_Filter;
  } else {}

  JsonArray apis = subFilter.createNestedArray("apis");
  apis.add(API);

  if (*fragments_To_Copy != NULL) {
    JsonArray fragtocopy = root.createNestedArray("fragmentsToCopy");
    fragtocopy.add(fragments_To_Copy);
  } else {}


  String body2send = "";
  serializeJsonPretty(root, body2send);
  //Serial.println(body2send);

  if (_networkClient->connect(URL, 443)) {
    Serial.println("Connected to the server to create subscription");
    // Make a HTTP request:
    _networkClient->println("POST /notification2/subscriptions HTTP/1.1");
    _networkClient->print("Host: ");
    _networkClient->println(URL);
    _networkClient->println("Content-Type: application/json");
    _networkClient->print("Content-Length: ");
    _networkClient->println(body2send.length());
    _networkClient->println("Accept: application/json");
    _networkClient->print("Authorization: Basic ");
    _networkClient->print(_base64);
    _networkClient->println();
    _networkClient->println();
    _networkClient->println(body2send);

  } else {
    Serial.println("Connection fail!");
  }  

  while (_networkClient->available() == 0) {
      Serial.println("Waiting message from server");
      yield();  
    } 

    
    while (_networkClient->available()) {
      char c = _networkClient->read();
      Serial.print(c);
    }
    
}

void HttpDownstreamClient::tokenCreatePassword(char* user, char* password, char* URL, char* Subname, char* Suber, int expiretime) {
  
  #if defined(ARDUINO_ARCH_ESP32)
  base64ESP(user, password);
  #else
  base64(user,password)
  #endif
  

  Serial.print("The subscription is associated with the Subscripter: ");
  Serial.println(Suber);

  StaticJsonDocument<150> root;

  root["subscriber"] = Suber;
  root["subscription"] = Subname;
  root["expiresInMinutes"] = expiretime;
  String body2send = "";

  serializeJsonPretty(root, body2send);
  //Serial.println(body2send);

  if (_networkClient->connect(URL, 443)) {
    Serial.println("Connected to the server");
    // Make a HTTP request:
    _networkClient->println("POST /notification2/token HTTP/1.1");
    _networkClient->print("Host: ");
    _networkClient->println(URL);
    Serial.println(URL);
    _networkClient->print("Authorization: Basic ");
    _networkClient->println(_base64);
    Serial.println(_base64);
    _networkClient->println("Content-Type: application/json");
    _networkClient->print("Content-Length: ");
    _networkClient->println(body2send.length());
    Serial.println(body2send.length());
    _networkClient->println("Accept: application/json");
    _networkClient->println();
    _networkClient->println(body2send);

  }

  while (_networkClient->available() == 0) {
      Serial.println("Waiting message from server");
      Serial.print(".");
      yield();  
    } 

    String msg = "";
    while (_networkClient->available()) {
      char c = _networkClient->read();
      msg += c;
    }
    Serial.println("debug!!!");
    Serial.println(msg);

}


.h file is


#ifndef HttpDownstream_h
#define HttpDownstream_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include <string.h>
#include <Client.h>
//#include <Base64.h> 

#if defined(ARDUINO_ARCH_ESP32)
#include <base64.h>
#else
#include <Base64.h>
#endif

class HttpDownstreamClient{


 private:

 String _token;
 char* _base64;
 //char* _msgToken;
 //String _deviceID;

#if defined(ARDUINO_ARCH_ESP32)
  //Base64 encoder for ESP32
  void base64ESP(char* username, char* password);
#else
  //Base64 encoder for none ESP32 board 
  void base64(char* username, char* password);
#endif
 
 
 public:

 Client* _networkClient;
 
 HttpDownstreamClient(Client& networkClient);

 //Delete the already existed subscription
 void subscriptionDelete(char* user, char* password,char* URL, char* context,char* source);
 
 //Create subscription
 void subscriptionCreate(char* user, char* password, char* URL, char* device_ID,char* context ,char* SubName, char* API,char* typeFilter, char* fragmentsToCopy);
 
 //Create token 
 void tokenCreate(char* URL, char* Subname, char* Suber, int expiretime);
 
 //Create token by giving password
 void tokenCreatePassword(char* user, char* password, char* URL, char* Subname, char* Suber, int expiretime);

 //Open WSS
 void connectWSS(char* URL,char* Suber);


};


#endif



In the .ino file:


void setup()
{
    Serial.begin(115200);
    delay(10);
    
 wifisecure.setInsecure();
 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, pass);

    // wait 5 seconds for connection:
    delay(5000);
  }
  
  Serial.println("Connected to WiFi"); 
  
  
  c8yclient.subscriptionCreate(username,password,host, device_id,"mo" ,SubscriptionName, APIs,typeFilter,fragmentsToCopy);
  c8yclient.tokenCreatePassword(username,password,host, SubscriptionName, SubscriberName, expiretime);
}

I can confirm that the function subscriptionCreate() has been successfully sent out. However, the second doesn't work as I expected. The given result is as following:


Attempting to connect to SSID: MagentaWLAN-MYHU
Connected to WiFi

Stored Based64 string is: 123456789fkcxxnfh
Connected to the server to create subscription
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
HTTP/1.1 201 Created
Date: Fri, 18 Nov 2022 21:35:00 GMT
Content-Type: application/vnd.com.nsn.cumulocity.subscription+json;charset=UTF-8;ver=0.9
Content-Length: 317
Connection: keep-alive
Cache-Control: no-cache,no-store,must-revalidate
Pragma: no-cache
Expires: -1
Location: https://t1664801559.cumulocity.com/notification2/subscriptions/783859
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains

{"subscriptionFilter":{"apis":["measurements"]},"context":"mo","self":"https://t1664801559.cumulocity.com/notification2/subscriptions/783859","subscription":"NotificationV2Test28","id":"783859","source":{"name":"Temperature #1","self":"https://t1664801559.cumulocity.com/inventory/managedObjects/13225","id":"13225"}}
Connected to the server to request token!
123456789fkcxxnfh
debug!!!

However, if I only use the function tokenCreatePassword(). The following result will be given:

Attempting to connect to SSID: MagentaWLAN-MYHU
Connected to WiFi

Stored Based64 string is: 123456789sjcnz123456cnmz
The subscription is associated with the Subscripter: Test2Sub1
Connected to the server
yingzheliutest2.cumulocity.com
123465789eqeqw
105
Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.debug!!!
HTTP/1.1 200 OK
Date: Fri, 18 Nov 2022 21:45:51 GMT
Content-Type: application/json
Content-Length: 576
Connection: keep-alive
Cache-Control: no-cache,no-store,must-revalidate
Pragma: no-cache
Expires: -1
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains

{"token":"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJUZXN0MlN1YjEiLCJ0b3BpYyI6InQxNjY0ODAxNTU5L3JlbG5vdGlmL05vdGlmaWNhdGlvblYyVGVzdDI4IiwianRpIjoiNjAwMDExYzMtY2JhYS00MWE4LWFmYmYtZGZhYzgzNTQyYWM1IiwiaWF0IjoxNjY4ODA3OTUxLCJleHAiOjE2Njg4NzM5NTF9.FqXPF62liyIigECNqKnKHUyjTDeGmlBoO3HHwEGLw167b0ix1o4eDC0D1VzFKkggiwN7Mbnr3EsWOmsfkQ3nR7smNAqhGF976YAKjIfmWrARiTDgaiSULQCc5Odq1vvuN-O8o1BB2CsafdV5a1n5W1t2Bf9zzgfkZjQTsIe-Ojj6A_DyqUviwvJ5QnVi4VF9BANDMiiNZtocsfwpz2-S8gWqosGgi704Je8_EaS5xdoRYtR1W3EuDPLhRCea4m39iU4n0S97lkJd52xLDkwil4ZVF7xHBvrW6Zy3krf3wIgVwKfRAOmoy3_lnpPCaZ1oi0oqqg0SznchDGxJe7L_Sw"}

It seems like that the following part in tokenCreatePassword() has never been activated when tokenCreatePassword() and subscriptionCreate() are put together:


_networkClient->println("POST /notification2/token HTTP/1.1");
    _networkClient->print("Host: ");
    _networkClient->println(URL);
    Serial.println(URL);
    _networkClient->print("Authorization: Basic ");
    _networkClient->println(_base64);
    Serial.println(_base64);
    _networkClient->println("Content-Type: application/json");
    _networkClient->print("Content-Length: ");
    _networkClient->println(body2send.length());
    Serial.println(body2send.length());
    _networkClient->println("Accept: application/json");
    _networkClient->println();
    _networkClient->println(body2send);

Where does this issue come from? How could this two functiones perform quite well individually and not compatible with each?

Many thanks in advance!

Why do you think they succeeded? I cannot see one successfully completed HTTP request here.

BTW: As you're using HTTP 1.1 you should add a "Connection" header.

This is response sent from the server after using the first function.



HTTP/1.1 200 OK
Date: Fri, 18 Nov 2022 21:45:51 GMT
Content-Type: application/json
Content-Length: 576
Connection: keep-alive
Cache-Control: no-cache,no-store,must-revalidate
Pragma: no-cache
Expires: -1
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains

{"token":"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJUZXN0MlN1YjEiLCJ0b3BpYyI6InQxNjY0ODAxNTU5L3JlbG5vdGlmL05vdGlmaWNhdGlvblYyVGVzdDI4IiwianRpIjoiNjAwMDExYzMtY2JhYS00MWE4LWFmYmYtZGZhYzgzNTQyYWM1IiwiaWF0IjoxNjY4ODA3OTUxLCJleHAiOjE2Njg4NzM5NTF9.FqXPF62liyIigECNqKnKHUyjTDeGmlBoO3HHwEGLw167b0ix1o4eDC0D1VzFKkggiwN7Mbnr3EsWOmsfkQ3nR7smNAqhGF976YAKjIfmWrARiTDgaiSULQCc5Odq1vvuN-O8o1BB2CsafdV5a1n5W1t2Bf9zzgfkZjQTsIe-Ojj6A_DyqUviwvJ5QnVi4VF9BANDMiiNZtocsfwpz2-S8gWqosGgi704Je8_EaS5xdoRYtR1W3EuDPLhRCea4m39iU4n0S97lkJd52xLDkwil4ZVF7xHBvrW6Zy3krf3wIgVwKfRAOmoy3_lnpPCaZ1oi0oqqg0SznchDGxJe7L_Sw"}

This is another response sent from the server after using the second function.

If none of HTTPs request has been successfully performed, then I won't get anything, right?

That's the reason why I asked that why the behaviour was so strange, or the https request from the second function doesn't work.

Sorry, my fault, I didn't realized the scroll bar.

The behavior is correct. You use HTTP/1.1 but don't tell the server to close the connection after the request. As you reuse the network client you get a still open connection so you get the rather weird behavior. Try to close the connection explicitly.

Hi,

Thanks! But I used the same code for the MKR WIFI 1010 and nano 33 and both of them worked. I tried and it doesn't work. Is that a problem for the ESP32?

BRs,

As you didn't post complete code I assume the error is in the part you hide from us.
I doubt that you used exactly the same code on the other platforms as they use different hardware for the network connection which need different libraries to connect.

It's true that I used different Wificlient in .ino file. The problem maybe here?

Yes and no. As these platforms use different libraries the behavior may be different and as we didn't see the other code there might be differences that you don't tell us, because you think it isn't important.

Did you try to close the connection explicitly as I recommended in post #4?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.