From 3fea084f575b5967961aa4005cbcf76dbe5bc3ad Mon Sep 17 00:00:00 2001 From: Joshua Barrett Date: Thu, 29 Oct 2026 20:53:48 -0400 Subject: [PATCH] webapp: multi-device multi-vibrator direct control with global emergency stop Replace the single-device UI with a list of every vibrate-capable feature on every connected device, each with its own slider, hold-to-max button, and hold-to-stop button. Devices may be added or removed at any time; the vibrator registry in logic.js diffs the set, preserves per-vibrator state, and new vibrators immediately join whatever the active driver is doing. logic.js is now a DOM-free vibration manager built around one output codepath: each vibrator's output is a hold override (max/stop) if pressed, otherwise the base value from the active mode's base provider (unset means direct control, i.e. the slider set-point). Holds return output to the slider value on release. Nonzero sends are throttled per vibrator with a trailing send; stops are immediate. The emergency stop button is now a fixed dock at the bottom of the screen that stays put across future views. Pressing it stops all devices, clears holds, and resets every slider to 0 while leaving the app operable; latched halts (page hide, failed commands) still require returning to the page or reconnecting. Pattern mode is removed temporarily and returns in the next commit. --- tsbridge/webapp/app.js | 468 ++++++++++++++++++------------------- tsbridge/webapp/index.html | 46 ++-- tsbridge/webapp/logic.js | 427 +++++++++++++++++++++------------ tsbridge/webapp/style.css | 109 +++++---- tsbridge/webapp/test.html | 398 ++++++++++++++++++++----------- 5 files changed, 844 insertions(+), 604 deletions(-) diff --git a/tsbridge/webapp/app.js b/tsbridge/webapp/app.js index 98df10c..e65c337 100644 --- a/tsbridge/webapp/app.js +++ b/tsbridge/webapp/app.js @@ -1,5 +1,9 @@ // tsbutt webapp — DOM wiring. All vibration logic lives in logic.js; this -// file connects it to buttplug.js and the page. +// file connects it to buttplug.js and the page, and renders the vibrator +// list. Every vibrator (one vibrate-capable feature on one device) gets its +// own slider, hold-to-max and hold-to-stop buttons. Devices may appear or +// disappear at any time; the registry diff in logic.js keeps output state +// consistent and the UI re-renders from manager state. import { ButtplugBrowserWebsocketClientConnector, @@ -9,7 +13,7 @@ import { InputType, OutputType, } from "./vendor/buttplug.mjs"; -import { createVibrationController, sanitizeSteps, MAX_PATTERN_STEPS } from "./logic.js"; +import { createVibrationManager, vibratorId } from "./logic.js"; // --- helpers ------------------------------------------------------------- @@ -38,16 +42,26 @@ function showError(msg) { } $("banner").addEventListener("click", () => $("banner").classList.add("hidden")); -// --- controller wiring --------------------------------------------------- +// --- manager wiring ------------------------------------------------------ -const controller = createVibrationController({ - sendIntensity(pct) { - if (!device) throw new Error("no device"); - return device.runOutput(DeviceOutput.Vibrate.percent(pct)); +// id -> buttplug feature object for one vibrator. Rebuilt on every registry +// refresh; logic.js holds the per-vibrator UI state. +const features = new Map(); + +const manager = createVibrationManager({ + sendVibrate(id, percent01) { + const f = features.get(id); + if (!f) throw new Error("vibrator is gone"); + return f.runOutput(DeviceOutput.Vibrate.percent(percent01)); + }, + sendStop(id) { + const f = features.get(id); + if (!f) return; // already gone; nothing to stop + return f.runOutput(DeviceOutput.Vibrate.percent(0)); }, - sendStop() { - if (!device) throw new Error("no device"); - return device.stop(); + stopAll() { + if (!client) throw new Error("not connected"); + return client.stopAllDevices(); }, now: () => performance.now(), schedule: (fn, ms) => setTimeout(fn, ms), @@ -56,15 +70,28 @@ const controller = createVibrationController({ showError(`Command failed: ${err?.message ?? err}`); log(`command error: ${err?.message ?? err}`); }, + onEmergencyStop() { + // Future modes stop their own drivers here; direct control has nothing + // beyond the manager's own reset. + }, + onChange: render, }); +function runCommand(fn) { + try { + fn(); + } catch (err) { + manager.handleCommandError(err); + } +} + // --- buttplug client ----------------------------------------------------- let client = null; -let device = null; let reconnectTimer = null; let reconnectDelay = 500; let intentionallyClosed = false; +const batteryText = new Map(); // deviceIndex -> "Battery 87%" function setPill(state, text) { const pill = $("status-pill"); @@ -72,69 +99,189 @@ function setPill(state, text) { pill.textContent = text; } -function setControlsEnabled(enabled) { - for (const id of ["intensity", "hold", "play", "stop", "estop", "add-step", "rescan"]) { - $(id).disabled = !enabled; +// Enumerate every vibrate-capable feature on every connected device and hand +// the list to the manager, which diffs it against the current set. +function refreshRegistry() { + features.clear(); + const descriptors = []; + for (const d of client?.devices.values() ?? []) { + if (!d.hasOutput(OutputType.Vibrate)) continue; + let n = 0; + for (const [featureIndex, f] of d.features) { + if (!f.hasOutput(OutputType.Vibrate)) continue; + n += 1; + const id = vibratorId(d.index, featureIndex); + features.set(id, f); + descriptors.push({ + deviceIndex: d.index, + featureIndex, + deviceName: d.displayName || d.name || "unknown device", + featureLabel: d.features.size > 1 ? `Vibrator ${n}` : "Vibrator", + }); + } } + manager.setVibrators(descriptors); } -function pickDevice(added) { - const candidate = added ?? [...client.devices.values()].find((d) => - d.hasOutput(OutputType.Vibrate), - ); - if (!candidate?.hasOutput(OutputType.Vibrate)) return; - device = candidate; - $("device-name").textContent = candidate.name ?? "unknown device"; - pollBattery(); - setControlsEnabled(true); - log(`device: ${device.name}`); -} - -let batteryTimer = null; +// --- battery polling ----------------------------------------------------- function stopBatteryPolling() { - if (batteryTimer !== null) { - clearInterval(batteryTimer); - batteryTimer = null; - } + // Managed per device below; this clears every poll timer. + for (const t of batteryTimers.values()) clearInterval(t); + batteryTimers.clear(); } +const batteryTimers = new Map(); // deviceIndex -> interval handle -function pollBattery() { +function startBatteryPolling() { stopBatteryPolling(); - const current = device; - if (!current?.hasInput(InputType.Battery)) return; - const refresh = () => { - if (device !== current) { - stopBatteryPolling(); - return; + if (!client) return; + for (const d of client.devices.values()) { + if (!d.hasInput(InputType.Battery)) continue; + const deviceIndex = d.index; + const refresh = () => { + const current = client?.devices.get(deviceIndex); + if (!current) { + const t = batteryTimers.get(deviceIndex); + if (t !== undefined) { + clearInterval(t); + batteryTimers.delete(deviceIndex); + } + batteryText.delete(deviceIndex); + return; + } + current + .battery() + .then((level) => { + batteryText.set(deviceIndex, `Battery ${Math.round(level * 100)}%`); + render(); + }) + .catch(() => { + /* battery read failures are non-fatal */ + }); + }; + refresh(); + batteryTimers.set(deviceIndex, setInterval(refresh, 30000)); + } +} + +// --- rendering ----------------------------------------------------------- + +// Renders the direct-control view from manager state. Called on registry +// changes, connection changes, and emergency stop; slider drags do not +// re-render (the manager holds the value). +function render() { + const host = $("device-list"); + const connected = manager.isConnected(); + host.textContent = ""; + + const vibrators = manager.vibrators(); + if (vibrators.length === 0) { + const p = document.createElement("p"); + p.className = "muted empty-note"; + p.textContent = connected ? "No vibrators found — try a rescan." : "Not connected."; + host.append(p); + return; + } + + // Group vibrators by device, preserving registry order. + const groups = new Map(); // deviceIndex -> {name, items} + for (const v of vibrators) { + let g = groups.get(v.deviceIndex); + if (!g) { + g = { name: v.deviceName, items: [] }; + groups.set(v.deviceIndex, g); } - current - .battery() - .then((level) => { - const bat = $("battery"); - bat.hidden = false; - bat.textContent = `Battery ${Math.round(level * 100)}%`; - }) - .catch(() => { - /* battery read failures are non-fatal */ - }); - }; - refresh(); - batteryTimer = setInterval(refresh, 30000); + g.items.push(v); + } + + for (const [deviceIndex, g] of groups) { + const card = document.createElement("section"); + card.className = "card device-card"; + + const head = document.createElement("div"); + head.className = "device-head"; + const name = document.createElement("h2"); + name.className = "device-name"; + name.textContent = g.name; + head.append(name); + const bat = batteryText.get(deviceIndex); + if (bat) { + const b = document.createElement("span"); + b.className = "muted battery"; + b.textContent = bat; + head.append(b); + } + card.append(head); + + for (const v of g.items) card.append(vibratorRow(v, connected)); + host.append(card); + } } -function onDeviceRemoved(d) { - if (device && d && device.index === d.index) { - device = null; - stopBatteryPolling(); - $("device-name").textContent = "no device"; - $("battery").hidden = true; - controller.emergencyStop(); - setControlsEnabled(!!client?.connected); - log("device removed"); +function vibratorRow(v, connected) { + const row = document.createElement("div"); + row.className = "vrow"; + + const label = document.createElement("span"); + label.className = "vlabel"; + label.textContent = v.featureLabel; + row.append(label); + + const slider = document.createElement("input"); + slider.type = "range"; + slider.min = "0"; + slider.max = "100"; + slider.step = "1"; + slider.value = String(v.slider); + slider.disabled = !connected; + slider.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel} intensity`); + slider.addEventListener("input", () => { + runCommand(() => manager.setSlider(v.id, Number(slider.value))); + }); + row.append(slider); + + const btns = document.createElement("div"); + btns.className = "vbtns"; + const maxBtn = document.createElement("button"); + maxBtn.type = "button"; + maxBtn.className = "hold hold-max"; + maxBtn.textContent = "Hold to max"; + maxBtn.disabled = !connected; + maxBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to vibrate at maximum`); + wireHold(maxBtn, v.id, "max"); + const stopBtn = document.createElement("button"); + stopBtn.type = "button"; + stopBtn.className = "hold hold-stop"; + stopBtn.textContent = "Hold to stop"; + stopBtn.disabled = !connected; + stopBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to stop`); + wireHold(stopBtn, v.id, "stop"); + btns.append(maxBtn, stopBtn); + row.append(btns); + return row; +} + +// Hold buttons: output runs at the hold level while pressed and returns to +// the slider value on release (handled by the manager). +function wireHold(btn, id, kind) { + btn.addEventListener("pointerdown", (e) => { + e.preventDefault(); + btn.setPointerCapture(e.pointerId); + btn.classList.add("holding"); + runCommand(() => manager.setHold(id, kind)); + }); + for (const ev of ["pointerup", "pointercancel", "lostpointercapture"]) { + btn.addEventListener(ev, () => { + if (!btn.classList.contains("holding")) return; + btn.classList.remove("holding"); + runCommand(() => manager.releaseHold(id)); + }); } + btn.addEventListener("contextmenu", (e) => e.preventDefault()); } +// --- connection ---------------------------------------------------------- + async function connect() { if (client?.connected) return; intentionallyClosed = false; @@ -142,17 +289,25 @@ async function connect() { // Register all listeners before connecting (buttplug.js requirement). client.on("disconnect", () => { - device = null; + features.clear(); + batteryText.clear(); stopBatteryPolling(); - setControlsEnabled(false); + manager.setVibrators([]); + manager.handleDisconnect(); setPill("bad", "disconnected"); - controller.handleDisconnect(); scheduleReconnect(); }); - client.on("deviceadded", pickDevice); - client.on("deviceremoved", onDeviceRemoved); + client.on("deviceadded", () => { + refreshRegistry(); + startBatteryPolling(); + log(`device added: ${[...client.devices.values()].at(-1)?.name ?? "?"}`); + }); + client.on("deviceremoved", (d) => { + refreshRegistry(); + log(`device removed: ${d?.name ?? "?"}`); + }); client.on("scanningfinished", () => { - if (!device) pickDevice(); + /* registry is already event-driven; nothing to do */ }); const connector = new ButtplugBrowserWebsocketClientConnector(wsURL()); @@ -161,8 +316,9 @@ async function connect() { await client.connect(connector); setPill("on", "connected"); reconnectDelay = 500; - controller.handleConnected(); - setControlsEnabled(!!device); + manager.handleConnected(); + refreshRegistry(); + startBatteryPolling(); await client.startScanning(); } catch (err) { setPill("bad", "connection failed"); @@ -184,191 +340,31 @@ function scheduleReconnect() { log(`reconnecting in ${reconnectDelay} ms`); } -// --- intensity + hold ---------------------------------------------------- - -$("intensity").addEventListener("input", (e) => { - const pct = Number(e.target.value); - $("intensity-value").textContent = `${pct}%`; - runCommand(() => controller.setIntensity(pct)); -}); -$("intensity").addEventListener("change", (e) => { - if (Number(e.target.value) === 0) runCommand(() => controller.stopVibration()); -}); - -const DEFAULT_HOLD_PERCENT = 50; -const holdBtn = $("hold"); -holdBtn.addEventListener("pointerdown", (e) => { - e.preventDefault(); - holdBtn.setPointerCapture(e.pointerId); - holdBtn.classList.add("holding"); - runCommand(() => controller.holdPress(DEFAULT_HOLD_PERCENT)); -}); -for (const ev of ["pointerup", "pointercancel", "lostpointercapture"]) { - holdBtn.addEventListener(ev, () => { - if (!holdBtn.classList.contains("holding")) return; - holdBtn.classList.remove("holding"); - runCommand(() => controller.holdRelease()); - }); -} - -// --- pattern editor ------------------------------------------------------ -// patternRows is the source of truth while editing; inputs are committed on -// every structural change (add/remove/reorder/play). - -let patternRows = []; - -function commitRows() { - patternRows = patternRows.map((_, i) => ({ - intensity: Number($(`step-intensity-${i}`)?.value) || 0, - duration: Number($(`step-duration-${i}`)?.value) || 0.1, - })); - controller.setPattern(patternRows, $("loop").checked); - savePattern(); -} - -function savePattern() { - try { - localStorage.setItem( - "tsbutt.pattern", - JSON.stringify({ steps: patternRows, loop: $("loop").checked }), - ); - } catch { - /* private mode etc. — pattern just won't persist */ - } -} - -function renderRows() { - const ol = $("steps"); - ol.textContent = ""; - patternRows.forEach((step, i) => { - const li = document.createElement("li"); - - const label = document.createElement("span"); - label.className = "step-label"; - label.textContent = `${i + 1}.`; - - const inten = document.createElement("input"); - inten.type = "number"; - inten.min = "0"; - inten.max = "100"; - inten.step = "5"; - inten.value = String(step.intensity); - inten.id = `step-intensity-${i}`; - inten.setAttribute("aria-label", `Step ${i + 1} intensity percent`); - - const dur = document.createElement("input"); - dur.type = "number"; - dur.min = "0.1"; - dur.max = "600"; - dur.step = "0.1"; - dur.value = String(step.duration); - dur.id = `step-duration-${i}`; - dur.setAttribute("aria-label", `Step ${i + 1} duration seconds`); - - const up = ghostButton("↑", `Move step ${i + 1} up`, () => moveStep(i, -1)); - const down = ghostButton("↓", `Move step ${i + 1} down`, () => moveStep(i, 1)); - const del = ghostButton("✕", `Remove step ${i + 1}`, () => removeStep(i)); - - li.append(label, inten, dur, up, down, del); - ol.append(li); - }); -} - -function ghostButton(text, ariaLabel, onClick) { - const b = document.createElement("button"); - b.type = "button"; - b.className = "ghost"; - b.textContent = text; - b.setAttribute("aria-label", ariaLabel); - b.addEventListener("click", onClick); - return b; -} - -function loadPattern() { - let parsed = null; - try { - parsed = JSON.parse(localStorage.getItem("tsbutt.pattern") ?? "null"); - } catch { - /* fall through to default */ - } - patternRows = sanitizeSteps(parsed?.steps?.length ? parsed.steps : [{ intensity: 60, duration: 1 }]); - $("loop").checked = !!parsed?.loop; - controller.setPattern(patternRows, $("loop").checked); - renderRows(); -} - -function moveStep(i, dir) { - commitRows(); - const j = i + dir; - if (j < 0 || j >= patternRows.length) return; - [patternRows[i], patternRows[j]] = [patternRows[j], patternRows[i]]; - controller.setPattern(patternRows, $("loop").checked); - savePattern(); - renderRows(); -} - -function removeStep(i) { - commitRows(); - patternRows.splice(i, 1); - controller.setPattern(patternRows, $("loop").checked); - savePattern(); - renderRows(); -} - -$("add-step").addEventListener("click", () => { - commitRows(); - if (patternRows.length >= MAX_PATTERN_STEPS) return; - patternRows.push({ intensity: 50, duration: 1 }); - controller.setPattern(patternRows, $("loop").checked); - savePattern(); - renderRows(); -}); - -$("loop").addEventListener("change", commitRows); - // --- transport buttons --------------------------------------------------- -$("play").addEventListener("click", () => { - commitRows(); - runCommand(() => controller.playPattern()); -}); -$("stop").addEventListener("click", () => { - runCommand(() => controller.stopPattern()); -}); $("estop").addEventListener("click", () => { - runCommand(() => controller.emergencyStop()); - $("intensity").value = "0"; - $("intensity-value").textContent = "0%"; + // Unlatched: stop and reset everything now, but keep the app operable. + runCommand(() => manager.emergencyStop({ latch: false })); }); $("rescan").addEventListener("click", () => { if (client?.connected) client.startScanning().catch((e) => log(`scan: ${e.message}`)); }); -function runCommand(fn) { - try { - fn(); - } catch (err) { - controller.handleCommandError(err); - } -} - -// --- safety: page lifecycle (AC.7) --------------------------------------- +// --- safety: page lifecycle ---------------------------------------------- document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") { - controller.handlePageHide(); + manager.handlePageHide(); } else { - controller.handleVisible(); + manager.handleVisible(); } }); -window.addEventListener("pagehide", () => controller.handlePageHide()); +window.addEventListener("pagehide", () => manager.handlePageHide()); // Last-resort net: any rejection that escapes every handler must still stop -// the toy. (All command paths are already routed through logic.js dispatch.) -window.addEventListener("unhandledrejection", () => controller.emergencyStop()); +// the toys. (All command paths are already routed through logic.js dispatch.) +window.addEventListener("unhandledrejection", () => manager.emergencyStop()); // --- boot ---------------------------------------------------------------- -setControlsEnabled(false); -loadPattern(); connect(); log(`webapp loaded; ws target ${wsURL()}`); diff --git a/tsbridge/webapp/index.html b/tsbridge/webapp/index.html index 448383c..90f7e44 100644 --- a/tsbridge/webapp/index.html +++ b/tsbridge/webapp/index.html @@ -10,43 +10,19 @@

