From 0c0a7169854cee32967624d073c37c48a228670d Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 16 Oct 2026 23:43:45 +0200 Subject: [PATCH] Add VHF and UHF Packet channels to the Winlink radio client --- README.md | 6 ++++++ manual-forwarding.mjs | 14 +++----------- public/winlink-radio.js | 16 ++++++++-------- radio-slot.mjs | 14 ++++++++++++++ server.mjs | 4 ++-- winlink-gateways.mjs | 28 +++++++++++++++++++++------- winlink-radio.mjs | 16 ++++++++++------ winlink-radio.test.mjs | 21 ++++++++++++++++++++- 8 files changed, 84 insertions(+), 35 deletions(-) create mode 100644 radio-slot.mjs diff --git a/README.md b/README.md index c45512b..5ef6b7c 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,12 @@ Before changing that profile, the panel backs up `BPQMail.cfg` under `BPQMailCha ## Forwarding, chat and terminal +The Winlink radio directory also downloads **PUBLIC Packet** channels when a UZ7HO/KISS/AX.25 port is present. Band filters include VHF (2 m), UHF (70 cm), both, and all bands. Packet channels use the published FM frequency exactly; the 1500 Hz USB offset applies only to HF channels. The channel details show the selected local port. Unsupported packet speeds stay visible with an explanation and cannot be selected; local support defaults to 1200 baud. + +Optional `winlinkRadio.packetPort` selects a specific local packet port and `winlinkRadio.packetBaud` declares its configured speed. These settings do not reprogram a TNC: its modem, audio and PTT must already be set up. The current packet client limits selection to 144–146 MHz and 430–440 MHz. Shared-radio installations may configure `winlinkRadio.packetController` with the same request/status file handshake described below. Their controller must acknowledge the requested frequency and keep the modem active while attached/connected. Internet forwarding is temporarily suspended and restored with the same recovery mechanism as HF radio sync. Directory downloads use Internet; the selected mail exchange uses radio. + +To publish a local packet gateway, configure BPQ's native `WL2KREPORT` on the packet port (before its `CONFIG` block), using mode `PKT1200`, the exact FM frequency in Hz, the RMS application's callsign, locator and actual UTC hours. BPQ must expose its RMS application on that port. The panel does not publish gateways itself. Reload BPQ after editing and verify the public directory after its next report; saving a line alone does not confirm publication. See the [official BPQ reporting documentation](https://www.cantab.net/users/john.wiseman/Documents/WL2KReporting.html). + **Forwarding** shows configured partners in a compact table. Click a row (or Enter/Space) to expand routing rules, scripts, schedules, queue counts and recent exchanges. Only one row opens at a time; focus survives refresh. Sync buttons are authenticated, serialised and protected against duplicate requests, active sessions and modem use. The next attempt is a log-based estimate; BPQ owns the real timer. Sensitive script commands are masked. Rules remain editable in BPQ. Optional `manualForwardingRoutes` in local `console.config.json` adds alternate radio paths to an existing BBS partner, without duplicating its queue or creating an automatic schedule: diff --git a/manual-forwarding.mjs b/manual-forwarding.mjs index 04956e3..abfd5b2 100644 --- a/manual-forwarding.mjs +++ b/manual-forwarding.mjs @@ -1,9 +1,8 @@ import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises'; import path from 'node:path'; -import {randomUUID} from 'node:crypto'; +import {reservePacketSlot,releasePacketSlot} from './radio-slot.mjs'; import {WinlinkRadio,rawProfile,activeMailStreams} from './winlink-radio.mjs'; import {safeScript} from './forwarding.mjs'; -const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)); export function manualRoutes(config){ const ids=new Set();return (config.manualForwardingRoutes||[]).map(route=>{ if(!/^[A-Z0-9-]{1,32}$/.test(route.id)||route.id===route.peer||ids.has(route.id)||! /^[A-Z0-9]{1,6}$/.test(route.peer)||! /^[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(route.connectCall)||!Number.isFinite(route.frequencyMHz)||route.frequencyMHz<1||route.frequencyMHz>500||! /^(USB|LSB|FM|DATA-FM)$/.test(route.mode)||!config.ports.some(p=>p.id===route.port&&!/TELNET|AXIP/i.test(p.driver)))throw Error('Percorso manuale di forwarding non valido'); @@ -16,15 +15,8 @@ export class ManualForwarding extends WinlinkRadio{ snapshot(){const state=super.snapshot();if(state?.error)state.error=state.error.replaceAll('profilo RMS','profilo del partner');return state;} async restore(){const state=await super.restore();await this.release();return state;} profiles(native){return this.routes.flatMap(route=>{const p=native.find(p=>p.call===route.peer);if(!p)return [];const j=this.job?.channel?.id===route.id?this.job:null;const history=j?p.history.filter(s=>Date.parse(s.startedAt)>=Date.parse(j.startedAt)-1500&&(!j.endedAt||Date.parse(s.startedAt)<=Date.parse(j.endedAt))):[];return [{...p,call:route.id,label:route.label,peer:route.peer,manualOnly:true,enabled:false,interval:0,immediate:false,reverseInterval:0,times:[],configured:true,port:route.port,driver:this.config.ports.find(p=>p.id===route.port)?.driver||'',transport:'Radio',frequency:[String(route.frequencyMHz),route.mode],script:safeScript(route.script),history,last:history[0]||null,active:Boolean(j?.restoring),preparing:j?.state==='preparing',requestedAt:j?.startedAt||null,nextEstimated:null}];});} - async prepare(route){ - if(!route.controller)return; - const request={id:randomUUID(),frequencyMHz:route.frequencyMHz,expiresAt:Date.now()+90000};this.job.controller={...route.controller,id:request.id};await this.persist(); - await writeFile(route.controller.requestFile+'.tmp',JSON.stringify(request));await rename(route.controller.requestFile+'.tmp',route.controller.requestFile); - const deadline=Date.now()+65000; - while(Date.now(){ const route=this.routes.find(r=>r.id===id);if(!route)throw Error('Percorso manuale non configurato'); if(this.job?.restoring||this.fwd.lockedPeers.has(route.peer))throw Error('Un inoltro per questo partner è già in corso'); diff --git a/public/winlink-radio.js b/public/winlink-radio.js index d92e292..12506d1 100644 --- a/public/winlink-radio.js +++ b/public/winlink-radio.js @@ -1,22 +1,22 @@ (() => { let directory=null,selectedId=null,fetching=false,requesting=false,session=null,expanded=false; const header=$('#winlink .chat-actions');$('#wl-sync').textContent='↻ Sync Internet';const toggle=document.createElement('button');toggle.className='secondary';toggle.id='wl-radio-toggle';toggle.textContent='◉ Sync Radio';toggle.setAttribute('aria-expanded','false');header.insertBefore(toggle,$('#wl-compose')); -const gatewayPanel=document.createElement('section');gatewayPanel.className='wl-radio-panel card';gatewayPanel.hidden=true;gatewayPanel.innerHTML=`
WINLINK · RADIO

Scegli un gateway

Directory ufficiale · canali PUBLIC

Caricamento…Frequenze sul display · USB · orari UTC
GatewayDial USBModo / bandaLocator / distanzaOrari UTCUltimo report
Nessun gateway selezionato

Seleziona un canale nell’elenco.

La distanza non indica la qualità del collegamento. Il report conferma la pubblicazione del gateway, non che il canale radio sia libero. La frequenza centrale è disponibile nel dettaglio del canale selezionato.

