- 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>
139 lines
4.6 KiB
TypeScript
139 lines
4.6 KiB
TypeScript
import type { DynamicData, InitData, RotatorConfig, RotatorState, Setpoint } from './types.js';
|
|
|
|
const ROTATOR_PORT = 88;
|
|
const POLL_INTERVAL_MS = 1000;
|
|
const REQUEST_TIMEOUT_MS = 2000;
|
|
|
|
type NumType = 'string' | 'int' | 'float';
|
|
|
|
const INIT_ENDPOINTS: ReadonlyArray<[keyof InitData, string, NumType]> = [
|
|
['azShift', 'readStart', 'int' ],
|
|
['azRange', 'readMax', 'int' ],
|
|
['antRadiationAngle', 'readAnt', 'int' ],
|
|
['antName', 'readAntName', 'string'],
|
|
['mapUrl', 'readMapUrl', 'string'],
|
|
['mac', 'readMAC', 'string'],
|
|
['elevation', 'readElevation', 'int' ],
|
|
];
|
|
|
|
/**
|
|
* Client for the simple_rotator_interface_v protocol.
|
|
* @see https://remoteqth.com/w/doku.php?id=simple_rotator_interface_v
|
|
*/
|
|
export default class RotClient {
|
|
readonly label: string;
|
|
private readonly ip: string;
|
|
private readonly bands: number[];
|
|
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 }: 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);
|
|
};
|
|
void poll();
|
|
}
|
|
|
|
onDynamicDataUpdate(handler: (data: DynamicData) => void): void {
|
|
this.dynamicHandlers.push(handler);
|
|
}
|
|
|
|
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> {
|
|
const [adc, azimuth, status] = await Promise.all([
|
|
this.readKey('readADC', 'float'),
|
|
this.readKey('readAZ', 'int'),
|
|
this.readKey('readStat', 'int'),
|
|
]);
|
|
const data: DynamicData = {
|
|
adc: adc as number | null,
|
|
azimuth: azimuth as number | null,
|
|
status: status as number | null,
|
|
online: azimuth !== null,
|
|
};
|
|
|
|
const old = this.dynamicData;
|
|
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));
|
|
}
|
|
|
|
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) });
|
|
if (!resp.ok) return null;
|
|
const text = await resp.text();
|
|
if (type === 'string') return text;
|
|
const value = type === 'int' ? parseInt(text, 10) : parseFloat(text);
|
|
return Number.isFinite(value) ? value : null;
|
|
} catch {
|
|
// Unreachable rotators are reported via the `online` flag rather than logged every second.
|
|
return null;
|
|
}
|
|
}
|
|
}
|