Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Native multi-controller unit tests
run: >-
cc -std=c11 -Wall -Wextra -Werror -pedantic
-Ifirmware/esp32-c3/main/include
firmware/esp32-c3/main/src/multi_controller.c
firmware/esp32-c3/test/native_multi_controller.c
-o /tmp/multi-controller-test && /tmp/multi-controller-test
- uses: astral-sh/setup-uv@v6
with:
version: 0.9.18
Expand Down
35 changes: 27 additions & 8 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

ESP32-C3を使った実験的なリモートコントローラーです。ブラウザの入力を
ローカルのNode.jsブリッジへ送り、USB Serial/JTAG経由でESP32-C3へ転送し、
ESP32-C3がBluetooth LEコントローラーとしてNintendo Switch 2へ接続します。
ESP32-C3が3つの独立したBluetooth LEコントローラーとしてNintendo Switch 2へ
接続します。

> Nintendoとは無関係の非公式コミュニティプロジェクトです。システム更新に
> よってコントローラー互換性が変わる可能性があります。
Expand All @@ -22,7 +23,7 @@ ESP32-C3がBluetooth LEコントローラーとしてNintendo Switch 2へ接続
v
ESP32-C3
|
| Bluetooth LE
| 3つのBLE ID / 接続
v
Nintendo Switch 2

Expand Down Expand Up @@ -91,18 +92,26 @@ npm run start:host
シリアル再接続、デジタル入力エッジの保持、ページ切断時のニュートラル送信を
行います。

3枚のコントローラーカードで、ローカル入力の送り先と各BLE接続の状態を個別に
確認できます。リモート参加者へ割り当てたカードはローカル側でロックされるため、
同じ仮想コントローラーを2人が同時操作することはありません。

## ペアリング

1. いずれかのプロファイルを書き込み、データ通信対応USBケーブルでESP32-C3を
接続し直します。
2. ホストアプリを起動し、ローカルURLを開きます。
3. Switch 2でコントローラーのペアリング画面を開きます。
4. エミュレートされたコントローラーが表示されるまで、画面上または割り当て済みの
**L**と**R**を押し、Switch 2側で登録を完了します。
5. リモート用URLを発行する前に、ローカルでボタンとスティックを確認します。
4. ブラウザで**コントローラー1**を選択し、画面上または割り当て済みの**L**と
**R**を押してSwitch 2側で登録を完了します。
5. **コントローラー2**と**コントローラー3**でも繰り返します。各カードの状態は
ペアリング中から接続済み/準備完了へ個別に変化します。
6. リモート用URLを発行する前に、全スロットのボタンとスティックを確認します。

ペアリング情報はESP32のフラッシュへ保存されます。シリアルケーブルを抜く前に
ホストページを閉じ、ニュートラル復帰処理が動作する状態にしてください。
3つのBLE IDはそれぞれ異なるアドレスを使い、NimBLEの相手アドレス単位のボンド
ストアに合わせて1つの永続LTKを共有します。ペアリング情報はESP32のフラッシュへ
保存されます。シリアルケーブルを抜く前にホストページを閉じ、ニュートラル復帰
処理が動作する状態にしてください。

## リモート接続

Expand All @@ -122,7 +131,10 @@ npm run deploy
デプロイ手順は[services/signaling/README.md](services/signaling/README.md)を参照して
ください。TURN認証情報はコミットせず、Wrangler secretsへ登録します。Workerは
静的assets、`ROOMS`というDurable Object binding、任意の`TURN_KEY_ID` /
`TURN_KEY_API_TOKEN` secretsを使用します。デプロイ後も操作入力はP2Pで流れます。
`TURN_KEY_API_TOKEN` secretsを使用します。操作入力はWebRTC DataChannelを優先し、
P2Pが利用できない場合またはリレー固定モードではルーム経由へ切り替わります。
最初の3人には空いているコントローラースロットが自動割り当てされ、4人目以降は
ロビーで待機します。ホストは参加者一覧からスロットを個別に解放・再割り当てできます。

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

