クライアントサイド
ハード
自作のESP-WROOM-02汎用機版。書き込み時に使うスイッチやレギュレータ、コンデンサ等最低限物がついているだけのもの。
空いているIO13からLED->抵抗(たまたま使いさしボックスにあった1.1k)->GNDと接続
プログラム
おもむろに全体像。Exampleに入っていたBearSSL_CertStore.inoの改造。なお、ssl接続用のcertファイルデータが別途必要。作成手順はこちら。アップロードの手順はこちら。ザックリ解説は下
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <CertStoreBearSSL.h>
#include <time.h>
#include <FS.h>
#include <LittleFS.h>
// 見えているけど店の公開wifiなので気にしない
#ifndef STASSID
#define STASSID "rocher_guest";
#define STAPSK "sd5ks86vn5nti";
#endif
#define LED_PIN 13
const char *ssid = STASSID;
const char *pass = STAPSK;
BearSSL::CertStore certStore;
// 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));
}
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
LittleFS.begin();
// 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());
setClock(); // Required for X.509 validation
int numCerts = certStore.initCertStore(LittleFS, PSTR("/certs.idx"), PSTR("/certs.ar"));
Serial.printf("Number of CA certs read: %d\n", numCerts);
if (numCerts == 0) {
Serial.printf("No certs found. Did you run certs-from-mozilla.py and upload the LittleFS directory before running?\n");
return; // Can't connect to anything w/o certs!
}
pinMode(LED_PIN, OUTPUT);
}
void loop() {
BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure();
// Integrate the cert store with this connection
bear->setCertStore(&certStore);
HTTPClient https;
if(https.begin(*bear,"https://mail.epea.co.jp/api/reserve_count")){
int httpCode = https.GET();
Serial.print("httpCode:");
Serial.println(httpCode);
String payload = https.getString();
Serial.print("payload:");
Serial.println(payload);
String zero = "0";
if(zero.equals(payload)){
Serial.print("0件だよ");
digitalWrite(LED_PIN, LOW);
} else {
// 0以外だと点灯。エラー等で変な値が返ってきたときもこっち(ステータス見る処理等はないので大体)
Serial.println("0件じゃないよ");
digitalWrite(LED_PIN, HIGH);
}
}
delete bear;
delay(10000);
}
setClockはSSLの認証ファイル(cert)の有効期限チェックのためのもの。BearSSL_CertStoreそのまま。
setupもほぼそのまま。不要なもの減らしてLED_PIN(13番)をOUTPUTにしているぐらい
pinMode(LED_PIN, OUTPUT);
loopのなかで扱いやすいHTTPClient を使用。サーバに接続して本文(サーバ側のAPIは予約メールの未読件数がそのまま数字で入ってくる仕様)が0かそれ以外で点灯するかどうかを変える。点灯を止めるにはPCのメーラーでメールを開く。
ページ: 1 2