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
+105 -124
View File
@@ -38,7 +38,6 @@
color: #fff; color: #fff;
border-bottom-color: #4a9eff; border-bottom-color: #4a9eff;
} }
.tab-spacer { flex: 1; }
.rotators { .rotators {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -158,6 +157,7 @@
this.adc = 0; this.adc = 0;
this.online = false; this.online = false;
this.bands = []; this.bands = [];
this.targetAngle = null;
} }
} }
@@ -500,8 +500,10 @@
: " | <span class=\"text-red\">&bull;</span> Offline"; : " | <span class=\"text-red\">&bull;</span> Offline";
} }
updateTurnedBy(sourceIp, targetAz) { updateTurnedBy(setpoint, station) {
this.els.turnedBy.textContent = `${sourceIp} \u2192 ${targetAz}\u00B0`; const el = this.els.turnedBy;
el.textContent = `${setpoint.station ?? setpoint.sourceIp} \u2192 ${setpoint.targetAz}\u00B0`;
el.style.color = station ? station.color : '';
} }
} }
@@ -511,85 +513,68 @@
this.labels = []; this.labels = [];
this.stations = {}; this.stations = {};
this.stationPills = {}; this.stationPills = {};
this.stationRadio = {};
this.selectedStation = null;
this.autoMode = false;
this.container = document.getElementById('rotators'); this.container = document.getElementById('rotators');
this.tabBar = document.getElementById('tab-bar'); this.tabBar = document.getElementById('tab-bar');
this.stationBar = document.getElementById('station-bar'); this.stationBar = document.getElementById('station-bar');
this.websocket = null; this.websocket = null;
this.activeTab = null;
this.autoMode = false;
this.selectedStation = null;
this.stationRadio = {};
} }
async initialize() { async initialize() {
const init = await this.startWs(); const init = await this.startWs();
this.stations = init.stations || {}; this.stations = init.stations;
this.stationRadio = init.stationRadio || {}; this.stationRadio = init.stationRadio;
this.selectedStation = init.clientStation || null; this.selectedStation = init.clientStation;
for (const [label, clientState] of Object.entries(init.rotators)) { for (const [label, rotState] of Object.entries(init.rotators)) {
const state = new RotatorState(); const state = new RotatorState();
state.bands = rotState.bands;
if (clientState.initData) {
for (const [key, value] of Object.entries(clientState.initData)) {
state[key] = value;
}
}
state.bands = clientState.bands || [];
const ui = new RotatorUI(label, this.container, state); const ui = new RotatorUI(label, this.container, state);
ui.updateStatic();
if (clientState.setpoint) {
state.targetAngle = clientState.setpoint.targetAz;
ui.updateTurnedBy(clientState.setpoint.sourceIp, clientState.setpoint.targetAz);
}
this.rotators[label] = { state, ui }; this.rotators[label] = { state, ui };
this.labels.push(label); this.labels.push(label);
if (rotState.initData) this.applyInitData(label, rotState.initData);
if (rotState.dynamic) this.applyDynamic(label, rotState.dynamic);
if (rotState.setpoint) this.applySetpoint(label, rotState.setpoint);
} }
this.buildTabBar(); this.buildTabBar();
this.buildStationBar(); this.buildStationBar();
this.updateTitle();
this.applyHash(); this.applyHash();
window.addEventListener('hashchange', () => this.applyHash()); window.addEventListener('hashchange', () => this.applyHash());
}
updateTitle() {
document.title = Object.values(this.rotators) document.title = Object.values(this.rotators)
.map(r => r.state.antName || "Rotator") .map(r => r.state.antName || "Rotator")
.join(" / "); .join(" / ");
} }
buildTabBar() { buildTabBar() {
this.autoTab = document.createElement('div'); this.autoTab = this.createTab('Auto', 'auto');
this.autoTab.className = 'tab';
this.autoTab.textContent = 'Auto';
this.autoTab.addEventListener('click', () => { location.hash = 'auto'; });
this.tabBar.appendChild(this.autoTab);
for (const label of this.labels) { for (const label of this.labels) {
const tab = document.createElement('div'); this.rotators[label].tab = this.createTab(this.rotators[label].state.antName || label, label);
tab.className = 'tab'; }
tab.textContent = this.rotators[label].state.antName || label; this.allTab = this.createTab('All', 'all');
tab.addEventListener('click', () => {
location.hash = encodeURIComponent(label);
});
this.rotators[label].tab = tab;
this.tabBar.appendChild(tab);
} }
this.allTab = document.createElement('div'); createTab(text, hash) {
this.allTab.className = 'tab'; const tab = document.createElement('div');
this.allTab.textContent = 'All'; tab.className = 'tab';
this.allTab.addEventListener('click', () => { location.hash = 'all'; }); tab.textContent = text;
this.tabBar.appendChild(this.allTab); tab.addEventListener('click', () => { location.hash = encodeURIComponent(hash); });
this.tabBar.appendChild(tab);
return tab;
} }
buildStationBar() { buildStationBar() {
for (const [name, cfg] of Object.entries(this.stations)) { for (const [name, cfg] of Object.entries(this.stations)) {
const pill = document.createElement('div'); const pill = document.createElement('div');
pill.className = 'station-pill'; pill.className = 'station-pill';
pill.style.borderColor = this.selectedStation === name ? cfg.color : '';
const dot = document.createElement('span'); const dot = document.createElement('span');
dot.className = 'dot'; dot.className = 'dot';
@@ -603,7 +588,7 @@
const freq = document.createElement('span'); const freq = document.createElement('span');
freq.className = 'freq'; freq.className = 'freq';
const radio = this.stationRadio[name]; const radio = this.stationRadio[name];
freq.textContent = radio ? this.formatFreq(radio.freq) : ''; freq.textContent = radio ? formatFreq(radio.freq) : '';
pill.appendChild(freq); pill.appendChild(freq);
pill.addEventListener('click', () => { pill.addEventListener('click', () => {
@@ -621,33 +606,21 @@
updateStationSelection() { updateStationSelection() {
for (const [name, pill] of Object.entries(this.stationPills)) { for (const [name, pill] of Object.entries(this.stationPills)) {
const selected = name === this.selectedStation; const selected = name === this.selectedStation;
const color = this.stations[name].color;
pill.el.classList.toggle('selected', selected); pill.el.classList.toggle('selected', selected);
pill.el.style.borderColor = selected ? color : ''; pill.el.style.borderColor = selected ? this.stations[name].color : '';
} }
} }
formatFreq(freq) {
return (freq / 100000).toFixed(3) + ' MHz';
}
applyHash() { applyHash() {
const hash = decodeURIComponent(location.hash.slice(1)); const hash = decodeURIComponent(location.hash.slice(1));
this.autoMode = false; this.autoMode = hash !== 'all' && !this.rotators[hash];
if (hash === 'auto' || hash === '') { if (this.autoMode) this.applyAutoTab();
this.autoMode = true; else if (hash === 'all') this.showAll();
this.applyAutoTab(); else this.showTab(hash);
} else if (hash === 'all') {
this.showAll();
} else if (this.rotators[hash]) {
this.showTab(hash);
} else {
this.autoMode = true;
this.applyAutoTab();
}
this.stationBar.classList.toggle('visible', this.autoMode); const hasStations = Object.keys(this.stations).length > 0;
this.stationBar.classList.toggle('visible', this.autoMode && hasStations);
this.autoTab.classList.toggle('active', this.autoMode); this.autoTab.classList.toggle('active', this.autoMode);
this.allTab.classList.toggle('active', hash === 'all'); this.allTab.classList.toggle('active', hash === 'all');
} }
@@ -655,82 +628,47 @@
applyAutoTab() { applyAutoTab() {
const radio = this.selectedStation ? this.stationRadio[this.selectedStation] : null; const radio = this.selectedStation ? this.stationRadio[this.selectedStation] : null;
const match = radio ? this.findRotatorForBand(radio.band) : null; const match = radio ? this.findRotatorForBand(radio.band) : null;
if (match) { if (match) this.showTab(match, true);
this.showTab(match, true); else this.showAll();
} else {
this.showAll(true);
}
} }
findRotatorForBand(band) { findRotatorForBand(band) {
for (const [label, rot] of Object.entries(this.rotators)) { return this.labels.find(l => this.rotators[l].state.bands.includes(band)) ?? null;
if (rot.state.bands.includes(band)) return label;
}
return null;
}
handleRadioInfo(station, band, freq) {
this.stationRadio[station] = { band, freq };
const pill = this.stationPills[station];
if (pill) pill.freqEl.textContent = this.formatFreq(freq);
if (this.autoMode && station === this.selectedStation) {
this.applyAutoTab();
}
} }
showTab(label, isAuto = false) { showTab(label, isAuto = false) {
this.activeTab = label;
for (const l of this.labels) { for (const l of this.labels) {
const rot = this.rotators[l]; const rot = this.rotators[l];
const visible = l === label; const visible = l === label;
rot.ui.card.classList.toggle('visible', visible); rot.ui.card.classList.toggle('visible', visible);
rot.tab.classList.toggle('active', !isAuto && visible); rot.tab.classList.toggle('active', !isAuto && visible);
} }
// re-render: the canvas may have been hidden
this.rotators[label].ui.renderer.render(); this.rotators[label].ui.renderer.render();
} }
showAll(isAuto = false) { showAll() {
this.activeTab = null;
for (const l of this.labels) { for (const l of this.labels) {
const rot = this.rotators[l]; const rot = this.rotators[l];
rot.ui.card.classList.add('visible'); rot.ui.card.classList.add('visible');
rot.tab.classList.toggle('active', false); rot.tab.classList.remove('active');
rot.ui.renderer.render(); rot.ui.renderer.render();
} }
if (!isAuto) this.allTab.classList.add('active');
} }
async startWs() { applyInitData(label, initData) {
return new Promise((resolve) => {
this.websocket = new WebSocket(location.origin.replace(/^http/, 'ws') + location.pathname.replace(/\/?$/, '/') + 'ws');
let resolved = false;
this.websocket.addEventListener("message", (e) => {
if (!e || !e.data) return;
const parsed = JSON.parse(e.data);
if (!parsed || !parsed.data) return;
const data = parsed.data;
if (!resolved) {
resolved = true;
resolve(data);
return;
}
if (data.radioInfo) {
this.handleRadioInfo(data.radioInfo.station, data.radioInfo.band, data.radioInfo.freq);
return;
}
for (const [label, rotData] of Object.entries(data)) {
const rot = this.rotators[label]; const rot = this.rotators[label];
if (!rot) continue; for (const [key, value] of Object.entries(initData)) {
if (value !== null) rot.state[key] = value;
}
rot.ui.updateStatic();
if (rot.tab) rot.tab.textContent = rot.state.antName || label;
this.updateTitle();
}
if (rotData.dynamic) { applyDynamic(label, { azimuth, status, adc, online }) {
const { azimuth, status, adc, online } = rotData.dynamic; const rot = this.rotators[label];
let needsRender = rot.state.azimuth !== azimuth const needsRender = rot.state.azimuth !== azimuth
|| rot.state.status !== status || rot.state.status !== status
|| rot.state.online !== online; || rot.state.online !== online;
@@ -743,24 +681,67 @@
rot.ui.updateDynamic(); rot.ui.updateDynamic();
} }
if (rotData.turnedBy) { applySetpoint(label, setpoint) {
rot.state.targetAngle = rotData.targetAz; const rot = this.rotators[label];
rot.state.targetAngle = setpoint.targetAz;
rot.ui.renderer.render(); rot.ui.renderer.render();
rot.ui.updateTurnedBy(rotData.turnedBy, rotData.targetAz); rot.ui.updateTurnedBy(setpoint, this.stations[setpoint.station]);
}
handleRadioInfo({ station, band, freq }) {
this.stationRadio[station] = { band, freq };
const pill = this.stationPills[station];
if (pill) pill.freqEl.textContent = formatFreq(freq);
if (this.autoMode && station === this.selectedStation) this.applyAutoTab();
}
handleMessage(msg) {
if (msg.type === 'radioInfo') {
this.handleRadioInfo(msg);
return;
}
if (!this.rotators[msg.label]) return;
switch (msg.type) {
case 'initData': this.applyInitData(msg.label, msg.initData); break;
case 'dynamic': this.applyDynamic(msg.label, msg.dynamic); break;
case 'setpoint': this.applySetpoint(msg.label, msg.setpoint); break;
} }
} }
startWs() {
return new Promise((resolve) => {
const ws = new WebSocket(wsUrl());
this.websocket = ws;
ws.addEventListener("message", (e) => {
let msg;
try {
msg = JSON.parse(e.data);
} catch {
return;
}
if (msg.type === 'init') resolve(msg);
else this.handleMessage(msg);
}); });
setInterval(() => { setInterval(() => {
this.websocket.send(JSON.stringify({ ping: 1 })); ws.send(JSON.stringify({ ping: 1 }));
}, 2000); }, 2000);
}); });
} }
} }
function wsUrl() {
return location.origin.replace(/^http/, 'ws') + location.pathname.replace(/\/?$/, '/') + 'ws';
}
/** N1MM frequencies are in tens of Hz. */
function formatFreq(freq) {
return (freq / 100000).toFixed(3) + ' MHz';
}
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
const app = new RotatorApp(); new RotatorApp().initialize();
app.initialize();
}); });
</script> </script>
</body> </body>
+59 -35
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 ROTATOR_PORT = 88;
const POLL_INTERVAL_MS = 1000; const POLL_INTERVAL_MS = 1000;
@@ -24,15 +24,21 @@ export default class RotClient {
readonly label: string; readonly label: string;
private readonly ip: string; private readonly ip: string;
private readonly bands: number[]; private readonly bands: number[];
private cachedData: InitData | null = null; private initData: InitData | null = null;
private initDataLoading = false;
private dynamicData: DynamicData | null = null; private dynamicData: DynamicData | null = null;
private setpoint: Setpoint | null = null;
private readonly dynamicHandlers: Array<(data: DynamicData) => void> = []; 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.label = label;
this.ip = ip; this.ip = ip;
this.bands = bands; this.bands = bands;
}
/** Starts polling the controller. Init data is loaded once the rotator is reachable. */
start(): void {
const poll = async () => { const poll = async () => {
await this.fetchDynamicData(); await this.fetchDynamicData();
setTimeout(() => void poll(), POLL_INTERVAL_MS); setTimeout(() => void poll(), POLL_INTERVAL_MS);
@@ -40,13 +46,56 @@ export default class RotClient {
void poll(); void poll();
} }
async readInitData(): Promise<InitData> { onDynamicDataUpdate(handler: (data: DynamicData) => void): void {
if (this.cachedData) return this.cachedData; 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))); 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; // The rotator may have dropped off mid-read; retry on the next successful poll.
console.log(`${this.label}: Loaded init data (azimuth offset ${this.cachedData.azShift}°).`); if (values.every(v => v === null)) return;
return this.cachedData; 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> { private async fetchDynamicData(): Promise<void> {
@@ -63,41 +112,16 @@ export default class RotClient {
}; };
const old = this.dynamicData; 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; this.dynamicData = data;
if (old?.online !== data.online) { if (old?.online !== data.online) {
console.log(`${this.label}: ${data.online ? 'online' : 'offline'}`); console.log(`${this.label}: ${data.online ? 'online' : 'offline'}`);
} }
if (data.online) void this.loadInitData();
if (changed) this.dynamicHandlers.forEach(h => h(data)); 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> { private async readKey(endpoint: string, type: NumType): Promise<string | number | null> {
try { try {
const resp = await fetch(`${this.baseUrl()}/${endpoint}`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); const resp = await fetch(`${this.baseUrl()}/${endpoint}`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
+67 -54
View File
@@ -1,97 +1,110 @@
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import RotClient from './RotClient.js'; import RotClient from './RotClient.js';
import type { FullConfig, StationConfig, DynamicData, InitialState, RadioInfoMessage, TurnMessage, TurnMessageHandler } from './types.js'; import type {
Config,
DynamicData,
InitData,
RadioInfoMessage,
RotatorState,
Setpoint,
StationConfig,
StationRadio,
TurnMessage,
} from './types.js';
export interface TurnEvent { export interface RadioInfoEvent extends StationRadio {
label: string; station: string;
az: number;
sourceIp: string;
} }
export default class RotRouter implements TurnMessageHandler { export default class RotRouter {
private readonly clients: Record<string, RotClient> = {}; private readonly clients = new Map<string, RotClient>();
private readonly stations: Record<string, StationConfig> = {}; private readonly stations: Record<string, StationConfig>;
private readonly stationsByIp: Record<string, string> = {}; private readonly stationsByIp = new Map<string, string>();
private readonly routerDataHandlers: Array<(rotator: RotClient, data: DynamicData) => void> = []; private readonly stationRadio: Record<string, StationRadio> = {};
private readonly turnEventHandlers: Array<(event: TurnEvent) => void> = []; private readonly dynamicDataHandlers: Array<(label: string, data: DynamicData) => void> = [];
private readonly radioInfoHandlers: Array<(station: string, band: number, freq: number) => void> = []; private readonly initDataHandlers: Array<(label: string, data: InitData) => void> = [];
private readonly setpointHandlers: Array<(label: string, setpoint: Setpoint) => void> = [];
private readonly radioInfoHandlers: Array<(event: RadioInfoEvent) => void> = [];
constructor() { constructor(configPath: string) {
this.loadConfig(); const config = JSON.parse(readFileSync(configPath, 'utf-8')) as Config;
for (const [label, rotatorConfig] of Object.entries(config.rotators)) {
const client = new RotClient(label, rotatorConfig);
client.onDynamicDataUpdate(data => this.dynamicDataHandlers.forEach(h => h(label, data)));
client.onInitDataLoaded(data => this.initDataHandlers.forEach(h => h(label, data)));
this.clients.set(label, client);
} }
private loadConfig(): void { this.stations = config.stations;
const raw = readFileSync('config.json', 'utf-8'); for (const [name, { ip }] of Object.entries(config.stations)) {
const parsed = JSON.parse(raw) as FullConfig; this.stationsByIp.set(ip, name);
for (const [label, clientConfig] of Object.entries(parsed.rotators)) {
const client = new RotClient(label, clientConfig);
client.onDynamicDataUpdate(data => this.routerDataHandlers.forEach(h => h(client, data)));
this.clients[label] = client;
} }
for (const [name, stationConfig] of Object.entries(parsed.stations)) {
this.stations[name] = stationConfig;
this.stationsByIp[stationConfig.ip] = name;
} }
start(): void {
this.clients.forEach(c => c.start());
} }
resolveStation(ip: string): string | null { resolveStation(ip: string): string | null {
return this.stationsByIp[ip] ?? null; return this.stationsByIp.get(ip) ?? null;
} }
getStations(): Record<string, StationConfig> { getStations(): Record<string, StationConfig> {
return this.stations; return this.stations;
} }
getStationRadio(): Record<string, StationRadio> {
return this.stationRadio;
}
getRotatorStates(): Record<string, RotatorState> {
return Object.fromEntries([...this.clients].map(([label, c]) => [label, c.getState()]));
}
handleRadioInfo({ sourceIp, band, freq }: RadioInfoMessage): void { handleRadioInfo({ sourceIp, band, freq }: RadioInfoMessage): void {
const station = this.resolveStation(sourceIp); const station = this.resolveStation(sourceIp);
if (!station) return; if (!station) return;
this.radioInfoHandlers.forEach(h => h(station, band, freq)); this.stationRadio[station] = { band, freq };
this.radioInfoHandlers.forEach(h => h({ station, band, freq }));
} }
onRadioInfo(handler: (station: string, band: number, freq: number) => void): void { handleTurnMessage({ band, az, sourceIp }: TurnMessage): void {
this.radioInfoHandlers.push(handler); const client = [...this.clients.values()].find(c => c.hasBand(band));
}
private findClientForBand(band: number): RotClient | null {
return Object.values(this.clients).find(c => c.hasBand(band)) ?? null;
}
handleTurnMessage(msg: TurnMessage): void {
const client = this.findClientForBand(msg.band);
if (!client) { if (!client) {
console.error(`No rotator configured for the ${msg.band} MHz band!`); console.error(`No rotator configured for the ${band} MHz band!`);
return; return;
} }
client.turn(msg.az); this.turnClient(client, az, sourceIp);
this.fireTurnEvent(client.label, msg.az, msg.sourceIp);
} }
/** Turns the rotator with the given label. Returns false if no such rotator exists. */
turn(label: string, az: number, sourceIp: string): boolean { turn(label: string, az: number, sourceIp: string): boolean {
const client = this.clients[label]; const client = this.clients.get(label);
if (!client) return false; if (!client) return false;
client.turn(az); this.turnClient(client, az, sourceIp);
this.fireTurnEvent(label, az, sourceIp);
return true; return true;
} }
private fireTurnEvent(label: string, az: number, sourceIp: string): void { private turnClient(client: RotClient, targetAz: number, sourceIp: string): void {
const event: TurnEvent = { label, az, sourceIp }; const setpoint: Setpoint = { targetAz, sourceIp, station: this.resolveStation(sourceIp) };
this.turnEventHandlers.forEach(h => h(event)); client.turn(setpoint);
this.setpointHandlers.forEach(h => h(client.label, setpoint));
} }
onTurnEvent(handler: (event: TurnEvent) => void): void { onDynamicData(handler: (label: string, data: DynamicData) => void): void {
this.turnEventHandlers.push(handler); this.dynamicDataHandlers.push(handler);
} }
onRotatorData(handler: (rotator: RotClient, data: DynamicData) => void): void { onInitData(handler: (label: string, data: InitData) => void): void {
this.routerDataHandlers.push(handler); this.initDataHandlers.push(handler);
} }
async readInitialState(): Promise<InitialState> { onSetpoint(handler: (label: string, setpoint: Setpoint) => void): void {
const state: InitialState = {}; this.setpointHandlers.push(handler);
for (const client of Object.values(this.clients)) {
state[client.label] = { initData: await client.readInitData(), bands: client.getBands() };
} }
return state;
onRadioInfo(handler: (event: RadioInfoEvent) => void): void {
this.radioInfoHandlers.push(handler);
} }
} }
+32 -53
View File
@@ -1,80 +1,59 @@
import type { WSContext } from 'hono/ws'; import type { WSContext } from 'hono/ws';
import type { ServerMessage } from './types.js';
interface IncomingMessage { const PING_TIMEOUT_MS = 60_000;
ping?: boolean; const PING_CHECK_INTERVAL_MS = 10_000;
data?: unknown;
interface ClientMessage {
ping?: unknown;
} }
export default class WebsocketManager { export default class WebsocketManager {
private readonly clients = new Set<WSContext>(); /** Last ping time per client. A Map keys by identity; a plain object would stringify every WSContext to the same key. */
// Map correctly tracks identity — plain object keys would stringify all WSContext to "[object Object]" private readonly clients = new Map<WSContext, number>();
private readonly lastPing = new Map<WSContext, number>(); private readonly buildInit: (clientStation: string | null) => ServerMessage;
private initData: Record<string, unknown> = {};
constructor() { /** @param buildInit builds the `init` message sent to each newly connected client. */
constructor(buildInit: (clientStation: string | null) => ServerMessage) {
this.buildInit = buildInit;
setInterval(() => { setInterval(() => {
const threshold = Date.now() - 60_000; const threshold = Date.now() - PING_TIMEOUT_MS;
for (const [client, ping] of this.lastPing) { for (const [ws, lastPing] of this.clients) {
if (ping < threshold) this.leaveClient(client); if (lastPing < threshold) {
this.clients.delete(ws);
ws.close();
} }
}, 10_000); }
}, PING_CHECK_INTERVAL_MS);
} }
getHandler(clientStation: string | null = null) { getHandler(clientStation: string | null) {
return { return {
onOpen: (_event: Event, ws: WSContext) => { onOpen: (_event: Event, ws: WSContext) => {
this.joinClient(ws, clientStation); this.clients.set(ws, Date.now());
this.send(ws, this.buildInit(clientStation));
}, },
onMessage: (event: MessageEvent, ws: WSContext) => { onMessage: (event: MessageEvent, ws: WSContext) => {
if (!event.data) return; if (typeof event.data !== 'string') return;
let msg: IncomingMessage;
try { try {
msg = JSON.parse(event.data as string) as IncomingMessage; const msg = JSON.parse(event.data) as ClientMessage;
if (msg.ping) this.clients.set(ws, Date.now());
} catch { } catch {
return; // ignore malformed messages
}
if (msg.ping) {
this.lastPing.set(ws, Date.now());
}
if (msg.data !== undefined) {
this.handleMessage(ws, msg.data);
console.log(`Data from client: ${event.data}`);
} }
}, },
onClose: (_event: CloseEvent, ws: WSContext) => { onClose: (_event: CloseEvent, ws: WSContext) => {
this.leaveClient(ws); this.clients.delete(ws);
}, },
}; };
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars broadcast(msg: ServerMessage): void {
private handleMessage(_ws: WSContext, _data: unknown): void { const payload = JSON.stringify(msg);
// Reserved for future incoming-message handling for (const ws of this.clients.keys()) ws.send(payload);
} }
private send(ws: WSContext, data: unknown): void { private send(ws: WSContext, msg: ServerMessage): void {
ws.send(JSON.stringify({ data })); ws.send(JSON.stringify(msg));
}
broadcast(data: unknown): void {
this.clients.forEach(client => this.send(client, data));
}
private joinClient(ws: WSContext, clientStation: string | null): void {
this.clients.add(ws);
this.lastPing.set(ws, Date.now());
this.send(ws, { ...this.initData, clientStation });
}
private leaveClient(ws: WSContext): void {
this.clients.delete(ws);
this.lastPing.delete(ws);
}
setInitData(initData: Record<string, unknown>): void {
this.initData = initData;
} }
} }
+28 -36
View File
@@ -1,71 +1,63 @@
import { Hono } from 'hono'; import { Hono, type Context } from 'hono';
import { serve } from '@hono/node-server'; import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static'; import { serveStatic } from '@hono/node-server/serve-static';
import { getConnInfo } from '@hono/node-server/conninfo';
import { createNodeWebSocket } from '@hono/node-ws'; import { createNodeWebSocket } from '@hono/node-ws';
import RotRouter from './RotRouter.js'; import RotRouter from './RotRouter.js';
import N1mmServer from './N1mmServer.js'; import N1mmServer from './N1mmServer.js';
import WebsocketManager from './WebsocketManager.js'; import WebsocketManager from './WebsocketManager.js';
import { getConnInfo } from '@hono/node-server/conninfo';
const router = new RotRouter(); const HTTP_PORT = 8787;
const router = new RotRouter('config.json');
const websocketManager = new WebsocketManager(clientStation => ({
type: 'init',
rotators: router.getRotatorStates(),
stations: router.getStations(),
stationRadio: router.getStationRadio(),
clientStation,
}));
router.onDynamicData((label, dynamic) => websocketManager.broadcast({ type: 'dynamic', label, dynamic }));
router.onInitData((label, initData) => websocketManager.broadcast({ type: 'initData', label, initData }));
router.onSetpoint((label, setpoint) => websocketManager.broadcast({ type: 'setpoint', label, setpoint }));
router.onRadioInfo(event => websocketManager.broadcast({ type: 'radioInfo', ...event }));
const n1mm = new N1mmServer(); const n1mm = new N1mmServer();
n1mm.onTurnMessage(msg => router.handleTurnMessage(msg)); n1mm.onTurnMessage(msg => router.handleTurnMessage(msg));
n1mm.onRadioInfo(msg => router.handleRadioInfo(msg)); n1mm.onRadioInfo(msg => router.handleRadioInfo(msg));
const app = new Hono(); function resolveClientIp(c: Context): string {
app.use('/*', serveStatic({ root: './public' }));
const websocketManager = new WebsocketManager();
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
const stationRadio: Record<string, { band: number; freq: number }> = {};
const rotators = await router.readInitialState();
websocketManager.setInitData({ rotators, stations: router.getStations(), stationRadio });
router.onRotatorData((rotator, data) => {
websocketManager.broadcast({ [rotator.label]: { dynamic: data } });
});
router.onTurnEvent((event) => {
const setpoint = { targetAz: event.az, sourceIp: event.sourceIp };
const client = rotators[event.label];
if (client) client.setpoint = setpoint;
websocketManager.broadcast({ [event.label]: { turnedBy: event.sourceIp, targetAz: event.az } });
});
router.onRadioInfo((station, band, freq) => {
stationRadio[station] = { band, freq };
websocketManager.broadcast({ radioInfo: { station, band, freq } });
});
function resolveClientIp(c: Parameters<typeof getConnInfo>[0]): string {
const forwarded = c.req.header('x-forwarded-for')?.split(',')[0]?.trim(); const forwarded = c.req.header('x-forwarded-for')?.split(',')[0]?.trim();
const rawIp = forwarded || getConnInfo(c).remote.address || 'unknown'; const rawIp = forwarded || getConnInfo(c).remote.address || 'unknown';
return rawIp.startsWith('::ffff:') ? rawIp.slice(7) : rawIp; return rawIp.startsWith('::ffff:') ? rawIp.slice(7) : rawIp;
} }
const app = new Hono();
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
app.post('/turn/:label', async (c) => { app.post('/turn/:label', async (c) => {
const label = c.req.param('label'); const label = c.req.param('label');
const rot = (await c.req.parseBody())['ROT']; const rot = (await c.req.parseBody())['ROT'];
const az = typeof rot === 'string' && rot.trim() !== '' ? Number(rot) : NaN; const az = typeof rot === 'string' && rot.trim() !== '' ? Number(rot) : NaN;
if (!Number.isInteger(az) || az < 0) return c.text('Invalid azimuth', 400); if (!Number.isInteger(az) || az < 0) return c.text('Invalid azimuth', 400);
const sourceIp = resolveClientIp(c); const ok = router.turn(label, az, resolveClientIp(c));
const ok = router.turn(label, az, sourceIp);
return ok ? c.text(`Turning ${label} to ${az}`) : c.text('Unknown rotator', 404); return ok ? c.text(`Turning ${label} to ${az}`) : c.text('Unknown rotator', 404);
}); });
app.get('/ws', upgradeWebSocket((c) => { app.get('/ws', upgradeWebSocket((c) => {
const clientIp = resolveClientIp(c); const clientStation = router.resolveStation(resolveClientIp(c));
const clientStation = router.resolveStation(clientIp);
return websocketManager.getHandler(clientStation); return websocketManager.getHandler(clientStation);
})); }));
app.use('/*', serveStatic({ root: './public' }));
const server = serve( const server = serve(
{ fetch: app.fetch, port: 8787 }, { fetch: app.fetch, port: HTTP_PORT },
info => console.log(`Listening on http://localhost:${info.port}`), info => console.log(`Listening on http://localhost:${info.port}`),
); );
injectWebSocket(server); injectWebSocket(server);
router.start();
n1mm.start(); n1mm.start();
+26 -11
View File
@@ -11,11 +11,7 @@ export interface RadioInfoMessage {
sourceIp: string; sourceIp: string;
} }
export interface TurnMessageHandler { export interface RotatorConfig {
handleTurnMessage(msg: TurnMessage): void;
}
export interface ClientConfig {
ip: string; ip: string;
bands: number[]; bands: number[];
} }
@@ -25,8 +21,8 @@ export interface StationConfig {
color: string; color: string;
} }
export interface FullConfig { export interface Config {
rotators: Record<string, ClientConfig>; rotators: Record<string, RotatorConfig>;
stations: Record<string, StationConfig>; stations: Record<string, StationConfig>;
} }
@@ -50,12 +46,31 @@ export interface InitData {
export interface Setpoint { export interface Setpoint {
targetAz: number; targetAz: number;
sourceIp: string; sourceIp: string;
station: string | null;
} }
export interface ClientState { export interface RotatorState {
initData: InitData; initData: InitData | null;
dynamic: DynamicData | null;
bands: number[]; bands: number[];
setpoint?: Setpoint; setpoint: Setpoint | null;
} }
export type InitialState = Record<string, ClientState>; export interface StationRadio {
band: number;
freq: number;
}
/** Messages pushed from the server to browser clients over WebSocket. */
export type ServerMessage =
| {
type: 'init';
rotators: Record<string, RotatorState>;
stations: Record<string, StationConfig>;
stationRadio: Record<string, StationRadio>;
clientStation: string | null;
}
| { type: 'initData'; label: string; initData: InitData }
| { type: 'dynamic'; label: string; dynamic: DynamicData }
| { type: 'setpoint'; label: string; setpoint: Setpoint }
| { type: 'radioInfo'; station: string; band: number; freq: number };