diff --git a/public/index.html b/public/index.html index d3a02ff..d2c6e95 100644 --- a/public/index.html +++ b/public/index.html @@ -38,7 +38,6 @@ color: #fff; border-bottom-color: #4a9eff; } - .tab-spacer { flex: 1; } .rotators { display: flex; flex-wrap: wrap; @@ -158,6 +157,7 @@ this.adc = 0; this.online = false; this.bands = []; + this.targetAngle = null; } } @@ -500,8 +500,10 @@ : " | • Offline"; } - updateTurnedBy(sourceIp, targetAz) { - this.els.turnedBy.textContent = `${sourceIp} \u2192 ${targetAz}\u00B0`; + updateTurnedBy(setpoint, station) { + 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.stations = {}; this.stationPills = {}; + this.stationRadio = {}; + this.selectedStation = null; + this.autoMode = false; this.container = document.getElementById('rotators'); this.tabBar = document.getElementById('tab-bar'); this.stationBar = document.getElementById('station-bar'); this.websocket = null; - this.activeTab = null; - this.autoMode = false; - this.selectedStation = null; - this.stationRadio = {}; } async initialize() { const init = await this.startWs(); - this.stations = init.stations || {}; - this.stationRadio = init.stationRadio || {}; - this.selectedStation = init.clientStation || null; + this.stations = init.stations; + this.stationRadio = init.stationRadio; + 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(); - - if (clientState.initData) { - for (const [key, value] of Object.entries(clientState.initData)) { - state[key] = value; - } - } - state.bands = clientState.bands || []; - + state.bands = rotState.bands; 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.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.buildStationBar(); + this.updateTitle(); this.applyHash(); window.addEventListener('hashchange', () => this.applyHash()); + } + updateTitle() { document.title = Object.values(this.rotators) .map(r => r.state.antName || "Rotator") .join(" / "); } buildTabBar() { - this.autoTab = document.createElement('div'); - this.autoTab.className = 'tab'; - this.autoTab.textContent = 'Auto'; - this.autoTab.addEventListener('click', () => { location.hash = 'auto'; }); - this.tabBar.appendChild(this.autoTab); - + this.autoTab = this.createTab('Auto', 'auto'); for (const label of this.labels) { - const tab = document.createElement('div'); - tab.className = 'tab'; - tab.textContent = this.rotators[label].state.antName || label; - tab.addEventListener('click', () => { - location.hash = encodeURIComponent(label); - }); - this.rotators[label].tab = tab; - this.tabBar.appendChild(tab); + this.rotators[label].tab = this.createTab(this.rotators[label].state.antName || label, label); } + this.allTab = this.createTab('All', 'all'); + } - this.allTab = document.createElement('div'); - this.allTab.className = 'tab'; - this.allTab.textContent = 'All'; - this.allTab.addEventListener('click', () => { location.hash = 'all'; }); - this.tabBar.appendChild(this.allTab); + createTab(text, hash) { + const tab = document.createElement('div'); + tab.className = 'tab'; + tab.textContent = text; + tab.addEventListener('click', () => { location.hash = encodeURIComponent(hash); }); + this.tabBar.appendChild(tab); + return tab; } buildStationBar() { for (const [name, cfg] of Object.entries(this.stations)) { const pill = document.createElement('div'); pill.className = 'station-pill'; - pill.style.borderColor = this.selectedStation === name ? cfg.color : ''; const dot = document.createElement('span'); dot.className = 'dot'; @@ -603,7 +588,7 @@ const freq = document.createElement('span'); freq.className = 'freq'; const radio = this.stationRadio[name]; - freq.textContent = radio ? this.formatFreq(radio.freq) : ''; + freq.textContent = radio ? formatFreq(radio.freq) : ''; pill.appendChild(freq); pill.addEventListener('click', () => { @@ -621,33 +606,21 @@ updateStationSelection() { for (const [name, pill] of Object.entries(this.stationPills)) { const selected = name === this.selectedStation; - const color = this.stations[name].color; 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() { const hash = decodeURIComponent(location.hash.slice(1)); - this.autoMode = false; + this.autoMode = hash !== 'all' && !this.rotators[hash]; - if (hash === 'auto' || hash === '') { - this.autoMode = true; - this.applyAutoTab(); - } else if (hash === 'all') { - this.showAll(); - } else if (this.rotators[hash]) { - this.showTab(hash); - } else { - this.autoMode = true; - this.applyAutoTab(); - } + if (this.autoMode) this.applyAutoTab(); + else if (hash === 'all') this.showAll(); + else this.showTab(hash); - 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.allTab.classList.toggle('active', hash === 'all'); } @@ -655,112 +628,120 @@ applyAutoTab() { const radio = this.selectedStation ? this.stationRadio[this.selectedStation] : null; const match = radio ? this.findRotatorForBand(radio.band) : null; - if (match) { - this.showTab(match, true); - } else { - this.showAll(true); - } + if (match) this.showTab(match, true); + else this.showAll(); } findRotatorForBand(band) { - for (const [label, rot] of Object.entries(this.rotators)) { - 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(); - } + return this.labels.find(l => this.rotators[l].state.bands.includes(band)) ?? null; } showTab(label, isAuto = false) { - this.activeTab = label; for (const l of this.labels) { const rot = this.rotators[l]; const visible = l === label; rot.ui.card.classList.toggle('visible', visible); rot.tab.classList.toggle('active', !isAuto && visible); } + // re-render: the canvas may have been hidden this.rotators[label].ui.renderer.render(); } - showAll(isAuto = false) { - this.activeTab = null; + showAll() { for (const l of this.labels) { const rot = this.rotators[l]; rot.ui.card.classList.add('visible'); - rot.tab.classList.toggle('active', false); + rot.tab.classList.remove('active'); rot.ui.renderer.render(); } - if (!isAuto) this.allTab.classList.add('active'); } - async startWs() { + applyInitData(label, initData) { + const rot = this.rotators[label]; + 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(); + } + + applyDynamic(label, { azimuth, status, adc, online }) { + const rot = this.rotators[label]; + const needsRender = rot.state.azimuth !== azimuth + || rot.state.status !== status + || rot.state.online !== online; + + rot.state.adc = adc; + rot.state.azimuth = azimuth; + rot.state.status = status; + rot.state.online = online; + + if (needsRender) rot.ui.renderer.render(); + rot.ui.updateDynamic(); + } + + applySetpoint(label, setpoint) { + const rot = this.rotators[label]; + rot.state.targetAngle = setpoint.targetAz; + rot.ui.renderer.render(); + 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) => { - this.websocket = new WebSocket(location.origin.replace(/^http/, 'ws') + location.pathname.replace(/\/?$/, '/') + 'ws'); - let resolved = false; + const ws = new WebSocket(wsUrl()); + this.websocket = ws; - 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); + ws.addEventListener("message", (e) => { + let msg; + try { + msg = JSON.parse(e.data); + } catch { 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]; - if (!rot) continue; - - if (rotData.dynamic) { - const { azimuth, status, adc, online } = rotData.dynamic; - let needsRender = rot.state.azimuth !== azimuth - || rot.state.status !== status - || rot.state.online !== online; - - rot.state.adc = adc; - rot.state.azimuth = azimuth; - rot.state.status = status; - rot.state.online = online; - - if (needsRender) rot.ui.renderer.render(); - rot.ui.updateDynamic(); - } - - if (rotData.turnedBy) { - rot.state.targetAngle = rotData.targetAz; - rot.ui.renderer.render(); - rot.ui.updateTurnedBy(rotData.turnedBy, rotData.targetAz); - } - } + if (msg.type === 'init') resolve(msg); + else this.handleMessage(msg); }); setInterval(() => { - this.websocket.send(JSON.stringify({ ping: 1 })); + ws.send(JSON.stringify({ ping: 1 })); }, 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", () => { - const app = new RotatorApp(); - app.initialize(); + new RotatorApp().initialize(); }); diff --git a/src/RotClient.ts b/src/RotClient.ts index 8a55c34..c13b568 100644 --- a/src/RotClient.ts +++ b/src/RotClient.ts @@ -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 { - 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 { + 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 { @@ -63,41 +112,16 @@ export default class RotClient { }; const old = this.dynamicData; - const changed = old !== null && (Object.keys(data) as Array).some(k => old[k] !== data[k]); + const changed = !old || (Object.keys(data) as Array).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 { try { const resp = await fetch(`${this.baseUrl()}/${endpoint}`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); diff --git a/src/RotRouter.ts b/src/RotRouter.ts index c5071e0..6af9195 100644 --- a/src/RotRouter.ts +++ b/src/RotRouter.ts @@ -1,97 +1,110 @@ import { readFileSync } from 'node:fs'; 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 { - label: string; - az: number; - sourceIp: string; +export interface RadioInfoEvent extends StationRadio { + station: string; } -export default class RotRouter implements TurnMessageHandler { - private readonly clients: Record = {}; - private readonly stations: Record = {}; - private readonly stationsByIp: Record = {}; - private readonly routerDataHandlers: Array<(rotator: RotClient, data: DynamicData) => void> = []; - private readonly turnEventHandlers: Array<(event: TurnEvent) => void> = []; - private readonly radioInfoHandlers: Array<(station: string, band: number, freq: number) => void> = []; +export default class RotRouter { + private readonly clients = new Map(); + private readonly stations: Record; + private readonly stationsByIp = new Map(); + private readonly stationRadio: Record = {}; + private readonly dynamicDataHandlers: Array<(label: string, data: DynamicData) => 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() { - this.loadConfig(); + constructor(configPath: string) { + 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); + } + + this.stations = config.stations; + for (const [name, { ip }] of Object.entries(config.stations)) { + this.stationsByIp.set(ip, name); + } } - private loadConfig(): void { - const raw = readFileSync('config.json', 'utf-8'); - const parsed = JSON.parse(raw) as FullConfig; - 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 { - return this.stationsByIp[ip] ?? null; + return this.stationsByIp.get(ip) ?? null; } getStations(): Record { return this.stations; } + getStationRadio(): Record { + return this.stationRadio; + } + + getRotatorStates(): Record { + return Object.fromEntries([...this.clients].map(([label, c]) => [label, c.getState()])); + } + handleRadioInfo({ sourceIp, band, freq }: RadioInfoMessage): void { const station = this.resolveStation(sourceIp); 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 { - this.radioInfoHandlers.push(handler); - } - - 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); + handleTurnMessage({ band, az, sourceIp }: TurnMessage): void { + const client = [...this.clients.values()].find(c => c.hasBand(band)); if (!client) { - console.error(`No rotator configured for the ${msg.band} MHz band!`); + console.error(`No rotator configured for the ${band} MHz band!`); return; } - client.turn(msg.az); - this.fireTurnEvent(client.label, msg.az, msg.sourceIp); + this.turnClient(client, az, sourceIp); } + /** Turns the rotator with the given label. Returns false if no such rotator exists. */ turn(label: string, az: number, sourceIp: string): boolean { - const client = this.clients[label]; + const client = this.clients.get(label); if (!client) return false; - client.turn(az); - this.fireTurnEvent(label, az, sourceIp); + this.turnClient(client, az, sourceIp); return true; } - private fireTurnEvent(label: string, az: number, sourceIp: string): void { - const event: TurnEvent = { label, az, sourceIp }; - this.turnEventHandlers.forEach(h => h(event)); + private turnClient(client: RotClient, targetAz: number, sourceIp: string): void { + const setpoint: Setpoint = { targetAz, sourceIp, station: this.resolveStation(sourceIp) }; + client.turn(setpoint); + this.setpointHandlers.forEach(h => h(client.label, setpoint)); } - onTurnEvent(handler: (event: TurnEvent) => void): void { - this.turnEventHandlers.push(handler); + onDynamicData(handler: (label: string, data: DynamicData) => void): void { + this.dynamicDataHandlers.push(handler); } - onRotatorData(handler: (rotator: RotClient, data: DynamicData) => void): void { - this.routerDataHandlers.push(handler); + onInitData(handler: (label: string, data: InitData) => void): void { + this.initDataHandlers.push(handler); } - async readInitialState(): Promise { - const state: InitialState = {}; - for (const client of Object.values(this.clients)) { - state[client.label] = { initData: await client.readInitData(), bands: client.getBands() }; - } - return state; + onSetpoint(handler: (label: string, setpoint: Setpoint) => void): void { + this.setpointHandlers.push(handler); + } + + onRadioInfo(handler: (event: RadioInfoEvent) => void): void { + this.radioInfoHandlers.push(handler); } } diff --git a/src/WebsocketManager.ts b/src/WebsocketManager.ts index 4989850..57045db 100644 --- a/src/WebsocketManager.ts +++ b/src/WebsocketManager.ts @@ -1,80 +1,59 @@ import type { WSContext } from 'hono/ws'; +import type { ServerMessage } from './types.js'; -interface IncomingMessage { - ping?: boolean; - data?: unknown; +const PING_TIMEOUT_MS = 60_000; +const PING_CHECK_INTERVAL_MS = 10_000; + +interface ClientMessage { + ping?: unknown; } export default class WebsocketManager { - private readonly clients = new Set(); - // Map correctly tracks identity — plain object keys would stringify all WSContext to "[object Object]" - private readonly lastPing = new Map(); - private initData: Record = {}; + /** Last ping time per client. A Map keys by identity; a plain object would stringify every WSContext to the same key. */ + private readonly clients = new Map(); + private readonly buildInit: (clientStation: string | null) => ServerMessage; - constructor() { + /** @param buildInit builds the `init` message sent to each newly connected client. */ + constructor(buildInit: (clientStation: string | null) => ServerMessage) { + this.buildInit = buildInit; setInterval(() => { - const threshold = Date.now() - 60_000; - for (const [client, ping] of this.lastPing) { - if (ping < threshold) this.leaveClient(client); + const threshold = Date.now() - PING_TIMEOUT_MS; + for (const [ws, lastPing] of this.clients) { + 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 { 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) => { - if (!event.data) return; - - let msg: IncomingMessage; + if (typeof event.data !== 'string') return; 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 { - return; - } - - 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}`); + // ignore malformed messages } }, onClose: (_event: CloseEvent, ws: WSContext) => { - this.leaveClient(ws); + this.clients.delete(ws); }, }; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - private handleMessage(_ws: WSContext, _data: unknown): void { - // Reserved for future incoming-message handling + broadcast(msg: ServerMessage): void { + const payload = JSON.stringify(msg); + for (const ws of this.clients.keys()) ws.send(payload); } - private send(ws: WSContext, data: unknown): void { - ws.send(JSON.stringify({ data })); - } - - 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): void { - this.initData = initData; + private send(ws: WSContext, msg: ServerMessage): void { + ws.send(JSON.stringify(msg)); } } diff --git a/src/index.ts b/src/index.ts index a9584eb..2f63995 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,71 +1,63 @@ -import { Hono } from 'hono'; +import { Hono, type Context } from 'hono'; import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; +import { getConnInfo } from '@hono/node-server/conninfo'; import { createNodeWebSocket } from '@hono/node-ws'; import RotRouter from './RotRouter.js'; import N1mmServer from './N1mmServer.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(); n1mm.onTurnMessage(msg => router.handleTurnMessage(msg)); n1mm.onRadioInfo(msg => router.handleRadioInfo(msg)); -const app = new Hono(); -app.use('/*', serveStatic({ root: './public' })); - -const websocketManager = new WebsocketManager(); -const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app }); - -const stationRadio: Record = {}; -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[0]): string { +function resolveClientIp(c: Context): string { const forwarded = c.req.header('x-forwarded-for')?.split(',')[0]?.trim(); const rawIp = forwarded || getConnInfo(c).remote.address || 'unknown'; return rawIp.startsWith('::ffff:') ? rawIp.slice(7) : rawIp; } +const app = new Hono(); +const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app }); + app.post('/turn/:label', async (c) => { const label = c.req.param('label'); const rot = (await c.req.parseBody())['ROT']; const az = typeof rot === 'string' && rot.trim() !== '' ? Number(rot) : NaN; if (!Number.isInteger(az) || az < 0) return c.text('Invalid azimuth', 400); - const sourceIp = resolveClientIp(c); - const ok = router.turn(label, az, sourceIp); + const ok = router.turn(label, az, resolveClientIp(c)); return ok ? c.text(`Turning ${label} to ${az}`) : c.text('Unknown rotator', 404); }); app.get('/ws', upgradeWebSocket((c) => { - const clientIp = resolveClientIp(c); - const clientStation = router.resolveStation(clientIp); + const clientStation = router.resolveStation(resolveClientIp(c)); return websocketManager.getHandler(clientStation); })); +app.use('/*', serveStatic({ root: './public' })); + const server = serve( - { fetch: app.fetch, port: 8787 }, + { fetch: app.fetch, port: HTTP_PORT }, info => console.log(`Listening on http://localhost:${info.port}`), ); - injectWebSocket(server); +router.start(); n1mm.start(); diff --git a/src/types.ts b/src/types.ts index 69bdc2e..8989229 100644 --- a/src/types.ts +++ b/src/types.ts @@ -11,11 +11,7 @@ export interface RadioInfoMessage { sourceIp: string; } -export interface TurnMessageHandler { - handleTurnMessage(msg: TurnMessage): void; -} - -export interface ClientConfig { +export interface RotatorConfig { ip: string; bands: number[]; } @@ -25,8 +21,8 @@ export interface StationConfig { color: string; } -export interface FullConfig { - rotators: Record; +export interface Config { + rotators: Record; stations: Record; } @@ -50,12 +46,31 @@ export interface InitData { export interface Setpoint { targetAz: number; sourceIp: string; + station: string | null; } -export interface ClientState { - initData: InitData; +export interface RotatorState { + initData: InitData | null; + dynamic: DynamicData | null; bands: number[]; - setpoint?: Setpoint; + setpoint: Setpoint | null; } -export type InitialState = Record; +export interface StationRadio { + band: number; + freq: number; +} + +/** Messages pushed from the server to browser clients over WebSocket. */ +export type ServerMessage = + | { + type: 'init'; + rotators: Record; + stations: Record; + stationRadio: Record; + 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 };