Files
RotRouter/src/N1mmServer.ts
T
erikbrockoandClaude Opus 5.5 debc6650d4 add stations and an Auto tab following each station's band
Parse N1MM RadioInfo packets, map sender IPs to configured stations,
and let the front-end auto-select the rotator for the selected
station's current band.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 02:34:20 +00:00

79 lines
2.3 KiB
TypeScript

import dgram from 'node:dgram';
import { XMLParser } from 'fast-xml-parser';
import type { TurnMessageHandler } from './types.js';
interface ParsedXml {
N1MMRotor?: {
freqband?: string;
goazi?: string;
};
RadioInfo?: {
Freq?: number;
RadioNr?: number;
FocusRadioNr?: number;
};
}
export default class N1mmServer {
private readonly xmlParser = new XMLParser();
private readonly turnHandlers: TurnMessageHandler[] = [];
private readonly radioInfoHandlers: Array<(sourceIp: string, band: number, freq: number) => void> = [];
start(): void {
const server = dgram.createSocket('udp4');
server.on('error', err => {
console.error(`server error:\n${err.stack}`);
server.close();
});
server.on('listening', () => {
const { address, port } = server.address();
console.log(`server listening ${address}:${port}`);
});
server.on('message', (msg, rinfo) => {
this.processXml(msg.toString(), rinfo.address);
});
server.bind(12040);
}
onTurnMessage(handler: TurnMessageHandler): void {
this.turnHandlers.push(handler);
}
onRadioInfo(handler: (sourceIp: string, band: number, freq: number) => void): void {
this.radioInfoHandlers.push(handler);
}
private processXml(xml: string, sourceIp: string): void {
try {
const parsed = this.xmlParser.parse(xml) as ParsedXml;
if (parsed.N1MMRotor) {
this.processRotor(parsed, sourceIp);
} else if (parsed.RadioInfo) {
this.processRadioInfo(parsed, sourceIp);
}
} catch (ex) {
console.error(`Failed to parse: ${xml}`, ex);
}
}
private processRotor(parsed: ParsedXml, sourceIp: string): void {
const band = parseInt(String(parsed.N1MMRotor?.freqband ?? '').split(',')[0] || '0', 10);
const az = parseInt(String(parsed.N1MMRotor?.goazi ?? '').split(',')[0] || '0', 10);
if (!band || !az) return;
this.turnHandlers.forEach(h => h.handleTurnMessage({ band, az, sourceIp }));
}
private processRadioInfo(parsed: ParsedXml, sourceIp: string): void {
const freq = Number(parsed.RadioInfo?.Freq ?? 0);
const radioNr = Number(parsed.RadioInfo?.RadioNr ?? 0);
const focusRadioNr = Number(parsed.RadioInfo?.FocusRadioNr ?? 0);
if (!freq || radioNr !== focusRadioNr) return;
const band = Math.floor(freq / 100000);
this.radioInfoHandlers.forEach(h => h(sourceIp, band, freq));
}
}