Expand All @@ -146,6 +158,10 @@ npm run deploy
```sh
npm test
npm run check:signaling
cc -std=c11 -Wall -Wextra -Werror -pedantic -Ifirmware/esp32-c3/main/include \
firmware/esp32-c3/main/src/multi_controller.c \
firmware/esp32-c3/test/native_multi_controller.c \
-o /tmp/multi-controller-test && /tmp/multi-controller-test
uv run --frozen python scripts/check_public_tree.py
```

Expand All @@ -157,6 +173,9 @@ CIでは3 OSのホストテストと、Linux上で両ファームウェアをビ
- ファームウェアはホスト入力が1.2秒途絶えるとキューを破棄してニュートラルへ戻します。
- ホストは操作ページ切断時にニュートラル状態を送ります。
- BLEキュー停止や通知失敗には時間制限付きの復旧処理があります。
- 3接続はESP32-C3の無線とメモリプールを共有します。コンソールやESP-IDFの更新後は
必ず3台を同時に実機検証してください。1接続の成功だけでは3接続時のタイミング安定性を
保証できません。
- 非標準の5 ms BLE間隔を利用するため、ESP32-C3対応は実験的です。

README用メディアは`docs/assets`へ置き、未圧縮動画はGitへコミットしません。
Expand Down
38 changes: 28 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

An experimental remote controller built around an ESP32-C3. A browser sends
controller state to a local Node.js bridge, the bridge writes compact EasyCon
frames over USB Serial/JTAG, and the ESP32-C3 presents the controller to a
Nintendo Switch 2 over Bluetooth LE.
frames over USB Serial/JTAG, and one ESP32-C3 presents three independent
controller identities to a Nintendo Switch 2 over Bluetooth LE.

> This is an unofficial community project and is not affiliated with or
> endorsed by Nintendo. Console updates may change controller compatibility.
Expand All @@ -23,7 +23,7 @@ remote browser -- WebRTC DataChannel --> host browser
v
ESP32-C3
|
| Bluetooth LE
| 3 BLE identities / links
v
Nintendo Switch 2

Expand Down Expand Up @@ -93,19 +93,26 @@ Open `http://127.0.0.1:8787`. The bridge accepts local WebSocket clients only,
reconnects the configured serial port, preserves digital button edges, and
sends neutral input when the controller page disconnects.

The three controller cards select the local input destination and show each
BLE link independently. A remotely assigned card is locked locally so two
input sources cannot fight over the same virtual controller.

## Pairing

1. Flash either firmware profile and reconnect the ESP32-C3 with a USB data
cable.
2. Start the host application and open its local URL.
3. Open the controller pairing screen on the Switch 2.
4. Press the on-screen or mapped **L** and **R** controls until the emulated
controller appears, then complete pairing on the console.
5. Confirm buttons and sticks locally before creating a remote guest link.
4. Select **Controller 1** in the browser, press the on-screen or mapped **L**
and **R** controls, and complete pairing on the console.
5. Repeat for **Controller 2** and **Controller 3**. The status cards change
independently from pairing to connected/ready.
6. Confirm buttons and sticks on every slot before creating a remote guest link.

Pairing data is saved in ESP32 flash. Keep the board powered and close the host
page before disconnecting the serial cable so the neutral-state safety path can
run.
The three BLE identities use distinct addresses and one shared persisted LTK,
which matches NimBLE's peer-keyed bond store. Pairing data is saved in ESP32
flash. Keep the board powered and close the host page before disconnecting the
serial cable so the neutral-state safety path can run.

## Remote access

