Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions FMScanMonitor/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,40 @@
# Changelog

## 0.9.13

- Add a native `Scan Monitor` shortcut beside the other Webserver plugin icons.
- Open and smoothly reveal the expanded `Frequency scan list` when a public visitor selects the shortcut.
- Open the administrator Scan Monitor panel from the same shortcut while signed in.
- Refine the desktop Frequency-card status spacing and text rendering.
- Improve the running indicator and public-control countdown legibility on desktop and mobile.
- Resume immediately after an explicit `Release tuner` action while retaining the reconnect grace period after an unexpected disconnect.

## 0.9.12

- Add a compact, always-visible FM scan status and tuner-handover control inside the existing Webserver `Frequency` card on desktop and mobile.
- Keep the original frequency-arrow area and surrounding receiver layout unchanged while scanner state, action and public-control countdown update in place.
- Add administrator pause/resume actions to the new control and move the public `Pause & tune` / `Release tuner` action there.
- Pause FM Scan Monitor automatically when Highpoint Scanner starts, then resume safely after Highpoint stops.
- Reject simultaneous scanner starts and preserve manual or visitor pauses during scanner handover.

## 0.9.11

- Stop an active Highpoint Scanner auto-scan before FM Scan Monitor starts a scan.
- Prevent the two plugins from sending competing frequency commands and skipping the upper FM band.
- Leave the Highpoint Scanner plugin and the FM-DX Webserver core unchanged.

## 0.9.10

- Wait up to 1.5 seconds for a slower TEF tuner to confirm the requested frequency before evaluating its signal.
- Poll only when telemetry still reports the previous frequency, preserving the normal scan speed on fast tuners.
- Prevent one delayed frequency update from making the remainder of the band scan too quickly without logging stations.

## 0.9.9

- Retry the internal telemetry request up to three times when the Webserver event loop is temporarily busy.
- Keep a single transient `/api` delay from stopping a continuous scan and leaving a permanent error status.
- Report the attempt count only when all recovery attempts fail.

## 0.9.8

- Limit simultaneous OpenTopoMap downloads, with a stricter three-request limit on iPhone and iPad.
Expand Down
7 changes: 5 additions & 2 deletions FMScanMonitor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

**FM Scan Monitor by Aurel** is a responsive live band scanner and reception monitor for FM-DX Webserver, designed for both desktop and mobile browsers. It is a standalone plugin and does not modify the Webserver core or the existing Scanner plugin.

## Version 0.9.8
## Version 0.9.13

- Single-pass and continuous scanning.
- Native `Scan Monitor` shortcut beside the Webserver's other plugin icons; it opens and reveals the frequency list or administrator panel.
- Compact live scanner status and tuner-handover button inside the Webserver's existing `Frequency` card, without replacing the frequency arrows or adding a new receiver row.
- Bidirectional Highpoint Scanner interlock: starting either scanner releases the other, and FM Scan Monitor resumes safely when Highpoint stops.
- Password-free public tuner handover: a visitor can explicitly pause an active scan, use the normal tuner controls or tune directly from any received-station card, and release them without gaining scanner administration rights.
- Public station-card tuning remains available when an administrator has already paused or stopped the scanner; no extra visitor pause is required in that state.
- Automatic scan resume ten seconds after the last controlling tab disconnects, with refresh/reconnect recovery and support for multiple control leases.
Expand Down Expand Up @@ -67,7 +70,7 @@ The report is generated locally and displayed directly in the browser's native P

## Installation

Copy `FMScanMonitorPlugin.js` and the complete `FMScanMonitor` directory into the Webserver `plugins` directory. Restart FM-DX Webserver, open Administration > Plugins, enable **FM Scan Monitor by Aurel [v0.9.8]**, save, restart once more when enabling it for the first time, and reload the receiver page while logged in as administrator.
Copy `FMScanMonitorPlugin.js` and the complete `FMScanMonitor` directory into the Webserver `plugins` directory. Restart FM-DX Webserver, open Administration > Plugins, enable **FM Scan Monitor by Aurel [v0.9.13]**, save, restart once more when enabling it for the first time, and reload the receiver page while logged in as administrator.

Upgrading from an earlier `FMScanMobile` release automatically copies the existing browser settings, hidden-frequency rules, distance filter and temporary public-control state to the new `fmScanMonitor` storage keys. The legacy values are retained as a safe fallback.

Expand Down
64 changes: 64 additions & 0 deletions FMScanMonitor/fm-scan-monitor-client.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';

const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const test = require('node:test');

const clientSource = fs.readFileSync(path.join(__dirname, 'fm-scan-monitor.js'), 'utf8');
const serverSource = fs.readFileSync(path.join(__dirname, 'fm-scan-monitor_server.js'), 'utf8');

