From e77d3ed5598e9373d40dcf30a0727cdcb619fe49 Mon Sep 17 00:00:00 2001 From: y52en <61645319+y52en@users.noreply.github.com> Date: Thu, 20 Aug 2026 13:38:01 +0900 Subject: [PATCH 1/2] feat: support three simultaneous controllers --- .github/workflows/ci.yml | 7 + README.ja.md | 35 +- README.md | 38 +- apps/host/cloudflare-signaling.test.mjs | 125 ++-- apps/host/controller-assignments.test.mjs | 60 ++ apps/host/controller-slots.mjs | 48 ++ apps/host/controller-slots.test.mjs | 41 ++ apps/host/easycon.mjs | 14 +- apps/host/easycon.test.mjs | 21 +- apps/host/esp32-status.mjs | 45 ++ apps/host/esp32-status.test.mjs | 43 ++ apps/host/local-control-origin.mjs | 18 + apps/host/local-control-origin.test.mjs | 16 + apps/host/package.json | 2 +- apps/host/public-ui.test.mjs | 27 + apps/host/public/app.js | 595 +++++++++++++----- apps/host/public/controller-slots.js | 18 + apps/host/public/controller-slots.test.mjs | 31 + apps/host/public/index.html | 53 +- apps/host/public/style.css | 33 +- apps/host/public/webrtc-ice.js | 13 + apps/host/public/webrtc-ice.test.mjs | 39 ++ apps/host/rumble.mjs | 20 +- apps/host/rumble.test.mjs | 10 +- apps/host/server.mjs | 158 +++-- firmware/esp32-c3/README.md | 26 +- firmware/esp32-c3/main/include/console.h | 3 +- .../main/include/controller/controller.h | 14 +- .../main/include/controller/hid_controller.h | 14 +- firmware/esp32-c3/main/include/device.h | 20 +- .../esp32-c3/main/include/multi_controller.h | 33 + firmware/esp32-c3/main/include/ns2_codec.h | 3 +- firmware/esp32-c3/main/include/pro2.h | 2 +- .../esp32-c3/main/include/rumble_feedback.h | 2 +- .../esp32-c3/main/include/runtime_status.h | 12 +- firmware/esp32-c3/main/main.c | 15 +- .../esp32-c3/main/src/controller/controller.c | 36 +- .../main/src/controller/hid_controller.c | 215 +++++-- firmware/esp32-c3/main/src/device.c | 218 ++++--- .../main/src/display/status_display_gc9a01.c | 6 +- firmware/esp32-c3/main/src/gap.c | 211 ++++--- firmware/esp32-c3/main/src/gatt.c | 9 +- firmware/esp32-c3/main/src/multi_controller.c | 33 + firmware/esp32-c3/main/src/ns2.c | 12 +- firmware/esp32-c3/main/src/ns2_codec.c | 35 +- firmware/esp32-c3/main/src/pro2.c | 24 +- .../src/protocol/easycon/easycon_parser_hid.c | 22 +- firmware/esp32-c3/main/src/rumble_feedback.c | 149 ++--- firmware/esp32-c3/main/src/runtime_status.c | 64 +- firmware/esp32-c3/sdkconfig.defaults | 9 + .../esp32-c3/test/native_multi_controller.c | 61 ++ services/signaling/README.md | 12 +- .../signaling/src/controller-assignments.js | 80 +++ services/signaling/src/worker.js | 203 ++++-- 54 files changed, 2250 insertions(+), 803 deletions(-) create mode 100644 apps/host/controller-assignments.test.mjs create mode 100644 apps/host/controller-slots.mjs create mode 100644 apps/host/controller-slots.test.mjs create mode 100644 apps/host/esp32-status.mjs create mode 100644 apps/host/esp32-status.test.mjs create mode 100644 apps/host/local-control-origin.mjs create mode 100644 apps/host/local-control-origin.test.mjs create mode 100644 apps/host/public-ui.test.mjs create mode 100644 apps/host/public/controller-slots.js create mode 100644 apps/host/public/controller-slots.test.mjs create mode 100644 apps/host/public/webrtc-ice.js create mode 100644 apps/host/public/webrtc-ice.test.mjs create mode 100644 firmware/esp32-c3/main/include/multi_controller.h create mode 100644 firmware/esp32-c3/main/src/multi_controller.c create mode 100644 firmware/esp32-c3/test/native_multi_controller.c create mode 100644 services/signaling/src/controller-assignments.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0493923..f30708e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/README.ja.md b/README.ja.md index 471dd80..22963be 100644 --- a/README.ja.md +++ b/README.ja.md @@ -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とは無関係の非公式コミュニティプロジェクトです。システム更新に > よってコントローラー互換性が変わる可能性があります。 @@ -22,7 +23,7 @@ ESP32-C3がBluetooth LEコントローラーとしてNintendo Switch 2へ接続 v ESP32-C3 | - | Bluetooth LE + | 3つのBLE ID / 接続 v Nintendo Switch 2 @@ -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のフラッシュへ +保存されます。シリアルケーブルを抜く前にホストページを閉じ、ニュートラル復帰 +処理が動作する状態にしてください。 ## リモート接続 @@ -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人目以降は +ロビーで待機します。ホストは参加者一覧からスロットを個別に解放・再割り当てできます。 ## トラブルシューティング @@ -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 ``` @@ -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へコミットしません。 diff --git a/README.md b/README.md index 29d22bf..725e6c1 100644 --- a/README.md +++ b/README.md @@ -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. @@ -23,7 +23,7 @@ remote browser -- WebRTC DataChannel --> host browser v ESP32-C3 | - | Bluetooth LE + | 3 BLE identities / links v Nintendo Switch 2 @@ -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 @@ -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 @@ -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 ``` @@ -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 diff --git a/apps/host/cloudflare-signaling.test.mjs b/apps/host/cloudflare-signaling.test.mjs index 78fbd79..22b7c25 100644 --- a/apps/host/cloudflare-signaling.test.mjs +++ b/apps/host/cloudflare-signaling.test.mjs @@ -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:"; @@ -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); diff --git a/apps/host/controller-assignments.test.mjs b/apps/host/controller-assignments.test.mjs new file mode 100644 index 0000000..7936fe7 --- /dev/null +++ b/apps/host/controller-assignments.test.mjs @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + CONTROLLER_SLOT_COUNT, + assignGuest, + firstAvailableSlot, + guestForSlot, + normalizeAssignments, + releaseGuest, + releaseSlot, + slotForClaim, + slotForGuest, +} from "../../services/signaling/src/controller-assignments.js"; + +const alice = "aaaaaaaaaaaaaaaa"; +const bob = "bbbbbbbbbbbbbbbb"; +const carol = "cccccccccccccccc"; + +test("maintains one guest per each of three controller slots", () => { + assert.equal(CONTROLLER_SLOT_COUNT, 3); + let assignments = {}; + for (const guestId of [alice, bob, carol]) { + const slot = firstAvailableSlot(assignments); + ({ assignments } = assignGuest(assignments, guestId, slot)); + } + assert.deepEqual(assignments, { [alice]: 0, [bob]: 1, [carol]: 2 }); + assert.equal(firstAvailableSlot(assignments), null); + assert.equal(guestForSlot(assignments, 1), bob); + assert.equal(slotForGuest(assignments, carol), 2); +}); + +test("rejects accidental displacement but permits an explicit host handoff", () => { + const initial = { [alice]: 0, [bob]: 1 }; + assert.deepEqual(assignGuest(initial, bob, 0).assignments, initial); + const moved = assignGuest(initial, bob, 0, { displace: true }); + assert.deepEqual(moved.assignments, { [bob]: 0 }); + assert.equal(moved.displacedGuestId, alice); +}); + +test("releases by controller or guest and drops malformed persisted data", () => { + const normalized = normalizeAssignments({ [alice]: 0, [bob]: 0, invalid: 2, [carol]: 7 }); + assert.deepEqual(normalized, { [alice]: 0 }); + assert.deepEqual(releaseSlot({ [alice]: 0, [bob]: 1 }, 0), { + assignments: { [bob]: 1 }, guestId: alice, + }); + assert.deepEqual(releaseGuest({ [alice]: 0, [bob]: 1 }, bob), { + assignments: { [alice]: 0 }, slot: 1, + }); +}); + +test("retains an active guest's slot when no different slot is requested", () => { + const assignments = { [alice]: 0, [bob]: 1 }; + assert.equal(slotForGuest(assignments, alice), 0); + assert.equal(firstAvailableSlot(assignments), 2); + assert.equal(slotForClaim(assignments, alice), 0); + assert.equal(slotForClaim(assignments, alice, 2), 2); + assert.equal(slotForClaim(assignments, alice, 1), 0); + assert.equal(slotForClaim(assignments, carol, 1), null); + assert.deepEqual(assignGuest(assignments, alice, 0).assignments, assignments); +}); diff --git a/apps/host/controller-slots.mjs b/apps/host/controller-slots.mjs new file mode 100644 index 0000000..7b7f089 --- /dev/null +++ b/apps/host/controller-slots.mjs @@ -0,0 +1,48 @@ +import { NEUTRAL_STATE, sanitizeState } from "./controller-state.mjs"; + +export const CONTROLLER_SLOT_COUNT = 3; + +export function sanitizeControllerSlot(value, fallback = null) { + const slot = Number(value); + return Number.isInteger(slot) && slot >= 0 && slot < CONTROLLER_SLOT_COUNT + ? slot + : fallback; +} + +export function controllerSlotLabel(slot) { + const value = sanitizeControllerSlot(slot); + return value === null ? "待機中" : `コントローラー ${value + 1}`; +} + +export function createControllerStates() { + return Array.from({ length: CONTROLLER_SLOT_COUNT }, () => ({ ...NEUTRAL_STATE })); +} + +export function sanitizeSlottedState(message = {}) { + const slot = sanitizeControllerSlot(message.slot); + if (slot === null) return null; + return { slot, state: sanitizeState(message.state) }; +} + +export function firstAvailableSlot(assignments, preferred = null) { + const occupied = new Set(Object.values(assignments ?? {}).filter(Number.isInteger)); + const requested = sanitizeControllerSlot(preferred); + if (requested !== null && !occupied.has(requested)) return requested; + for (let slot = 0; slot < CONTROLLER_SLOT_COUNT; slot += 1) { + if (!occupied.has(slot)) return slot; + } + return null; +} + +export function normalizeAssignments(value = {}) { + const result = {}; + const usedSlots = new Set(); + for (const [guestId, rawSlot] of Object.entries(value ?? {})) { + if (!/^[0-9a-f]{16}$/.test(guestId)) continue; + const slot = sanitizeControllerSlot(rawSlot); + if (slot === null || usedSlots.has(slot)) continue; + result[guestId] = slot; + usedSlots.add(slot); + } + return result; +} diff --git a/apps/host/controller-slots.test.mjs b/apps/host/controller-slots.test.mjs new file mode 100644 index 0000000..c3e82c5 --- /dev/null +++ b/apps/host/controller-slots.test.mjs @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + CONTROLLER_SLOT_COUNT, + controllerSlotLabel, + createControllerStates, + firstAvailableSlot, + normalizeAssignments, + sanitizeControllerSlot, + sanitizeSlottedState, +} from "./controller-slots.mjs"; + +test("accepts exactly the three supported controller slots", () => { + assert.equal(CONTROLLER_SLOT_COUNT, 3); + assert.deepEqual([0, 1, 2].map(sanitizeControllerSlot), [0, 1, 2]); + assert.equal(sanitizeControllerSlot(3), null); + assert.equal(sanitizeControllerSlot("1"), 1); + assert.equal(controllerSlotLabel(2), "コントローラー 3"); +}); + +test("creates independent neutral states and sanitizes slotted input", () => { + const states = createControllerStates(); + states[0].buttons = 1; + assert.equal(states[1].buttons, 0); + assert.deepEqual(sanitizeSlottedState({ slot: 2, state: { buttons: 8, lx: 999 } }), { + slot: 2, + state: { buttons: 8, hat: 8, lx: 255, ly: 128, rx: 128, ry: 128 }, + }); + assert.equal(sanitizeSlottedState({ slot: 7 }), null); +}); + +test("normalizes unique assignments and picks an available slot", () => { + const assignments = normalizeAssignments({ + "0123456789abcdef": 1, + "fedcba9876543210": 1, + invalid: 2, + }); + assert.deepEqual(assignments, { "0123456789abcdef": 1 }); + assert.equal(firstAvailableSlot(assignments, 2), 2); + assert.equal(firstAvailableSlot({ a: 0, b: 1, c: 2 }), null); +}); diff --git a/apps/host/easycon.mjs b/apps/host/easycon.mjs index ee3f7c7..80b6f3e 100644 --- a/apps/host/easycon.mjs +++ b/apps/host/easycon.mjs @@ -1,8 +1,18 @@ +import { CONTROLLER_SLOT_COUNT } from "./controller-slots.mjs"; + const RAW_SIZE = 7; const ENCODED_SIZE = 8; +export const EASYCON_CONTROLLER_SLOT_COUNT = CONTROLLER_SLOT_COUNT; +export const EASYCON_BUTTON_MASK = 0x3fff; -export function encodeEasyConState(state) { - const buttons = Number(state.buttons) & 0xffff; +export function encodeEasyConState(state, slot = 0) { + if (!Number.isInteger(slot) || slot < 0 || slot >= EASYCON_CONTROLLER_SLOT_COUNT) { + throw new RangeError(`controller slot must be from 0 to ${EASYCON_CONTROLLER_SLOT_COUNT - 1}`); + } + // EasyCon has two unused button bits. Carry the virtual-controller slot in + // those bits so the on-wire frame remains eight bytes and old slot-0 hosts + // remain compatible with the new firmware. + const buttons = (Number(state.buttons) & EASYCON_BUTTON_MASK) | (slot << 14); const raw = Uint8Array.of( buttons >>> 8, buttons, diff --git a/apps/host/easycon.test.mjs b/apps/host/easycon.test.mjs index 6f1523c..a108f23 100644 --- a/apps/host/easycon.test.mjs +++ b/apps/host/easycon.test.mjs @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { encodeEasyConState } from "./easycon.mjs"; +import { + EASYCON_BUTTON_MASK, + encodeEasyConState, +} from "./easycon.mjs"; function decode(frame) { let accumulator = 0; @@ -20,8 +23,20 @@ function decode(frame) { } test("encodes the host state as an EasyCon HID frame", () => { - const frame = encodeEasyConState({ buttons: 0xa55a, hat: 6, lx: 1, ly: 127, rx: 128, ry: 255 }); + const frame = encodeEasyConState({ buttons: 0x255a, hat: 6, lx: 1, ly: 127, rx: 128, ry: 255 }); assert.equal(frame.length, 8); assert.equal(frame[7] & 0x80, 0x80); - assert.deepEqual([...decode(frame)], [0xa5, 0x5a, 6, 1, 127, 128, 255]); + assert.deepEqual([...decode(frame)], [0x25, 0x5a, 6, 1, 127, 128, 255]); +}); + +test("encodes three controller slots without changing the frame size", () => { + for (let slot = 0; slot < 3; slot += 1) { + const raw = decode(encodeEasyConState({ + buttons: 0xffff, hat: 8, lx: 128, ly: 128, rx: 128, ry: 128, + }, slot)); + const taggedButtons = (raw[0] << 8) | raw[1]; + assert.equal(taggedButtons >>> 14, slot); + assert.equal(taggedButtons & EASYCON_BUTTON_MASK, EASYCON_BUTTON_MASK); + } + assert.throws(() => encodeEasyConState({}, 3), /controller slot/); }); diff --git a/apps/host/esp32-status.mjs b/apps/host/esp32-status.mjs new file mode 100644 index 0000000..2a2b532 --- /dev/null +++ b/apps/host/esp32-status.mjs @@ -0,0 +1,45 @@ +import { CONTROLLER_SLOT_COUNT } from "./controller-slots.mjs"; + +export const ESP32_CONTROLLER_SLOT_COUNT = CONTROLLER_SLOT_COUNT; + +export function initialEsp32ControllerStatus(slot) { + return { + slot, + state: "disconnected", + connected: false, + ready: false, + connectionIntervalUnits: null, + disconnectReason: null, + inputLatencyMs: null, + }; +} + +export function parseEsp32ControllerStatus(line, currentControllers) { + const match = /^DS:([0-2]):(advertising|connected|ready|disconnected):(\d+)(?::(\d+))?$/.exec(line); + if (!match) return null; + const slot = Number(match[1]); + const state = match[2]; + const connectionIntervalUnits = Number(match[3]); + const disconnectReason = match[4] === undefined ? null : Number(match[4]); + if (!Number.isInteger(connectionIntervalUnits) || connectionIntervalUnits < 0 || + connectionIntervalUnits > 0xffff || + (disconnectReason !== null && (!Number.isInteger(disconnectReason) || + disconnectReason < 0 || disconnectReason > 0xffff))) return null; + const previous = currentControllers?.[slot] ?? initialEsp32ControllerStatus(slot); + const connected = state === "connected" || state === "ready"; + return { + slot, + controller: { + ...previous, + slot, + state, + connected, + ready: state === "ready", + connectionIntervalUnits: connectionIntervalUnits || null, + disconnectReason, + }, + becameConnected: connected && !previous.connected, + becameDisconnected: state === "disconnected" && previous.connected, + disconnectReason, + }; +} diff --git a/apps/host/esp32-status.test.mjs b/apps/host/esp32-status.test.mjs new file mode 100644 index 0000000..9fb7957 --- /dev/null +++ b/apps/host/esp32-status.test.mjs @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + ESP32_CONTROLLER_SLOT_COUNT, + initialEsp32ControllerStatus, + parseEsp32ControllerStatus, +} from "./esp32-status.mjs"; + +const statuses = () => Array.from( + { length: ESP32_CONTROLLER_SLOT_COUNT }, + (_, slot) => initialEsp32ControllerStatus(slot), +); + +test("tracks three structured BLE statuses without recounting periodic updates", () => { + const controllers = statuses(); + const connected = parseEsp32ControllerStatus("DS:1:connected:4", controllers); + assert.equal(connected.slot, 1); + assert.equal(connected.becameConnected, true); + assert.equal(connected.controller.connectionIntervalUnits, 4); + controllers[1] = connected.controller; + + const ready = parseEsp32ControllerStatus("DS:1:ready:4", controllers); + assert.equal(ready.becameConnected, false); + controllers[1] = ready.controller; + const periodic = parseEsp32ControllerStatus("DS:1:ready:4", controllers); + assert.equal(periodic.becameConnected, false); + assert.equal(periodic.becameDisconnected, false); +}); + +test("records a bounded disconnect reason only on a valid slot line", () => { + const controllers = statuses(); + controllers[2] = { + ...controllers[2], state: "ready", connected: true, ready: true, + }; + const disconnected = parseEsp32ControllerStatus("DS:2:disconnected:0:19", controllers); + assert.equal(disconnected.becameDisconnected, true); + assert.equal(disconnected.disconnectReason, 19); + assert.equal(disconnected.controller.connected, false); + assert.equal(parseEsp32ControllerStatus("DS:3:ready:4", controllers), null); + assert.equal(parseEsp32ControllerStatus("DS:2:ready:65536", controllers), null); + assert.equal(parseEsp32ControllerStatus("DS:2:disconnected:0:65536", controllers), null); + assert.equal(parseEsp32ControllerStatus("unstructured", controllers), null); +}); diff --git a/apps/host/local-control-origin.mjs b/apps/host/local-control-origin.mjs new file mode 100644 index 0000000..b2e6f2f --- /dev/null +++ b/apps/host/local-control-origin.mjs @@ -0,0 +1,18 @@ +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]); + +export function allowedLocalControlOrigin(origin, port) { + // Native diagnostic clients do not send Origin. Browser clients do, so a + // cross-site page cannot drive the loopback WebSocket merely because the + // bridge itself listens on 127.0.0.1. + if (origin === undefined || origin === null || origin === "") return true; + try { + const url = new URL(origin); + const effectivePort = url.port ? Number(url.port) : 80; + return url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname) && + Number.isInteger(port) && effectivePort === port && + !url.username && !url.password && url.pathname === "/" && + !url.search && !url.hash; + } catch { + return false; + } +} diff --git a/apps/host/local-control-origin.test.mjs b/apps/host/local-control-origin.test.mjs new file mode 100644 index 0000000..7ae1365 --- /dev/null +++ b/apps/host/local-control-origin.test.mjs @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { allowedLocalControlOrigin } from "./local-control-origin.mjs"; + +test("accepts the host UI and origin-less native loopback clients", () => { + assert.equal(allowedLocalControlOrigin("http://127.0.0.1:8787", 8787), true); + assert.equal(allowedLocalControlOrigin("http://localhost:8787", 8787), true); + assert.equal(allowedLocalControlOrigin("http://[::1]:8787", 8787), true); + assert.equal(allowedLocalControlOrigin(undefined, 8787), true); +}); + +test("rejects cross-site, mismatched-port, and opaque browser origins", () => { + assert.equal(allowedLocalControlOrigin("https://example.com", 8787), false); + assert.equal(allowedLocalControlOrigin("http://127.0.0.1:9999", 8787), false); + assert.equal(allowedLocalControlOrigin("null", 8787), false); +}); diff --git a/apps/host/package.json b/apps/host/package.json index 92af7c8..23812b4 100644 --- a/apps/host/package.json +++ b/apps/host/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "start": "node server.mjs", - "test": "node --test controller-state.test.mjs config.test.mjs easycon.test.mjs input-reliability.test.mjs keymap.test.mjs gamepad-map.test.mjs transport.test.mjs rumble.test.mjs haptics.test.mjs", + "test": "node --test controller-state.test.mjs controller-slots.test.mjs controller-assignments.test.mjs config.test.mjs easycon.test.mjs esp32-status.test.mjs input-reliability.test.mjs keymap.test.mjs gamepad-map.test.mjs local-control-origin.test.mjs transport.test.mjs rumble.test.mjs haptics.test.mjs public/controller-slots.test.mjs public/webrtc-ice.test.mjs public-ui.test.mjs", "test:cloudflare": "node cloudflare-signaling.test.mjs" }, "dependencies": { diff --git a/apps/host/public-ui.test.mjs b/apps/host/public-ui.test.mjs new file mode 100644 index 0000000..bedcde2 --- /dev/null +++ b/apps/host/public-ui.test.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; + +const here = new URL("./public/", import.meta.url); + +test("renders three accessible controller selectors and assignment controls", async () => { + const html = await readFile(new URL("index.html", here), "utf8"); + const slots = [...html.matchAll(/data-controller-slot="(\d)"/g)].map((match) => Number(match[1])); + const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]); + assert.deepEqual(slots, [0, 1, 2]); + assert.equal(new Set(ids).size, ids.length, "interactive status targets must have unique IDs"); + assert.match(html, /id="controller-target"[^>]*role="status"/); + assert.match(html, /参加者を3台のコントローラーへ個別に割り当て/); + assert.match(html, /
{ + const css = await readFile(new URL("style.css", here), "utf8"); + assert.match(css, /\.slot-card\.selected/); + assert.match(css, /\.slot-card\.assigned/); + assert.match(css, /\.slot-card\.selected\.assigned/); + assert.match(css, /:focus-visible/); + assert.doesNotMatch(css, /#join-session\s*\{[^}]*display:\s*none/); + assert.match(css, /@media \(max-width: 430px\)[\s\S]*\.controller-slots \{ grid-template-columns: 1fr; \}/); +}); diff --git a/apps/host/public/app.js b/apps/host/public/app.js index 5c70a9a..211e017 100644 --- a/apps/host/public/app.js +++ b/apps/host/public/app.js @@ -2,6 +2,14 @@ import { setupKeyboardBindings } from "./keymap.js"; import { gamepadState, setupGamepadBindings } from "./gamepad-map.js"; import { createHapticsController } from "./haptics.js"; import { DigitalEdgeHistory, highestDigitalEdgeSequence } from "./input-reliability.js"; +import { addIceCandidateOrQueue, drainIceCandidates } from "./webrtc-ice.js"; +import { + CONTROLLER_SLOT_COUNT, + controllerSlotLabel, + participantForSlot, + slotIsLocallyAvailable, + validControllerSlot, +} from "./controller-slots.js"; import { DATA_CHANNEL_HIGH_WATER, DATA_CHANNEL_LOW_WATER, @@ -14,11 +22,17 @@ import { transportModeLabel, } from "./transport.js"; const neutral = () => ({ buttons: 0, hat: 8, lx: 128, ly: 128, rx: 128, ry: 128 }); -let state = neutral(), socket, dataChannel, signalSocket, peer, reconnectTimer, signalReconnectTimer, peerStatsTimer, p2pWatchTimer, peerDisconnectTimer, localSocketReplaced = false; -let relaySequence = 0, lastRelaySequence = -1, canControl = true, activeGuestId = null; +let state = neutral(), socket, guestDataChannel, signalSocket, guestPeer, reconnectTimer, signalReconnectTimer, peerStatsTimer, p2pWatchTimer, peerDisconnectTimer, localSocketReplaced = false; +let relaySequence = 0, canControl = true, assignedSlot = null; let pendingDataPayload = null, pendingRelayState = null, relayInFlightSequence = null, relayAckTimer = null; let p2pSequence = 0, lastP2pAckAt = 0, lastP2pSendAt = 0; let localGuestId = null; +let pendingGuestIce = []; +let participantsCache = []; +let controllerDiagnostics = []; +const hostSessions = new Map(); +const storedSlot = Number(localStorage.getItem("controllerSlot")); +let selectedSlot = validControllerSlot(storedSlot) ? storedSlot : 0; let digitalEdges; const edgeRetryTimers = new Set(); const params = new URLSearchParams(location.search); @@ -34,6 +48,7 @@ const claimControl = document.querySelector("#claim-control"); const topControlState = document.querySelector("#top-control-state"); const rumbleToggle = document.querySelector("#rumble-toggle"); const rumbleStatus = document.querySelector("#rumble-status"); +const controllerTarget = document.querySelector("#controller-target"); const activeGamepad = () => [...navigator.getGamepads()].find(Boolean); const haptics = createHapticsController({ getGamepad: activeGamepad, @@ -90,7 +105,7 @@ addEventListener("pointerdown", reclaimLocalBridge, { capture: true }); addEventListener("keydown", reclaimLocalBridge, { capture: true }); function flushDataChannel() { - const channel = dataChannel; + const channel = guestDataChannel; if (!pendingDataPayload || channel?.readyState !== "open" || channel.bufferedAmount >= DATA_CHANNEL_HIGH_WATER) return; const payload = pendingDataPayload; pendingDataPayload = null; @@ -118,17 +133,35 @@ function resetRemoteSendQueues() { edgeRetryTimers.clear(); } +function closeGuestPeer() { + const oldChannel = guestDataChannel; + const oldPeer = guestPeer; + guestDataChannel = null; + guestPeer = null; + pendingGuestIce = []; + if (oldChannel) oldChannel.onclose = null; + if (oldPeer) oldPeer.onconnectionstatechange = null; + try { oldChannel?.close(); } catch { } + try { oldPeer?.close(); } catch { } +} + function routeRumble(message) { - if (remoteCode || !activeGuestId) { - haptics.handle(message); + if (remoteCode) { + if (assignedSlot === null || message.slot === undefined || message.slot === assignedSlot) haptics.handle(message); + return; + } + if (!validControllerSlot(message.slot)) return; + const session = hostSessions.get(message.slot); + if (!session) { + if (message.slot === selectedSlot) haptics.handle(message); return; } const payload = JSON.stringify(message); const stopping = message.duration === 0 || (message.strong === 0 && message.weak === 0); - if (dataChannel?.readyState === "open") { + if (session.channel?.readyState === "open") { // Haptics are latest-value-wins. Never add them behind a congested input/ack queue. - if (dataChannel.bufferedAmount < DATA_CHANNEL_LOW_WATER) { - try { dataChannel.send(payload); } catch { } + if (session.channel.bufferedAmount < DATA_CHANNEL_LOW_WATER) { + try { session.channel.send(payload); } catch { } } else if (stopping && signalSocket?.readyState === WebSocket.OPEN) { // A stop may bypass a congested P2P queue through the relay. Its higher // sequence makes any older unordered P2P vibration harmless on arrival. @@ -143,15 +176,9 @@ function routeRumble(message) { function fallbackGuestToRelay(reason = "P2P応答なし") { if (!remoteCode || !canControl) return; - const oldChannel = dataChannel, oldPeer = peer; - dataChannel = null; - peer = null; - if (oldChannel) oldChannel.onclose = null; - if (oldPeer) oldPeer.onconnectionstatechange = null; - try { oldChannel?.close(); } catch { } - try { oldPeer?.close(); } catch { } + closeGuestPeer(); resetRemoteSendQueues(); - status.textContent = `操作権取得済み(リレー・${reason})`; + status.textContent = `${controllerSlotLabel(assignedSlot)} 操作中(リレー・${reason})`; status.className = "status online"; pendingRelayState = digitalEdges.envelope(state); flushRelay(); @@ -162,7 +189,7 @@ function startP2pWatch() { lastP2pAckAt = Date.now(); lastP2pSendAt = 0; p2pWatchTimer = setInterval(() => { - if (dataChannel?.readyState !== "open" || !lastP2pSendAt) return; + if (guestDataChannel?.readyState !== "open" || !lastP2pSendAt) return; if (Date.now() - lastP2pAckAt > P2P_ACK_TIMEOUT_MS) fallbackGuestToRelay("P2P無応答"); }, 250); } @@ -194,9 +221,9 @@ function acknowledgeRelay(message) { } async function refreshPeerStats() { - if (!peer || peer.connectionState !== "connected") return; + if (!guestPeer || guestPeer.connectionState !== "connected") return; try { - const stats = await peer.getStats(); + const stats = await guestPeer.getStats(); let pair; for (const report of stats.values()) { if (report.type === "transport" && report.selectedCandidatePairId) pair = stats.get(report.selectedCandidatePairId); @@ -209,8 +236,7 @@ async function refreshPeerStats() { const route = remoteCandidate?.candidateType === "relay" ? "TURN" : "direct"; const rtt = Number.isFinite(pair.currentRoundTripTime) ? `・RTT ${Math.round(pair.currentRoundTripTime * 1000)}ms` : ""; const label = `P2P/${route}${rtt}`; - if (remoteCode && canControl && dataChannel?.readyState === "open") status.textContent = `操作権取得済み(${label})`; - else if (!remoteCode && dataChannel?.readyState === "open") document.querySelector("#session-code").dataset.transport = `${label}操作中`; + if (remoteCode && canControl && guestDataChannel?.readyState === "open") status.textContent = `${controllerSlotLabel(assignedSlot)} 操作中(${label})`; } catch { } } @@ -224,26 +250,44 @@ function send() { const envelope = digitalEdges.envelope(state); if (remoteCode) { if (!canControl) return; - if (dataChannel?.readyState === "open") { + if (guestDataChannel?.readyState === "open") { pendingDataPayload = JSON.stringify({ ...envelope, _p2pSeq: p2pSequence++ }); flushDataChannel(); } else if (signalSocket?.readyState === WebSocket.OPEN) { pendingRelayState = envelope; flushRelay(); } - } else if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "input", ...envelope })); + } else if (inputEnabled() && socket?.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ type: "input", slot: selectedSlot, ...envelope })); + } } -function forwardInput(message) { +function forwardInput(message, slot) { + if (!validControllerSlot(slot)) return false; const envelope = { state: message?.state && typeof message.state === "object" ? message.state : message, sid: message?.sid, edges: message?.edges, }; - state = envelope.state; if (socket?.readyState !== WebSocket.OPEN) return false; - socket.send(JSON.stringify({ type: "input", ...envelope })); + socket.send(JSON.stringify({ type: "input", slot, ...envelope })); return true; } + +function sendNeutralToBridge(slot) { + if (!validControllerSlot(slot) || socket?.readyState !== WebSocket.OPEN) return; + socket.send(JSON.stringify({ + type: "input", + slot, + state: neutral(), + sid: randomHex(8), + edges: [], + })); +} + +function inputEnabled() { + return remoteCode ? canControl + : slotIsLocallyAvailable(participantsCache, selectedSlot) && !hostSessions.has(selectedSlot); +} // Input handlers send changes immediately; this 100 Hz refresh keeps held // buttons/sticks alive and bounds recovery time after a lost network packet. setInterval(send, 10); @@ -265,6 +309,9 @@ digitalEdges = new DigitalEdgeHistory(randomHex(8), state); function resetInput() { state = neutral(); heldHats.clear(); downKeys.clear(); heldKeyboardSticks.left.clear(); heldKeyboardSticks.right.clear(); + document.querySelectorAll("[data-button].active, [data-hat].active").forEach((element) => element.classList.remove("active")); + document.querySelectorAll(".stick-knob").forEach((knob) => { knob.style.transform = ""; }); + document.querySelectorAll(".stick.active").forEach((stick) => stick.classList.remove("active")); digitalEdges.observe(state); } function resetDigitalSession() { digitalEdges.reset(randomHex(8), state); } @@ -276,24 +323,139 @@ function scheduleDigitalRetries() { } } function sendDigitalChange() { + if (!inputEnabled()) return; const changed = digitalEdges.observe(state); send(); if (changed) scheduleDigitalRetries(); } -function setControlEnabled(enabled) { - canControl = enabled; if (enabled) previousGamepad = ""; controller.classList.toggle("locked", !enabled); - if (!enabled) { haptics.stop(); resetInput(); resetRemoteSendQueues(); peer?.close(); peer = null; dataChannel = null; } +function updateInputAvailability() { + const enabled = inputEnabled(); + controller.classList.toggle("locked", !enabled); + controller.setAttribute("aria-disabled", String(!enabled)); + controller.toggleAttribute("inert", !enabled); + const owner = remoteCode ? null : participantForSlot(participantsCache, selectedSlot); + if (remoteCode) { + controllerTarget.textContent = canControl + ? `${controllerSlotLabel(assignedSlot)}を操作しています` + : "コントローラーの空きを待っています"; + } else if (owner || hostSessions.has(selectedSlot)) { + controllerTarget.textContent = owner + ? `${controllerSlotLabel(selectedSlot)}は ${owner.name} さんが遠隔操作中です` + : `${controllerSlotLabel(selectedSlot)}は遠隔接続を準備中です`; + } else { + controllerTarget.textContent = `${controllerSlotLabel(selectedSlot)}をローカル操作しています`; + } + const releaseButton = document.querySelector("#release-control"); + if (!remoteCode && releaseButton) { + releaseButton.textContent = `${controllerSlotLabel(selectedSlot)}の割り当てを解除`; + releaseButton.disabled = !owner || signalSocket?.readyState !== WebSocket.OPEN; + } +} + +function updateSlotCards() { + for (let slot = 0; slot < CONTROLLER_SLOT_COUNT; slot += 1) { + const card = document.querySelector(`[data-controller-slot="${slot}"]`); + if (!card) continue; + const owner = participantForSlot(participantsCache, slot); + const remotelyAssigned = Boolean(owner || hostSessions.has(slot)); + const diagnostic = controllerDiagnostics[slot]; + const stateLabel = diagnostic?.ready ? "Switch接続済み" + : diagnostic?.connected ? "接続準備中" + : diagnostic?.state === "advertising" ? "ペアリング待ち" : "未接続"; + card.classList.toggle("selected", !remoteCode && slot === selectedSlot); + card.classList.toggle("assigned", remotelyAssigned); + card.classList.toggle("ready", Boolean(diagnostic?.ready)); + card.setAttribute("aria-pressed", String(!remoteCode && slot === selectedSlot)); + card.querySelector(".slot-state").textContent = stateLabel; + card.querySelector(".slot-owner").textContent = owner + ? `${owner.name} さんが遠隔操作` + : remotelyAssigned ? "遠隔接続を準備中" : "ローカル操作可"; + } +} + +function selectControllerSlot(slot) { + if (remoteCode || !validControllerSlot(slot) || slot === selectedSlot) return; + if (slotIsLocallyAvailable(participantsCache, selectedSlot) && + !hostSessions.has(selectedSlot)) { + resetInput(); + send(); + } + selectedSlot = slot; + localStorage.setItem("controllerSlot", String(slot)); + state = neutral(); + previousGamepad = ""; + resetDigitalSession(); + updateSlotCards(); + updateInputAvailability(); + refreshDeviceDiagnostics(); +} + +for (const card of document.querySelectorAll("[data-controller-slot]")) { + card.addEventListener("click", () => selectControllerSlot(Number(card.dataset.controllerSlot))); +} + +function setControlEnabled(enabled, slot = null) { + const nextSlot = enabled && validControllerSlot(slot) ? slot : null; + const slotChanged = canControl && nextSlot !== null && assignedSlot !== nextSlot; + canControl = enabled && nextSlot !== null; + assignedSlot = nextSlot; + if (canControl) previousGamepad = ""; + if (!canControl || slotChanged) { + haptics.stop(); + resetRemoteSendQueues(); + closeGuestPeer(); + } + if (!canControl) resetInput(); else resetDigitalSession(); - document.querySelector("#control-state").textContent = enabled ? "あなたが操作中です" : "操作権が渡されるまで待機してください"; + updateInputAvailability(); + document.querySelector("#control-state").textContent = canControl + ? `${controllerSlotLabel(assignedSlot)}を操作中です` + : "空いているコントローラーが割り当てられるまで待機してください"; if (remoteCode) { - claimControl.disabled = enabled || signalSocket?.readyState !== WebSocket.OPEN; - claimControl.textContent = enabled ? "操作中" : "操作権を取る"; - topControlState.textContent = enabled ? "あなたが操作中です" : "全員が操作権を取得できます"; + claimControl.disabled = canControl || signalSocket?.readyState !== WebSocket.OPEN; + claimControl.textContent = canControl ? `${controllerSlotLabel(assignedSlot)} 操作中` : "空きを取得する"; + topControlState.textContent = canControl + ? `${controllerSlotLabel(assignedSlot)}を操作しています` + : "3台すべて使用中の場合は待機します"; } } claimControl.onclick = () => signalSocket?.send(JSON.stringify({ type: "claim" })); +function attachGuestDataChannel(channel) { + guestDataChannel = channel; + channel.bufferedAmountLowThreshold = DATA_CHANNEL_LOW_WATER; + channel.onbufferedamountlow = flushDataChannel; + channel.onmessage = ({ data }) => { + try { + const message = JSON.parse(data); + if (message.type === "input-ack" && Number.isSafeInteger(message.seq)) { + lastP2pAckAt = Date.now(); + digitalEdges.acknowledge(message.edgeAck); + } + if (message.type === "rumble" && canControl && message.slot === assignedSlot) haptics.handle(message); + } catch { } + }; + channel.onopen = () => { + resetRemoteSendQueues(); + p2pSequence = 0; + status.textContent = `${controllerSlotLabel(assignedSlot)} 操作中(P2P)`; + status.className = "status online"; + startPeerStats(); + startP2pWatch(); + send(); + }; + channel.onclose = () => { + if (channel !== guestDataChannel) return; + guestDataChannel = null; + if (canControl) { + resetRemoteSendQueues(); + status.textContent = `${controllerSlotLabel(assignedSlot)} 操作中(リレー)`; + send(); + } + }; +} + async function connectGuest() { if (signalSocket && [WebSocket.CONNECTING, WebSocket.OPEN].includes(signalSocket.readyState)) return; const nameInput = document.querySelector("#guest-name"); @@ -313,58 +475,50 @@ async function connectGuest() { document.querySelector("#guest-join-fields").hidden = true; status.textContent = "ロビー参加中"; status.className = "status online"; claimControl.disabled = false; - topControlState.textContent = "全員が操作権を取得できます"; + topControlState.textContent = "空いているコントローラーを自動取得します"; }; signalSocket.onmessage = async ({ data }) => { const message = JSON.parse(data); if (message.type === "participants") renderGuestParticipants(message.participants); if (message.type === "input-ack") acknowledgeRelay(message); - if (message.type === "rumble" && canControl) haptics.handle(message); + if (message.type === "rumble" && canControl && message.slot === assignedSlot) haptics.handle(message); if (message.type === "control") { - setControlEnabled(message.active); + setControlEnabled(message.active, message.slot); status.textContent = message.active - ? remoteTransportMode === TRANSPORT_RELAY ? "操作権取得済み(リレー固定)" : "操作権取得済み(P2P接続待ち・一時リレー)" + ? remoteTransportMode === TRANSPORT_RELAY + ? `${controllerSlotLabel(message.slot)} 操作中(リレー固定)` + : `${controllerSlotLabel(message.slot)} 操作中(P2P接続待ち・一時リレー)` : "ロビーで待機中"; status.className = message.active ? "status online" : "status waiting"; if (message.active) { relaySequence = 0; resetInput(); send(); } - } else if (message.type === "offer" && canControl && remoteTransportMode !== TRANSPORT_RELAY) { - peer?.close(); peer = new RTCPeerConnection({ iceServers: ice }); - peer.onicecandidate = ({ candidate }) => candidate && signalSocket.send(JSON.stringify({ type: "ice", candidate })); - const channel = peer.createDataChannel("input", DATA_CHANNEL_OPTIONS); - dataChannel = channel; - channel.bufferedAmountLowThreshold = DATA_CHANNEL_LOW_WATER; - channel.onbufferedamountlow = flushDataChannel; - channel.onmessage = ({ data }) => { - try { - const message = JSON.parse(data); - if (message.type === "input-ack" && Number.isSafeInteger(message.seq)) { - lastP2pAckAt = Date.now(); - digitalEdges.acknowledge(message.edgeAck); - } - if (message.type === "rumble" && canControl) haptics.handle(message); - } catch { } - }; - channel.onopen = () => { resetRemoteSendQueues(); p2pSequence = 0; status.textContent = "操作権取得済み(P2P)"; status.className = "status online"; startPeerStats(); startP2pWatch(); send(); }; - channel.onclose = () => { - if (channel !== dataChannel) return; - dataChannel = null; - if (canControl) { resetRemoteSendQueues(); status.textContent = "操作権取得済み(リレー)"; send(); } - }; - peer.onconnectionstatechange = () => { - const connectionState = peer?.connectionState; + } else if (message.type === "offer" && canControl && message.slot === assignedSlot && remoteTransportMode !== TRANSPORT_RELAY) { + const earlyIce = pendingGuestIce; + closeGuestPeer(); + pendingGuestIce = earlyIce; + guestPeer = new RTCPeerConnection({ iceServers: ice }); + const currentPeer = guestPeer; + currentPeer.ondatachannel = ({ channel }) => attachGuestDataChannel(channel); + currentPeer.onicecandidate = ({ candidate }) => candidate && signalSocket.send(JSON.stringify({ type: "ice", slot: assignedSlot, candidate })); + currentPeer.onconnectionstatechange = () => { + const connectionState = currentPeer.connectionState; if (!canControl) return; if (connectionState === "failed") fallbackGuestToRelay("P2P切断"); else if (connectionState === "disconnected") { clearTimeout(peerDisconnectTimer); peerDisconnectTimer = setTimeout(() => { - if (peer?.connectionState === "disconnected") fallbackGuestToRelay("P2P切断"); + if (currentPeer === guestPeer && currentPeer.connectionState === "disconnected") fallbackGuestToRelay("P2P切断"); }, 1000); } else if (connectionState === "connected") clearTimeout(peerDisconnectTimer); }; - await peer.setRemoteDescription(message.offer); - await peer.setLocalDescription(await peer.createAnswer()); - signalSocket.send(JSON.stringify({ type: "answer", answer: peer.localDescription })); - } else if (message.type === "ice" && peer) await peer.addIceCandidate(message.candidate); + await currentPeer.setRemoteDescription(message.offer); + await drainIceCandidates(currentPeer, pendingGuestIce); + await currentPeer.setLocalDescription(await currentPeer.createAnswer()); + if (currentPeer === guestPeer && signalSocket?.readyState === WebSocket.OPEN) { + signalSocket.send(JSON.stringify({ type: "answer", slot: assignedSlot, answer: currentPeer.localDescription })); + } + } else if (message.type === "ice" && message.slot === assignedSlot) { + await addIceCandidateOrQueue(guestPeer, message.candidate, pendingGuestIce); + } }; signalSocket.onclose = (event) => { if (signalSocket !== guestSignalSocket) return; @@ -380,107 +534,193 @@ async function connectGuest() { } function renderParticipants(participants) { + participantsCache = Array.isArray(participants) ? participants : []; const list = document.querySelector("#participant-list"); list.replaceChildren(); - document.querySelector("#participant-count").textContent = `${participants.length}人参加中`; - for (const participant of participants) { + document.querySelector("#participant-count").textContent = `${participantsCache.length}人参加中・最大3人操作`; + for (const participant of participantsCache) { const row = document.createElement("div"); row.className = `participant${participant.active ? " active" : ""}`; - const label = document.createElement("span"); label.textContent = participant.active ? `${participant.name}(操作中)` : participant.name; - const button = document.createElement("button"); button.textContent = participant.active ? "操作中" : "操作権を渡す"; - button.disabled = participant.active; - button.onclick = () => signalSocket?.send(JSON.stringify({ type: "grant", guestId: participant.id })); - row.append(label, button); list.append(row); + const label = document.createElement("span"); + label.textContent = participant.active ? `${participant.name}・${controllerSlotLabel(participant.slot)}` : `${participant.name}・待機中`; + const select = document.createElement("select"); + select.setAttribute("aria-label", `${participant.name} の割り当て`); + const waiting = document.createElement("option"); waiting.value = ""; waiting.textContent = "待機"; select.append(waiting); + for (let slot = 0; slot < CONTROLLER_SLOT_COUNT; slot += 1) { + const option = document.createElement("option"); + const owner = participantForSlot(participantsCache, slot); + option.value = String(slot); + option.textContent = owner && owner.id !== participant.id + ? `${controllerSlotLabel(slot)}(${owner.name} さんと交代)` + : controllerSlotLabel(slot); + select.append(option); + } + select.value = participant.active ? String(participant.slot) : ""; + select.onchange = () => { + if (select.value === "") { + if (validControllerSlot(participant.slot)) signalSocket?.send(JSON.stringify({ type: "release", slot: participant.slot })); + } else { + signalSocket?.send(JSON.stringify({ type: "grant", guestId: participant.id, slot: Number(select.value) })); + } + }; + row.append(label, select); list.append(row); } - if (!participants.length) { const empty = document.createElement("p"); empty.className = "empty"; empty.textContent = "参加者を待っています"; list.append(empty); } + if (!participantsCache.length) { const empty = document.createElement("p"); empty.className = "empty"; empty.textContent = "参加者を待っています"; list.append(empty); } + updateSlotCards(); + updateInputAvailability(); } function renderGuestParticipants(participants) { const list = document.querySelector("#guest-participant-list"); list.replaceChildren(); - document.querySelector("#guest-participant-count").textContent = `${participants.length}人参加中`; + const activeCount = participants.filter((participant) => participant.active).length; + document.querySelector("#guest-participant-count").textContent = `${activeCount}/3台使用中・${participants.length}人参加`; for (const participant of participants) { const row = document.createElement("div"); row.className = `participant${participant.active ? " active" : ""}`; const label = document.createElement("span"); - label.textContent = `${participant.name}${participant.id === localGuestId ? "(自分)" : ""}${participant.active ? "(操作中)" : ""}`; - const button = document.createElement("button"); - if (participant.active) { button.textContent = "操作中"; button.disabled = true; } - else { - button.textContent = participant.id === localGuestId ? "操作権を取る" : "この人に渡す"; - button.onclick = () => signalSocket?.send(JSON.stringify(participant.id === localGuestId ? { type: "claim" } : { type: "grant", guestId: participant.id })); + label.textContent = `${participant.name}${participant.id === localGuestId ? "(自分)" : ""}・${controllerSlotLabel(participant.slot)}`; + row.append(label); + if (!participant.active && participant.id === localGuestId) { + const button = document.createElement("button"); + button.textContent = "空きを取得する"; + button.onclick = () => signalSocket?.send(JSON.stringify({ type: "claim" })); + row.append(button); } - row.append(label, button); list.append(row); + list.append(row); } if (!participants.length) { const empty = document.createElement("p"); empty.className = "empty"; empty.textContent = "参加者を待っています"; list.append(empty); } } -async function startPeer(base, code, guestId) { - activeGuestId = guestId; haptics.stop(); lastRelaySequence = -1; resetRemoteSendQueues(); resetInput(); send(); +function updateSessionTransportLabel() { + const codeLabel = document.querySelector("#session-code"); + const sessions = [...hostSessions.values()]; + if (!sessions.length) { + codeLabel.dataset.transport = "遠隔操作未割当"; + updateSlotCards(); + updateInputAvailability(); + return; + } + const p2p = sessions.filter((session) => session.mode === "p2p").length; + const relay = sessions.filter((session) => session.mode === "relay").length; + const waiting = sessions.length - p2p - relay; + codeLabel.dataset.transport = `${sessions.length}/3台割当・P2P ${p2p}・リレー ${relay}${waiting ? `・接続中 ${waiting}` : ""}`; + updateSlotCards(); + updateInputAvailability(); +} + +function stopHostSession(slot, { neutralize = true } = {}) { + const session = hostSessions.get(slot); + if (!session) { + if (neutralize) sendNeutralToBridge(slot); + return; + } + hostSessions.delete(slot); + clearTimeout(session.disconnectTimer); + if (session.channel) session.channel.onclose = null; + if (session.peer) session.peer.onconnectionstatechange = null; + try { session.channel?.close(); } catch { } + try { session.peer?.close(); } catch { } + if (neutralize) sendNeutralToBridge(slot); + if (slot === selectedSlot) { + resetInput(); + resetDigitalSession(); + } + updateSessionTransportLabel(); +} + +function stopAllHostSessions() { + for (const slot of [...hostSessions.keys()]) stopHostSession(slot); +} + +function startRelayGuest(guestId, slot) { + if (!validControllerSlot(slot)) return; + stopHostSession(slot); + if (slot === selectedSlot) { + resetInput(); + resetDigitalSession(); + } + hostSessions.set(slot, { guestId, slot, peer: null, channel: null, lastRelaySequence: -1, mode: "relay", disconnectTimer: null }); + updateSessionTransportLabel(); +} + +async function startHostPeer(base, code, guestId, slot) { + if (!validControllerSlot(slot)) return; + stopHostSession(slot); + if (slot === selectedSlot) { + resetInput(); + resetDigitalSession(); + } + const session = { + guestId, slot, peer: null, channel: null, lastRelaySequence: -1, + mode: "connecting", disconnectTimer: null, pendingIce: [], + }; + hostSessions.set(slot, session); + updateSessionTransportLabel(); const ice = await iceServers(base, code); - peer?.close(); peer = new RTCPeerConnection({ iceServers: ice }); - const hostPeer = peer; - dataChannel = peer.createDataChannel("input", DATA_CHANNEL_OPTIONS); - const hostChannel = dataChannel; - dataChannel.bufferedAmountLowThreshold = DATA_CHANNEL_LOW_WATER; - dataChannel.onbufferedamountlow = flushDataChannel; - dataChannel.onmessage = ({ data }) => { + if (hostSessions.get(slot) !== session) return; + const hostPeer = new RTCPeerConnection({ iceServers: ice }); + const hostChannel = hostPeer.createDataChannel("input", DATA_CHANNEL_OPTIONS); + session.peer = hostPeer; + session.channel = hostChannel; + + hostChannel.onmessage = ({ data }) => { try { const message = JSON.parse(data); - const forwarded = forwardInput(message); + const forwarded = forwardInput(message, slot); if (Number.isSafeInteger(message._p2pSeq) && hostChannel.readyState === "open") { hostChannel.send(JSON.stringify({ type: "input-ack", + slot, seq: message._p2pSeq, edgeAck: forwarded ? highestDigitalEdgeSequence(message) : null, })); } - document.querySelector("#session-code").dataset.transport = "P2P操作中"; } catch { } }; - dataChannel.onopen = () => { document.querySelector("#session-code").dataset.transport = "P2P操作中"; startPeerStats(); }; - dataChannel.onclose = () => { - if (dataChannel === hostChannel) dataChannel = null; - resetInput(); send(); - if (signalSocket?.readyState === WebSocket.OPEN) document.querySelector("#session-code").dataset.transport = "リレー待機"; + hostChannel.onopen = () => { + if (hostSessions.get(slot) !== session) return; + session.mode = "p2p"; + updateSessionTransportLabel(); + }; + hostChannel.onclose = () => { + if (hostSessions.get(slot) !== session) return; + session.channel = null; + session.mode = "relay"; + sendNeutralToBridge(slot); + updateSessionTransportLabel(); }; const returnHostToRelay = () => { - if (peer !== hostPeer) return; - dataChannel = null; - peer = null; - hostChannel.onclose = null; + if (hostSessions.get(slot) !== session) return; + clearTimeout(session.disconnectTimer); + if (session.channel) session.channel.onclose = null; hostPeer.onconnectionstatechange = null; - try { hostChannel.close(); } catch { } + try { session.channel?.close(); } catch { } try { hostPeer.close(); } catch { } - resetInput(); send(); - document.querySelector("#session-code").dataset.transport = "リレー操作中"; + session.channel = null; + session.peer = null; + session.mode = "relay"; + sendNeutralToBridge(slot); + updateSessionTransportLabel(); }; - peer.onconnectionstatechange = () => { - if (peer !== hostPeer) return; + hostPeer.onconnectionstatechange = () => { + if (hostSessions.get(slot) !== session) return; if (hostPeer.connectionState === "failed") returnHostToRelay(); else if (hostPeer.connectionState === "disconnected") { - clearTimeout(peerDisconnectTimer); - peerDisconnectTimer = setTimeout(() => { + clearTimeout(session.disconnectTimer); + session.disconnectTimer = setTimeout(() => { if (hostPeer.connectionState === "disconnected") returnHostToRelay(); }, 1000); - } else if (hostPeer.connectionState === "connected") clearTimeout(peerDisconnectTimer); + } else if (hostPeer.connectionState === "connected") clearTimeout(session.disconnectTimer); }; - peer.onicecandidate = ({ candidate }) => candidate && signalSocket.send(JSON.stringify({ type: "ice", candidate })); - await peer.setLocalDescription(await peer.createOffer()); - signalSocket.send(JSON.stringify({ type: "offer", offer: peer.localDescription })); -} - -function startRelayGuest(guestId) { - activeGuestId = guestId; - haptics.stop(); - lastRelaySequence = -1; - peer?.close(); - peer = null; - dataChannel = null; - resetRemoteSendQueues(); - resetInput(); - send(); - document.querySelector("#session-code").dataset.transport = "リレー待機"; + hostPeer.onicecandidate = ({ candidate }) => candidate && signalSocket?.send(JSON.stringify({ type: "ice", guestId, slot, candidate })); + await hostPeer.setLocalDescription(await hostPeer.createOffer()); + if (hostSessions.get(slot) === session && signalSocket?.readyState === WebSocket.OPEN) { + signalSocket.send(JSON.stringify({ type: "offer", guestId, slot, offer: hostPeer.localDescription })); + } } async function createHostSession() { - signalSocket?.close(); peer?.close(); activeGuestId = null; dataChannel = null; haptics.stop(); renderParticipants([]); + signalSocket?.close(); + stopAllHostSessions(); + haptics.stop(); + renderParticipants([]); const baseInput = document.querySelector("#signal-base"), base = baseInput.value.replace(/\/$/, ""); if (!/^https:\/\//.test(base)) { alert("HTTPSのCloudflare Worker URLを入力してください"); return; } localStorage.setItem("signalBase", base); @@ -494,61 +734,76 @@ async function createHostSession() { const message = JSON.parse(data); if (message.type === "participants") renderParticipants(message.participants); else if (message.type === "control-released") { - activeGuestId = null; peer?.close(); peer = null; dataChannel = null; haptics.stop(); resetInput(); send(); - document.querySelector("#session-code").dataset.transport = "操作権未割当"; + if (validControllerSlot(message.slot)) stopHostSession(message.slot); } else if (message.type === "peer-ready") { - if (hostTransportMode === TRANSPORT_RELAY) startRelayGuest(message.guestId); - else await startPeer(base, code, message.guestId); + if (hostTransportMode === TRANSPORT_RELAY) startRelayGuest(message.guestId, message.slot); + else await startHostPeer(base, code, message.guestId, message.slot); } - else if (message.type === "answer" && peer) await peer.setRemoteDescription(message.answer); - else if (message.type === "ice" && peer) await peer.addIceCandidate(message.candidate); - else if (message.type === "input" && dataChannel?.readyState !== "open") { - if (Number.isSafeInteger(message.seq) && message.seq > lastRelaySequence) { - lastRelaySequence = message.seq; forwardInput(message); - document.querySelector("#session-code").dataset.transport = "リレー操作中"; + else if (message.type === "answer" && validControllerSlot(message.slot)) { + const session = hostSessions.get(message.slot); + if (session?.guestId === message.guestId && session.peer) { + await session.peer.setRemoteDescription(message.answer); + await drainIceCandidates(session.peer, session.pendingIce); + } + } else if (message.type === "ice" && validControllerSlot(message.slot)) { + const session = hostSessions.get(message.slot); + if (session?.guestId === message.guestId && session.peer) { + await addIceCandidateOrQueue(session.peer, message.candidate, session.pendingIce); + } + } else if (message.type === "input" && validControllerSlot(message.slot)) { + const session = hostSessions.get(message.slot); + if (!session || session.guestId !== message.guestId || session.channel?.readyState === "open") return; + let forwarded = message.seq === session.lastRelaySequence; + if (Number.isSafeInteger(message.seq) && message.seq > session.lastRelaySequence) { + forwarded = forwardInput(message, message.slot); + if (forwarded) { + session.lastRelaySequence = message.seq; + session.mode = "relay"; + updateSessionTransportLabel(); + } } - hostSignalSocket.send(JSON.stringify({ type: "input-ack", seq: message.seq, edgeAck: highestDigitalEdgeSequence(message) })); + hostSignalSocket.send(JSON.stringify({ + type: "input-ack", slot: message.slot, seq: message.seq, + edgeAck: forwarded ? highestDigitalEdgeSequence(message) : null, + })); } }; signalSocket.onclose = () => { if (signalSocket !== hostSignalSocket) return; signalSocket = null; - peer?.close(); activeGuestId = null; dataChannel = null; haptics.stop(); resetInput(); send(); renderParticipants([]); + stopAllHostSessions(); haptics.stop(); renderParticipants([]); document.querySelector("#session-code").textContent = `${code}(セッション切断)`; }; const link = buildGuestLink(base, code, hostTransportMode); - const codeLabel = document.querySelector("#session-code"); codeLabel.textContent = code; codeLabel.dataset.transport = "操作権未割当"; + const codeLabel = document.querySelector("#session-code"); codeLabel.textContent = code; codeLabel.dataset.transport = "遠隔操作未割当"; const anchor = document.querySelector("#guest-link"); anchor.href = link; anchor.textContent = link; - document.querySelector("#release-control").disabled = false; document.querySelector("#revoke-session").disabled = false; } document.querySelector("#signal-base").value = localStorage.getItem("signalBase") || "https://switch2-remote-signal.y52en.workers.dev"; document.querySelector("#transport-mode").value = normalizeTransportMode(localStorage.getItem("transportMode")); document.querySelector("#new-session").onclick = createHostSession; -document.querySelector("#release-control").onclick = () => signalSocket?.send(JSON.stringify({ type: "release" })); +document.querySelector("#release-control").onclick = () => signalSocket?.send(JSON.stringify({ type: "release", slot: selectedSlot })); document.querySelector("#revoke-session").onclick = () => { - signalSocket?.send(JSON.stringify({ type: "revoke" })); peer?.close(); activeGuestId = null; dataChannel = null; lastRelaySequence = -1; - resetRemoteSendQueues(); resetInput(); send(); renderParticipants([]); document.querySelector("#session-code").textContent = "終了済み(新しいセッションを発行してください)"; + signalSocket?.send(JSON.stringify({ type: "revoke" })); + stopAllHostSessions(); + resetInput(); + send(); + renderParticipants([]); + document.querySelector("#session-code").textContent = "終了済み(新しいセッションを発行してください)"; }; document.querySelector("#join-session").onclick = connectGuest; document.querySelector("#guest-name").value = localStorage.getItem("guestName") || ""; const guestNameInput = document.querySelector("#guest-name"); -let guestJoinTimer; -function scheduleGuestJoin() { - clearTimeout(guestJoinTimer); - if (guestNameInput.value.trim()) guestJoinTimer = setTimeout(connectGuest, 450); -} -guestNameInput.addEventListener("input", scheduleGuestJoin); -guestNameInput.addEventListener("change", connectGuest); guestNameInput.addEventListener("keydown", (event) => { - if (event.key === "Enter") { event.preventDefault(); clearTimeout(guestJoinTimer); connectGuest(); guestNameInput.blur(); } + if (event.key === "Enter") { event.preventDefault(); connectGuest(); guestNameInput.blur(); } }); if (remoteCode && guestNameInput.value.trim()) queueMicrotask(connectGuest); function setButton(bit, pressed) { + if (!inputEnabled()) return; state.buttons = pressed ? state.buttons | (1 << bit) : state.buttons & ~(1 << bit); - document.querySelector(`[data-button="${bit}"]`)?.classList.toggle("active", pressed); sendDigitalChange(); + document.querySelectorAll(`[data-button="${bit}"]`).forEach((button) => button.classList.toggle("active", pressed)); sendDigitalChange(); } function combinedHat() { const up = heldHats.has(0), right = heldHats.has(2), down = heldHats.has(4), left = heldHats.has(6); @@ -556,10 +811,12 @@ function combinedHat() { if (up) return 0; if (right) return 2; if (down) return 4; if (left) return 6; return 8; } function setHat(direction, pressed) { + if (!inputEnabled()) return; pressed ? heldHats.add(direction) : heldHats.delete(direction); state.hat = combinedHat(); - document.querySelector(`[data-hat="${direction}"]`)?.classList.toggle("active", pressed); sendDigitalChange(); + document.querySelectorAll(`[data-hat="${direction}"]`).forEach((button) => button.classList.toggle("active", pressed)); sendDigitalChange(); } function setKeyboardStick(side, direction, pressed) { + if (!inputEnabled()) return; const held = heldKeyboardSticks[side]; pressed ? held.add(direction) : held.delete(direction); const horizontal = held.has("left") === held.has("right") ? 128 : held.has("left") ? 0 : 255; @@ -581,7 +838,7 @@ const handleKeyboard = setupKeyboardBindings((action, pressed) => { } return; } - if (remoteCode && !canControl) return; + if (!inputEnabled()) return; if (action.type === "hat") setHat(action.value, pressed); else if (action.type === "stick") setKeyboardStick(action.side, action.direction, pressed); else setButton(action.value, pressed); @@ -606,7 +863,7 @@ function pollGamepad() { const activeActions = readGamepad(pad); if (pad) { gamepadLabel.textContent = `ゲームパッド: ${pad.id}`; - if (!remoteCode || canControl) { + if (inputEnabled()) { const next = gamepadState(pad, activeActions); const serialized = JSON.stringify(next); if (serialized !== previousGamepad) { state = next; previousGamepad = serialized; @@ -626,11 +883,19 @@ addEventListener("visibilitychange", () => { }); addEventListener("pagehide", () => { haptics.stop(); resetInput(); send(); }); if (remoteCode) { - canControl = false; controller.classList.add("locked"); document.querySelector("#session-panel").hidden = true; + canControl = false; document.querySelector("#session-panel").hidden = true; + document.querySelector("#controller-slots").hidden = true; document.querySelector("#top-control-bar").hidden = false; document.querySelector("#guest-panel").hidden = false; document.querySelector("#remote-code").textContent = remoteCode; document.querySelector("#remote-transport").textContent = transportModeLabel(remoteTransportMode); -} else { document.querySelector("#guest-panel").hidden = true; connect(); renderParticipants([]); } + setControlEnabled(false); +} else { + document.querySelector("#guest-panel").hidden = true; + connect(); + renderParticipants([]); + updateSlotCards(); + updateInputAvailability(); +} pollGamepad(); async function refreshDeviceDiagnostics() { @@ -641,6 +906,8 @@ async function refreshDeviceDiagnostics() { try { const response = await fetch("/api/status", { cache: "no-store" }); const device = await response.json(); + controllerDiagnostics = device.esp32SerialConnected && Array.isArray(device.controllers) ? device.controllers : []; + const selectedController = controllerDiagnostics[selectedSlot] ?? {}; document.querySelector("#diag-browser").textContent = device.localControllerConnected ? "接続" : "切断"; const serialPort = device.esp32SerialPort || "未設定"; document.querySelector("#diag-serial").textContent = device.esp32SerialConnected @@ -648,9 +915,15 @@ async function refreshDeviceDiagnostics() { : `${serialPort}: ${device.esp32SerialError || "切断"}`; document.querySelector("#diag-frames").textContent = `${device.esp32SerialFramesWritten.toLocaleString()} / 破棄 ${device.esp32SerialFramesDropped.toLocaleString()}`; document.querySelector("#diag-queue").textContent = `${device.esp32SerialQueueBytes ?? 0} byte`; - document.querySelector("#diag-input-latency").textContent = device.esp32LastInputLatencyMs == null ? "計測待ち" : `${device.esp32LastInputLatencyMs} ms`; - document.querySelector("#diag-ble-interval").textContent = device.esp32BleConnIntervalMs == null ? "接続待ち" : `${device.esp32BleConnIntervalMs} ms`; + document.querySelector("#diag-input-latency").textContent = selectedController.inputLatencyMs == null ? "計測待ち" : `${selectedController.inputLatencyMs} ms`; + document.querySelector("#diag-ble-interval").textContent = selectedController.connectionIntervalMs == null ? "接続待ち" : `${selectedController.connectionIntervalMs} ms`; document.querySelector("#diag-ble-queue").textContent = device.esp32BleQueueFree == null ? "計測待ち" : `${device.esp32BleQueueFree}/${device.esp32BleQueueCeiling}・待機 ${device.esp32BleCongestionSkips}`; + updateSlotCards(); + if (!localSocketReplaced && device.localControllerConnected) { + const readyCount = controllerDiagnostics.filter((entry) => entry.ready).length; + status.textContent = `PC→ESP32接続済み・Switch ${readyCount}/3台`; + status.className = readyCount ? "status online" : "status waiting"; + } } catch { document.querySelector("#diag-browser").textContent = "取得失敗"; } diff --git a/apps/host/public/controller-slots.js b/apps/host/public/controller-slots.js new file mode 100644 index 0000000..4815746 --- /dev/null +++ b/apps/host/public/controller-slots.js @@ -0,0 +1,18 @@ +export const CONTROLLER_SLOT_COUNT = 3; + +export function validControllerSlot(value) { + return Number.isInteger(value) && value >= 0 && value < CONTROLLER_SLOT_COUNT; +} + +export function controllerSlotLabel(slot) { + return validControllerSlot(slot) ? `コントローラー ${slot + 1}` : "待機中"; +} + +export function participantForSlot(participants, slot) { + if (!validControllerSlot(slot) || !Array.isArray(participants)) return null; + return participants.find((participant) => participant?.active && participant.slot === slot) ?? null; +} + +export function slotIsLocallyAvailable(participants, slot) { + return validControllerSlot(slot) && !participantForSlot(participants, slot); +} diff --git a/apps/host/public/controller-slots.test.mjs b/apps/host/public/controller-slots.test.mjs new file mode 100644 index 0000000..c16f3be --- /dev/null +++ b/apps/host/public/controller-slots.test.mjs @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + CONTROLLER_SLOT_COUNT, + controllerSlotLabel, + participantForSlot, + slotIsLocallyAvailable, + validControllerSlot, +} from "./controller-slots.js"; + +test("exposes exactly three controller slots", () => { + assert.equal(CONTROLLER_SLOT_COUNT, 3); + assert.equal(validControllerSlot(0), true); + assert.equal(validControllerSlot(2), true); + assert.equal(validControllerSlot(3), false); + assert.equal(validControllerSlot("1"), false); + assert.equal(controllerSlotLabel(0), "コントローラー 1"); + assert.equal(controllerSlotLabel(null), "待機中"); +}); + +test("finds remote ownership without treating malformed rows as assignments", () => { + const participants = [ + { id: "a", active: true, slot: 1 }, + { id: "b", active: false, slot: 2 }, + { id: "c", active: true, slot: 7 }, + ]; + assert.equal(participantForSlot(participants, 1)?.id, "a"); + assert.equal(participantForSlot(participants, 2), null); + assert.equal(slotIsLocallyAvailable(participants, 0), true); + assert.equal(slotIsLocallyAvailable(participants, 1), false); +}); diff --git a/apps/host/public/index.html b/apps/host/public/index.html index cab7aa6..2e2a64e 100644 --- a/apps/host/public/index.html +++ b/apps/host/public/index.html @@ -2,7 +2,7 @@ - + Switch 2 Remote Controller @@ -19,17 +19,33 @@ ロビーへ接続中 -
- ブラウザ確認中 - ESP32確認中 - 送信— - キュー— - PC→ESP32— - BLE間隔— - BLE空き— +
+ 接続の詳細診断 +
+ ブラウザ確認中 + ESP32確認中 + 送信— + キュー— + PC→ESP32— + BLE間隔— + BLE空き— +
+
+ +
+ + +
+

コントローラー 1をローカル操作しています

-
+
@@ -61,20 +77,6 @@
-
-
- - -
-
-
- - -
-
-
-
-

キーボード:

ゲームパッド未接続

@@ -116,6 +118,7 @@

コントローラーロビー

Web遠隔操作

+

参加者を3台のコントローラーへ個別に割り当て、同時に操作できます。