Expand All @@ -126,7 +133,11 @@ For deployment, see [services/signaling/README.md](services/signaling/README.md)
TURN credentials must be stored with Wrangler secrets rather than committed to
the repository. The Worker configuration provides static assets, one Durable
Object binding named `ROOMS`, and optional `TURN_KEY_ID` / `TURN_KEY_API_TOKEN`
secrets. Controller input remains peer-to-peer even when signaling is deployed.
secrets. Controller input prefers a direct WebRTC DataChannel and falls back to
the room relay when P2P is unavailable or relay mode is selected.
The first three guests are assigned to the first three free controller slots;
additional guests wait in the lobby. The host can release or reassign each slot
independently from the participant list.

## Troubleshooting

Expand All @@ -150,6 +161,10 @@ secrets. Controller input remains peer-to-peer even when signaling is deployed.
```sh
npm test
npm run check:signaling
cc -std=c11 -Wall -Wextra -Werror -pedantic -Ifirmware/esp32-c3/main/include \
firmware/esp32-c3/main/src/multi_controller.c \
firmware/esp32-c3/test/native_multi_controller.c \
-o /tmp/multi-controller-test && /tmp/multi-controller-test
uv run --frozen python scripts/check_public_tree.py
```

Expand All @@ -162,6 +177,9 @@ still be checked on a physical console before publishing a release binary.
- Firmware clears queued input after 1.2 seconds without a fresh host frame.
- The host sends neutral state when its active controller page disconnects.
- BLE queue stalls and failed notifications have bounded recovery paths.
- Three simultaneous links share the ESP32-C3 radio and memory pool. Validate
all three together after console or ESP-IDF updates; one-link success does not
establish three-link timing stability.
- ESP32-C3 support uses a non-standard 5 ms BLE interval and remains experimental.

Media intended for the README belongs in `docs/assets`; keep raw video outside
Expand Down
125 changes: 73 additions & 52 deletions apps/host/cloudflare-signaling.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ if (!base?.startsWith("https://")) throw new Error("SIGNAL_BASE is required");
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const code = Array.from(crypto.randomBytes(10), (byte) => alphabet[byte % alphabet.length]).join("");
const secret = crypto.randomBytes(16).toString("hex");
const guest1Id = crypto.randomBytes(8).toString("hex"), guest2Id = crypto.randomBytes(8).toString("hex");
const guestIds = Array.from({ length: 4 }, () => crypto.randomBytes(8).toString("hex"));

const websocketUrl = (params) => {
const url = new URL(`/api/room/${code}`, base); url.protocol = "wss:";
Expand Down Expand Up @@ -46,68 +46,89 @@ class Inbox {
}
}

const input = (seq, hat, reliability = {}) => JSON.stringify({ type: "input", seq, state: { buttons: 0, hat, lx: 128, ly: 128, rx: 128, ry: 128 }, ...reliability });
const input = (seq, hat, reliability = {}) => JSON.stringify({
type: "input", seq,
state: { buttons: 0, hat, lx: 128, ly: 128, rx: 128, ry: 128 },
...reliability,
});
const host = new WebSocket(websocketUrl({ role: "host", secret }));
const hostInbox = new Inbox(host); await opened(host);
const ice = await fetch(new URL(`/api/ice/${code}`, base));
if (!ice.ok || !Array.isArray((await ice.json()).iceServers)) throw new Error("ICE endpoint failed");

let guest1 = new WebSocket(websocketUrl({ role: "guest", id: guest1Id, name: "Alice" }));
let guest1Inbox = new Inbox(guest1); await opened(guest1);
await guest1Inbox.until((m) => m.type === "control" && m.active === true);
await hostInbox.until((m) => m.type === "peer-ready" && m.guestId === guest1Id);
const names = ["Alice", "Bob", "Carol", "Dave"];
const guests = [];
const guestInboxes = [];
for (let index = 0; index < names.length; index += 1) {
const guest = new WebSocket(websocketUrl({ role: "guest", id: guestIds[index], name: names[index] }));
const inbox = new Inbox(guest);
await opened(guest);
const expectedSlot = index < 3 ? index : null;
await inbox.until((message) => message.type === "control" &&
message.active === (expectedSlot !== null) && message.slot === expectedSlot);
if (expectedSlot !== null) {
await hostInbox.until((message) => message.type === "peer-ready" &&
message.guestId === guestIds[index] && message.slot === expectedSlot);
}
guests.push(guest);
guestInboxes.push(inbox);
}