`; +const gatewayPanel=document.createElement('section');gatewayPanel.className='wl-radio-panel card';gatewayPanel.hidden=true;gatewayPanel.innerHTML=`
WINLINK · RADIO

Scegli un gateway

Directory ufficiale · canali PUBLIC

Caricamento…Frequenze sul display · USB / FM · orari UTC
GatewayFrequenza / modoModo / bandaLocator / distanzaOrari UTCUltimo report
Nessun gateway selezionato

Seleziona un canale nell’elenco.

La distanza non indica la qualità del collegamento. Il report conferma la pubblicazione del gateway, non che il canale radio sia libero. La frequenza centrale è disponibile nel dettaglio del canale selezionato.

`; $('#winlink .wl-status').before(gatewayPanel);$('#winlink .wl-status span:last-child').id='wl-transport-label'; const hz=f=>(f/1e6).toFixed(6)+' MHz'; const time=t=>t?new Date(t).toLocaleString('it-IT',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'}):'Non disponibile'; -const band=hz=>hz>=7e6&&hz<=7.3e6?'40':hz>=14e6&&hz<=14.35e6?'20':hz>=3.5e6&&hz<=4e6?'80':hz>=10.1e6&&hz<=10.15e6?'30':hz>=18.068e6&&hz<=18.168e6?'17':hz>=21e6&&hz<=21.45e6?'15':hz>=24.89e6&&hz<=24.99e6?'12':hz>=28e6?'10':'HF'; -const available=c=>directory&&!directory.stale&&c.fresh&&c.open===true; -function rows(){const q=$('#wl-gateway-search').value.trim().toUpperCase(),bands=$('#wl-gateway-band').value,open=$('#wl-gateway-open').checked,sort=$('#wl-gateway-sort').value;return (directory?.channels||[]).filter(c=>(bands==='all'||bands.split(',').includes(band(c.dialHz)))&&(!open||available(c))&&(!q||[c.call,c.grid,c.qth].join(' ').toUpperCase().includes(q))).sort((a,b)=>sort==='call'?a.call.localeCompare(b.call)||a.dialHz-b.dialHz:sort==='frequency'?a.dialHz-b.dialHz:(a.distanceKm??Infinity)-(b.distanceKm??Infinity)||a.call.localeCompare(b.call)||a.dialHz-b.dialHz);} -function render(){if(!directory)return;const list=rows();$('#wl-directory-meta').textContent='Winlink PUBLIC · '+directory.mode+' · aggiornato '+time(directory.fetchedAt)+' · '+mailTimezone();$('#wl-directory-error').hidden=!!wlData?.radioSupported&&!directory.error&&!directory.stale;$('#wl-directory-error').textContent=!wlData?'Verifica configurazione radio…':!wlData.radioSupported?'Sync radio non configurato: verifica modem e controllo CAT.':directory.stale?'Elenco non aggiornato: aggiorna prima di collegarti.':directory.error||'';$('#wl-gateway-count').textContent=list.length+(list.length===1?' canale · ':' canali · ')+new Set(list.map(c=>c.call)).size+' gateway';const focused=document.activeElement?.matches('input[name="wl-channel"]')?document.activeElement.closest('[data-channel]').dataset.channel:null;const scroll=$('.wl-gateway-scroll').scrollTop;$('#wl-gateway-rows').innerHTML=list.map(c=>`${esc(c.call)}${esc(c.qth)}${hz(c.dialHz)}${esc(c.mode)}${band(c.dialHz)} m${esc(c.grid)}${c.distanceKm==null?'Distanza non disponibile':c.distanceKm.toLocaleString('it-IT')+' km'}${esc(c.hours||'Non dichiarati')}${c.open===true?'In orario':c.open===false?'Fuori orario':'Orari non riconosciuti'}${time(c.postedAt)}${c.fresh?'Recente':'Report scaduto / assente'}`).join('')||'Nessun canale corrisponde ai filtri.';$('.wl-gateway-scroll').scrollTop=scroll;if(focused)$('[data-channel="'+focused+'"] input')?.focus({preventScroll:true});selection();} -function selection(){const c=directory?.channels.find(c=>c.id===selectedId);$('#wl-radio-selected').textContent=c?c.call+' · '+hz(c.dialHz)+' USB':'Nessun gateway selezionato';$('#wl-radio-selected-detail').textContent=c?'Centro: '+hz(c.centerHz)+' · '+c.grid+' · '+c.mode:'Seleziona un canale nell’elenco.';const active=Boolean(session?.restoring);$('#wl-radio-connect').disabled=requesting||active||!c||!available(c)||!wlData?.radioSupported;$('#wl-radio-connect').textContent=requesting?'Richiesta…':active?'Sessione in corso…':'Connetti e sincronizza →';} +const band=hz=>hz>=430e6&&hz<=440e6?'uhf':hz>=144e6&&hz<=146e6?'vhf':hz>=7e6&&hz<=7.3e6?'40':hz>=14e6&&hz<=14.35e6?'20':hz>=3.5e6&&hz<=4e6?'80':hz>=10.1e6&&hz<=10.15e6?'30':hz>=18.068e6&&hz<=18.168e6?'17':hz>=21e6&&hz<=21.45e6?'15':hz>=24.89e6&&hz<=24.99e6?'12':hz>=28e6?'10':'HF'; +const available=c=>directory&&!directory.stale&&c.fresh&&c.open===true&&c.supported!==false; +function rows(){const q=$('#wl-gateway-search').value.trim().toUpperCase(),bands=$('#wl-gateway-band').value,open=$('#wl-gateway-open').checked,sort=$('#wl-gateway-sort').value;return (directory?.channels||[]).filter(c=>(bands==='all'||bands==='hf'&&!['vhf','uhf'].includes(band(c.dialHz))||bands.split(',').includes(band(c.dialHz)))&&(!open||!directory.stale&&c.fresh&&c.open===true)&&(!q||[c.call,c.grid,c.qth].join(' ').toUpperCase().includes(q))).sort((a,b)=>sort==='call'?a.call.localeCompare(b.call)||a.dialHz-b.dialHz:sort==='frequency'?a.dialHz-b.dialHz:(a.distanceKm??Infinity)-(b.distanceKm??Infinity)||a.call.localeCompare(b.call)||a.dialHz-b.dialHz);} +function render(){if(!directory)return;const list=rows();$('#wl-directory-meta').textContent='Winlink PUBLIC · '+directory.mode+' · aggiornato '+time(directory.fetchedAt)+' · '+mailTimezone();$('#wl-directory-error').hidden=!!wlData?.radioSupported&&!directory.error&&!directory.stale;$('#wl-directory-error').textContent=!wlData?'Verifica configurazione radio…':!wlData.radioSupported?'Sync radio non configurato: verifica modem e controllo CAT.':directory.stale?'Elenco non aggiornato: aggiorna prima di collegarti.':directory.error||'';$('#wl-gateway-count').textContent=list.length+(list.length===1?' canale · ':' canali · ')+new Set(list.map(c=>c.call)).size+' gateway';const focused=document.activeElement?.matches('input[name="wl-channel"]')?document.activeElement.closest('[data-channel]').dataset.channel:null;const scroll=$('.wl-gateway-scroll').scrollTop;$('#wl-gateway-rows').innerHTML=list.map(c=>`${esc(c.call)}${esc(c.qth)}${hz(c.dialHz)}${esc(c.radioMode||'USB')}${esc(c.mode)}${band(c.dialHz)==='vhf'?'VHF · 2 m':band(c.dialHz)==='uhf'?'UHF · 70 cm':band(c.dialHz)+' m'}${esc(c.grid)}${c.distanceKm==null?'Distanza non disponibile':c.distanceKm.toLocaleString('it-IT')+' km'}${esc(c.hours||'Non dichiarati')}${c.open===true?'In orario':c.open===false?'Fuori orario':'Orari non riconosciuti'}${time(c.postedAt)}${c.fresh?'Recente':'Report scaduto / assente'}${c.supported===false?''+esc(c.reason)+'':''}`).join('')||'Nessun canale corrisponde ai filtri.';$('.wl-gateway-scroll').scrollTop=scroll;if(focused)$('[data-channel="'+focused+'"] input')?.focus({preventScroll:true});selection();} +function selection(){const c=directory?.channels.find(c=>c.id===selectedId);$('#wl-radio-selected').textContent=c?c.call+' · '+hz(c.dialHz)+' '+(c.radioMode||'USB'):'Nessun gateway selezionato';$('#wl-radio-selected-detail').textContent=c?(c.family==='Packet'?'Frequenza FM: ':'Centro: ')+hz(c.centerHz)+' · '+c.grid+' · '+c.mode+' · porta '+c.port:'Seleziona un canale nell’elenco.';const active=Boolean(session?.restoring);$('#wl-radio-connect').disabled=requesting||active||!c||!available(c)||!wlData?.radioSupported;$('#wl-radio-connect').textContent=requesting?'Richiesta…':active?'Sessione in corso…':'Connetti e sincronizza →';} async function load(force=false){if(fetching||!csrf)return;fetching=true;$('#wl-gateway-refresh').disabled=true;try{directory=await api('/winlink/gateways'+(force?'?refresh=1':''));render();}catch(e){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent=e.message;$('#wl-gateway-count').textContent='Elenco non disponibile';}finally{fetching=false;$('#wl-gateway-refresh').disabled=false;}} -toggle.onclick=()=>{expanded=!expanded;gatewayPanel.hidden=!expanded;toggle.setAttribute('aria-expanded',String(expanded));toggle.classList.toggle('active',expanded);if(expanded){if(!wlData?.radioSupported){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent='Sync radio non configurato: serve un modem HF supportato e il controllo CAT abilitato.';}load();}}; +toggle.onclick=()=>{expanded=!expanded;gatewayPanel.hidden=!expanded;toggle.setAttribute('aria-expanded',String(expanded));toggle.classList.toggle('active',expanded);if(expanded){if(!wlData?.radioSupported){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent='Sync radio non configurato: serve un modem supportato e il controllo CAT abilitato.';}load();}}; $('#wl-gateway-refresh').onclick=()=>load(true);for(const id of ['wl-gateway-search','wl-gateway-band','wl-gateway-open','wl-gateway-sort'])$('#'+id).oninput=render; gatewayPanel.addEventListener('click',e=>{const row=e.target.closest('[data-channel]');if(!row)return;const c=directory.channels.find(c=>c.id===row.dataset.channel);if(!available(c))return;selectedId=c.id;render();}); gatewayPanel.addEventListener('change',e=>{if(e.target.matches('input[name="wl-channel"]')){selectedId=e.target.closest('[data-channel]').dataset.channel;render();}}); $('#wl-radio-connect').onclick=async()=>{if(requesting||!selectedId)return;requesting=true;selection();try{session=await api('/winlink/radio/sync',{method:'POST',body:JSON.stringify({channelId:selectedId})});toast('Sync radio richiesto verso '+session.channel.call);updateSession();setTimeout(wlLoad,1200);}catch(e){$('#wl-directory-error').hidden=false;$('#wl-directory-error').textContent=e.message;toast(e.message);}finally{requesting=false;selection();}}; -function updateSession(){session=wlData?.radioSession||session;const active=session?.restoring;restore.hidden=!(active&&['conflict','error'].includes(session.state));$('#wl-sync').disabled=Boolean(active);$('#wl-transport-label').textContent=wlData?.transport==='radio'||active?'Radio · '+(session?.channel.call||'RMS'):'CMS · Internet';const box=$('#wl-radio-progress');box.hidden=!session;if(session){const label={requested:'Richiesta inviata a BPQ',calling:'Chiamata radio in corso',connected:'Collegato · scambio posta',complete:'Sync radio completato',ended:'Profilo Internet ripristinato',failed:'Collegamento non riuscito',incomplete:'Sessione interrotta',error:'Errore nella richiesta',conflict:'Ripristino da verificare'}[session.state]||session.state;box.className='wl-radio-progress '+(active?'running':session.state==='complete'?'complete':'');box.textContent=(active?'◉ ':'')+label+' · '+session.channel.call+' · '+hz(session.channel.dialHz)+(session.sent!=null?' · TX '+session.sent+' / RX '+session.received:'')+(active?' · profilo Internet sospeso':session.endedAt?' · '+time(session.endedAt):'')+(session.error?' · '+session.error:'');}selection();} +function updateSession(){session=wlData?.radioSession||session;const active=session?.restoring;restore.hidden=!(active&&['conflict','error'].includes(session.state));$('#wl-sync').disabled=Boolean(active);$('#wl-transport-label').textContent=wlData?.transport==='radio'||active?'Radio · '+(session?.channel.call||'RMS'):'CMS · Internet';const box=$('#wl-radio-progress');box.hidden=!session;if(session){const label={preparing:'Preparazione modem packet e frequenza',requested:'Richiesta inviata a BPQ',calling:'Chiamata radio in corso',connected:'Collegato · scambio posta',complete:'Sync radio completato',ended:'Profilo Internet ripristinato',failed:'Collegamento non riuscito',incomplete:'Sessione interrotta',error:'Errore nella richiesta',conflict:'Ripristino da verificare'}[session.state]||session.state;box.className='wl-radio-progress '+(active?'running':session.state==='complete'?'complete':'');box.textContent=(active?'◉ ':'')+label+' · '+session.channel.call+' · '+hz(session.channel.dialHz)+(session.sent!=null?' · TX '+session.sent+' / RX '+session.received:'')+(active?' · profilo Internet sospeso':session.endedAt?' · '+time(session.endedAt):'')+(session.error?' · '+session.error:'');}selection();} setInterval(()=>{if(expanded&&csrf&&!document.hidden)load();},60000); const restore=document.createElement('button');restore.className='secondary wl-radio-restore';restore.textContent='Ripristina profilo Internet';restore.hidden=true;$('#wl-radio-progress').after(restore);restore.onclick=async()=>{restore.disabled=true;try{session=await api('/winlink/radio/restore',{method:'POST',body:'{}'});await wlLoad();}catch(e){toast(e.message);}finally{restore.disabled=false;}}; const previousRender=wlRender;wlRender=function(){previousRender();if(directory){$('#wl-directory-error').hidden=!!wlData?.radioSupported&&!directory.error&&!directory.stale;$('#wl-directory-error').textContent=!wlData?'Verifica configurazione radio…':!wlData.radioSupported?'Sync radio non configurato: verifica modem e controllo CAT.':directory.stale?'Elenco non aggiornato: aggiorna prima di collegarti.':directory.error||'';}updateSession();}; diff --git a/radio-slot.mjs b/radio-slot.mjs new file mode 100644 index 0000000..f13fab3 --- /dev/null +++ b/radio-slot.mjs @@ -0,0 +1,14 @@ +import {readFile,writeFile,rename} from 'node:fs/promises'; +import {randomUUID} from 'node:crypto'; +export async function reservePacketSlot(client,controller,frequencyMHz,port){ + if(!controller)return; + const request={id:randomUUID(),frequencyMHz,expiresAt:Date.now()+90000};client.job.controller={...controller,id:request.id};await client.persist(); + await writeFile(controller.requestFile+'.tmp',JSON.stringify(request));await rename(controller.requestFile+'.tmp',controller.requestFile); + const deadline=Date.now()+65000; + while(Date.now()setTimeout(resolve,300));} + throw Error('Modem packet non pronto: nessuna chiamata avviata'); +} +export async function releasePacketSlot(client){ + const c=client.job?.controller;if(!c||c.released)return; + try{const request=JSON.parse(await readFile(c.requestFile,'utf8'));if(request.id===c.id&&request.expiresAt){request.expiresAt=0;await writeFile(c.requestFile,JSON.stringify(request));}c.released=true;}catch{} +} diff --git a/server.mjs b/server.mjs index 92de365..dc6c19c 100644 --- a/server.mjs +++ b/server.mjs @@ -2,7 +2,7 @@ import {Terminal} from './terminal.mjs'; import {SingleFlight} from './single-flight.mjs'; import http from 'node:http'; import {Journal} from './journal.mjs'; -import {GatewayDirectory,modemFamily} from './winlink-gateways.mjs'; +import {GatewayDirectory,modemFamily,packetPort} from './winlink-gateways.mjs'; import {WinlinkRadio} from './winlink-radio.mjs'; import {ManualForwarding} from './manual-forwarding.mjs'; import {forwardingHistory} from './forwarding.mjs'; @@ -85,7 +85,7 @@ const metadataCache=new Map();let metadataKey=null,metadataKeyAt=0; function messageFields(id){return metadataReads.run(id,()=>readMessageFields(id));} async function readMessageFields(id){let cached=metadataCache.get(id);if(cached&&Date.now()-cached.at<60000)return cached.fields;if(!metadataKey||Date.now()-metadataKeyAt>600000){const status=await bpq('/Mail/Status');metadataKey=status.match(/href=\/Mail\/Msgs\?([^\s>]+)/)?.[1];metadataKeyAt=Date.now();}if(!metadataKey)throw new Error('Metadati BBS non disponibili');const html=await bpq('/Mail/MsgDetails?'+metadataKey,{method:'POST',body:String(id)});const fields={};for(const input of html.matchAll(/]*>/gi)){const name=input[0].match(/\bname=(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i),value=input[0].match(/\bvalue=(?:"([^"]*)"|'([^']*)'|([^\s>]*))/i);if(name)fields[name[1]??name[2]??name[3]]=decode(value?.[1]??value?.[2]??value?.[3]??'');}metadataCache.set(id,{at:Date.now(),fields});return fields;} async function mailMetadata(list){const out=[];for(const item of list.filter(m=>m.type==='P')){const f=await messageFields(item.id);const m={...item,from:f.From||item.from,to:f.To||item.to,subject:f.Title||item.subject};const via=f.VIA||m.via,emailFrom=f.EFROM||'';if(m.to==='RMS'||m.from==='RMS'||/WINLINK|@/i.test(via+emailFrom)){const full={...m,via,emailFrom,address:m.to==='RMS'?via:m.to,fromAddress:emailFrom?(emailFrom.startsWith('@')?m.from+emailFrom:emailFrom):m.from};out.push({...full,direction:mailDirection(full,config.sysop.call),folder:mailFolder(full,config.sysop.call)});}}return out;} -async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&modemFamily(config.radio.driver)&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};} +async function winlink(){const list=await mailMetadata(await messages(false));for(const m of list)Object.assign(m,await messageTimes(m.id));const today=new Date().toLocaleDateString('sv-SE',{timeZone:'UTC'}).replaceAll('-','').slice(2);let sync=cmsStatus('');try{sync=cmsStatus(await readFile(path.join(root,'Logs',`log_${today}_BBS.txt`),'utf8'));}catch{}const radioSession=winlinkRadio.snapshot();const history=forwardingHistory(await forwarding.logs().catch(()=>''),config.cmsPeer||'RMS');const last=history[0];const radioLatest=radioSession&&(radioSession.restoring||last&&Math.abs(Date.parse(last.startedAt)-Date.parse(radioSession.startedAt))<5000);return {messages:list,sync,account:config.sysop.call.replace(/-\d+$/,'')+'@winlink.org',requestedAt:lastCmsRequest||null,radioSession,transport:radioLatest?'radio':'internet',radioSupported:Boolean(config.radio&&(modemFamily(config.radio.driver)||packetPort(config))&&config.winlinkRadio?.catControl),modem:config.radio?.driver||null};} async function deleteMessage(id){const list=await messages();if(!list.some(m=>m.id===id))throw new Error('Messaggio non presente');const {key}=await mailContext();await bpq('/WebMail/WMDel/'+id+'?'+key);metadataCache.delete(id);timestampCache.delete(id);metadataReads.invalidate(id);mailReads.clear();if((await messages()).some(m=>m.id===id))throw new Error('BPQ non ha confermato la cancellazione');return {ok:true};} async function attachedMessage(id){const visible=await messages(false);const item=visible.find(m=>m.id===id);if(!item)throw new Error('Messaggio non disponibile');const file=path.join(root,'BPQMailChat','Mail','m_'+String(id).padStart(6,'0')+'.mes');const info=await stat(file);if(info.size>32*1024*1024)throw new Error('Messaggio troppo grande per il download web (32 MB)');const bytes=await readFile(file);const files=parseAttachments(bytes);const rebuilt=await sevenPlus.forMessage(id,visible);if(rebuilt?.file)files.push({...rebuilt.file,index:files.length});const encoded=item.subject.match(/^7\+\s+(.+?)\s+(\d+)\/(\d+)$/i);return {item,bytes,files,encoded:rebuilt?.metadata||(encoded?{name:safeName(encoded[1]),part:Number(encoded[2]),total:Number(encoded[3]),state:'unavailable'}:null)};} async function sendMessage(data){ diff --git a/winlink-gateways.mjs b/winlink-gateways.mjs index f88dfad..77a3bd7 100644 --- a/winlink-gateways.mjs +++ b/winlink-gateways.mjs @@ -9,23 +9,37 @@ const attr=(s,n)=>decode(s.match(new RegExp('\\b'+n+'="([^"]*)"','i'))?.[1]||'') export function csvRows(text){const rows=[];let row=[],cell='',quoted=false;for(let i=0;is.trim().match(/^(\d{2})-(\d{2})$/)).filter(Boolean);if(!ranges.length)return null;const h=now.getUTCHours();return ranges.some(m=>+m[1]<=23&&+m[2]<=23&&(+m[1]<=+m[2]?h>=+m[1]&&h<=+m[2]:h>=+m[1]||h<=+m[2])); + if(String(hours).trim()==='24')return true;const ranges=String(hours).split(',').map(s=>s.trim().match(/^(\d{2})-(\d{2})$/)).filter(Boolean);if(!ranges.length)return null;const h=now.getUTCHours();return ranges.some(m=>+m[1]<=23&&+m[2]<=23&&(+m[1]<=+m[2]?h>=+m[1]&&h<=+m[2]:h>=+m[1]||h<=+m[2])); } export function distanceKm(a,b){const rad=x=>x*Math.PI/180,lat=rad(b.lat-a.lat),lon=rad(b.lon-a.lon);return Math.round(6371*2*Math.asin(Math.min(1,Math.sqrt(Math.sin(lat/2)**2+Math.cos(rad(a.lat))*Math.cos(rad(b.lat))*Math.sin(lon/2)**2))));} export function parseChannels(csv,mode){ const rows=csvRows(csv.replace(/^\uFEFF/,'')),head=rows.shift();if(!['Timestamp','Callsign','GridSquare','Frequency','Mode','Hours'].every(k=>head?.includes(k)))throw new Error('Formato elenco Winlink non riconosciuto'); - const out=new Map();for(const row of rows){const o=Object.fromEntries(head.map((k,i)=>[k,row[i]||''])),match=o.Frequency.match(/^([\d,.]+)\s*(KHz|MHz)$/i),call=o.Callsign.trim().toUpperCase(),position=locatorPosition(o.GridSquare.trim());if(!match||!position||! /^(?=.*\d)[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(call))continue;const centerHz=Math.round(Number(match[1].replaceAll(',',''))*(match[2].toUpperCase()==='MHZ'?1e6:1e3));if(!Number.isFinite(centerHz)||centerHz<1e6||centerHz>30e6)continue;const id=createHash('sha256').update([call,centerHz,o.Mode,o.GridSquare].join('|')).digest('hex').slice(0,24);out.set(id,{id,call,grid:o.GridSquare.trim().toUpperCase(),centerHz,dialHz:centerHz-1500,mode:o.Mode.trim(),family:mode,hours:o.Hours.trim(),postedAt:parsePosted(o.Timestamp),qth:o.QTH.trim().slice(0,160),position:{lat:position.lat,lon:position.lon}});} + const out=new Map();for(const row of rows){const o=Object.fromEntries(head.map((k,i)=>[k,row[i]||''])),match=o.Frequency.match(/^([\d,.]+)\s*(KHz|MHz)$/i),call=o.Callsign.trim().toUpperCase(),position=locatorPosition(o.GridSquare.trim());if(!match||!position||! /^(?=.*\d)[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(call))continue;const centerHz=Math.round(Number(match[1].replaceAll(',',''))*(match[2].toUpperCase()==='MHZ'?1e6:1e3));if(!Number.isFinite(centerHz)||centerHz<1e6||centerHz>(mode==='Packet'?500e6:30e6))continue;const id=createHash('sha256').update([call,centerHz,o.Mode,o.GridSquare].join('|')).digest('hex').slice(0,24);out.set(id,{id,call,grid:o.GridSquare.trim().toUpperCase(),centerHz,dialHz:mode==='Packet'?centerHz:centerHz-1500,radioMode:mode==='Packet'?'DATA-FM':'USB',baud:mode==='Packet'?Number(o.Mode.match(/\d+/)?.[0])||null:null,mode:o.Mode.trim(),family:mode,hours:o.Hours.trim(),postedAt:parsePosted(o.Timestamp),qth:o.QTH.trim().slice(0,160),position:{lat:position.lat,lon:position.lon}});} return [...out.values()]; } export function modemFamily(driver){return /VARA/i.test(driver)?'VARA':/PACTOR|SCS/i.test(driver)?'Pactor':/ARDOP/i.test(driver)?'ARDOP':null;} +export function directoryModes(config){const hf=modemFamily(config.radio?.driver);return [...new Set([...(hf?[hf]:[]),...(packetPort(config)?['Packet']:[])])];} +export function packetPort(config){return (config.ports||[]).find(p=>p.id===Number(config.winlinkRadio?.packetPort))||(config.ports||[]).find(p=>/UZ7HO|KISS|AX25|AX\.25/i.test(p.driver)&&!/AXIP/i.test(p.driver));} +export function channelSupport(config,channel){ + if(channel.family==='Packet'){ + const port=packetPort(config);if(!port)return {supported:false,reason:'Nessuna porta packet configurata'}; + if(channel.baud!==Number(config.winlinkRadio?.packetBaud||1200))return {supported:false,reason:'Velocità packet non supportata dal modem locale'}; + if(!((channel.dialHz>=144e6&&channel.dialHz<=146e6)||(channel.dialHz>=430e6&&channel.dialHz<=440e6)))return {supported:false,reason:'Frequenza fuori dalle bande packet abilitate (2 m / 70 cm)'}; + return {supported:true,port:port.id,radioMode:'DATA-FM'}; + } + if(channel.family!==modemFamily(config.radio?.driver))return {supported:false,reason:'Modem non compatibile'}; + return {supported:true,port:config.radio.id,radioMode:'USB'}; +} export class GatewayDirectory{ constructor(config,dir,fetcher=fetch){this.config=config;this.file=path.join(dir,'winlink-gateways.cache.json');this.fetcher=fetcher;this.cache=null;this.pending=null;this.lastAttempt=0;this.error=null;} async refresh(){if(this.pending)return this.pending;this.pending=(async()=>{ - const mode=modemFamily(this.config.radio?.driver);if(!mode)throw new Error('Nessun modem HF compatibile con la directory Winlink'); + const modes=directoryModes(this.config);if(!modes.length)throw new Error('Nessun modem compatibile con la directory Winlink');const all=[]; + for(const mode of modes){ this.lastAttempt=Date.now();const page=await this.fetcher(directoryURL,{signal:AbortSignal.timeout(15000)});if(!page.ok)throw new Error('Directory pubblica Winlink non disponibile');const html=await page.text();if(html.length>4e6)throw new Error('Pagina Winlink troppo grande');const form=new URLSearchParams();for(const m of html.matchAll(/]*>/gi))if(/type="hidden"/i.test(m[0]))form.set(attr(m[0],'name'),attr(m[0],'value'));if(!form.has('__VIEWSTATE'))throw new Error('Modulo pubblico Winlink non riconosciuto');form.set('rblModes',mode);form.set('txtServiceCodes','PUBLIC');form.set('btnCsvFile','CSV File'); - const response=await this.fetcher(directoryURL,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:form,signal:AbortSignal.timeout(20000)});if(!response.ok)throw new Error('Download canali Winlink non disponibile');const csv=await response.text();if(csv.length>8e6)throw new Error('Elenco canali troppo grande');const channels=parseChannels(csv,mode);if(!channels.length)throw new Error('Nessun canale HF valido nel download Winlink');this.cache={fetchedAt:new Date().toISOString(),mode,channels};this.error=null;await writeFile(this.file+'.tmp',JSON.stringify(this.cache));await rename(this.file+'.tmp',this.file);return this.cache; + const response=await this.fetcher(directoryURL,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:form,signal:AbortSignal.timeout(20000)});if(!response.ok)throw new Error('Download canali Winlink non disponibile');const csv=await response.text();if(csv.length>8e6)throw new Error('Elenco canali troppo grande');const channels=parseChannels(csv,mode);if(!channels.length)throw new Error('Nessun canale valido nel download Winlink');all.push(...channels);} + this.cache={version:2,fetchedAt:new Date().toISOString(),mode:modes.join(' + '),channels:all};this.error=null;await writeFile(this.file+'.tmp',JSON.stringify(this.cache));await rename(this.file+'.tmp',this.file);return this.cache; })().catch(e=>{this.error=e.message;throw e}).finally(()=>this.pending=null);return this.pending;} - async load(force=false){if(!this.cache)try{const c=JSON.parse(await readFile(this.file,'utf8'));if(c.mode===modemFamily(this.config.radio?.driver)&&Array.isArray(c.channels))this.cache=c;}catch{}if((force||!this.cache||Date.now()-Date.parse(this.cache.fetchedAt)>15*60000)&&Date.now()-this.lastAttempt>60000)try{await this.refresh();}catch(e){if(!this.cache)throw e;}if(!this.cache)throw new Error(this.error||'Elenco gateway non disponibile');return this.cache;} - async snapshot(force=false){const c=await this.load(force),own=String(this.config.sysop.call).replace(/-\d+$/,''),origin=locatorPosition(this.config.locator),now=Date.now();return {source:directoryURL,fetchedAt:c.fetchedAt,mode:c.mode,error:this.error,stale:now-Date.parse(c.fetchedAt)>30*60000,channels:c.channels.filter(ch=>ch.call.replace(/-\d+$/,'')!==own).map(ch=>({...ch,distanceKm:origin?distanceKm(origin,ch.position):null,open:channelOpen(ch.hours),fresh:ch.postedAt&&now-Date.parse(ch.postedAt)<6*3600000&&Date.parse(ch.postedAt)<=now+300000})),station:{grid:this.config.locator,radio:this.config.radio,offsetHz:1500}};} - async selected(id){const d=await this.snapshot();const ch=d.channels.find(c=>c.id===id);if(!ch||d.stale||!ch.fresh||ch.open!==true)throw new Error('Canale non disponibile: aggiorna elenco e verifica orari del gateway');return ch;} + async load(force=false){if(!this.cache)try{const c=JSON.parse(await readFile(this.file,'utf8'));if(c.version===2&&c.mode===directoryModes(this.config).join(' + ')&&Array.isArray(c.channels))this.cache=c;}catch{}if((force||!this.cache||Date.now()-Date.parse(this.cache.fetchedAt)>15*60000)&&Date.now()-this.lastAttempt>60000)try{await this.refresh();}catch(e){if(!this.cache)throw e;}if(!this.cache)throw new Error(this.error||'Elenco gateway non disponibile');return this.cache;} + async snapshot(force=false){const c=await this.load(force),own=String(this.config.sysop.call).replace(/-\d+$/,''),origin=locatorPosition(this.config.locator),now=Date.now();return {source:directoryURL,fetchedAt:c.fetchedAt,mode:c.mode,error:this.error,stale:now-Date.parse(c.fetchedAt)>30*60000,channels:c.channels.filter(ch=>ch.call.replace(/-\d+$/,'')!==own).map(ch=>({...ch,...channelSupport(this.config,ch),distanceKm:origin?distanceKm(origin,ch.position):null,open:channelOpen(ch.hours),fresh:ch.postedAt&&now-Date.parse(ch.postedAt)<6*3600000&&Date.parse(ch.postedAt)<=now+300000})),station:{grid:this.config.locator,radio:this.config.radio,offsetHz:1500}};} + async selected(id){const d=await this.snapshot();const ch=d.channels.find(c=>c.id===id);if(!ch||!ch.supported||d.stale||!ch.fresh||ch.open!==true)throw new Error('Canale non disponibile: aggiorna elenco e verifica orari del gateway');return ch;} } diff --git a/winlink-radio.mjs b/winlink-radio.mjs index e1a8e7f..bf91a14 100644 --- a/winlink-radio.mjs +++ b/winlink-radio.mjs @@ -1,5 +1,7 @@ import {readFile,writeFile,rename,mkdir,copyFile} from 'node:fs/promises'; import path from 'node:path'; +import {channelSupport} from './winlink-gateways.mjs'; +import {reservePacketSlot,releasePacketSlot} from './radio-slot.mjs'; import {forwardingHistory} from './forwarding.mjs'; export function rawProfile(text,peer){const escaped=peer.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),block=text.match(new RegExp('\\b'+escaped+'\\s*:\\s*\\{([^{}]*)\\}'));if(!block)throw new Error('Profilo RMS non presente in BPQ');const fields={};for(const m of block[1].matchAll(/\b(\w+)\s*=\s*(?:"([^"\r\n]*)"|(\d+))\s*;/g))fields[m[1]]=m[2]??m[3];return fields;} const textKeys=['TOCalls','ATCalls','FWDTimes','ConnectScript','HRoutes','HRoutesP','BBSHA']; @@ -8,8 +10,9 @@ const booleans=new Set(['Enabled','RequestReverse','FWDNewImmediately','AllowBlo export function profilePayload(fields){return [...textKeys.map(k=>(fields[k]||'').replaceAll('|','\r\n')),...keyOrder.map(k=>booleans.has(k)?fields[k]==='1'?'true':'false':String(Number(fields[k])||0)),''].join('|');} export function activeMailStreams(html){const options=[...html.matchAll(/]*value=["']?\d+["']?[^>]*>([\s\S]*?)<\/option>/gi)];if(!options.length)throw new Error('Stato sessioni BBS non verificabile');return options.map(m=>m[1].replace(/ /g,' ').replace(/<[^>]*>/g,'').trim()).filter(s=>s&&!/^Idle\b/i.test(s));} export function radioProfile(original,channel,port){ - if(!Number.isInteger(port)||port<1||port>64||! /^(?=.*\d)[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(channel.call)||!Number.isInteger(channel.dialHz)||channel.dialHz<1e6||channel.dialHz>30e6)throw new Error('Canale radio non valido'); - return {...original,ConnectScript:`ATTACH ${port}|RADIO ${(channel.dialHz/1e6).toFixed(6)} USB|PAUSE 2|C ${channel.call}`,Enabled:'0',FWDNewImmediately:'0',UseB1Protocol:'0',UseB2Protocol:'1',AllowBlocked:'1',AllowCompressed:'1',FWDPersonalsOnly:'1'}; + const packet=channel.family==='Packet'; + if(!Number.isInteger(port)||port<1||port>64||! /^(?=.*\d)[A-Z0-9]{3,7}(?:-\d{1,2})?$/.test(channel.call)||!Number.isInteger(channel.dialHz)||channel.dialHz<1e6||channel.dialHz>(packet?500e6:30e6))throw new Error('Canale radio non valido'); + return {...original,ConnectScript:`ATTACH ${port}|RADIO ${(channel.dialHz/1e6).toFixed(6)} ${packet?'DATA-FM':'USB'}|PAUSE 2|C ${channel.call}`,Enabled:'0',FWDNewImmediately:'0',UseB1Protocol:'0',UseB2Protocol:'1',AllowBlocked:'1',AllowCompressed:'1',FWDPersonalsOnly:'1'}; } export class WinlinkRadio{ constructor(config,dir,forwarding,directory,options={}){this.config=config;this.fwd=forwarding;this.directory=directory;this.file=path.join(dir,options.stateFile||'winlink-radio.session.json');this.job=null;this.busy=false;this.recovered=false;this.init=this.recover();this.timer=setInterval(()=>this.tick().catch(()=>{}),4000);this.timer.unref();} @@ -18,7 +21,7 @@ export class WinlinkRadio{ snapshot(){const j=this.job;return j?{channel:j.channel,startedAt:j.startedAt,endedAt:j.endedAt||null,state:j.state,error:j.error||null,restoring:j.restoring,sent:j.sent??null,received:j.received??null}:null;} async saveNative(fields){const key=await this.fwd.context();await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:this.job.peer});await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:profilePayload(fields)});this.fwd.cached=null;return key;} async currentProfile(){return rawProfile(await readFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),'utf8'),this.job?.peer||this.config.cmsPeer||'RMS');} - async restore(){await this.init;return this.fwd.exclusive(async()=>{if(!this.job?.restoring)return this.snapshot();if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw new Error('Attendi la fine della sessione BBS prima di ripristinare Internet');await this.saveNative(this.job.original);this.job.restoring=false;this.job.endedAt=new Date().toISOString();this.job.state='ended';this.job.error=null;this.fwd.lockedPeers.delete(this.job.peer);await this.persist();return this.snapshot();});} + async restore(){await this.init;return this.fwd.exclusive(async()=>{if(!this.job?.restoring)return this.snapshot();if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw new Error('Attendi la fine della sessione BBS prima di ripristinare Internet');await this.saveNative(this.job.original);this.job.restoring=false;this.job.endedAt=new Date().toISOString();this.job.state='ended';this.job.error=null;this.fwd.lockedPeers.delete(this.job.peer);await this.persist();await releasePacketSlot(this);return this.snapshot();});} async start(id){await this.init;return this.fwd.exclusive(async()=>{ if(this.job?.restoring)throw new Error('Una sessione Winlink radio è già in corso o in ripristino'); if(!this.config.radio||!this.config.winlinkRadio?.catControl)throw new Error('Controllo frequenza CAT per Winlink radio non configurato'); @@ -28,9 +31,10 @@ export class WinlinkRadio{ if(now-(this.fwd.requested.get(peer)||0)<30000)throw new Error('Sync Winlink già richiesto: attendi'); const status=await this.fwd.bpq('/Mail/Status');if(activeMailStreams(status).length)throw new Error('Una sessione BBS è attiva: riprova al termine'); const original=rawProfile(await readFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),'utf8'),peer);if(!/^(?:RMS|C(?:ONNECT)?\s+\d+\s+CMS)$/i.test(original.ConnectScript?.trim()||''))throw new Error('Il profilo RMS non è impostato per Internet: verifica la configurazione prima del cambio'); - const temporary=radioProfile(original,channel,this.config.radio.id),backup=path.join(this.config.root,'BPQMailChat','Backup-winlink-radio-'+new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup);await copyFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),path.join(backup,'BPQMail.cfg')); + const support=channelSupport(this.config,channel.family?channel:{...channel,family:channel.mode});if(!support.supported)throw Error(support.reason); + const temporary=radioProfile(original,channel,support.port),backup=path.join(this.config.root,'BPQMailChat','Backup-winlink-radio-'+new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup);await copyFile(path.join(this.config.root,'BPQMailChat','BPQMail.cfg'),path.join(backup,'BPQMail.cfg')); this.job={peer,channel:{id:channel.id,call:channel.call,dialHz:channel.dialHz,centerHz:channel.centerHz,mode:channel.mode,grid:channel.grid},original,temporary,startedAt:new Date().toISOString(),state:'requested',restoring:true};this.fwd.lockedPeers.set(peer,'Sessione Winlink radio in corso');await this.persist(); - try{const key=await this.saveNative(temporary);await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});this.fwd.requested.set(peer,Date.now());return this.snapshot();}catch{this.job.state='error';this.job.error='Richiesta BPQ non confermata; verifica e ripristino automatico in corso';await this.persist();throw new Error(this.job.error);} + this.busy=true;try{if(channel.family==='Packet'&&this.config.winlinkRadio?.packetController){this.job.temporary={...original,Enabled:'0',FWDNewImmediately:'0'};this.job.state='preparing';await this.persist();await this.saveNative(this.job.temporary);await reservePacketSlot(this,this.config.winlinkRadio.packetController,channel.dialHz/1e6,support.port);if(activeMailStreams(await this.fwd.bpq('/Mail/Status')).length)throw Error('Una sessione BBS è iniziata: riprova al termine');this.job.temporary=temporary;this.job.startedAt=new Date().toISOString();this.job.state='requested';await this.persist();}const key=await this.saveNative(temporary);await this.fwd.bpq('/Mail/FwdDetails?'+key,{method:'POST',body:peer});await this.fwd.bpq('/Mail/FWDSave?'+key,{method:'POST',body:'StartForward'});this.fwd.requested.set(peer,Date.now());return this.snapshot();}catch{this.job.state='error';this.job.error='Richiesta BPQ non confermata; verifica e ripristino automatico in corso';await this.persist();throw new Error(this.job.error);}finally{this.busy=false;} });} async tick(){await this.init;if(!this.job?.restoring||this.busy)return;this.busy=true;try{await this.fwd.exclusive(async()=>{ const j=this.job,age=Date.now()-Date.parse(j.startedAt),h=forwardingHistory(await this.fwd.logs(),j.peer).find(s=>Date.parse(s.startedAt)>=Date.parse(j.startedAt)-2000),streams=activeMailStreams(await this.fwd.bpq('/Mail/Status')); @@ -38,6 +42,6 @@ export class WinlinkRadio{ if(streams.length||(!h?.endedAt&&age<45000)){await this.persist();return;} const current=await this.currentProfile();if(profilePayload(current)!==profilePayload(j.temporary)&&profilePayload(current)!==profilePayload(j.original)){j.state='conflict';j.error='Il profilo RMS è stato modificato durante la sessione: ripristino automatico sospeso';await this.persist();return;} if(profilePayload(current)!==profilePayload(j.original))await this.saveNative(j.original); - j.restoring=false;j.endedAt=h?.endedAt||new Date().toISOString();j.state=h?.status||'failed';if(!h)j.error='BPQ non ha registrato l’avvio della sessione';this.fwd.lockedPeers.delete(j.peer);await this.persist(); + await releasePacketSlot(this);j.restoring=false;j.endedAt=h?.endedAt||new Date().toISOString();j.state=h?.status||'failed';if(!h)j.error='BPQ non ha registrato l’avvio della sessione';this.fwd.lockedPeers.delete(j.peer);await this.persist(); });}catch{this.job.error='Ripristino del profilo RMS in attesa: BPQ non disponibile';}finally{this.busy=false;}} } diff --git a/winlink-radio.test.mjs b/winlink-radio.test.mjs index 9dd8b1b..1433693 100644 --- a/winlink-radio.test.mjs +++ b/winlink-radio.test.mjs @@ -1,7 +1,8 @@ import {test} from 'node:test';import assert from 'node:assert/strict'; -import {csvRows,parseChannels,channelOpen,modemFamily,GatewayDirectory} from './winlink-gateways.mjs'; +import {csvRows,parseChannels,channelOpen,modemFamily,GatewayDirectory,channelSupport,directoryModes} from './winlink-gateways.mjs'; import {rawProfile,profilePayload,radioProfile,activeMailStreams,WinlinkRadio} from './winlink-radio.mjs'; import {Forwarding} from './forwarding.mjs'; +import {reservePacketSlot,releasePacketSlot} from './radio-slot.mjs'; import {mkdtemp,mkdir,readFile,writeFile,rm} from 'node:fs/promises';import path from 'node:path';import os from 'node:os'; const csv='Timestamp,Callsign,BaseCallsign,GridSquare,Frequency,Mode,Hours,Sysop,QTH\r\n10/16/2026 3:29:00 PM,N0TEST,N0TEST,JN45NN,"14,123.500 KHz",VARA,00-23,Test,"A town, Italy"\r\n'; const original={TOCalls:'',ATCalls:'',FWDTimes:'',ConnectScript:'RMS',HRoutes:'',HRoutesP:'',BBSHA:'',Enabled:'1',FwdInterval:'3600',RequestReverse:'1',RevFWDInterval:'3600',FWDNewImmediately:'0',AllowBlocked:'1',MaxFBBBlock:'10000',FWDPersonalsOnly:'0',AllowCompressed:'1',UseB1Protocol:'0',UseB2Protocol:'1',SendCTRLZ:'0',ConTimeout:'180'}; @@ -9,6 +10,24 @@ const channel={id:'fixture',call:'N0TEST',grid:'JN45NN',dialHz:14122000,centerHz const configText=f=>'BBSForwarding : {\n RMS : {\n'+Object.entries(f).map(([k,v])=>` ${k} = "${v}";`).join('\n')+'\n }\n}\n'; test('public Winlink CSV preserves quoted fields and converts center to dial exactly',()=>{assert.deepEqual(csvRows('a,b\n"x,y","a""b"\n'),[['a','b'],['x,y','a"b']]);const [c]=parseChannels(csv,'VARA');assert.equal(c.dialHz,14122000);assert.equal(c.centerHz,14123500);assert.equal(c.qth,'A town, Italy');assert.equal(c.postedAt,'2026-10-16T15:29:00.000Z');assert.equal(c.id.length,24);assert.equal(parseChannels(csv.replace('N0TEST,N0TEST','BAD|CALL,N0TEST'),'VARA').length,0);assert.throws(()=>parseChannels('invalid','VARA'));assert.throws(()=>csvRows('"unfinished'));}); test('gateway opening hours use UTC including midnight and unknown hours stay unknown',()=>{assert.equal(channelOpen('22-04',new Date('2026-10-16T23:30:00Z')),true);assert.equal(channelOpen('22-04',new Date('2026-10-16T12:30:00Z')),false);assert.equal(channelOpen('unknown'),null);assert.equal(modemFamily('SCSPACTOR'),'Pactor');assert.equal(modemFamily('VARA'),'VARA');assert.equal(modemFamily('KISS'),null);}); + +test('packet VHF/UHF uses exact FM frequency and rejects incompatible baud or bands',()=>{ + const packet=csv.replace('"14,123.500 KHz",VARA','145.8250 MHz,Packet 1200').replace('00-23','24');const [c]=parseChannels(packet,'Packet');assert.equal(c.centerHz,145825000);assert.equal(c.dialHz,c.centerHz);assert.equal(c.radioMode,'DATA-FM');assert.equal(c.baud,1200);assert.equal(channelOpen('24'),true); + const config={radio:{id:1,driver:'VARA'},ports:[{id:1,driver:'VARA'},{id:3,driver:'UZ7HO'}]};assert.deepEqual(directoryModes(config),['VARA','Packet']);assert.equal(channelSupport(config,c).port,3);assert.equal(channelSupport(config,{...c,baud:9600}).supported,false);assert.equal(channelSupport(config,{...c,dialHz:433725000}).supported,true);assert.equal(channelSupport(config,{...c,dialHz:148000000}).supported,false); + const profile=radioProfile(original,c,3);assert.equal(profile.ConnectScript,'ATTACH 3|RADIO 145.825000 DATA-FM|PAUSE 2|C N0TEST');assert.equal(profile.Enabled,'0');assert.equal(profile.UseB2Protocol,'1');assert.equal(parseChannels(packet.replace('145.8250','433.7250'),'Packet')[0].dialHz,433725000);assert.equal(parseChannels(packet,'VARA').length,0); +}); + +test('directory merges independent HF and Packet downloads and marks incompatible channels',async()=>{ + const dir=await mkdtemp(path.join(os.tmpdir(),'wl-modes-')),requested=[];const config={sysop:{call:'N9LOCAL'},locator:'JN45NN',radio:{id:1,driver:'VARA'},ports:[{id:1,driver:'VARA'},{id:3,driver:'UZ7HO'}]}; + const fake=async(url,opts)=>({ok:true,text:async()=>{if(opts?.method!=='POST')return '';const mode=opts.body.get('rblModes');requested.push(mode);return mode==='Packet'?csv.replace('"14,123.500 KHz",VARA','433.7250 MHz,Packet 9600'):csv;}}); + try{const d=new GatewayDirectory(config,dir,fake);const result=await d.snapshot();assert.deepEqual(requested,['VARA','Packet']);assert.equal(result.channels.length,2);assert.equal(result.channels.find(c=>c.family==='Packet').supported,false);assert.equal(result.channels.find(c=>c.family==='VARA').supported,true);assert.equal(result.mode,'VARA + Packet');}finally{await rm(dir,{recursive:true,force:true});} +}); + +test('packet controller reservation verifies acknowledgement and releases its own request',async()=>{ + const dir=await mkdtemp(path.join(os.tmpdir(),'wl-slot-'));const controller={requestFile:path.join(dir,'request.json'),statusFile:path.join(dir,'status.json')};const urls=[]; + const client={job:{},persist:async()=>writeFile(controller.statusFile,JSON.stringify({manualRequestId:client.job.controller.id,phase:'vhf',frequency:'433.750',at:new Date().toISOString()})),fwd:{bpq:async url=>{urls.push(url);return 'Connected to TNC AFSK AX.25 1200bd';}}}; + try{await reservePacketSlot(client,controller,433.750,3);assert.deepEqual(urls,['/Node/Port?3']);const request=JSON.parse(await readFile(controller.requestFile));assert.equal(request.frequencyMHz,433.750);assert.ok(request.expiresAt>Date.now());await releasePacketSlot(client);assert.equal(JSON.parse(await readFile(controller.requestFile)).expiresAt,0);}finally{await rm(dir,{recursive:true,force:true});} +}); test('temporary RMS profile preserves routing, disables timers and never overrides busy channel',()=>{const p=radioProfile(original,channel,3);assert.equal(p.Enabled,'0');assert.equal(p.ConnectScript,'ATTACH 3|RADIO 14.122000 USB|PAUSE 2|C N0TEST');assert.ok(!p.ConnectScript.includes('OVERRIDEBUSY'));assert.equal(p.UseB2Protocol,'1');assert.equal(p.HRoutes,original.HRoutes);assert.equal(p.TOCalls,original.TOCalls);assert.deepEqual(rawProfile(configText(original),'RMS'),original);assert.equal(profilePayload(original).split('|').length,21);assert.throws(()=>radioProfile(original,{...channel,call:'N0TEST|C EVIL'},3));assert.throws(()=>radioProfile(original,{...channel,dialHz:0},3));assert.deepEqual(activeMailStreams(''),[]);assert.equal(activeMailStreams('').length,1);assert.throws(()=>activeMailStreams('signin page'));}); test('public directory download uses viewstate and PUBLIC mode, caches, and rejects stale selection',async()=>{ const dir=await mkdtemp(path.join(os.tmpdir(),'wl-directory-'));const calls=[];const now=new Date();const stamp=`${now.getUTCMonth()+1}/${now.getUTCDate()}/${now.getUTCFullYear()} ${now.getUTCHours()%12||12}:${String(now.getUTCMinutes()).padStart(2,'0')}:00 ${now.getUTCHours()<12?'AM':'PM'}`;const liveCsv=csv.replace('10/16/2026 3:29:00 PM',stamp);