# m5stack-claude-meter

Turn the M5Stack **StopWatch** (ESP32-S3, 466×466 round AMOLED) into a
**standalone Claude usage meter** — the same data as Claude Code's `/usage`
screen, always on your desk.

<p align="center">
  <img src="docs/m5stack-claude-meter.jpg" width="420"
       alt="M5Stack StopWatch running m5stack-claude-meter on a 3D-printed desk stand">
</p>

**English** (below) | [日本語](#日本語)

---

## English

Firmware that shows your Claude subscription usage (current session / weekly
all-models / weekly per-model) as three concentric rings.

**Fully standalone**: no companion app, no BLE bridge. The device itself polls
Anthropic's usage endpoint over WiFi every 10 minutes.

The 3D-printed desk stand in the photo is published on
[Thingiverse: thing:7401040](https://www.thingiverse.com/thing:7401040).

```
outer ring  = SESSION (5-hour rolling window)
middle ring = WEEK (weekly, all models)
inner ring  = weekly per-model (Fable / Opus / ... auto-detected per account)
center      = session % + time until reset
lower rows  = weekly / per-model numbers, last update time
colors      = green (<60%) → yellow (<80%) → orange (<95%) → red
```

### Requirements

- M5Stack StopWatch (ESP32-S3R8, 16MB flash / 8MB octal PSRAM)
- 2.4GHz WiFi
- A Claude subscription (Pro / Max — any account where `/usage` works)
- macOS + [Arduino IDE 2.x](https://www.arduino.cc/en/software) or `arduino-cli`
  (the build scripts assume macOS; on other OSes, build with arduino-cli
  using the FQBN in `tools/common.sh`). Works on Apple Silicon without
  Rosetta.

### Setup

```bash
# 1) clone into your Arduino sketchbook
cd ~/Documents/Arduino
git clone <this-repo> m5stack-claude-meter
cd m5stack-claude-meter

# 2) install pinned dependencies (board core m5stack:esp32 3.3.9 /
#    M5Unified 0.2.20 / M5GFX 0.2.27 / ArduinoJson 7.4.3; re-runnable)
./tools/setup.sh

# 3) build
./tools/build.sh

# 4) connect the StopWatch over USB and flash
./tools/flash.sh

# 5) initial configuration (WiFi + Claude auth; see below)
./tools/provision.sh
```

Library versions are pinned to a combination verified to work.

### Provisioning

`./tools/provision.sh` collects your WiFi credentials, performs Claude
authentication, and writes everything to the device over USB serial.

By default it **mints a dedicated OAuth session for the meter** (the same
PKCE flow as `claude login`):

1. Enter your WiFi SSID / password
2. Open the printed URL in a browser and approve with your Claude account
3. Paste the `xxxx#yyyy` code shown on the callback page into the terminal
4. The token is verified (your actual usage JSON is displayed), written to
   the device, and the rings appear within seconds

Because the session is dedicated, the device refreshing its token **never
interferes with a Claude Code login on your machine**.

Other options:

| Option | Behavior |
|---|---|
| `--token-stdin` | Paste an OAuth access token you already have (no refresh; works until it expires) |
| `--keychain` | Reuse Claude Code's macOS Keychain credentials (`claudeAiOauth`). **Not recommended** — refresh-token rotation may conflict with Claude Code's own session |
| `--no-refresh` | Don't store the refresh token (the device stops at access-token expiry) |
| `--ssid <name>` | Pass the SSID on the command line |

### Controls

| Input | Action |
|---|---|
| KEY1 / tap screen | Poll now (30s minimum interval) |
| KEY2 | Cycle brightness (80→140→200→40) |

### Serial commands (115200 bps)

View logs with `./tools/monitor.sh`. Maintenance commands:

| Command | Action |
|---|---|
| `CMINFO` | Show configuration state (never prints tokens or other secrets) |
| `CMPOLL` | Poll immediately (`[net] usage keys:` / `[net] limits:` show a summary of the raw response) |
| `CMCLR` | Erase all configuration (back to unprovisioned) |
| `CMCFG {json}` | Manual provisioning (used internally by `tools/provision.sh`) |

### Security notes

- The auth token is stored **in plain text** in the device's flash (NVS).
  **The device itself becomes a credential** — if it is lost or handed over,
  revoke the session at
  [claude.ai/settings/claude-code](https://claude.ai/settings/claude-code).
- The firmware only GETs the usage endpoint and refreshes its token, but the
  token's scope is broader than that. Treat it like a password.
- TLS uses pinned root CAs (`certs.h`: GTS Root R1/R4, GlobalSign Root CA,
  ISRG Root X1). If the certificate chains change in the future, `certs.h`
  needs updating.

### Limitations & known issues

- **Depends on an unofficial API** (`api.anthropic.com/api/oauth/usage`).
  Field names and auth requirements may change on Anthropic's side.
  - The per-model ring prefers the `limits` array
    (`scope.model.display_name`) and falls back to `seven_day_*` keys, so it
    tracks model-generation changes to some extent.
  - Inspect the actual response with `CMPOLL` (above).
- The usage endpoint rate-limits aggressively. Polling is 10-minute cadence
  with automatic backoff on 429, but **do not poll the same account at high
  frequency from multiple devices or tools**.
- Always-on display + periodic WiFi/TLS means **USB power is assumed**
  (a few hours on battery alone).
- As AMOLED burn-in mitigation, text drifts ±2px on a 10-minute cycle and
  the default brightness is low (80/255). For a permanent desk fixture,
  consider KEY2 down to the lowest level.

### Troubleshooting

- **Flashing fails with `Failed to connect`**: if the current firmware uses
  USB-OTG (TinyUSB), specify the upload mode once:
  `bash -c 'source tools/common.sh && "$ACLI" --config-file "$CLI_CONFIG" upload --fqbn "$FQBN,UploadMode=cdc" --port "$(detect_port)" --input-dir "$CMETER_ROOT/.build" "$CMETER_ROOT"'`
  If it still fails, hold BOOT while resetting to enter ROM download mode.
- **Provisioning says `no reply`**: check that this firmware is running
  (`./tools/monitor.sh`). USB re-enumeration takes a few seconds after
  flashing.
- **Persistent `rate limited (429)`**: check whether another tool is polling
  the same account; the automatic backoff will recover.
- **`AUTH ERROR`**: token revoked/expired. Re-run `./tools/provision.sh`.

### External packages

All pinned (a combination verified to work):

| Package | Version |
|---|---|
| m5stack:esp32 (board core) | 3.3.9 |
| M5Unified | 0.2.20 |
| M5GFX | 0.2.27 |
| ArduinoJson | 7.4.3 |

The OAuth URLs, client ID, and User-Agent requirements match the behavior of
Claude Code itself (see comments in `net.cpp` / `tools/oauth_login.py`).

### License

[CC0 1.0 Universal](LICENSE) — public domain dedication. Use, modify, and
redistribute freely, no attribution required.

---

## 日本語

M5Stack **StopWatch**（ESP32-S3, 466×466 円形AMOLED）を、**Claude 使用量メーター**に
するファームウェア。Claude Code の `/usage` 画面と同じデータ
（現在セッション / 週間全モデル / 週間モデル別）を 3本の同心リングで常時表示する。

**完全スタンドアロン**: ホスト側の常駐アプリや BLE 連携は不要。デバイス自身が
WiFi で Anthropic の使用量エンドポイントを 10分ごとにポーリングする。

写真のデスクスタンド（3Dプリント）は
[Thingiverse: thing:7401040](https://www.thingiverse.com/thing:7401040)
でデータを公開している。

```
外周リング = SESSION（5時間ローリングウィンドウ）
中間リング = WEEK（週間・全モデル）
内周リング = モデル別週間（Fable / Opus など、アカウントが返すものを自動検出）
中央       = セッション% + リセットまでの残り時間
下部       = 週間/モデル別の数値行、最終更新時刻
色         = 緑(<60%) → 黄(<80%) → 橙(<95%) → 赤
```

### 必要なもの

- M5Stack StopWatch（ESP32-S3R8, 16MB Flash / 8MB Octal PSRAM）
- 2.4GHz WiFi
- Claude のサブスクリプション（Pro / Max 等、`/usage` が見えるアカウント）
- macOS + [Arduino IDE 2.x](https://www.arduino.cc/en/software) または `arduino-cli`
  （ビルドスクリプトは macOS 前提。他OSでも `tools/common.sh` の FQBN を使えば
  arduino-cli で同等にビルド可能）。Apple Silicon で Rosetta 無しでもビルド可。

### セットアップ

```bash
# 1) Arduino のスケッチブックにクローン
cd ~/Documents/Arduino
git clone <this-repo> m5stack-claude-meter
cd m5stack-claude-meter

# 2) 依存を導入（ボードコア m5stack:esp32 3.3.9 / M5Unified 0.2.20 /
#    M5GFX 0.2.27 / ArduinoJson 7.4.3 を固定バージョンでインストール。再実行可）
./tools/setup.sh

# 3) ビルド
./tools/build.sh

# 4) USB で StopWatch を接続して書き込み
./tools/flash.sh

# 5) 初期設定（WiFi + Claude 認証。下記参照）
./tools/provision.sh
```

ライブラリのバージョンは動作検証済みの組み合わせで固定している。

### 初期設定（プロビジョニング）

`./tools/provision.sh` が WiFi 情報の入力と Claude の認証をまとめて行い、
USB シリアル経由でデバイスに書き込む。

既定では**このメーター専用の OAuth セッションを新規発行**する（`claude login` と
同じ PKCE フロー）:

1. WiFi の SSID / パスワードを入力
2. 表示された URL をブラウザで開き、Claude アカウントで承認
3. コールバックページに表示される `xxxx#yyyy` 形式のコードをターミナルに貼り付け
4. トークン検証（実際の使用量 JSON が表示される）→ デバイスへ書き込み → 数秒でリング表示

専用セッションなので、デバイス側のトークンリフレッシュが**手元の Claude Code の
ログインに影響することはない**。

その他のオプション:

| オプション | 動作 |
|---|---|
| `--token-stdin` | 手持ちの OAuth アクセストークンを直接貼り付ける（リフレッシュ不可なので期限切れまで） |
| `--keychain` | macOS Keychain の Claude Code 認証情報（`claudeAiOauth`）を流用する。**リフレッシュトークンのローテーションで Claude Code 側のセッションと競合する可能性があるため非推奨** |
| `--no-refresh` | リフレッシュトークンを書き込まない（アクセストークンの期限切れで停止） |
| `--ssid <name>` | SSID をコマンドラインで指定 |

### 操作

| 操作 | 動作 |
|---|---|
| KEY1 / 画面タップ | 今すぐ更新（最短30秒間隔） |
| KEY2 | 輝度切り替え（80→140→200→40） |

### シリアルコマンド（115200bps）

`./tools/monitor.sh` でログ閲覧。メンテナンスコマンド:

| コマンド | 動作 |
|---|---|
| `CMINFO` | 設定状態の確認（トークン等の秘密情報は出力しない） |
| `CMPOLL` | 即時ポーリング（`[net] usage keys:` / `[net] limits:` に生レスポンスの概要が出る） |
| `CMCLR` | 設定を全消去（未設定状態に戻る） |
| `CMCFG {json}` | 手動プロビジョニング（`tools/provision.sh` が内部で使用） |

### セキュリティ上の注意

- 認証トークンはデバイスのフラッシュ（NVS）に**平文で**保存される。
  **デバイス自体が資格情報**になるので、紛失・譲渡時は
  [claude.ai/settings/claude-code](https://claude.ai/settings/claude-code) から
  該当セッションを Revoke すること。
- このファームウェアが行うのは使用量エンドポイントの GET とトークンリフレッシュ
  のみだが、トークン自体のスコープはそれより広い。扱いはパスワード相当で。
- TLS はルート CA ピン留め（`certs.h`: GTS Root R1/R4, GlobalSign Root CA,
  ISRG Root X1）。証明書チェーンが将来変わった場合は `certs.h` の更新が必要。

### 制約・既知の事項

- **非公式 API に依存**（`api.anthropic.com/api/oauth/usage`）。Anthropic 側の
  変更でフィールド名や認証要件が変わる可能性がある。
  - モデル別リングはレスポンスの `limits` 配列（`scope.model.display_name`）を
    最優先で拾い、`seven_day_*` キーへフォールバックするため、モデル世代の
    変化にはある程度追従する。
  - 実際のレスポンスは `CMPOLL`（上記）で確認できる。
- 使用量エンドポイントはレート制限が厳しい。ポーリングは10分間隔+429時自動
  バックオフにしているが、**同じアカウントを複数のデバイスやツールで高頻度
  ポーリングしない**こと。
- 常時点灯 + 定期的な WiFi/TLS 通信のため **USB 給電前提**（バッテリー単体では
  数時間）。
- AMOLED 焼き付き対策として文字表示を10分周期で±2pxずらし、既定輝度を低め
  （80/255）にしている。据え置きなら KEY2 で最低輝度まで下げるのを推奨。

### トラブルシューティング

- **書き込みで `Failed to connect` になる**: 既存ファームが USB-OTG (TinyUSB)
  モードの場合は初回のみアップロードモードの指定が必要:
  `bash -c 'source tools/common.sh && "$ACLI" --config-file "$CLI_CONFIG" upload --fqbn "$FQBN,UploadMode=cdc" --port "$(detect_port)" --input-dir "$CMETER_ROOT/.build" "$CMETER_ROOT"'`
  それでも入らない場合は BOOT ボタンを押しながらリセットで ROM ダウンロード
  モードに入れてから書き込む。
- **プロビジョニングが `no reply`**: 本ファームが起動しているか確認
  （`./tools/monitor.sh`）。書き込み直後は USB の再列挙に数秒かかる。
- **`rate limited (429)` が続く**: 他のツールが同じアカウントをポーリング
  していないか確認。自動バックオフで回復を待つ。
- **`AUTH ERROR`**: トークン失効。`./tools/provision.sh` を再実行。

### 外部パッケージ

すべて固定バージョン（動作検証済みの組み合わせ）:

| パッケージ | バージョン |
|---|---|
| m5stack:esp32 (board core) | 3.3.9 |
| M5Unified | 0.2.20 |
| M5GFX | 0.2.27 |
| ArduinoJson | 7.4.3 |

OAuth 関連の URL・クライアント ID・User-Agent 要件は Claude Code 本体の挙動に
合わせている（`net.cpp` / `tools/oauth_login.py` のコメント参照）。

### ライセンス

[CC0 1.0 Universal](LICENSE) — パブリックドメイン相当。表示義務なく自由に利用・改変・再配布可。
