import {readFile,writeFile,rename} from 'node:fs/promises'; import path from 'node:path';import {randomUUID} from 'node:crypto'; export function scanChannels(text,rig=1){ const lines=text.split(/\r?\n/);let inside=false;const out=[]; for(let i=0;ir.id));if(!Array.isArray(enabled)||!enabled.length||enabled.some(id=>!ids.has(id))||new Set(enabled).size!==enabled.length)throw Error('Seleziona almeno una frequenza configurata');const lines=text.split(/\r?\n/);for(const row of rows)lines[row.line]=' '+(enabled.includes(row.id)?'':'; CONSOLE-OFF ')+row.entry;return lines.join(text.includes('\r\n')?'\r\n':'\n');} export class RadioControl{ constructor(config){this.config=config;this.options=config.radioControl;this.request=null;} async snapshot(){const rows=scanChannels(await readFile(path.join(this.config.root,'BPQ32.cfg'),'utf8'),this.options?.rig||1);let state=null;try{state=JSON.parse(await readFile(this.options.statusFile,'utf8'));}catch{}try{this.request=JSON.parse(await readFile(this.options.requestFile,'utf8'));}catch{}this.blocked=Boolean(this.request&&state?.appliedRevision!==this.request.revision);this.txSuspended=Boolean(this.request?.txSuspended||state?.txSuspended);const ready=Boolean(this.options&&state&&Date.now()-Date.parse(state.at)<6000);return {supported:ready,channels:rows.map(({entry,line,...r})=>({...r,enabled:this.request?this.request.enabled.includes(r.id):r.enabled,current:state&&Math.abs(Number(state.frequency)-r.frequencyMHz)<0.0001})),txSuspended:this.txSuspended,pending:Boolean(this.request&&state?.appliedRevision!==this.request.revision),error:state?.error||null,at:state?.at||null};} async update(data){const current=await this.snapshot();if(!current.supported)throw Error('Controller radio non disponibile');if(typeof data.txSuspended!=='boolean')throw Error('Stato TX non valido');const text=await readFile(path.join(this.config.root,'BPQ32.cfg'),'utf8');scanConfig(text,this.options.rig||1,data.enabled);this.request={revision:randomUUID(),enabled:data.enabled,txSuspended:data.txSuspended};await writeFile(this.options.requestFile+'.tmp',JSON.stringify(this.request));await rename(this.options.requestFile+'.tmp',this.options.requestFile);return this.snapshot();} }