|
| 1 | +import { hubManagementV1Api } from '$lib/api'; |
| 2 | +import { ControlType } from '$lib/signalr/models/ControlType'; |
| 3 | +import { SvelteMap } from 'svelte/reactivity'; |
| 4 | +import { toast } from 'svelte-sonner'; |
| 5 | + |
| 6 | +const TICK_INTERVAL_MS = 100; |
| 7 | + |
| 8 | +export enum LiveConnectionState { |
| 9 | + Disconnected = 0, |
| 10 | + Connecting = 1, |
| 11 | + Connected = 2, |
| 12 | +} |
| 13 | + |
| 14 | +export class LiveShockerState { |
| 15 | + isDragging = $state(false); |
| 16 | + intensity = $state(0); |
| 17 | + type = $state<ControlType>(ControlType.Vibrate); |
| 18 | +} |
| 19 | + |
| 20 | +export class LiveDeviceConnection { |
| 21 | + deviceId: string; |
| 22 | + state = $state<LiveConnectionState>(LiveConnectionState.Disconnected); |
| 23 | + gateway = $state<string | null>(null); |
| 24 | + country = $state<string | null>(null); |
| 25 | + latency = $state(0); |
| 26 | + |
| 27 | + shockers = new SvelteMap<string, LiveShockerState>(); |
| 28 | + |
| 29 | + private ws: WebSocket | null = null; |
| 30 | + private tickTimer: ReturnType<typeof setTimeout> | null = null; |
| 31 | + |
| 32 | + constructor(deviceId: string) { |
| 33 | + this.deviceId = deviceId; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Ensure a LiveShockerState exists. Call from $effect or event handler, not template. |
| 38 | + */ |
| 39 | + ensureShockerState(shockerId: string): void { |
| 40 | + if (!this.shockers.has(shockerId)) { |
| 41 | + this.shockers.set(shockerId, new LiveShockerState()); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Read-only getter, safe for templates. Returns undefined if not yet initialised. |
| 47 | + */ |
| 48 | + getShockerState(shockerId: string): LiveShockerState | undefined { |
| 49 | + return this.shockers.get(shockerId); |
| 50 | + } |
| 51 | + |
| 52 | + async connect() { |
| 53 | + this.disconnect(); |
| 54 | + this.state = LiveConnectionState.Connecting; |
| 55 | + |
| 56 | + try { |
| 57 | + const res = await hubManagementV1Api.devicesGetLiveControlGatewayInfo(this.deviceId); |
| 58 | + if (!res.data) { |
| 59 | + throw new Error('No LCG data returned'); |
| 60 | + } |
| 61 | + |
| 62 | + this.gateway = res.data.gateway; |
| 63 | + this.country = res.data.country; |
| 64 | + |
| 65 | + const ws = new WebSocket(`wss://${this.gateway}/1/ws/live/${this.deviceId}`); |
| 66 | + this.ws = ws; |
| 67 | + |
| 68 | + ws.onopen = () => { |
| 69 | + this.state = LiveConnectionState.Connected; |
| 70 | + this.startTickLoop(); |
| 71 | + }; |
| 72 | + |
| 73 | + ws.onmessage = (event) => { |
| 74 | + try { |
| 75 | + const msg = JSON.parse(event.data); |
| 76 | + switch (msg.ResponseType) { |
| 77 | + case 'Ping': |
| 78 | + ws.send( |
| 79 | + JSON.stringify({ |
| 80 | + RequestType: 'Pong', |
| 81 | + Data: { Timestamp: msg.Data.Timestamp }, |
| 82 | + }), |
| 83 | + ); |
| 84 | + break; |
| 85 | + case 'LatencyAnnounce': |
| 86 | + this.latency = msg.Data.OwnLatency; |
| 87 | + break; |
| 88 | + } |
| 89 | + } catch { |
| 90 | + // Ignore malformed messages |
| 91 | + } |
| 92 | + }; |
| 93 | + |
| 94 | + ws.onclose = () => { |
| 95 | + this.handleDisconnect(); |
| 96 | + }; |
| 97 | + |
| 98 | + ws.onerror = () => { |
| 99 | + this.handleDisconnect(); |
| 100 | + }; |
| 101 | + } catch (error) { |
| 102 | + console.error('Failed to connect to LCG:', error); |
| 103 | + toast.error('Failed to connect to live control gateway'); |
| 104 | + this.handleDisconnect(); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + disconnect() { |
| 109 | + this.stopTickLoop(); |
| 110 | + if (this.ws) { |
| 111 | + this.ws.onclose = null; |
| 112 | + this.ws.onerror = null; |
| 113 | + this.ws.close(); |
| 114 | + this.ws = null; |
| 115 | + } |
| 116 | + this.state = LiveConnectionState.Disconnected; |
| 117 | + this.latency = 0; |
| 118 | + } |
| 119 | + |
| 120 | + private handleDisconnect() { |
| 121 | + this.stopTickLoop(); |
| 122 | + this.ws = null; |
| 123 | + this.state = LiveConnectionState.Disconnected; |
| 124 | + this.latency = 0; |
| 125 | + } |
| 126 | + |
| 127 | + private startTickLoop() { |
| 128 | + this.stopTickLoop(); |
| 129 | + const tick = () => { |
| 130 | + if (this.state !== LiveConnectionState.Connected || !this.ws) return; |
| 131 | + |
| 132 | + for (const [shockerId, shocker] of this.shockers) { |
| 133 | + if (!shocker.isDragging) continue; |
| 134 | + |
| 135 | + this.ws.send( |
| 136 | + JSON.stringify({ |
| 137 | + RequestType: 'Frame', |
| 138 | + Data: { |
| 139 | + Shocker: shockerId, |
| 140 | + Intensity: Math.round(shocker.intensity), |
| 141 | + Type: ControlType[shocker.type].toLowerCase(), |
| 142 | + }, |
| 143 | + }), |
| 144 | + ); |
| 145 | + } |
| 146 | + |
| 147 | + this.tickTimer = setTimeout(tick, TICK_INTERVAL_MS); |
| 148 | + }; |
| 149 | + tick(); |
| 150 | + } |
| 151 | + |
| 152 | + private stopTickLoop() { |
| 153 | + if (this.tickTimer !== null) { |
| 154 | + clearTimeout(this.tickTimer); |
| 155 | + this.tickTimer = null; |
| 156 | + } |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +/** Map of deviceId → LiveDeviceConnection */ |
| 161 | +export const liveConnections = new SvelteMap<string, LiveDeviceConnection>(); |
| 162 | + |
| 163 | +/** |
| 164 | + * Ensure a LiveDeviceConnection exists for the given device. |
| 165 | + * Call this from an $effect or event handler — NOT from a template expression or $derived. |
| 166 | + */ |
| 167 | +export function ensureLiveConnection(deviceId: string): void { |
| 168 | + if (!liveConnections.has(deviceId)) { |
| 169 | + liveConnections.set(deviceId, new LiveDeviceConnection(deviceId)); |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +/** |
| 174 | + * Get an existing LiveDeviceConnection. Returns undefined if not yet initialised. |
| 175 | + * Safe to call from template expressions since it never mutates. |
| 176 | + */ |
| 177 | +export function getLiveConnection(deviceId: string): LiveDeviceConnection | undefined { |
| 178 | + return liveConnections.get(deviceId); |
| 179 | +} |
| 180 | + |
| 181 | +export async function toggleLiveControl(deviceId: string) { |
| 182 | + ensureLiveConnection(deviceId); |
| 183 | + const conn = liveConnections.get(deviceId)!; |
| 184 | + if (conn.state !== LiveConnectionState.Disconnected) { |
| 185 | + conn.disconnect(); |
| 186 | + } else { |
| 187 | + await conn.connect(); |
| 188 | + } |
| 189 | +} |
0 commit comments