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

UbuntuにTelegrafとInfluxDBとChronografとKapacitorを入れた

せっかくだしinfluxDataで揃えたがChronografとKapacitorはaptで管理できないのがつらい。
しかしChronografはInfluxDBの管理ができたりLog Viewerでsyslogを見れたりという感じで便利度は高い。
Telegrafはデータを集めてInfluxDBへ投げてくれるやつで、Kapacitorはアラートを飛ばすやつ。

インストール

InfluxDBとTelegrafは公式リポジトリからaptで入るがChronografとKapacitorはDownloadsから落として手で入れる必要がある。
インストールの手順もこっちに書いてありドキュメントがとっ散らかっていて厳しい。
kapacitorはsudo systemctl start kapacitorしてやる必要があった。
後から気づいたがUbuntu 20.04でドキュメントに従うとインストールされるInfluxDBが古いものでInstall InfluxDB on Ubuntu 20.04/18.04 and Debian 9 | ComputingForGeeksによると18.04向けのリポジトリが使えるよとのことだったのでそうした。
GitHubのIssueを見ると指摘されて更新するみたいなのを繰り返しているのであまりメンテされていないようだ。

設定

どれも特に設定することなくデフォルトで動く。
Telegrafはinfluxdata/telegraf: The plugin-driven server agent for collecting & reporting metrics.を見てプラグインを追加したconfigを出力したのでrsyslog側の設定が必要になった。
telegraf --input-filter syslog:cpu:disk:diskio:mem:net:netstat:processes:procstat:swap:system --output-filter influxdb config | sudo tee /etc/telegraf/telegraf.conf
また、rsyslogはTCPで通信するとsyslogがエラーまみれになる問題があり、omfwd: TCPSendBuf error -2027 · Issue #3910 · rsyslog/rsyslogを見てUDPに切り替えた。

グラフ

ChronografのHost ListやLog ViewerはTelegrafプラグインでInfluxDBへデータが投入されると自動的に使えるようになる。
Log Viewerでsyslogを見るのは手軽な割になかなか便利で検索クエリをセーブさせてくれたら文句無いのにな…という感じ。 System Log Viewer

このあと

Raspberry Piに付けたセンサーで計測したデータを投入する

追記

結局ChronografとKapacitorは使わなくなった。
とにかく機能が不足していてやはりGrafanaの方が圧倒的に便利。
Log Viewerでsyslogを見るというのもTelegraf / InfluxDB / Grafana as syslog receiver – NWMichl Blogで公開されているjsonをインポートするとGrafanaでも苦労なくできる。
デフォルトだとInfluxDBのログとかがうるさいのでSetting>Variables>$appnameでRegex/^(?!influxd|grafana-server)/を追加したぐらい。