test('stops the Highpoint Scanner before starting FM Scan Monitor', () => {
const startFunction = clientSource.indexOf('function startScan(continuous)');
const stopCall = clientSource.indexOf('stopCompetingScanner();', startFunction);
const startCall = clientSource.indexOf("sendCommand('start'", startFunction);

assert.notEqual(startFunction, -1);
assert.ok(stopCall > startFunction);
assert.ok(startCall > stopCall);
});

test('uses the legacy Scanner stop protocol without changing the Scanner plugin', () => {
const stopFunction = clientSource.indexOf('function stopCompetingScanner()');
const startFunction = clientSource.indexOf('function startScan(continuous)', stopFunction);
const implementation = clientSource.slice(stopFunction, startFunction);

assert.match(implementation, /type:\s*'Scanner'/);
assert.match(implementation, /status:\s*'command'/);
assert.match(implementation, /Scan:\s*'off'/);
assert.match(implementation, /source:\s*'FM Scan Monitor'/);
});

test('mounts the scan status inside the existing Frequency card instead of the tuning arrows', () => {
const statusFunction = clientSource.indexOf('function ensureTunerStatusControl()');
const actionFunction = clientSource.indexOf('function handleTunerStatusAction', statusFunction);
const implementation = clientSource.slice(statusFunction, actionFunction);

assert.notEqual(statusFunction, -1);
assert.match(implementation, /getElementById\('freq-container'\)/);
assert.match(implementation, /frequencyPanel\.appendChild\(control\)/);
assert.doesNotMatch(implementation, /tune-buttons/);
});

test('provides Frequency-card actions for public and administrator tuner handover', () => {
assert.match(clientSource, /action = 'public-control'/);
assert.match(clientSource, /action = 'pause-admin'/);
assert.match(clientSource, /action = 'resume-admin'/);
assert.match(clientSource, /text = 'Highpoint Scanner active'/);
});

test('adds a Webserver header shortcut that opens and reveals Scan Monitor', () => {
assert.match(clientSource, /addIconToPluginPanel\(/);
assert.match(clientSource, /'Scan Monitor'/);
assert.match(clientSource, /'tower-broadcast'/);
assert.match(clientSource, /publicList\.open = true/);
assert.match(clientSource, /publicList\.scrollIntoView/);
assert.match(clientSource, /launcher\.click\(\)/);
});

test('resumes immediately after an explicit tuner release while retaining disconnect grace', () => {
assert.match(serverSource, /releasePublicControl\(ws, \{ immediate: true \}\)/);
assert.match(serverSource, /function releasePublicControl\(ws, \{ immediate = false \} = \{\}\)/);
assert.match(serverSource, /if \(immediate\)[\s\S]*engine\.resume\(\)/);
assert.match(serverSource, /function removeClient\(ws\)[\s\S]*releasePublicControl\(ws\)/);
});
79 changes: 72 additions & 7 deletions FMScanMonitor/fm-scan-monitor-engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const DEFAULTS = Object.freeze({
});

const RDS_SAMPLE_INTERVAL = 300;
const TUNER_FREQUENCY_CONFIRM_TIMEOUT = 1500;
const TUNER_FREQUENCY_CONFIRM_INTERVAL = 100;
const RDS_MINIMUM_VOTES = 3;
const RDS_MAX_ACCEPTED_PS_ERROR = 4;
const ADJACENT_CHANNEL_GAP_DB = 15;
Expand All @@ -35,6 +37,22 @@ function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}

async function retryAsync(operation, { attempts = 3, delayMs = 250 } = {}) {
if (typeof operation !== 'function') throw new TypeError('A retry operation is required.');
const maximumAttempts = Math.max(1, Math.trunc(Number(attempts) || 1));
const retryDelay = Math.max(0, Number(delayMs) || 0);
let lastError = null;
for (let attempt = 1; attempt <= maximumAttempts; attempt += 1) {
try {
return await operation(attempt);
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (attempt < maximumAttempts && retryDelay > 0) await sleep(retryDelay);
}
}
throw lastError;
}

