why ESP32 ssl connect fails - c++

I am using the WiFiSecureClient example n arduino studio. I first ran the example on my ESP 32 cam with the website howsmyssl and it works.
Then I created and hosted my own nodejs app on a domain and generated a letsencrypt certificate for it so all requests are directed to ssl.
I than exported the certificate from google chrome and changed the howsmyssl certificate to my own site's certificate.
The problem is that it does not connect and I get the message connection failed in the serial monitor.
Here is my code,
Essentially its the same code as in the example but for some reason the server is not connecting. Would appreciate any advise on how to debug/correct this.:
/*
Wifi secure connection example for ESP32
Running on TLS 1.2 using mbedTLS
Suporting the following chipersuites:
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CCM","TLS_DHE_RSA_WITH_AES_256_CCM","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8","TLS_DHE_RSA_WITH_AES_256_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CCM","TLS_DHE_RSA_WITH_AES_128_CCM","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8","TLS_DHE_RSA_WITH_AES_128_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_GCM_SHA384","TLS_DHE_PSK_WITH_AES_256_CCM","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384","TLS_DHE_PSK_WITH_AES_256_CBC_SHA384","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_DHE_WITH_AES_256_CCM_8","TLS_DHE_PSK_WITH_AES_128_GCM_SHA256","TLS_DHE_PSK_WITH_AES_128_CCM","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256","TLS_DHE_PSK_WITH_AES_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_DHE_WITH_AES_128_CCM_8","TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_256_CCM","TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_256_CCM_8","TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_WITH_AES_128_GCM_SHA256","TLS_RSA_WITH_AES_128_CCM","TLS_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_128_CCM_8","TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_RSA_PSK_WITH_AES_256_GCM_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_128_GCM_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA","TLS_PSK_WITH_AES_256_GCM_SHA384","TLS_PSK_WITH_AES_256_CCM","TLS_PSK_WITH_AES_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CBC_SHA","TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CCM_8","TLS_PSK_WITH_AES_128_GCM_SHA256","TLS_PSK_WITH_AES_128_CCM","TLS_PSK_WITH_AES_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CBC_SHA","TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CCM_8","TLS_PSK_WITH_3DES_EDE_CBC_SHA","TLS_EMPTY_RENEGOTIATION_INFO_SCSV"]
2017 - Evandro Copercini - Apache 2.0 License.
*/
#include <WiFiClientSecure.h>
const char* ssid = "myap"; // your network SSID (name of wifi network)
const char* password = "mypass"; // your network password
const char* server = "growgreen.life"; // 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" \
"MIIFNTCCBB2gAwIBAgISA923aMjf7A21sbQ131UqqWdiMA0GCSqGSIb3DQEBCwUA\n" \
"MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD\n" \
"EwJSMzAeFw0yMTA3MTIwNTI3MzJaFw0yMTEwMTAwNTI3MzFaMBkxFzAVBgNVBAMT\n" \
"Dmdyb3dncmVlbi5saWZlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n" \
"ocNfRneLCVSsl6ZOHaQQ9wQqtEjfuX/rn625xP/VWmikNlPkFrhP6Hm5HbXkpMSB\n" \
"+vGX3ms6tjoIWgipeusHo3shz+RsqVDGpfdxsNbKApHL8JxaIWjYaAlJDfw7SPOP\n" \
"lv+wqJXR7it83l5DuPrgu2jxbmDgrWdWbbXJYTs2kLbMANIMplYgHua3wGSovpGt\n" \
"PcK8LeohsEJk1cntqtcaznJFxA6s54hKtv/L03WgkNUlONX2BWrwv/OBsGkCN123\n" \
"5JmZ7iyocjaH6x5ixp7ULAtPKpsI5OQ+2zcgQIBRx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vlxzDbN/ggGK\n" \
"fD0PjwuREln5vgHXKOysYCJ7ho58g9DN4mkS2679FD2WiYXMpntYQtQP24noIaw1\n" \
"DmeS8h6xXQcDIEVVWki9Rst/S3dvI/LQUaQ0UCe8EeDbrYgKj9eMZH32ENqcb5NE\n" \
"LikNcXQpl/cgAbb3xczFAMBL7Vo8QxAM9bMiyfp58zh0bcFJkH9bNDEQ9uQdkHTP\n" \
"nukplj5DC7V5+FHPyBvTdUCRTPKf9cjHEvbCLCMicCMbeCjZ69cYhSo=\n" \
"-----END CERTIFICATE-----\n";
// 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
WiFiClientSecure client;
void setup() {
//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://growgreen.life");
client.println("Host: growgreen.life");
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
}
I changed the leaf certificate with the root certificate and now I am able to connect to the server. But for some reason I am getting the bad request 400 response...following is the response in the serial monitor:
Starting connection to server...
Connected to server!
headers received
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.14.0 (Ubuntu)</center>
</body>
</html>