tsbutt

+
connecting…
-
-

Device

-

no device

- - -
- -
-

Intensity

- 0% - - -
- -
-

Pattern

-
    -
    - - -
    -
    - - -
    -
    - -
    - -
    +
    + +
    +
    +
    +
    Status log @@ -54,6 +30,12 @@
    + +
    + +
    + diff --git a/tsbridge/webapp/logic.js b/tsbridge/webapp/logic.js index c528a88..bac16f6 100644 --- a/tsbridge/webapp/logic.js +++ b/tsbridge/webapp/logic.js @@ -1,94 +1,122 @@ // tsbutt webapp logic — DOM-free so test.html can exercise it with a fake // clock. All device interaction goes through `ports`: // -// ports.sendIntensity(percent01) — vibrate at 0..1 (throws on failure) -// ports.sendStop() — stop vibration (throws on failure) -// ports.now() — milliseconds -// ports.schedule(fn, delayMs) — timer handle -// ports.cancel(handle) — clear timer +// ports.sendVibrate(id, percent01) — vibrate one vibrator at 0..1; may +// throw or reject on failure +// ports.sendStop(id) — stop one vibrator (may throw/reject) +// ports.stopAll() — stop every device (emergency stop) +// ports.now() — milliseconds +// ports.schedule(fn, delayMs) — one-shot timer handle +// ports.cancel(handle) — clear timer +// ports.onError(err) — optional failed-command reporter +// ports.onChange() — optional registry/state change hook +// ports.onEmergencyStop() — optional hook run when halting (modes +// use it to stop their own drivers) // -// Safety invariants (AC.7): any disconnect, page hide, or failed command -// halts every timer and issues sendStop() exactly once per event. +// Every vibrator is addressed by a stable id ("deviceIndex:featureIndex"). +// The output for each vibrator is computed by ONE codepath: a hold override +// ("max" or "stop") if one is active, otherwise the base value supplied by +// the active mode's base provider. Modes switch providers via +// setBaseProvider(); devices may be added or removed at any time via +// setVibrators() and every vibrator immediately joins the current base. +// +// Safety invariants: any disconnect, page hide, or failed command halts +// everything and issues a stop. Emergency stop also clears holds and resets +// all slider set-points to 0. export const MIN_COMMAND_INTERVAL_MS = 100; -export const MAX_PATTERN_STEPS = 32; export function clampPercent(pct) { if (typeof pct !== "number" || Number.isNaN(pct)) return 0; return Math.min(100, Math.max(0, pct)); } -export function sanitizeSteps(steps) { - if (!Array.isArray(steps)) return []; - return steps - .slice(0, MAX_PATTERN_STEPS) - .map((s) => ({ - intensity: clampPercent(Number(s && s.intensity)), - duration: Math.max(0.1, Math.min(600, Number(s && s.duration) || 0.1)), - })); +export function vibratorId(deviceIndex, featureIndex) { + return `${deviceIndex}:${featureIndex}`; } -export function createVibrationController(ports) { +// Normalize a list of vibrator descriptors ({deviceIndex, featureIndex, +// deviceName, featureLabel}) into stable, deduplicated snapshots. +export function sanitizeVibrators(list) { + if (!Array.isArray(list)) return []; + const seen = new Set(); + const out = []; + for (const d of list) { + if (!d) continue; + if (typeof d.deviceIndex !== "number" || typeof d.featureIndex !== "number") continue; + const id = vibratorId(d.deviceIndex, d.featureIndex); + if (seen.has(id)) continue; + seen.add(id); + out.push({ + id, + deviceIndex: d.deviceIndex, + featureIndex: d.featureIndex, + deviceName: String(d.deviceName ?? "unknown device"), + featureLabel: String(d.featureLabel ?? "?"), + }); + } + return out; +} + +export function createVibrationManager(ports) { + // id -> {id, deviceIndex, featureIndex, deviceName, featureLabel, + // slider, hold, lastSentPct, lastSentAt, pendingTrailing} + const vibrators = new Map(); let connected = false; - let desired = 0; // last requested intensity, percent - let lastSentAt = -Infinity; - let pendingTrailing = null; - let halted = false; // set by safety events until explicitly resumed - - // Pattern executor state. - let steps = []; - let loop = false; - let playing = false; - let stepIndex = -1; - let stepTimer = null; - - function cancelPending() { - if (pendingTrailing !== null) { - ports.cancel(pendingTrailing); - pendingTrailing = null; - } + let halted = true; // safety latch; lifted by handleConnected/handleVisible + let baseProvider = null; // (vibratorState) => percent 0..100 + + function snapshot(st) { + return { + id: st.id, + deviceIndex: st.deviceIndex, + featureIndex: st.featureIndex, + deviceName: st.deviceName, + featureLabel: st.featureLabel, + slider: st.slider, + hold: st.hold, + }; } - function cancelStepTimer() { - if (stepTimer !== null) { - ports.cancel(stepTimer); - stepTimer = null; + function onChange() { + if (typeof ports.onChange === "function") { + try { + ports.onChange(); + } catch { + /* UI render failures must never affect device state */ + } } } - function sendIntensity(pct) { - desired = pct; - if (!connected || halted) return; - const elapsed = ports.now() - lastSentAt; - if (elapsed >= MIN_COMMAND_INTERVAL_MS) { - lastSentAt = ports.now(); - dispatch(() => ports.sendIntensity(pct / 100)); - return; + function cancelPending(st) { + if (st.pendingTrailing !== null) { + ports.cancel(st.pendingTrailing); + st.pendingTrailing = null; } - // Trailing edge: make sure the final requested value is sent once the - // throttle window closes. A later setIntensity reschedules, not stacks. - if (pendingTrailing === null) { - pendingTrailing = ports.schedule(() => { - pendingTrailing = null; - if (!connected || halted) return; - lastSentAt = ports.now(); - dispatch(() => ports.sendIntensity(desired / 100)); - }, MIN_COMMAND_INTERVAL_MS - elapsed); + } + + function baseFor(st) { + if (typeof baseProvider === "function") { + try { + return clampPercent(baseProvider(st)); + } catch { + return 0; + } } + // No mode installed: direct control falls back to the slider set-point. + return st.slider; } - function sendStop() { - desired = 0; - cancelPending(); - if (!connected || halted) return; - lastSentAt = ports.now(); - dispatch(() => ports.sendStop()); + function effective(st) { + if (st.hold === "max") return 100; + if (st.hold === "stop") return 0; + return baseFor(st); } // dispatch funnels every device command through safety handling: buttplug // commands are async, so failures surface as rejections, and ports may also - // throw synchronously (e.g. no device). Either way a failed command halts - // everything and issues a stop (AC.7) — including from timer callbacks, + // throw synchronously (e.g. device vanished). Either way a failed command + // halts everything and issues a stop — including from timer callbacks, // which have no other try/catch around them. function dispatch(issue) { let result; @@ -101,121 +129,218 @@ export function createVibrationController(ports) { Promise.resolve(result).catch((err) => handleCommandError(err)); } - // --- safety events --- - - function emergencyStop() { - halted = true; - playing = false; - stepIndex = -1; - cancelPending(); - cancelStepTimer(); - desired = 0; - if (connected) { - // Bypasses the halted guard deliberately: a stop must go out even - // though we are halting. Failure here is surfaced by dispatch. - dispatch(() => ports.sendStop()); + function sendNow(st, pct) { + st.lastSentPct = pct; + st.lastSentAt = ports.now(); + if (pct === 0) { + dispatch(() => ports.sendStop(st.id)); + } else { + dispatch(() => ports.sendVibrate(st.id, pct / 100)); } } - function handleCommandError(err) { - emergencyStop(); - if (ports.onError) ports.onError(err); + // Bring one vibrator's output to its current effective value. Skips work + // when the value is unchanged; nonzero values are throttled per vibrator + // with a trailing send so the latest value always lands. + function sync(id, force = false) { + const st = vibrators.get(id); + if (!st) return; + const pct = halted ? 0 : effective(st); + if (!force && pct === st.lastSentPct) return; + st.lastSentPct = pct; + if (pct === 0) { + // Stops are never throttled; they must land immediately. + cancelPending(st); + if (!connected) return; + st.lastSentAt = ports.now(); + dispatch(() => ports.sendStop(st.id)); + return; + } + if (!connected) return; + const elapsed = ports.now() - st.lastSentAt; + if (elapsed >= MIN_COMMAND_INTERVAL_MS) { + sendNow(st, pct); + return; + } + // Inside the throttle window: make sure the latest value is sent once it + // closes. A later sync reschedules nothing and stacks nothing — the + // trailing callback reads the effective value at fire time. + if (st.pendingTrailing === null) { + st.pendingTrailing = ports.schedule(() => { + st.pendingTrailing = null; + if (!connected || halted) return; + const pctNow = effective(st); + sendNow(st, pctNow); + }, MIN_COMMAND_INTERVAL_MS - elapsed); + } } - function handleDisconnect() { - const wasConnected = connected; - connected = false; - emergencyStop(); - return wasConnected; + function refreshBase() { + for (const st of vibrators.values()) sync(st.id); } - function handlePageHide() { - emergencyStop(); - } + // --- registry ------------------------------------------------------------ - function handleConnected() { - connected = true; - halted = false; + // Replace the vibrator set. Removed vibrators are dropped (their device is + // gone; the server has already stopped it). Added vibrators start with a + // 0 slider, no hold, and immediately sync to the current base so they join + // whatever the active mode is doing. + function setVibrators(descriptors) { + const list = sanitizeVibrators(descriptors); + const next = new Map(); + for (const d of list) { + const prev = vibrators.get(d.id); + next.set( + d.id, + prev ?? { + id: d.id, + deviceIndex: d.deviceIndex, + featureIndex: d.featureIndex, + deviceName: d.deviceName, + featureLabel: d.featureLabel, + slider: 0, + hold: null, + lastSentPct: 0, + lastSentAt: -Infinity, + pendingTrailing: null, + }, + ); + } + const changed = + next.size !== vibrators.size || + [...next.keys()].some((id) => !vibrators.has(id)) || + [...next.values()].some( + (st) => + st.deviceName !== vibrators.get(st.id)?.deviceName || + st.featureLabel !== vibrators.get(st.id)?.featureLabel, + ); + vibrators.clear(); + for (const [k, v] of next) vibrators.set(k, v); + refreshBase(); + if (changed) onChange(); } - // handleVisible undoes the halt from handlePageHide for the common - // app-switch case (hidden then visible with no disconnect). Desired - // intensity was reset to 0 by the emergency stop, so nothing vibrates on - // resume until the user acts. - function handleVisible() { - if (connected) { - halted = false; - } + // --- controls ------------------------------------------------------------ + + // Direct-control set-point. Applies immediately unless a hold is active; + // the hold release then returns output to this value. + function setSlider(id, pct) { + const st = vibrators.get(id); + if (!st) return; + st.slider = clampPercent(pct); + if (st.hold === null) sync(id); } - function isPlaying() { - return playing; + function setHold(id, kind) { + const st = vibrators.get(id); + if (!st) return; + if (kind !== "max" && kind !== "stop") return; + st.hold = kind; + sync(id); } - function currentDesired() { - return desired; + function releaseHold(id) { + const st = vibrators.get(id); + if (!st || st.hold === null) return; + st.hold = null; + sync(id); } - // --- pattern executor --- + // --- mode abstraction ---------------------------------------------------- - function setPattern(newSteps, newLoop) { - if (playing) stopPattern(); - steps = sanitizeSteps(newSteps); - loop = !!newLoop; + // The active mode installs a provider; it is consulted for every vibrator + // on every sync. Pass null for "everything at 0". + function setBaseProvider(fn) { + baseProvider = fn; + refreshBase(); } - function playPattern() { - if (playing || steps.length === 0) return; - playing = true; - stepIndex = 0; - runStep(); - } + // --- safety events ------------------------------------------------------- - function runStep() { - const step = steps[stepIndex]; - if (!step) { - stopPattern(); - return; + // Stop everything now: clear holds, reset slider set-points, halt all + // timers, and issue a global stop. `latch` keeps controls halted afterwards + // (used by safety events: page hide, failed commands); the user-facing + // emergency stop button passes latch:false so the app stays operable. + function emergencyStop({ latch = true } = {}) { + halted = latch; + for (const st of vibrators.values()) { + st.hold = null; + st.slider = 0; + st.lastSentPct = 0; + cancelPending(st); + } + if (typeof ports.onEmergencyStop === "function") { + try { + ports.onEmergencyStop(); + } catch { + /* mode cleanup must not block the stop */ + } } - sendIntensity(step.intensity); - stepTimer = ports.schedule(() => { - stepTimer = null; - if (!playing) return; - stepIndex++; - if (stepIndex >= steps.length) { - if (loop) { - stepIndex = 0; - } else { - stopPattern(); - return; + if (connected) { + // Reported directly rather than through dispatch: a failure here must + // not re-enter emergencyStop. + try { + const r = ports.stopAll(); + if (r && typeof r.catch === "function") { + r.catch((err) => ports.onError?.(err)); } + } catch (err) { + ports.onError?.(err); } - runStep(); - }, step.duration * 1000); + } + onChange(); } - function stopPattern() { - playing = false; - stepIndex = -1; - cancelStepTimer(); - sendStop(); + function handleCommandError(err) { + emergencyStop(); + if (ports.onError) ports.onError(err); } - // --- hold button --- + function handleDisconnect() { + const wasConnected = connected; + connected = false; + halted = true; + for (const st of vibrators.values()) { + st.hold = null; + st.slider = 0; + st.lastSentPct = 0; + cancelPending(st); + } + return wasConnected; + } + + function handlePageHide() { + emergencyStop(); + } - function holdPress(pct) { - sendIntensity(clampPercent(pct)); + function handleConnected() { + connected = true; + halted = false; + // Devices were stopped at disconnect; desired state is all zeros, so a + // plain (deduplicated) refresh is enough. + refreshBase(); } - function holdRelease() { - sendStop(); + // handleVisible undoes the halt from handlePageHide for the common + // app-switch case (hidden then visible with no disconnect). Emergency stop + // already reset sliders to 0, so nothing vibrates on resume until the user + // or an active mode drives output again. + function handleVisible() { + if (connected) { + halted = false; + refreshBase(); + } } return { // state queries (for tests/UI) - currentDesired, - isPlaying, - patternLength: () => steps.length, + vibrators: () => [...vibrators.values()].map(snapshot), + vibrator: (id) => { + const st = vibrators.get(id); + return st ? snapshot(st) : undefined; + }, + isConnected: () => connected, + isHalted: () => halted, // connection lifecycle handleConnected, handleDisconnect, @@ -223,13 +348,13 @@ export function createVibrationController(ports) { handleVisible, handleCommandError, emergencyStop, + // registry + modes + setVibrators, + setBaseProvider, + refreshBase, // controls - setIntensity: sendIntensity, - stopVibration: sendStop, - holdPress, - holdRelease, - setPattern, - playPattern, - stopPattern, + setSlider, + setHold, + releaseHold, }; } diff --git a/tsbridge/webapp/style.css b/tsbridge/webapp/style.css index 19ac97e..2f6e8dd 100644 --- a/tsbridge/webapp/style.css +++ b/tsbridge/webapp/style.css @@ -10,6 +10,8 @@ --ok: #2ed573; --warn: #ffa502; --radius: 12px; + /* Height of the fixed emergency-stop dock; content must clear it. */ + --estop-dock: 4.4rem; } * { box-sizing: border-box; } @@ -28,9 +30,12 @@ body { #app { margin: 0 auto; - max-width: 32rem; + /* Wide enough to use desktop real estate (waveforms, freehand canvas), + narrow enough to keep visible margins on very large screens. */ + max-width: 60rem; padding: 1rem; - padding-bottom: calc(1rem + env(safe-area-inset-bottom)); + /* Always leave room for the fixed emergency-stop dock. */ + padding-bottom: calc(var(--estop-dock) + env(safe-area-inset-bottom)); display: flex; flex-direction: column; gap: 0.9rem; @@ -101,6 +106,7 @@ button.ghost { color: var(--muted); padding: 0.4rem 0.6rem; } +button.ghost:disabled { color: #55555e; } input[type="range"] { width: 100%; @@ -108,33 +114,69 @@ input[type="range"] { accent-color: var(--accent); } -output { font-size: 1.6rem; font-weight: 700; } +/* --- direct control: per-vibrator rows ---------------------------------- */ -#hold { width: 100%; margin-top: 0.5rem; } -#hold.holding { background: var(--danger); } - -#steps { list-style: none; margin: 0 0 0.5rem; padding: 0; display: flex; flex-direction: column; gap: 0.4rem; } -#steps li { +.device-head { display: flex; - align-items: center; - gap: 0.4rem; + align-items: baseline; + justify-content: space-between; + gap: 0.5rem; +} +.device-name { + font-size: 1rem; + margin: 0 0 0.5rem; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.05em; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.battery { font-size: 0.85rem; white-space: nowrap; } + +.vrow { background: var(--bg); border-radius: var(--radius); - padding: 0.4rem 0.6rem; + padding: 0.5rem 0.7rem; + display: flex; + flex-direction: column; + gap: 0.3rem; } -#steps .step-label { flex: 1; font-variant-numeric: tabular-nums; } -#steps input[type="number"] { - width: 4.5rem; - background: var(--card); +.vrow + .vrow { margin-top: 0.5rem; } +.vlabel { + font-size: 0.9rem; + font-weight: 600; color: var(--text); - border: 1px solid #33333c; - border-radius: 8px; - padding: 0.4rem; - font-size: 0.95rem; } - -.row { display: flex; gap: 0.5rem; align-items: center; margin-top: 0.5rem; flex-wrap: wrap; } -.row button { flex: 1; } +.vbtns { display: flex; gap: 0.5rem; } +.vbtns .hold { flex: 1; padding: 0.6rem 0.4rem; font-size: 0.9rem; } +/* Hold button colors are shared with every mode's compact hold buttons. */ +.hold-max { background: var(--accent); } +.hold-stop { background: var(--danger); } +.hold.holding { filter: brightness(1.35); } +.empty-note { padding: 0.5rem 0.2rem; } + +/* --- emergency stop dock ------------------------------------------------- */ +/* Fixed to the bottom of the viewport in every view; nothing may cover it. */ + +#estop-dock { + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 100; + padding: 0.5rem 1.25rem calc(0.5rem + env(safe-area-inset-bottom)); + background: linear-gradient(to top, var(--bg) 70%, transparent); +} +#estop-dock .danger { + border-radius: var(--radius); + /* Prominent but not overwhelming; centered with breathing room. */ + max-width: 40rem; + margin: 0 auto; + display: block; + padding: 0.9rem 1.2rem; + font-size: 1.05rem; +} #log { max-height: 12rem; @@ -146,26 +188,3 @@ output { font-size: 1.6rem; font-weight: 700; } details { font-size: 0.85rem; } summary { color: var(--muted); cursor: pointer; } - -/* Landscape phones: two-column layout for intensity + pattern. */ -@media (orientation: landscape) and (min-width: 640px) { - #app { - max-width: 46rem; - display: grid; - grid-template-columns: 1fr 1fr; - grid-template-areas: - "header header" - "banner banner" - "device device" - "intensity pattern" - "estop estop" - "log log"; - } - header { grid-area: header; } - .banner { grid-area: banner; } - #device-card { grid-area: device; } - #intensity-card { grid-area: intensity; } - #pattern-card { grid-area: pattern; } - #estop-card { grid-area: estop; } - #log-details { grid-area: log; } -} diff --git a/tsbridge/webapp/test.html b/tsbridge/webapp/test.html index d4188c9..765fb1f 100644 --- a/tsbridge/webapp/test.html +++ b/tsbridge/webapp/test.html @@ -17,10 +17,10 @@