function normalizePi(value) {
const pi = String(value ?? '').trim().toUpperCase();
return /^[0-9A-F]{4}$/.test(pi) && pi !== '0000' ? pi : '';
Expand Down Expand Up @@ -88,6 +106,27 @@ function publicTuneAccessMode({
return Math.max(0, Number(publicControlUsers) || 0) === 0 ? 'administrator-pause' : '';
}

function highpointScannerState(message) {
if (!message || message.type !== 'Scanner' || !message.value || typeof message.value !== 'object') return null;
const status = String(message.value.status ?? '').trim().toLowerCase();
if (!['broadcast', 'command', 'send'].includes(status)) return null;
const scan = String(message.value.Scan ?? '').trim().toLowerCase();
if (scan === 'on') return true;
if (scan === 'off') return false;
return null;
}

function shouldResumeAfterHighpoint({
scanning = false,
paused = false,
pauseReason = '',
publicControlUsers = 0
} = {}) {
if (!scanning) return false;
if (!paused) return true;
return Math.max(0, Number(publicControlUsers) || 0) > 0 || pauseReason === 'Tuner in use';
}

function destinationPoint(latitude, longitude, distanceKm, azimuthDeg) {
if (![latitude, longitude, distanceKm, azimuthDeg].every(Number.isFinite)) return null;
const angularDistance = distanceKm / 6371;
Expand Down Expand Up @@ -335,8 +374,9 @@ class FMScanMonitorEngine {
return true;
}

pause(reason = 'Tuner in use') {
if (!this.scanning || this.paused) return false;
pause(reason = 'Tuner in use', { replaceReason = false } = {}) {
if (!this.scanning) return false;
if (this.paused && !replaceReason) return false;
this.paused = true;
this.pauseReason = String(reason || 'Tuner in use');
this.frequency = null;
Expand Down Expand Up @@ -459,14 +499,15 @@ class FMScanMonitorEngine {
this.frequency = frequency;
this.status = this.continuous ? 'Continuous scan' : 'Single scan';
this.publish();
const confirmationDeadline = Date.now() + Math.max(cfg.tuningDelay, TUNER_FREQUENCY_CONFIRM_TIMEOUT);
const sent = await this.sendCommand(`T${Math.round(frequency * 1000)}`);
if (!sent) throw new Error('Receiver connection is not ready.');
const tuningWait = await this.sleepInterruptible(cfg.tuningDelay);
if (tuningWait !== 'complete') return tuningWait;
const initialSample = normalizeTelemetry(await this.readTelemetry());
if (this.stopRequested) return 'stopped';
if (this.paused) return 'paused';
if (!this.matchesFrequency(initialSample, frequency, cfg.step)) return 'complete';
const confirmation = await this.waitForTunedSample(frequency, cfg.step, confirmationDeadline);
if (confirmation.outcome !== 'complete') return confirmation.outcome;
const initialSample = confirmation.sample;
if (!initialSample) return 'complete';
if (!Number.isFinite(initialSample.signal) || initialSample.signal < cfg.signalThreshold) return 'complete';

this.status = `Station detected - waiting ${(cfg.rdsTimeout / 1000).toFixed(1)} s for data`;
Expand All @@ -487,6 +528,27 @@ class FMScanMonitorEngine {
return 'complete';
}

async waitForTunedSample(frequency, step, deadline) {
while (!this.stopRequested && !this.paused) {
const sample = normalizeTelemetry(await this.readTelemetry());
if (this.stopRequested) return { outcome: 'stopped', sample: null };
if (this.paused) return { outcome: 'paused', sample: null };
if (this.matchesFrequency(sample, frequency, step)) {
return { outcome: 'complete', sample };
}

const remaining = deadline - Date.now();
if (remaining <= 0) return { outcome: 'complete', sample: null };
const confirmationWait = await this.sleepInterruptible(
Math.min(TUNER_FREQUENCY_CONFIRM_INTERVAL, remaining)
);
if (confirmationWait !== 'complete') {
return { outcome: confirmationWait, sample: null };
}
}
return { outcome: this.stopRequested ? 'stopped' : 'paused', sample: null };
}

matchesFrequency(sample, frequency, step) {
return Boolean(sample && Math.abs(sample.frequency - frequency) <= Math.max(step / 2, 0.006));
}
Expand Down Expand Up @@ -587,6 +649,9 @@ module.exports = {
normalizeTelemetry,
normalizeTransmitterCountry,
parsePsErrors,
highpointScannerState,
publicTuneAccessMode,
sanitizeSettings
retryAsync,
sanitizeSettings,
shouldResumeAfterHighpoint
};
93 changes: 92 additions & 1 deletion FMScanMonitor/fm-scan-monitor-engine.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,48 @@ const assert = require('node:assert/strict');
const {
FMScanMonitorEngine,
consolidateTelemetrySamples,
highpointScannerState,
normalizeTelemetry,
normalizeTransmitterCountry,
publicTuneAccessMode,
sanitizeSettings
retryAsync,
sanitizeSettings,
shouldResumeAfterHighpoint
} = require('./fm-scan-monitor-engine');

test('recognizes Highpoint Scanner ownership broadcasts and commands', () => {
assert.equal(highpointScannerState({ type: 'Scanner', value: { status: 'command', Scan: 'on' } }), true);
assert.equal(highpointScannerState({ type: 'Scanner', value: { status: 'broadcast', Scan: 'off' } }), false);
assert.equal(highpointScannerState({ type: 'Scanner', value: { status: 'send', Scan: 'on' } }), true);
assert.equal(highpointScannerState({ type: 'Scanner', value: { status: 'request', Scan: 'on' } }), null);
assert.equal(highpointScannerState({ type: 'Scanner', value: { status: 'command', Scan: '' } }), null);
assert.equal(highpointScannerState({ type: 'Other', value: { Scan: 'on' } }), null);
});

test('retries a transient telemetry operation and returns the recovered value', async () => {
let calls = 0;
const value = await retryAsync(async attempt => {
calls += 1;
if (attempt < 3) throw new Error('temporary telemetry delay');
return { frequency: 100.9 };
}, { attempts: 3, delayMs: 0 });

assert.deepEqual(value, { frequency: 100.9 });
assert.equal(calls, 3);
});

test('preserves the last telemetry error after all retry attempts fail', async () => {
let calls = 0;
await assert.rejects(
retryAsync(async () => {
calls += 1;
throw new Error(`failure ${calls}`);
}, { attempts: 3, delayMs: 0 }),
/failure 3/
);
assert.equal(calls, 3);
});

test('sanitizes the shared LOC and DX distance thresholds', () => {
const configured = sanitizeSettings({ localDistanceKm: 15, dxDistanceKm: 250 });
assert.equal(configured.localDistanceKm, 15);
Expand Down Expand Up @@ -62,6 +98,28 @@ test('grants public station tuning only in safe scanner states', () => {
assert.equal(publicTuneAccessMode({ canUsePublicTuner: false, scanning: false }), '');
});

test('lets a competing scanner replace the current pause reason safely', () => {
const scanner = new FMScanMonitorEngine({
sendCommand: async () => true,
readTelemetry: async () => ({}),
publish: () => {}
});
scanner.scanning = true;
assert.equal(scanner.pause('Tuner in use'), true);
assert.equal(scanner.pause('Highpoint Scanner active', { replaceReason: true }), true);
assert.equal(scanner.paused, true);
assert.equal(scanner.pauseReason, 'Highpoint Scanner active');
scanner.stop();
});

test('resumes after Highpoint only when FM scanning was active or publicly paused', () => {
assert.equal(shouldResumeAfterHighpoint({ scanning: true, paused: false }), true);
assert.equal(shouldResumeAfterHighpoint({ scanning: true, paused: true, pauseReason: 'Tuner in use' }), true);
assert.equal(shouldResumeAfterHighpoint({ scanning: true, paused: true, publicControlUsers: 1 }), true);
assert.equal(shouldResumeAfterHighpoint({ scanning: true, paused: true, pauseReason: 'Administrator tuner control' }), false);
assert.equal(shouldResumeAfterHighpoint({ scanning: false, paused: false }), false);
});

function telemetry({ freq = 102.2, sig = 65, pi = 'F748', ps = 'CHAMP FM', psErrors = '0,0,0,0,0,0,0,0', tx = 'Champagne FM', itu = 'F' } = {}) {
return normalizeTelemetry({
freq,
Expand Down Expand Up @@ -107,6 +165,39 @@ async function waitFor(predicate, timeoutMs = 1500) {
assert.equal(predicate(), true, 'Timed out waiting for scanner state.');
}

test('waits for a slower tuner to confirm the requested frequency before measuring signal', async () => {
const commands = [];
const reportedFrequencies = [105.9, 105.9, 106.0];
let telemetryReads = 0;
const scanner = new FMScanMonitorEngine({
sendCommand: async command => {
commands.push(command);
return true;
},
readTelemetry: async () => ({
freq: reportedFrequencies[Math.min(telemetryReads++, reportedFrequencies.length - 1)],
sig: 55,
pi: '',
ps: '',
rds: false,
st: true
}),
publish: () => {}
});

const outcome = await scanner.scanFrequency(106.0, {
step: 0.1,
tuningDelay: 100,
signalThreshold: 30,
rdsTimeout: 0
});

assert.equal(outcome, 'complete');
assert.deepEqual(commands, ['T106000']);
assert.equal(telemetryReads, 3);
assert.equal(scanner.results.get('106.000|-').signal, 55);
});

test('pauses without ending a continuous scan and retries the interrupted frequency on resume', async () => {
const commands = [];
const scanner = new FMScanMonitorEngine({
Expand Down
Loading
Loading