send full rotator state to new clients over a typed WebSocket protocol

- Build the init message per connection from live state. Dynamic data is
  only broadcast on change, so new browsers showed rotators as OFFLINE
  until something moved.
- Load init data once a rotator is reachable and push it to clients;
  rotators offline at startup used to stay without name/map/offsets.
- Replace label-keyed messages (which could collide with 'radioInfo') with
  typed ServerMessage variants: init, initData, dynamic, setpoint, radioInfo.
- Keep setpoints in RotClient and station radio state in RotRouter instead
  of mutating a snapshot in index.ts.
- Include the resolved station in setpoints; the UI shows the station name
  in its colour instead of the source IP.
- Close stale WebSocket clients; drop the empty handleMessage stub.
- Replace TurnMessageHandler with plain callbacks; rename config types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 03:00:34 +00:00
co-authored by Claude Opus 5.5
parent db328336f1
commit 1fa6f2251c
6 changed files with 334 additions and 330 deletions
+60 -36
View File
@@ -1,4 +1,4 @@
import type { ClientConfig, DynamicData, InitData } from './types.js';
import type { DynamicData, InitData, RotatorConfig, RotatorState, Setpoint } from './types.js';
const ROTATOR_PORT = 88;
const POLL_INTERVAL_MS = 1000;
@@ -24,15 +24,21 @@ export default class RotClient {
readonly label: string;
private readonly ip: string;
private readonly bands: number[];
private cachedData: InitData | null = null;
private initData: InitData | null = null;
private initDataLoading = false;
private dynamicData: DynamicData | null = null;
private setpoint: Setpoint | null = null;
private readonly dynamicHandlers: Array<(data: DynamicData) => void> = [];
private readonly initDataHandlers: Array<(data: InitData) => void> = [];
constructor(label: string, { ip, bands }: ClientConfig) {
constructor(label: string, { ip, bands }: RotatorConfig) {
this.label = label;
this.ip = ip;
this.bands = bands;
}
/** Starts polling the controller. Init data is loaded once the rotator is reachable. */
start(): void {
const poll = async () => {
await this.fetchDynamicData();
setTimeout(() => void poll(), POLL_INTERVAL_MS);
@@ -40,13 +46,56 @@ export default class RotClient {
void poll();
}
async readInitData(): Promise<InitData> {
if (this.cachedData) return this.cachedData;
onDynamicDataUpdate(handler: (data: DynamicData) => void): void {
this.dynamicHandlers.push(handler);
}
const values = await Promise.all(INIT_ENDPOINTS.map(([, url, type]) => this.readKey(url, type)));
this.cachedData = Object.fromEntries(INIT_ENDPOINTS.map(([key], i) => [key, values[i]])) as unknown as InitData;
console.log(`${this.label}: Loaded init data (azimuth offset ${this.cachedData.azShift}°).`);
return this.cachedData;
onInitDataLoaded(handler: (data: InitData) => void): void {
this.initDataHandlers.push(handler);
}
hasBand(band: number): boolean {
return this.bands.includes(band);
}
getState(): RotatorState {
return {
initData: this.initData,
dynamic: this.dynamicData,
bands: this.bands,
setpoint: this.setpoint,
};
}
turn(setpoint: Setpoint): void {
this.setpoint = setpoint;
console.log(`Turning ${this.label} to ${setpoint.targetAz}° (by ${setpoint.station ?? setpoint.sourceIp})`);
fetch(`${this.baseUrl()}/`, {
body: `ROT=${setpoint.targetAz}`,
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
}).catch((ex: Error) => console.error(`${this.label}: Failed to send turn command: ${ex.cause ?? ex.message}`));
}
private baseUrl(): string {
return `http://${this.ip}:${ROTATOR_PORT}`;
}
private async loadInitData(): Promise<void> {
if (this.initData || this.initDataLoading) return;
this.initDataLoading = true;
try {
const values = await Promise.all(INIT_ENDPOINTS.map(([, url, type]) => this.readKey(url, type)));
// The rotator may have dropped off mid-read; retry on the next successful poll.
if (values.every(v => v === null)) return;
const data = Object.fromEntries(INIT_ENDPOINTS.map(([key], i) => [key, values[i]])) as unknown as InitData;
this.initData = data;
console.log(`${this.label}: Loaded init data (azimuth offset ${data.azShift}°).`);
this.initDataHandlers.forEach(h => h(data));
} finally {
this.initDataLoading = false;
}
}
private async fetchDynamicData(): Promise<void> {
@@ -63,41 +112,16 @@ export default class RotClient {
};
const old = this.dynamicData;
const changed = old !== null && (Object.keys(data) as Array<keyof DynamicData>).some(k => old[k] !== data[k]);
const changed = !old || (Object.keys(data) as Array<keyof DynamicData>).some(k => old[k] !== data[k]);
this.dynamicData = data;
if (old?.online !== data.online) {
console.log(`${this.label}: ${data.online ? 'online' : 'offline'}`);
}
if (data.online) void this.loadInitData();
if (changed) this.dynamicHandlers.forEach(h => h(data));
}
onDynamicDataUpdate(handler: (data: DynamicData) => void): void {
this.dynamicHandlers.push(handler);
}
hasBand(band: number): boolean {
return this.bands.includes(band);
}
getBands(): number[] {
return this.bands;
}
turn(az: number): void {
console.log(`Turning ${this.label} to ${az}°...`);
fetch(`${this.baseUrl()}/`, {
body: `ROT=${az}`,
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
}).catch((ex: Error) => console.error(`${this.label}: Failed to send turn command: ${ex.cause ?? ex.message}`));
}
private baseUrl(): string {
return `http://${this.ip}:${ROTATOR_PORT}`;
}
private async readKey(endpoint: string, type: NumType): Promise<string | number | null> {
try {
const resp = await fetch(`${this.baseUrl()}/${endpoint}`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });