ATOM Lite(ESP32)でWiFiに常時接続してHTTP POSTする

追記: 公式ライブラリのできがあんまり良くないので使わないやつも書いた M5 ATOM(ESP32)でWiFiに常時接続してHTTP POSTするやつ

めっちゃググったりして頑張ったのでその結果をまとめておく。

#define FASTLED_INTERNAL

#include <M5Atom.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <HttpClient.h>

const char* ssid = "**********";
const char* password = "**********";

void post(const char* content) {
  DynamicJsonDocument doc(JSON_OBJECT_SIZE(2));
  doc["title"] = "ATOM Lite Wifi Test";
  doc["content"] = content;
  String json;
  serializeJson(doc, json);

  HTTPClient http;
  http.begin("http://httpbin.org/post");
  http.addHeader("Content-Type", "application/json");
  http.POST(json);
  Serial.println(http.getString());
  http.end();
}

void setup() {
  M5.begin(true, false, true);
  Serial.println();
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    if (M5.Btn.wasPressed()) {
      post("The button was pressed.");
    } 
    delay(50);
    M5.update();
  } else {
    M5.dis.drawpix(0, 0x001000);
    WiFi.begin(ssid, password);
    int wifiReconnectCount = 0;
    while (WiFi.status() != WL_CONNECTED) {
      if (wifiReconnectCount >= 300) { ESP.restart(); }
      wifiReconnectCount++;
      delay(100);
    }
    post("It's now online.");
    M5.dis.drawpix(0, 0x100000);
  }
}

ATOM Liteでインターホン鳴ったりボタン押されたらDiscordに通知するやつ作った

今までRaspberry Pi ZeroでやっていたのをATOM Liteに移した。
特別なことはしていないが慣れていないとそこそこ詰まりどころがあったのでまとめておく。

Grove端子

できあいのケーブルやユニバーサル基板用のメスコネクタは売っているが、ケーブル自作用のコンタクトやハウジングは公式には存在しない。
NS-TECHの1125を使っているらしくSMH200, YST200, HY2.0といったやつが互換品のようだがAliExpressでさえ僅かな店舗が出品しているという程度で入手難度が高い。
JST PHのコンタクトで代替できない事もないが刺さり具合が不安定。
現状日本で買えるのはGrove互換コネクタ HY2.0mm ハウジング・コンタクトピンセット / CON302-HY2-4P-5Pだけの様子。
以前はaitendoでも取り扱いがあったようだが長く入荷が無いらしくコンタクトの在庫が1個あるだけでハウジングは売られていなかった。

PlatformIO on VSCode

ATOM Liteでhttp postしてwebhookを叩いて通知を飛ばすやつ

家のインターホンはボタンが押されると2vが流れる拡張用端子がついていたのでGPIO32とGNDに繋いだ。

NginxとOAuth2 ProxyでWebアプリに認証をつける

こないだセットアップしたChronografを外部に公開するために認証を付ける。
OAuthのプロバイダとしてGitHubを使うとOrganizationとTeamで権限を付けられるのでわかりやすく便利。

Nginxの設定はわりと複雑だがSSLに関してはMozilla SSL Configuration Generatorがあり、OAuth2 Proxy向けの設定はConfiguration - OAuth2 Proxyに載っているのでさほど苦労はしない。
Let's Encryptのワイルドカード証明書の取得と更新を済ませてある前提。

OAuth2 Proxy

Releases · oauth2-proxy/oauth2-proxy
cookie-secretはpython -c 'import os,base64; print(base64.urlsafe_b64encode(os.urandom(16)).decode())'しろとConfiguration - OAuth2 Proxyにあった。
リポジトリに入っているoauth2-proxy.service.exampleはメンテされていないっぽいので適当に書いた。

wget https://github.com/oauth2-proxy/oauth2-proxy/releases/download/v5.1.0/oauth2_proxy-v5.1.0.linux-amd64.go1.14.tar.gz
tar xf oauth2_proxy-v5.1.0.linux-amd64.go1.14.tar.gz
sudo cp oauth2_proxy-v5.1.0.linux-amd64.go1.14/oauth2_proxy /usr/local/bin/

sudo tee /etc/systemd/system/oauth2_proxy.service << EOM > /dev/null
[Unit]
Description=OAuth2 Proxy
After=network.target

[Service]
Type=simple
Restart=always
ExecStart=/usr/local/bin/oauth2_proxy -cookie-secret=foo -email-domain=* -provider=github -client-id=bar -client-secret=baz -github-org=qux -github-team=quux