const replacedGuestClosed = closed(guest1);
const reconnectedGuest1 = new WebSocket(websocketUrl({ role: "guest", id: guest1Id, name: "Alice" }));
const reconnectedGuest1Inbox = new Inbox(reconnectedGuest1); await opened(reconnectedGuest1);
await reconnectedGuest1Inbox.until((m) => m.type === "control" && m.active === true);
await hostInbox.until((m) => m.type === "peer-ready" && m.guestId === guest1Id);
const replacedGuestClosed = closed(guests[0]);
const reconnectedGuest = new WebSocket(websocketUrl({ role: "guest", id: guestIds[0], name: names[0] }));
const reconnectedInbox = new Inbox(reconnectedGuest); await opened(reconnectedGuest);
await reconnectedInbox.until((message) => message.type === "control" && message.active && message.slot === 0);
await hostInbox.until((message) => message.type === "peer-ready" && message.guestId === guestIds[0] && message.slot === 0);
const replacedGuest = await replacedGuestClosed;
if (replacedGuest.status !== 4001) throw new Error("active controller reconnect did not replace the stale socket");
guest1 = reconnectedGuest1;
guest1Inbox = reconnectedGuest1Inbox;
const guest2 = new WebSocket(websocketUrl({ role: "guest", id: guest2Id, name: "Bob" }));
const guest2Inbox = new Inbox(guest2); await opened(guest2);
await guest2Inbox.until((m) => m.type === "control" && m.active === false);
const joined = await hostInbox.until((m) => m.type === "participants" &&
m.participants.some((p) => p.name === "Alice") && m.participants.some((p) => p.name === "Bob"));
if (replacedGuest.status !== 4001) throw new Error("controller reconnect did not replace the stale socket");
guests[0] = reconnectedGuest;
guestInboxes[0] = reconnectedInbox;

guest2.send(input(0, 2));
await hostInbox.expectNone((m) => m.type === "input");
guest1.send(input(0, 8, { sid: guest1Id, edges: [[0, 2, 8, 128, 128, 128, 128], [1, 0, 8, 128, 128, 128, 128]] }));
const firstInput = await hostInbox.until((m) => m.type === "input");
if (firstInput.state.hat !== 8) throw new Error("first controller relay failed");
if (firstInput.sid !== guest1Id || firstInput.edges?.length !== 2) throw new Error("digital edge history was not relayed");
host.send(JSON.stringify({ type: "input-ack", seq: firstInput.seq, edgeAck: 1 }));
await guest1Inbox.until((m) => m.type === "input-ack" && m.seq === firstInput.seq && m.edgeAck === 1);
host.send(JSON.stringify({ type: "rumble", seq: 1, strong: 0.75, weak: 0.25, duration: 40 }));
await guest1Inbox.until((m) => m.type === "rumble" && m.seq === 1 && m.strong === 0.75);
await guest2Inbox.expectNone((m) => m.type === "rumble");
for (let slot = 0; slot < 3; slot += 1) {
guests[slot].send(input(slot, slot * 2, slot === 0 ? {
sid: guestIds[slot],
edges: [[0, 2, 8, 128, 128, 128, 128], [1, 0, 8, 128, 128, 128, 128]],
} : {}));
}
const inputs = new Map();
while (inputs.size < 3) {
const message = await hostInbox.until((candidate) => candidate.type === "input");
inputs.set(message.slot, message);
}
for (let slot = 0; slot < 3; slot += 1) {
if (inputs.get(slot)?.guestId !== guestIds[slot]) throw new Error(`slot ${slot} relay routed to the wrong guest`);
}
if (inputs.get(0).edges?.length !== 2) throw new Error("digital edge history was not relayed");

