harden rotator polling

- Time out requests after 2 s and never start a poll before the previous
  one finished; an offline rotator used to pile up hanging requests.
- Fetch endpoints in parallel.
- Treat non-200 responses and unparseable numbers as null instead of NaN.
- Log online/offline transitions instead of every reading each second.
- Log failed turn commands instead of swallowing them.
- Drop unused getters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 03:00:15 +00:00
co-authored by Claude Opus 5.5
parent 455a4794e3
commit db328336f1
+55 -82
View File
@@ -1,16 +1,20 @@
import type { ClientConfig, DynamicData, InitData } from './types.js'; import type { ClientConfig, DynamicData, InitData } from './types.js';
const enum NumType { const ROTATOR_PORT = 88;
String, const POLL_INTERVAL_MS = 1000;
Int, const REQUEST_TIMEOUT_MS = 2000;
Float,
}
interface EndpointDef { type NumType = 'string' | 'int' | 'float';
key: string;
url: string; const INIT_ENDPOINTS: ReadonlyArray<[keyof InitData, string, NumType]> = [
numType: 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. * Client for the simple_rotator_interface_v protocol.
@@ -29,62 +33,43 @@ export default class RotClient {
this.ip = ip; this.ip = ip;
this.bands = bands; this.bands = bands;
setInterval(() => void this.fetchDynamicData(), 1000); const poll = async () => {
await this.fetchDynamicData();
setTimeout(() => void poll(), POLL_INTERVAL_MS);
};
void poll();
} }
async readInitData(): Promise<InitData> { async readInitData(): Promise<InitData> {
if (this.cachedData) return this.cachedData; if (this.cachedData) return this.cachedData;
const endpoints: EndpointDef[] = [ const values = await Promise.all(INIT_ENDPOINTS.map(([, url, type]) => this.readKey(url, type)));
{ key: 'azShift', url: 'readStart', numType: NumType.Int }, this.cachedData = Object.fromEntries(INIT_ENDPOINTS.map(([key], i) => [key, values[i]])) as unknown as InitData;
{ key: 'azRange', url: 'readMax', numType: NumType.Int }, console.log(`${this.label}: Loaded init data (azimuth offset ${this.cachedData.azShift}°).`);
{ key: 'antRadiationAngle', url: 'readAnt', numType: NumType.Int },
{ key: 'antName', url: 'readAntName', numType: NumType.String },
{ key: 'mapUrl', url: 'readMapUrl', numType: NumType.String },
{ key: 'mac', url: 'readMAC', numType: NumType.String },
{ key: 'elevation', url: 'readElevation', numType: NumType.Int },
];
this.cachedData = await this.readEndpoints(endpoints) as unknown as InitData;
console.log(`${this.label} Set the initial offset to ${this.cachedData.azShift}.`);
return this.cachedData; return this.cachedData;
} }
private async readEndpoints(endpoints: EndpointDef[]): Promise<Record<string, string | number | null>> {
const data: Record<string, string | number | null> = {};
for (const { key, url, numType } of endpoints) {
data[key] = await this.readKey(url, numType);
}
return data;
}
private async fetchDynamicData(): Promise<void> { private async fetchDynamicData(): Promise<void> {
const endpoints: EndpointDef[] = [ const [adc, azimuth, status] = await Promise.all([
{ key: 'adc', url: 'readADC', numType: NumType.Float }, this.readKey('readADC', 'float'),
{ key: 'azimuth', url: 'readAZ', numType: NumType.Int }, this.readKey('readAZ', 'int'),
{ key: 'status', url: 'readStat', numType: NumType.Int }, this.readKey('readStat', 'int'),
]; ]);
const raw = await this.readEndpoints(endpoints);
const data: DynamicData = { const data: DynamicData = {
adc: raw.adc as number | null, adc: adc as number | null,
azimuth: raw.azimuth as number | null, azimuth: azimuth as number | null,
status: raw.status as number | null, status: status as number | null,
online: raw.azimuth !== null, online: azimuth !== null,
}; };
if (this.dynamicData !== null) { const old = this.dynamicData;
const oldData = this.dynamicData; const changed = old !== null && (Object.keys(data) as Array<keyof DynamicData>).some(k => old[k] !== data[k]);
const hasChanged = (Object.keys(oldData) as Array<keyof DynamicData>).some(
key => oldData[key] !== data[key]
);
if (hasChanged) {
this.dynamicHandlers.forEach(handler => handler(data));
}
}
this.dynamicData = data; this.dynamicData = data;
console.log(`${this.label}: `, this.dynamicData);
if (old?.online !== data.online) {
console.log(`${this.label}: ${data.online ? 'online' : 'offline'}`);
}
if (changed) this.dynamicHandlers.forEach(h => h(data));
} }
onDynamicDataUpdate(handler: (data: DynamicData) => void): void { onDynamicDataUpdate(handler: (data: DynamicData) => void): void {
@@ -100,42 +85,30 @@ export default class RotClient {
} }
turn(az: number): void { turn(az: number): void {
fetch(`http://${this.ip}:88/`, { console.log(`Turning ${this.label} to ${az}°...`);
fetch(`${this.baseUrl()}/`, {
body: `ROT=${az}`, body: `ROT=${az}`,
method: 'POST', method: 'POST',
headers: { headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
'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}`));
}).catch(() => {});
console.log(`Turning ${this.label} to ${az}°...`);
} }
private async readKey(endpoint: string, numType: NumType): Promise<string | number | null> { private baseUrl(): string {
return `http://${this.ip}:${ROTATOR_PORT}`;
}
private async readKey(endpoint: string, type: NumType): Promise<string | number | null> {
try { try {
const resp = await fetch(`http://${this.ip}:88/${endpoint}`); const resp = await fetch(`${this.baseUrl()}/${endpoint}`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
if (!resp.ok) return null;
const text = await resp.text(); const text = await resp.text();
if (numType === NumType.String) return text; if (type === 'string') return text;
if (numType === NumType.Int) return parseInt(text, 10); const value = type === 'int' ? parseInt(text, 10) : parseFloat(text);
return parseFloat(text); return Number.isFinite(value) ? value : null;
} catch (ex) { } catch {
console.error(`${this.label}: Failed to read ${endpoint}:`, ex); // Unreachable rotators are reported via the `online` flag rather than logged every second.
return null; return null;
} }
} }
getDynamicData(): DynamicData | null {
return this.dynamicData;
}
getAzimuth(): number | null {
return this.dynamicData?.azimuth ?? null;
}
getAdc(): number | null {
return this.dynamicData?.adc ?? null;
}
getStatus(): number | null {
return this.dynamicData?.status ?? null;
}
} }