Files
bpq_gui/aprs-kiss.mjs
T

15 lines
1.6 KiB
JavaScript

import net from 'node:net';
export function kissAprs(frame){
if(frame.length<17||(frame[0]&15)!==0)return null;
const addresses=[];let pos=1,ended=false;
while(pos+7<=frame.length&&addresses.length<10){const a=frame.subarray(pos,pos+7),ssid=(a[6]>>1)&15;addresses.push([...a.subarray(0,6)].map(c=>String.fromCharCode(c>>1)).join('').trim()+(ssid?'-'+ssid:''));pos+=7;if(a[6]&1){ended=true;break;}}
if(!ended||addresses.length<2||(frame[pos]&0xef)!==3||frame[pos+1]!==240)return null;
return addresses[1]+'>'+addresses[0]+(addresses.length>2?','+addresses.slice(2).join(','):'')+':'+frame.subarray(pos+2).toString('latin1');
}
// Receive-only connection: never writes commands or AX.25 data to the modem.
export class AprsKiss {
constructor(endpoint,receive){this.endpoint=endpoint;this.receive=receive;this.state='offline';this.bytes=[];this.escape=false;}
connect(){if(this.socket&&!this.socket.destroyed)return;this.state='connecting';this.bytes=[];this.escape=false;const socket=net.connect(this.endpoint.tcpPort,this.endpoint.host||'127.0.0.1');this.socket=socket;socket.on('connect',()=>this.state='online');socket.on('error',()=>this.state='error');socket.on('close',()=>{if(this.state!=='error')this.state='offline';});socket.on('data',data=>{for(let x of data){if(x===192){const packet=kissAprs(Buffer.from(this.bytes));if(packet)this.receive(packet,this.endpoint.port);this.bytes=[];this.escape=false;continue;}if(x===219){this.escape=true;continue;}if(this.escape){x=x===220?192:x===221?219:x;this.escape=false;}this.bytes.push(x);if(this.bytes.length>4096)this.bytes=[];}});}
close(){this.socket?.destroy();}
}