guest2.send(JSON.stringify({ type: "claim" }));
await hostInbox.until((m) => m.type === "peer-ready" && m.guestId === guest2Id);
await guest1Inbox.until((m) => m.type === "control" && m.active === false);
await guest2Inbox.until((m) => m.type === "control" && m.active === true);
guest1.send(input(1, 4));
await hostInbox.expectNone((m) => m.type === "input");
guest2.send(input(1, 2));
const secondInput = await hostInbox.until((m) => m.type === "input");
if (secondInput.state.hat !== 2) throw new Error("controller handoff failed");
host.send(JSON.stringify({ type: "input-ack", seq: secondInput.seq }));
await guest2Inbox.until((m) => m.type === "input-ack" && m.seq === secondInput.seq);
host.send(JSON.stringify({ type: "rumble", seq: 2, strong: 0, weak: 1, duration: 40 }));
await guest2Inbox.until((m) => m.type === "rumble" && m.seq === 2 && m.weak === 1);
guests[3].send(input(9, 6));
await hostInbox.expectNone((message) => message.type === "input" && message.guestId === guestIds[3]);

host.send(JSON.stringify({ type: "input-ack", slot: 1, seq: inputs.get(1).seq, edgeAck: 4 }));
await guestInboxes[1].until((message) => message.type === "input-ack" && message.slot === 1 && message.edgeAck === 4);
for (const inbox of [guestInboxes[0], guestInboxes[2], guestInboxes[3]]) {
await inbox.expectNone((message) => message.type === "input-ack" && message.slot === 1);
}

host.send(JSON.stringify({ type: "rumble", slot: 2, seq: 1, strong: 0.75, weak: 0.25, duration: 40 }));
await guestInboxes[2].until((message) => message.type === "rumble" && message.slot === 2 && message.seq === 1);
for (const inbox of [guestInboxes[0], guestInboxes[1], guestInboxes[3]]) {
await inbox.expectNone((message) => message.type === "rumble" && message.slot === 2);
}

host.send(JSON.stringify({ type: "release" }));
await hostInbox.until((m) => m.type === "control-released" && m.guestId === guest2Id);
await guest2Inbox.until((m) => m.type === "control" && m.active === false);
guest2.send(input(2, 6));
await hostInbox.expectNone((m) => m.type === "input");
host.send(JSON.stringify({ type: "release", slot: 1 }));
await hostInbox.until((message) => message.type === "control-released" && message.guestId === guestIds[1] && message.slot === 1);
await guestInboxes[1].until((message) => message.type === "control" && message.active === false);
guests[3].send(JSON.stringify({ type: "claim", slot: 1 }));
await hostInbox.until((message) => message.type === "peer-ready" && message.guestId === guestIds[3] && message.slot === 1);
await guestInboxes[3].until((message) => message.type === "control" && message.active && message.slot === 1);
guests[3].send(input(10, 6));
const claimedInput = await hostInbox.until((message) => message.type === "input" && message.guestId === guestIds[3]);
if (claimedInput.slot !== 1 || claimedInput.state.hat !== 6) throw new Error("released slot claim failed");

const guest1Closed = closed(guest1), guest2Closed = closed(guest2);
const closePromises = guests.map(closed);
host.send(JSON.stringify({ type: "revoke" }));
const [revoked1, revoked2] = await Promise.all([guest1Closed, guest2Closed]);
if (revoked1.status !== 4002 || revoked2.status !== 4002) throw new Error("session revoke failed");
const revoked = await Promise.all(closePromises);
if (revoked.some(({ status }) => status !== 4002)) throw new Error("session revoke failed");
host.terminate();
console.log("CLOUDFLARE_MULTI_GUEST_E2E_OK=1");
console.log("CLOUDFLARE_THREE_CONTROLLER_E2E_OK=1");
process.exit(0);
Loading
Loading