Created
May 26, 2019 21:57
-
-
Save phdoerfler/03d9bf89c8ee89ebe71a9f2b8ba4b4da to your computer and use it in GitHub Desktop.
WiFi + HTTP[S] + JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#include <ESP8266WiFi.h> | |
#include <ESP8266WiFiMulti.h> | |
#include <ESP8266HTTPClient.h> | |
#include <WiFiClientSecureBearSSL.h> | |
const uint8_t fingerprint[20] = {0xA3, 0xDE, 0xBD, 0xC9, 0x77, 0xE0, 0xDC, 0x68, 0x2F, 0x97, 0xB5, 0x59, 0xA0, 0xD0, 0x0A, 0x8E, 0x3B, 0xBA, 0x5C, 0xFC}; | |
ESP8266WiFiMulti WiFiMulti; | |
#define ARDUINOJSON_DECODE_UNICODE 1 | |
#include <ArduinoJson.h> | |
const size_t capacity = JSON_ARRAY_SIZE(64) + JSON_OBJECT_SIZE(128) + 1024; // + 2048 | |
StaticJsonDocument<capacity> doc; | |
const char* ssid = "the ssid"; | |
const char* password = "the password"; | |
std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure); | |
HTTPClient https; | |
bool https_get(const String &url); | |
void setup() { | |
Serial.begin(9600); | |
Serial.println(); | |
Serial.println(); | |
Serial.println(); | |
Serial.print("LED_BUILTIN = "); | |
Serial.print(LED_BUILTIN, DEC); | |
Serial.println(); | |
pinMode(2, OUTPUT); | |
pinMode(LED_BUILTIN, OUTPUT); | |
pinMode(D1, OUTPUT); | |
WiFi.mode(WIFI_STA); | |
WiFiMulti.addAP(ssid, password); | |
client->setFingerprint(fingerprint); | |
} | |
void loop() { | |
// wait for WiFi connection | |
if ((WiFiMulti.run() == WL_CONNECTED)) { | |
Serial.println(F("[HTTPS] begin...")); | |
digitalWrite(LED_BUILTIN, LOW); | |
if (https_get(F("https://www.beeminder.com/api/v1/users/me.json?auth_token=deadbeef"))) { // HTTPS | |
digitalWrite(LED_BUILTIN, HIGH); | |
Serial.println(F("[HTTPS] GET...")); | |
serializeJson(doc, Serial); | |
Serial.println(); | |
https.end(); | |
} else { | |
Serial.println(F("[HTTPS] Unable to connect")); | |
for (int i = 0; i < 4; ++i) { | |
tone(D1, 432, 500); | |
tone(D1, 216, 500); | |
} | |
} | |
} | |
delay(100); | |
} | |
bool https_get(const String &url) { | |
Serial.print(F("GET ")); | |
Serial.print(url); | |
Serial.println(F(" HTTP/1.0")); | |
if (https.begin(*client, url)) { | |
digitalWrite(2, LOW); | |
int httpCode = https.GET(); | |
digitalWrite(2, HIGH); | |
if (httpCode > 0) { | |
Serial.print(F("Success: ")); | |
Serial.println(httpCode); | |
deserializeJson(doc, https.getString()); | |
return true; | |
} else { | |
Serial.print(F("[HTTPS] GET failed, error: ")); | |
Serial.println(https.errorToString(httpCode).c_str()); | |
return false; | |
} | |
} else { | |
Serial.println(F("[HTTPS] Unable to connect")); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment