41 lines
5.5 KiB
JavaScript
41 lines
5.5 KiB
JavaScript
import {readFile,writeFile,rename} from 'node:fs/promises';
|
|
import path from 'node:path';import {randomUUID} from 'node:crypto';
|
|
import {plain,parseRadio} from './bpq.mjs';
|
|
export function packetChannels(rows){
|
|
if(!Array.isArray(rows)||rows.length<1||rows.length>12)throw Error('Configura da 1 a 12 frequenze');
|
|
const ids=new Set();return rows.map(r=>{const hz=Math.round(Number(r.frequencyMHz)*1e6),dwell=Number(r.dwellSeconds);
|
|
if(!Number.isFinite(hz)||!((hz>=144e6&&hz<=146e6)||(hz>=430e6&&hz<=440e6))||!Number.isInteger(dwell)||dwell<5||dwell>300||typeof r.enabled!=='boolean'||ids.has(hz))throw Error('Frequenza, intervallo o selezione non validi');
|
|
ids.add(hz);return {id:hz+'-FM',frequencyMHz:hz/1e6,mode:'FM',dwellSeconds:dwell,enabled:r.enabled};
|
|
});
|
|
}
|
|
export function packetStats(html){const text=plain(html);const value=label=>{const n=text.match(new RegExp(label+'\\s+(\\d+)','i'));return n?Number(n[1]):null;};return {txFrames:value('L2 Frames Sent'),rxFrames:value('L2 Frames Received'),timeouts:value('L2 Timeouts')};}
|
|
export class RadioPorts{
|
|
constructor(config,control,bpq,primary){this.config=config;this.control=control;this.bpq=bpq;this.primary=primary;this.history=new Map();this.prior=new Map();this.state=null;this.busy=false;this.chain=Promise.resolve();this.request={revision:null,ports:{}};this.file=config.radioPortsControl?.requestFile;}
|
|
async load(){if(this.file)try{this.request=JSON.parse(await readFile(this.file,'utf8'));}catch{}return this.request;}
|
|
paused(id){const p=this.request.ports?.[id];return p?.txSuspended===true||p?.listening===false;}
|
|
async sample(){if(this.busy)return;this.busy=true;try{
|
|
await this.load();const global=await this.control.snapshot(),rows=[];
|
|
for(const port of this.config.radioPorts){const descriptor=this.config.radioPortsControl?.ports?.find(p=>p.port===port.id),policy=this.request.ports?.[port.id]||{},isPrimary=port.id===this.config.radio?.id;let telemetry=null,channels=[],fresh=false,error=null;
|
|
try{if(isPrimary){telemetry={...this.primary().current};channels=global.channels;fresh=global.supported;}else if(descriptor?.statusFile){const s=JSON.parse(await readFile(descriptor.statusFile,'utf8'));fresh=Date.now()-Date.parse(s.at)<6000;telemetry={at:Date.parse(s.at),appliedPortRevision:s.appliedPortRevision,available:fresh&&s.pttReady&&s.connections>0,frequency:s.frequency,active:s.ptt||s.sessionActive,ptt:s.ptt,state:s.phase,scan:s.scanning,busy:s.busy,sent:s.txBytes??null,received:s.rxBytes??null,txFrames:s.txFrames??null,rxFrames:s.rxFrames??null,txBps:null,rxBps:null,caller:s.caller??null,called:s.called??null,snr:null,lastSnr:null,cpu:this.primary().current?.cpu??null,varaCpu:null};error=s.error||null;channels=(policy.channels||descriptor.channels||[]).map(r=>({...r,current:Math.abs(Number(s.frequency)-r.frequencyMHz)<.0001}));}
|
|
else{const html=await this.bpq('/Node/Port?'+port.id);telemetry={...parseRadio(html),available:/TNC State|Connected to|Frequency/i.test(plain(html)),at:Date.now()};}
|
|
const stats=packetStats(await this.bpq('/Node/PortStats?'+port.id+'&'+encodeURIComponent(port.driver)).catch(()=>''));Object.assign(telemetry,stats);
|
|
}catch(e){error=e.code==='ENOENT'?'Controller non disponibile':e.message;telemetry={at:Date.now(),available:false};}
|
|
const now=Date.now(),prior=this.prior.get(port.id),dt=prior?(now-prior.at)/1000:0;
|
|
if(!isPrimary){for(const [key,counter]of [['txBps','sent'],['rxBps','received']])telemetry[key]=dt&&telemetry[counter]!=null&&prior?.[counter]!=null&&telemetry[counter]>=prior[counter]?8*(telemetry[counter]-prior[counter])/dt:null;}
|
|
this.prior.set(port.id,{at:now,sent:telemetry.sent,received:telemetry.received});
|
|
const history=this.history.get(port.id)||[];history.push(telemetry);if(history.length>120)history.shift();this.history.set(port.id,history);
|
|
rows.push({id:port.id,name:port.name,driver:port.driver,independent:descriptor?.independent===true,supported:Boolean(this.file&&descriptor&&fresh),editableChannels:descriptor?.kind==='packet',channels,current:telemetry,history,control:{listening:policy.listening!==false,txSuspended:policy.txSuspended===true,globalTxSuspended:global.txSuspended,pending:descriptor?.kind==='packet'?Boolean(policy.revision&&telemetry.available&&policy.revision!==telemetry.appliedPortRevision):Boolean(policy.revision&&policy.revision!==global.appliedPortRevision)},error});
|
|
}
|
|
this.state={ports:rows,global,updatedAt:new Date().toISOString()};return this.state;
|
|
}finally{this.busy=false;}}
|
|
update(id,data){const task=this.chain.then(()=>this.apply(id,data));this.chain=task.catch(()=>{});return task;}
|
|
async apply(id,data){await this.load();const descriptor=this.config.radioPortsControl?.ports?.find(p=>p.port===id),row=this.state?.ports.find(p=>p.id===id);if(!this.file||!descriptor||!row?.supported)throw Error('Controllo porta non disponibile');
|
|
if(typeof data.txSuspended!=='boolean'||typeof data.listening!=='boolean')throw Error('Stato porta non valido');
|
|
let channels=descriptor.kind==='packet'?packetChannels(data.channels):data.channels;
|
|
if(!channels.some(r=>r.enabled))throw Error('Mantieni almeno una frequenza selezionata');
|
|
if(descriptor.kind==='native')await this.control.update({enabled:channels.filter(r=>r.enabled).map(r=>r.id),txSuspended:this.control.txSuspended});
|
|
const revision=randomUUID();this.request={...this.request,revision,ports:{...this.request.ports,[id]:{revision,txSuspended:data.txSuspended,listening:data.listening,channels}}};
|
|
await writeFile(this.file+'.tmp',JSON.stringify(this.request));await rename(this.file+'.tmp',this.file);await this.sample();return this.state;
|
|
}
|
|
}
|