[Install]
WantedBy=multi-user.target
EOM

sudo systemctl enable --now oauth2_proxy

Nginx

sudo apt install nginx-light
sudo rm modules-enabled/50-mod-http-echo.conf
sudo rm sites-enabled/default
sudo systemctl reload nginx

sudo tee /etc/nginx/snippets/ssl.conf << EOM > /dev/null
# generated 2020-05-02, Mozilla Guideline v5.4, nginx 1.17.7, OpenSSL 1.1.1f, modern configuration
# https://ssl-config.mozilla.org/#server=nginx&version=1.17.7&config=modern&openssl=1.1.1f&guideline=5.4

listen 443 ssl http2;
listen [::]:443 ssl http2;

ssl_certificate /etc/letsencrypt/certificates/example.com.crt;
ssl_certificate_key /etc/letsencrypt/certificates/example.com.key;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m;  # about 40000 sessions
ssl_session_tickets off;

# modern configuration
ssl_protocols TLSv1.3;
ssl_prefer_server_ciphers off;

# HSTS (ngx_http_headers_module is required) (63072000 seconds)
add_header Strict-Transport-Security "max-age=63072000" always;

# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;

# verify chain of trust of OCSP response using Root CA and Intermediate certs
ssl_trusted_certificate /etc/letsencrypt/certificates/example.com.issuer.crt;

# replace with the IP address of your resolver
resolver 127.0.0.1;
EOM

sudo tee /etc/nginx/sites-available/chronograf << 'EOM' > /dev/null
server {
  server_name chronograf.example.com;

  include snippets/ssl.conf;

  location /oauth2/ {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host                    $host;
    proxy_set_header X-Real-IP               $remote_addr;
    proxy_set_header X-Scheme                $scheme;
    proxy_set_header X-Auth-Request-Redirect $request_uri;
    # or, if you are handling multiple domains:
    # proxy_set_header X-Auth-Request-Redirect $scheme://$host$request_uri;
  }

  location = /oauth2/auth {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Scheme         $scheme;
    # nginx auth_request includes headers but not body
    proxy_set_header Content-Length   "";
    proxy_pass_request_body           off;
  }

  location / {
    auth_request /oauth2/auth;
    error_page 401 = /oauth2/sign_in;

    # pass information via X-User and X-Email headers to backend,
    # requires running with --set-xauthrequest flag
    auth_request_set $user   $upstream_http_x_auth_request_user;
    auth_request_set $email  $upstream_http_x_auth_request_email;
    proxy_set_header X-User  $user;
    proxy_set_header X-Email $email;

    # if you enabled --pass-access-token, this will pass the token to the backend
    auth_request_set $token  $upstream_http_x_auth_request_access_token;
    proxy_set_header X-Access-Token $token;

    # if you enabled --cookie-refresh, this is needed for it to work with auth_request
    auth_request_set $auth_cookie $upstream_http_set_cookie;
    add_header Set-Cookie $auth_cookie;

    # When using the --set-authorization-header flag, some provider's cookies can exceed the 4kb
    # limit and so the OAuth2 Proxy splits these into multiple parts.
    # Nginx normally only copies the first `Set-Cookie` header from the auth_request to the response,
    # so if your cookies are larger than 4kb, you will need to extract additional cookies manually.
    auth_request_set $auth_cookie_name_upstream_1 $upstream_cookie_auth_cookie_name_1;

    # Extract the Cookie attributes from the first Set-Cookie header and append them
    # to the second part ($upstream_cookie_* variables only contain the raw cookie content)
    if ($auth_cookie ~* "(; .*)") {
        set $auth_cookie_name_0 $auth_cookie;
        set $auth_cookie_name_1 "auth_cookie_name_1=$auth_cookie_name_upstream_1$1";
    }

    # Send both Set-Cookie headers now if there was a second part
    if ($auth_cookie_name_upstream_1) {
        add_header Set-Cookie $auth_cookie_name_0;
        add_header Set-Cookie $auth_cookie_name_1;
    }

    proxy_pass http://127.0.0.1:8888/;
    # or "root /path/to/site;" or "fastcgi_pass ..." etc
  }
}
EOM

sudo ln -s /etc/nginx/sites-available/chronograf /etc/nginx/sites-enabled/chronograf
sudo nginx -t
sudo systemctl reload nginx