const char* host="Your host server" ;
const int httpsPort = 443;
//use below inside the function u want to connect with server
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
client.connect(host, httpsPort);
http.begin(client, host);
String payload;
if (http.GET() == HTTP_CODE_OK)
payload = http.getString();

Related

WiFiClient.cpp socket error "Software caused connection abort - PlatformIo

For a project I am working on a mesh network on ESP32 (devkit).
I'm using the https://gitlab.com/painlessMesh/painlessMesh library for this to work.
The data received by the other ESP32's need to be sended to an REST API on Home Assistent with adres: http://192.168.1.4:8123/api/states/sensor.mesh.
To to this I am using the https://www.arduino.cc/reference/en/libraries/http/ library to send these HTTP requests.
This is my code:
#include <painlessMesh.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#define MESH_PREFIX "MeshNetwork"
#define MESH_PASSWORD "MeshPassword"
#define MESH_PORT 5555
const char* ssid_wifi = "<wifissid>";
const char* password_wifi = "<wifipassword>";
painlessMesh mesh;
Scheduler userScheduler;
void receivedCallback( uint32_t from, String &msg ) {
Serial.printf("Received from %u msg=%s\n", from, msg.c_str());
// Send To Home Assistent
Serial.printf("Node %u sends to HA....\n", from);
WiFiClient client;
HTTPClient http;
String serverName = "http://192.168.1.4:8123/api/states/sensor.mesh";
http.begin(client, serverName);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer <TOKEN>");
String httpRequestData = "{\"state\":"+ String(random(0,30));
Serial.println(httpRequestData + ", \"attributes\": {\"unit_of_measurement\": \"°C\"}}");
int httpResponseCode = http.POST(httpRequestData + ", \"attributes\": {\"unit_of_measurement\": \"°C\"}}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
void newConnectionCallback(uint32_t nodeId) {
Serial.printf("startHere: New Connection found!, nodeId = %u\n", nodeId);
}
void changedConnectionCallback() {
Serial.printf("Changed connections\n");
}
void nodeTimeAdjustedCallback(int32_t offset) {
Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(),offset);
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid_wifi, password_wifi);
Serial.printf("\n Connecting to Wifi: %s", ssid_wifi);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n Connected to Wifi! \n ");
// start Mesh Network
mesh.setDebugMsgTypes(ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE );
mesh.init( MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
// Set Root Node
mesh.setContainsRoot(true);
// Mesh Events
mesh.onReceive(&receivedCallback);
mesh.onNewConnection(&newConnectionCallback);
mesh.onChangedConnections(&changedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
}
void loop() {
mesh.update();
}
When the data is sending it gives me the following error
[E][WiFiClient.cpp:258] connect(): socket error on fd 61, errno: 113, "Software caused connection abort"
HTTP Response code: -1
I don't know what to do know,I have tried a lot of things.
Can anybody help me?
Thanks!
Update: When requesting the HTTP POST in the setup() it works. Not in the loop()

Spotify web api connection refused on ESP32

I'm trying to control spotify through an ESP32 but I always get a connection refused error.
Here I created a function to get the accessToken:
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
WiFiMulti wifiMulti;
const char *ca_cert =
"-----BEGIN CERTIFICATE-----\n" \
"MIIGEDCCBPigAwIBAgIQBS8G4gPhQtIePtEv2M7pnzANBgkqhkiG9w0BAQsFADBN\n" \
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMScwJQYDVQQDEx5E\n" \
"aWdpQ2VydCBTSEEyIFNlY3VyZSBTZXJ2ZXIgQ0EwHhcNMjAwNjIzMDAwMDAwWhcN\n" \
"MjEwOTAyMTIwMDAwWjBOMQswCQYDVQQGEwJTRTESMBAGA1UEBxMJU3RvY2tob2xt\n" \
"MRMwEQYDVQQKEwpTcG90aWZ5IEFCMRYwFAYDVQQDDA0qLnNwb3RpZnkuY29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\n" \
"aWdpY2VydC5jb20vRGlnaUNlcnRTSEEyU2VjdXJlU2VydmVyQ0EuY3J0MAwGA1Ud\n" \
"EwEB/wQCMAAwggEEBgorBgEEAdZ5AgQCBIH1BIHyAPAAdgD2XJQv0XcwIhRUGAgw\n" \
"lFaO400TGTO/3wwvIAvMTvFk4wAAAXLhDERlAAAEAwBHMEUCIASIo9eFKEVLL4cD\n" \
"xlBhAGSo82I0TRd66jvwFhx6Se79AiEAhL0I6dqaIZTsorV0XwSObs8gbh48ba5h\n" \
"XqQesmvVjH0AdgBc3EOS/uarRUSxXprUVuYQN/vV+kfcoXOUsl7m9scOygAAAXLh\n" \
"DESTAAAEAwBHMEUCIQDnnsP6nLnwtiUHORgRCBqPqFTHsPaTA9FxbmRw0gxGfAIg\n" \
"HLukydDmJy6a3f4ZXa5eJ63kUB1iQc/oai3aXSHbP6MwDQYJKoZIhvcNAQELBQAD\n" \
"ggEBAHfGtU9XU+pUAMgZoc0NenTV2fQfZl5MM5EPG/Jf0Fp4YnIIz92vReVnUvco\n" \
"MxO73E/mP15nxaXQtknQTpCn4ZBSD4OF5oMKM1M98iSGC+ZvKlk0UektOv9zrRTn\n" \
"A2JLJH695cul3nyaoqhuAWtzfFft8y6fm1Bclt1q6OvEGkNtWJ07aQFBXeaIzr4W\n" \
"kZR8sdw+EkiGk1bN/C1CMU0xBnkQE19OycfE2Ax5Qag81KwLlcdkgMtXkMie2ZV1\n" \
"ytyF8FFgyCakrFkDeDOnc5YAOpjlkD8J0uNTZIPv1rF/nA67EgAW9NFxulCqqrXb\n" \
"AFkCjRN8xiv10mrVbcQ86LwZdGA=\n" \
"-----END CERTIFICATE-----\n";
WiFiClientSecure *client;
void getAccessToken(){
HTTPClient http;
Serial.print("[HTTP] begin...\n");
if(!http.begin(*client, "https://accounts.spotify.com/api/token")) return;
http.addHeader("Authorization", "Basic [b64(id:secret)]");
http.addHeader("Content-type", "application/x-www-form-urlencoded");
Serial.print("[HTTP] POST...\n");
// start connection and send HTTP header
int httpCode = http.POST("grant_type=refresh_token&refresh_token=[RefreshToken]");
if(httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
String payload = http.getString();
Serial.println(payload);
} else {
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
wifiMulti.addAP("ssid", "password");
while(wifiMulti.run() != WL_CONNECTED){
delay(50);
Serial.print(".");
}
Serial.println();
configTime(3600, 3600, "pool.ntp.org", "time.nist.gov");
struct tm timeinfo;
if(!getLocalTime(&timeinfo)) Serial.println("Failed to obtain time");
else Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
client = new WiFiClientSecure();
if (client) client -> setCACert(ca_cert);
else Serial.println("Error setting ca_cert");
}
void loop() {
getAccessToken();
delay(10000);
}
Output:
13:41:01.057 -> Thursday, March 18 2021 14:41:19
13:41:01.057 -> [HTTP] begin...
13:41:01.057 -> [V][HTTPClient.cpp:239] beginInternal(): url: https://accounts.spotify.com/api/token
13:41:01.057 -> [D][HTTPClient.cpp:287] beginInternal(): host: accounts.spotify.com port: 443 url: /api/token
13:41:01.057 -> [HTTP] POST...
13:41:01.057 -> [D][HTTPClient.cpp:573] sendRequest(): request type: 'POST' redirCount: 0
13:41:01.057 ->
13:41:01.057 -> [V][ssl_client.cpp:59] start_ssl_client(): Free internal heap before TLS 279108
13:41:01.057 -> [V][ssl_client.cpp:65] start_ssl_client(): Starting socket
13:41:01.104 -> [V][ssl_client.cpp:104] start_ssl_client(): Seeding the random number generator
13:41:01.104 -> [V][ssl_client.cpp:113] start_ssl_client(): Setting up the SSL/TLS structure...
13:41:01.104 -> [V][ssl_client.cpp:129] start_ssl_client(): Loading CA cert
13:41:01.104 -> [V][ssl_client.cpp:197] start_ssl_client(): Setting hostname for TLS session...
13:41:01.104 -> [V][ssl_client.cpp:212] start_ssl_client(): Performing the SSL/TLS handshake...
13:41:01.197 -> [E][ssl_client.cpp:36] _handle_error(): [start_ssl_client():216]: (-9984) X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
13:41:01.197 -> [E][WiFiClientSecure.cpp:127] connect(): start_ssl_client: -9984
13:41:01.197 -> [V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.
13:41:01.197 -> [D][HTTPClient.cpp:1112] connect(): failed connect to accounts.spotify.com:443
13:41:01.197 -> [W][HTTPClient.cpp:1411] returnError(): error(-1): connection refused
13:41:01.197 -> [HTTP] POST... failed, error: connection refused
13:41:01.197 -> [D][HTTPClient.cpp:394] disconnect(): tcp is closed
13:41:01.197 ->
13:41:01.197 -> [V][ssl_client.cpp:265] stop_ssl_socket(): Cleaning SSL connection.
It gives me the same error every time I try to make a request to the spotify api, but the sample https code works.
I tried to make the request via Postman and it went through.
What am I getting wrong?
I have found that I had the wrong certificate by setting the debug level to verbose in the Tools section on the Arduino IDE.

How to get multiple responses per second with Get Request using ESP32

I'm using an ESP32 controller to send Get requests to a page. I can get 1 response per second using the http protocol and one response every three seconds using HTTPS. I would like to get as many as 3 responses per second if possible. Is there a faster way to get these responses and is the problem with my ESP32, the code, or the server itself? I'm not sure if it helps but my ESP32 is sending the Get request to an ASP.NET application running on a Windows server through an Amazon Web Services EC2 instance. My API is simply returning true or false.
Here is the code running on the ESP32:
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
WiFiMulti wifiMulti;
//Certificate when using HTTPS
/*
const char* ca = \
"-----BEGIN CERTIFICATE-----\n" \
"examplecertificate\n" \
"-----END CERTIFICATE-----\n" \
*/
void setup() {
USE_SERIAL.begin(115200);
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
wifiMulti.addAP("ssid", "password");
}
void loop() {
// wait for WiFi connection
if((wifiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
//USE_SERIAL.print("[HTTP] begin...\n");
//http.begin("https://example.com/webapi/controller/getstatus/0", ca); //Using HTTPS takes 3 seconds
http.begin("http://example.com/webapi/controller/getstatus/0"); //Using HTTP takes 1 second
//USE_SERIAL.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0) {
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
}

ESP32 using BLE and WiFi API calls gives error code -1

I have a program trying to connect to a Bluetooth device and then sending an ack over a server (the server is private so I just used some pseudonym).
The first ACK on setup, goes through with 204 http return code which is fine, then it searches for a device, and whether it finds one or not it gives an error code of -1, then further on it gives 204 as well.
Here is the code that I have: (I have another project so this is just stripped down version trying things). This is also largely based form the Bluetooth client connect example on the esp32.
Code:
#include "BLEDevice.h"
#include "esp_bt.h"
#include "WiFi.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Arduino_JSON.h>
//WiFi variables
//HTTPClient http;
const char* ssid = "SSID";
const char* password = "Password";
char* serverName = "ServerName";
char* serverQR = "ServerName1";
String serverPath;
String httpRequestData;
bool wifiOn = 0;
bool wifiAck = 0;
int Connection = 0;
int httpResponseCode;
String Data = "";
String externalID = "";
bool answer = "false";
String payload = "{}";
BLEScan* pBLEScan;
// The remote service we wish to connect to.
static BLEUUID serviceUUID("0000fff0-0000-1000-8000-00805f9b34fb");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("0000fff1-0000-1000-8000-00805f9b34fb");
static boolean doConnect = false; //should esp connect to ble device
static boolean connected = false; // is esp connected to a ble device
static boolean doScan = false; //should esp scan for ble devices
static BLERemoteCharacteristic* pRemoteCharacteristic; //init remote characterestic
static BLEAdvertisedDevice* myDevice; //init device found
static void notifyCallback( //beginning of functions, parameters follow
BLERemoteCharacteristic* pBLERemoteCharacteristic, //this is the device characterisitc value
uint8_t* pData, //data it received
size_t length,//length of data received
bool isNotify) {
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
Serial.print("data: ");
Serial.println((char*)pData);
esp_bt_controller_deinit();
esp_bt_controller_disable();
}
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {//when connecting
connected = true;
Serial.println("onConnect");
}
void onDisconnect(BLEClient* pclient) {//when disconnecting
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {//connect to ble device
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();//create esp as a client
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());//set the function of client callbacks
// Connect to the remove BLE server.
pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be
recognized type of peer device address (public or private)
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);//can we connect to ble device
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
// Obtain a reference to the characteristic in the service of the remote BLE server.
pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);//does the ble device have the
characteristic function we want?
if (pRemoteCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our characteristic");
// Read the value of the characteristic.
if (pRemoteCharacteristic->canRead()) {
std::string value = pRemoteCharacteristic->readValue();
Serial.print("The characteristic value was: ");
Serial.println(value.c_str());
}
if (pRemoteCharacteristic->canNotify()) //if ble server transmits data do a callback
pRemoteCharacteristic->registerForNotify(notifyCallback);
connected = true;
return true;
}
/**
Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {//When a scan is activated
/**
Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {//when a ble device is found
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);//ble server connected
doConnect = true;//has to connect
doScan = true;//has to scan
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
//WiFi setup
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting to WiFi...");
delay(1000);
}//end while
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
serverPath = serverName;
if (WiFi.status() == WL_CONNECTED) {
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Data to send with HTTP POST
JSONVar json_test;
json_test["id"] = WiFi.macAddress();
httpRequestData = JSON.stringify(json_test);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
httpResponseCode = http.POST(httpRequestData);
payload = " {}";
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println("This is the response code");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
WiFi.disconnect(true);
delay(1); // disable WIFI altogether
WiFi.mode(WIFI_OFF);
delay(1);
} else
{
Serial.println("WiFi disconnected");
}
} // End of setup.
// This is the Arduino main loop function.
void loop() {
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BLE);
if (!connected)
{
Serial.println("Initialising");
pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
Serial.println("Scan starting");
pBLEScan->start(30, false);
Serial.println("Scan ended");
}
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {//if ble server was found connect to it
if (connectToServer()) {
Serial.println("We are now connected to the BLE Server.");
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
esp_bt_controller_deinit();
esp_bt_controller_disable();
//WiFi setup
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
//WiFi.config(staticIP, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting to WiFi...");
delay(1000);
}//end while
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
serverPath = serverName;
if (WiFi.status() == WL_CONNECTED) {
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Data to send with HTTP POST
JSONVar json_test;
json_test["id"] = WiFi.macAddress();
httpRequestData = JSON.stringify(json_test);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println("This is the loop");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
Serial.println("This is the loop");
}
// Free resources
http.end();
WiFi.disconnect(true);
delay(1); // disable WIFI altogether
WiFi.mode(WIFI_OFF);
delay(1);
} else
{
Serial.println("WiFi disconnected");
}
delay(1000); // Delay a second between loops.
} // End of loop
The output of the code is:
Starting Arduino BLE Client application...
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the response code IS this done? Initialising Scan starting BLE Advertised Device found: Name: , Address: address, manufacturer data:random stuff Scan ended Forming a connection to addresss
- Created client onConnect
- Connected to server
- Found our service
- Found our characteristic We are now connected to the BLE Server.
Connecting to SSID Connecting to WiFi... Connected, IP address: IP Error code: -1 This is the loop
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the loop
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the loop
My question basically is does anyone know what an erro0 rcode if -1 is? On my main project I am unable to send a get request after scanning for a ble device even if I disabl the controller.
To answer your question about error code -1:
It means that a connection was not successful according to this example from the HTTPClient repository.
Your log shows that you are able to connect to your server and afterwards to your BLE peripheral. But it seems like you never disconnect from the peripheral and continue to block the other wifi connections. Have a look at this for further ideas on using BLE and WiFi together.

ESP32 to ESP32 WiFi Server/Client Problem

I've got one ESP32 acting as client and another ESP32 acting as an access-point for direct communication and outdoor use.
I have set up a server on the AP end and would like the client to communicate with it but I can't seem to make this work.
I would like to know two things:
How do I send or write data to the server from the client?
How do I read and display the data that was sent to the server from the client?
I have attached the code below:
Code for AP/Server
//SERVER
//Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
//Set web server port number to 80
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println("Setting AP (Access Point)…");
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address ");
Serial.println(IP);
Serial.print("MAC address ");
Serial.println(WiFi.softAPmacAddress());
server.begin();
}
void loop(){
WiFiClient client = server.available(); //Listen for incoming clients
if (client)
{ //If a new client connects,
Serial.println("New Client."); //print a message out in the serial port
while (client.connected())
{
Serial.println("Client connected.");
Serial.println(client.available());
if (client.available() > 0)
{
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
client.stop();
Serial.println("Client disconnected.");
Serial.println();
}
}
Code for Client
//Client
#include <WiFi.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
WiFiClient client;
IPAddress server(192, 168, 4, 1);
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
if(client.connect(server, 80))
{
Serial.println("connected to server");
client.write("Data");
}
else
{
Serial.println("failed to connect to server");
}
}
void loop()
{
}
Alternatively to the previous answer, you could use espnow as a protocol between various esp32. Here an example.
You must implement some sort of protocol like TCP, UDP to exchange data.
Example Project using TCP
https://www.instructables.com/id/WiFi-Communication-Between-Two-ESP8266-Based-MCU-T/
Example Project using UDP
https://circuits4you.com/2018/01/01/esp-to-esp-communication/
Look at this very handy function:
void SetWifi(const char *name, const char *password) { // Turn on wifi with server
Serial.println("Starting server");
WiFi.disconnect();
WiFi.softAP(name, password);
delay(2000);
IPAddress IP = WiFi.softAPIP();
Serial.print("Server IP : ");
Serial.println(IP);
server.begin();
server.setNoDelay(true);
Serial.println("Server started");
}
You can write data with this function :
void sendDataTCP(String message) { // function to send message back to client
if (client && client.connected()) { //check if client is there
client.println(message);
}
client.flush();
}
Receive data with this function:
void availableMessage() {
if (client.available()) {//check if client is there
while (client.available()) {
String message = client.readStringUntil('\n'); //read string until enter (end of message)
Serial.println("Received: " + message);
message.toCharArray(buffer, BUFFER); // put message in char array (buffer)
client.flush(); // discard all bytes that have been read
}
}
}
Check if someone has connected:
void connectClient() {
if (server.hasClient()) // if server has a client
{
if (client = server.available()) { // if client is connected
Serial.println("Connected");
}
}
}
I think this will get you in the direction of accomplishing your goal, good luck!