import dgram from 'node:dgram'; import { XMLParser } from 'fast-xml-parser'; import { freqToBand } from './bands.js'; import type { RadioInfoMessage, TurnMessage } from './types.js'; const N1MM_PORT = 12040; // fast-xml-parser converts numeric-looking tag values to numbers. interface ParsedXml { N1MMRotor?: { freqband?: string | number; goazi?: string | number; }; RadioInfo?: { Freq?: number; RadioNr?: number; FocusRadioNr?: number; }; } /** Takes the first entry of a possibly comma-separated N1MM value. */ function firstNumber(value: string | number | undefined): number { return parseFloat(String(value ?? '').split(',')[0] ?? ''); } export default class N1mmServer { private readonly xmlParser = new XMLParser(); private readonly turnHandlers: Array<(msg: TurnMessage) => void> = []; private readonly radioInfoHandlers: Array<(msg: RadioInfoMessage) => void> = []; start(): void { const server = dgram.createSocket('udp4'); server.on('error', err => { console.error('N1MM UDP server error:', err); server.close(); }); server.on('listening', () => { const { address, port } = server.address(); console.log(`N1MM UDP server listening on ${address}:${port}`); }); server.on('message', (msg, rinfo) => { this.processXml(msg.toString(), rinfo.address); }); server.bind(N1MM_PORT); } onTurnMessage(handler: (msg: TurnMessage) => void): void { this.turnHandlers.push(handler); } onRadioInfo(handler: (msg: RadioInfoMessage) => void): void { this.radioInfoHandlers.push(handler); } private processXml(xml: string, sourceIp: string): void { let parsed: ParsedXml; try { parsed = this.xmlParser.parse(xml) as ParsedXml; } catch (ex) { console.error(`Failed to parse N1MM packet from ${sourceIp}: ${xml}`, ex); return; } if (parsed.N1MMRotor) { this.processRotor(parsed.N1MMRotor, sourceIp); } else if (parsed.RadioInfo) { this.processRadioInfo(parsed.RadioInfo, sourceIp); } } private processRotor(rotor: NonNullable, sourceIp: string): void { const band = firstNumber(rotor.freqband); const az = Math.round(firstNumber(rotor.goazi)); if (!Number.isFinite(band) || !Number.isFinite(az)) { console.error(`Rotor packet from ${sourceIp} is missing band or azimuth`, rotor); return; } this.turnHandlers.forEach(h => h({ band, az, sourceIp })); } private processRadioInfo(info: NonNullable, sourceIp: string): void { const freq = Number(info.Freq ?? 0); // In SO2R/SO2V, only follow the radio that has keyboard focus. if (!freq || Number(info.RadioNr) !== Number(info.FocusRadioNr)) return; const band = freqToBand(freq / 100_000); if (band === null) return; this.radioInfoHandlers.forEach(h => h({ band, freq, sourceIp })); } }