GET Api ESP8233

#include <ESP8266WiFi.h>
#define ssid "Airtel"
#define password "Airtel"


const int API_TIMEOUT = 15000;  //keep it long if you want to receive headers from client
const int httpsPort = 443;

const char* resource = "/ords/rest/IOT/id";
const char* server = "uo0cpjwmc7m9wro-subratdw.adb.ap-mumbai-1.oraclecloudapps.com";

void setup() {
  delay(5000);
  Serial.begin(74880);
  while(!Serial) {
  }
  connectToWifi();

  makeIFTTTRequest();

  //now sending board to sleep
  WiFi.disconnect();
  Serial.println("deepsleepnow ");
  ESP.deepSleep(0);
}

void loop(){
  //if deep sleep is working, this code will never run.
  Serial.println("This shouldn't get printed");
}

void connectToWifi() {
  WiFi.disconnect();
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Attempting to connect: ");

  //try to connect for 10 seconds
  int i = 11;
  while((WiFi.status() != WL_CONNECTED) && (i-- > 0)) {
    delay(1000);
    Serial.print(i);
    Serial.print(", ");
  }
  Serial.println();
  //print connection result
  if(WiFi.status() == WL_CONNECTED){
    Serial.println("Connected.");
    Serial.print("D1 Mini IP address: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.println("Connection failed - check your credentials or connection");
    Serial.println("deepsleepnow ");
    WiFi.disconnect();
    ESP.deepSleep(0);
  }
}

// Make an HTTP request to the IFTTT web service

void makeIFTTTRequest() {
 Serial.print("Connecting to ");
 Serial.print(server);

 BearSSL::WiFiClientSecure client;
 client.setInsecure();
 client.setTimeout(API_TIMEOUT);
 int retries = 6;
 while(!client.connect(server, httpsPort) && (retries-- > 0)) {
   Serial.print(".");
   delay(1000);
 }
 Serial.println();
 if(!client.connected()) {
    Serial.println("Failed to connect, going back to sleep");
    client.stop();
    return;
 }
 Serial.print("Request resource: ");
 Serial.println(resource);
 client.print(String("GET ") + resource +
                 " HTTP/1.1\r\n" +
                 "Host: " + server + "\r\n" +
                 "Connection: close\r\n\r\n");

 int timeout = 5 * 10; // 5 seconds           
 while(!client.available() && (timeout-- > 0)){
   delay(100);
 }

 if(!client.available()) {
    Serial.println("No response, going back to sleep");
    client.stop();
    return;
 }
 while(client.available()){
   Serial.write(client.read());
 }
 Serial.println("\nclosing connection");
 delay(1000);
 client.stop();
}


Other One:

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <StackThunk.h>
#include <time.h>

#ifndef STASSID
#define STASSID "Airtel_skp"
#define STAPSK  "Airtel123"
#endif

const char *ssid = STASSID;
const char *pass = STAPSK;

const char *   host = "uo0cpjwmc7m9wro-subratdw.adb.ap-mumbai-1.oraclecloudapps.com";
const uint16_t port = 443;
const char *   path = "/ords/rest/IOT/id";

// Set time via NTP, as required for x.509 validation
void setClock() {
  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("");
  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));
}

// Try and connect using a WiFiClientBearSSL to specified host:port and dump HTTP response
void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const uint16_t port, const char *path) {
//void fetchURL(BearSSL::WiFiClientSecure *client, const char *host, const char *path) {
  if (!path) {
    path = "/";
  }

  ESP.resetFreeContStack();
  uint32_t freeStackStart = ESP.getFreeContStack();
  Serial.printf("Trying: %s:443...", host);
  client->connect(host, port);
  if (!client->connected()) {
    Serial.printf("*** Can't connect. ***\n-------\n");
    return;
  }
  Serial.printf("Connected!\n-------\n");
  client->write("GET ");
  client->write(path);
  client->write(" HTTP/1.0\r\nHost: ");
  client->write(host);
  client->write("\r\nUser-Agent: ESP8266\r\n");
  client->write("\r\n");
  uint32_t to = millis() + 5000000;
  if (client->connected()) {
    do {
      char tmp[32];
      memset(tmp, 0, 32);
      int rlen = client->read((uint8_t*)tmp, sizeof(tmp) - 1);
      yield();
      if (rlen < 0) {
        break;
      }
      // Only print out first line up to \r, then abort connection
      char *nl = strchr(tmp, '\r');
      if (nl) {
        *nl = 0;
        Serial.print(tmp);
        break;
      }
      Serial.print(tmp);
    } while (millis() < to);
  }
  client->stop();
  uint32_t freeStackEnd = ESP.getFreeContStack();
  Serial.printf("\nCONT stack used: %d\n", freeStackStart - freeStackEnd);
  Serial.printf("BSSL stack used: %d\n-------\n\n", stack_thunk_get_max_usage());
}

