gpio-webhook-arduino/wifi.h

70 lines
1.5 KiB
C
Raw Normal View History

2020-05-14 18:26:02 +00:00
#include "config.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
2020-05-14 18:26:02 +00:00
#include <WiFiClientSecureBearSSL.h>
HTTPClient client;
2020-05-14 18:26:02 +00:00
BearSSL::WiFiClientSecure *secure_transport;
BearSSL::Session *tls_session;
BearSSL::X509List cert_list;
2020-05-14 18:26:02 +00:00
void syncTime() {
// sync time
Serial.print("Syncing time");
configTime(8 * 3600, 0, "pool.ntp.org", "time.nist.gov");
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
}
void initTLS() {
secure_transport = new BearSSL::WiFiClientSecure();
syncTime();
cert_list.append(ca_cert);
secure_transport->setTrustAnchors(&cert_list);
tls_session = new BearSSL::Session();
secure_transport->setSession(tls_session);
}
2020-05-14 18:26:02 +00:00
void InitWifi() {
Serial.println("Attempting to connect to wifi");
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
int elapsed = 0;
while (WiFi.status() != WL_CONNECTED) {
Serial.print("Wifi connecting for ");
Serial.print(elapsed);
Serial.println(" seconds");
elapsed++;
delay(1000);
}
Serial.println("Wifi connected");
2020-05-14 18:26:02 +00:00
initTLS();
}
2020-05-14 18:26:02 +00:00
String FetchURL(const char *path) {
client.begin(*secure_transport, WEBHOOK_URL);
2020-05-14 18:26:02 +00:00
int status = client.GET();
if (status < 0) {
Serial.print("Client error communicating with server: ");
Serial.println(status);
return "";
}
2020-05-14 18:26:02 +00:00
if (status >= 400) {
Serial.print("Received HTTP status code ");
Serial.println(status);
return "";
}
2020-05-14 18:26:02 +00:00
return client.getString();
}