void fetchNoConfig() {
  Serial.printf(R"EOF(
If there are no CAs or insecure options specified, BearSSL will not connect.
Expect the following call to fail as none have been configured.
)EOF");
  BearSSL::WiFiClientSecure client;
  fetchURL(&client, host, port, path);
}

void fetchInsecure() {
  Serial.printf(R"EOF(
This is absolutely *insecure*, but you can tell BearSSL not to check the
certificate of the server.  In this mode it will accept ANY certificate,
which is subject to man-in-the-middle (MITM) attacks.
)EOF");
  BearSSL::WiFiClientSecure client;
  client.setInsecure();
  fetchURL(&client, host, port, path);
}

void fetchFingerprint() {
  Serial.printf(R"EOF(
The SHA-1 fingerprint of an X.509 certificate can be used to validate it
instead of the while certificate.  This is not nearly as secure as real
X.509 validation, but is better than nothing.
)EOF");
  BearSSL::WiFiClientSecure client;
  static const char fp[] PROGMEM = "93:05:7A:88:15:C6:4F:CE:88:2F:SA:91:16:52:28:78:BC:53:64:17";
  client.setFingerprint(fp);
  fetchURL(&client, host, port, path);
}

void fetchSelfSigned() {
  Serial.printf(R"EOF(
It is also possible to accept *any* self-signed certificate.  This is
absolutely insecure as anyone can make a self-signed certificate.
)EOF");
  BearSSL::WiFiClientSecure client;
  Serial.printf("First, try and connect to a badssl.com self-signed website (will fail):\n");
  fetchURL(&client, "self-signed.badssl.com", 443, "/");
  Serial.printf("Now we'll enable self-signed certs (will pass)\n");
  client.allowSelfSignedCerts();
  fetchURL(&client, "self-signed.badssl.com", 443, "/");
}

void fetchKnownKey() {
  Serial.printf(R"EOF(
The server certificate can be completely ignored and its public key
hardcoded in your application. This should be secure as the public key
needs to be paired with the private key of the site, which is obviously
private and not shared.  A MITM without the private key would not be
able to establish communications.
)EOF");
  // Extracted by: openssl x509 -pubkey -noout -in servercert.pem
  static const char pubkey[] PROGMEM = R"KEY(
-----BEGIN PUBLIC KEY-----
AAAAB3NzaC1ymc2EAAAADAQABAAABAQC+zEQAY7wwYR/FdeiRFlwoAIPUwt7vyhc/mFLjlGDKOhcXeZRinARAFpvOlIMmSRubzMVqQy75lPiwhGmarc2Dj6nFzXf7psZ29d1qu86oqmvTuuTYD4SQauH45zkAMD05HW8dpBouyQHp1f43JVRJSmXFiBTpSfYQCLnWnrDtQAk+9H1mxYcj4sivsbt1TGlpslG7VgvDaDaMI38x7Lw/RpeyPUpH5p4Ql6dMgVamc0kcnzT/FUY20hj19JbN32ehGjK4yIg11uaqO3esVh8hAoiyvfhjjQCTSOnGebpvBwm11LVrM/jhf/DbnhrZHtLRR9M3UYdIF0/mz8v5ARdru4b
-----END PUBLIC KEY-----
)KEY";
  BearSSL::WiFiClientSecure client;
  BearSSL::PublicKey key(pubkey);
  client.setKnownKey(&key);
  fetchURL(&client, host, port, path);
}

void fetchCertAuthority() {
  static const char digicert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
AAABACAambAPkVud6g9xWKUL6dewBwHef4ROY7RC3DzQpBkEWEtyJItkwaV8dDCd
i1o9aBHBPnv3eay9lmFFOZ/rROb5ua1QViAD70xUVhJQhzqYGq/gHTc5m/mL/56k
gvhXxajDUF0aHiop7rT9u8s7Pm8uRMz1Hg6wbv8s5jXMAmUFLFYEb1JzMTiGEyEN
FXODeOM9V0gS6FTuU3HmOJ1Wy1Ab5m/Q3qsUzUsLZtYZGIP35wXcYZQvJ33+AQU4q
dwHtGb+45mM4G8JVWTzsgrcmLJTr4vvGN+XNdUWBcBGpu2WV9+jCvY+zWgCm2EZs
DRRCDgk1PM1HrJsyiDEkJF95yy0AAACBANNgkRsIVMR/Zk3c9iG6PSRnaS318I2c
NI4m7zAN334ap8q6JhAAFCfnl1oFCawTIiBo4SXO2ge7KFldH3BQesXr+zxP3RLRR
9YU/6syk1bZR/FbC9ZocYtTLd7hK7XEda8qw1y8uOpwOZmTr4MaNOrd01wx1a7tC
rowHbY/JeCS5AAAxxxxAgQCz01gckKuQwFep4s7FoiZwhwo/cnAbkBJeaNwTHuNqvK2c
k5/KpY1J9pMZ51seetoHB6Tt2Uj69yTctGizWzurc+IQhN9WdEVMNMEzi/JQFRmR
Q5ptHPEPnc+PcwPpObgYzOgK4sJsLZAvC9UwDwSbzwX7XnLmZRQgC0KrNs9C+wAA
AIEA0cSbnDRGu089OfD1gNrk+SyzolpyEhaIazAvVdAAnUmM4VXLIJZGatc0dPw+
4iTAEjtSB/NenpHOH3BCojGv2POQ6orFzAotcbHSpmUhK/ZXI1lOwbK1QP2AGri5
eQfurtwXzqDzoWcurym+4mwpK7/Kb6XHx8A1ECLv0QyBn/c=
-----END CERTIFICATE-----
)EOF";

  Serial.printf(R"EOF(
A specific certification authority can be passed in and used to validate
a chain of certificates from a given server.  These will be validated
using BearSSL's rules, which do NOT include certificate revocation lists.
A specific server's certificate, or your own self-signed root certificate
can also be used.  ESP8266 time needs to be valid for checks to pass as
BearSSL does verify the notValidBefore/After fields.
)EOF");

  BearSSL::WiFiClientSecure client;
  BearSSL::X509List cert(digicert);
  client.setTrustAnchors(&cert);
  Serial.printf("Try validating without setting the time (should fail)\n");
  fetchURL(&client, host, port, path);

  Serial.printf("Try again after setting NTP time (should pass)\n");
  setClock();
  fetchURL(&client, host, port, path);
}

void fetchFaster() {
  Serial.printf(R"EOF(
The ciphers used to set up the SSL connection can be configured to
only support faster but less secure ciphers.  If you care about security
you won't want to do this.  If you need to maximize battery life, these
may make sense
)EOF");
  BearSSL::WiFiClientSecure client;
  client.setInsecure();
  uint32_t now = millis();
  fetchURL(&client, host, port, path);
  uint32_t delta = millis() - now;
  client.setInsecure();
  client.setCiphersLessSecure();
  now = millis();
  fetchURL(&client, host, port, path);
  uint32_t delta2 = millis() - now;
  std::vector<uint16_t> myCustomList = { BR_TLS_RSA_WITH_AES_256_CBC_SHA256, BR_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, BR_TLS_RSA_WITH_3DES_EDE_CBC_SHA };
  client.setInsecure();
  client.setCiphers(myCustomList);
  now = millis();
  fetchURL(&client, host, port, path);
  uint32_t delta3 = millis() - now;
  Serial.printf("Using more secure: %dms\nUsing less secure ciphers: %dms\nUsing custom cipher list: %dms\n", delta, delta2, delta3);
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");

  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  //fetchNoConfig();
  fetchInsecure();
 // fetchFingerprint();
//  fetchSelfSigned();
//  fetchKnownKey();
//  fetchCertAuthority();
//  fetchFaster();
}


void loop() {
  // Nothing to do here
}

Comments

Popular posts from this blog

Easy Text-to-Speech with Python

Flutter for Single-Page Scrollable Websites with Navigator 2.0

Better File Storage in Oracle Cloud