Compare commits

..

8 Commits

Author SHA1 Message Date
denny
463a805890 #2717 Tuners tab converted to JavaFX with a new frequency control.
- New FrequencyControl replaces JFrequencyControl: MHz to 1 Hz, hover a digit and scroll or click its upper/lower half to step it (with carry, clamped to the tuner's range), or type a frequency (e.g. 851.0125) and press Enter.  Arrow keys move between digits and step them.  Copy/paste supported.
- Tuners tab redesigned: tuner list with status pills and configurable columns, Add Tuner menu, and a sectioned editor (header with status, enable switch, spectrum/record/restart; Tuning; Gain; Options; Frequency Correction; collapsible Frequency Limits).
- All tuner editors converted to JavaFX with their full set of controls.  RSP editors share option bindings in RspTunerEditor.
- Add recording and network tuner dialogs converted to JavaFX dialogs.
- DiscoveredTunerModel is no longer a Swing table model.
- Fixes: FCD Pro gain/phase correction loaded swapped; RSPdx saved the FM notch as the DAB notch and never applied the HDR bandwidth; RSP2 external reference output and network tuner PPM weren't saved; Airspy/HydraSDR gain mode changes now apply the mode's gains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 04:10:39 -05:00
Denny Sheirer
156dd40bfe #2718 App branding, icons and splash screen. (#2719)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 04:06:12 -05:00
Denny Sheirer
e01dd02b74 #2715 Removes the MacOS Tahoe libusb workaround from the README; usb4java was replaced by jlibusb, which bundles libusb. (#2716)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 03:07:32 -05:00
Denny Sheirer
8324233acb #2704 Waterfall contrast for weak signals relative to the noise floor (#2712)
The waterfall mapped 256 palette indexes over the absolute dBFS level of the
mean bin value, about 2.5 steps per dB at a -100 dBFS floor, so weak signals
were only a few steps above the noise.  WaterfallScaler now tracks the noise
floor as a smoothed 25th percentile of the bins (robust to occupied spans) and
maps a fixed 45 dB span above it, so contrast no longer depends on sample size,
DFT size or tuner gain.  The classic palette's flat blue blocks are replaced
with a blue ramp over the bottom quarter, where the noise floor now sits.

Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-20 02:47:57 -05:00
Denny Sheirer
838e7708c0 #2713 HistoryTableViewTest fires the platform copy shortcut (Cmd-C on macOS) (#2714)
The copy handler matches KeyCombination.SHORTCUT_DOWN, which is Meta on
macOS, but the test always fired Ctrl-C, so nothing was copied on the Mac
CI runner.

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:43:38 -05:00
Denny Sheirer
d3a9adc06f #2697 talker alias auto-add only creates one alias for both the radio id and the fully qualified radio id when both are transmitted on the system (#2705)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-19 03:59:44 -05:00
Denny Sheirer
cd098955aa #2696 Change alias 'group' labeling to 'category' to avoid confusing group to mean talkgroup. (#2703)
Co-authored-by: denny <dennis.sheirer@gmail.com>
2026-11-19 03:45:05 -05:00
Denny Sheirer
61efb3d299 #2698 SIMD component factories explicitly handle UNCALIBRATED calibration state (#2699)
ComplexMixerFactory logged an unrecognized implementation warning when calibration had not been run (e.g. CI) before falling back to the scalar mixer. All SIMD component factories now map UNCALIBRATED to the scalar implementation explicitly.

Co-authored-by: denny <dennis.sheirer@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 03:06:50 -05:00
86 changed files with 8046 additions and 8017 deletions

View File

@@ -25,24 +25,6 @@ A cross-platform java application for decoding, monitoring, recording and stream
![sdrtrunk primary application window decoding a P25 trunked radio system](https://github.com/DSheirer/sdrtrunk/wiki/images/application_overview.png)
**Figure 1:** sdrtrunk decoding a P25 Phase 1 simulcast trunked radio system
## MacOS Tahoe 26.1 Users - Attention
Changes to USB support in Tahoe version 26.x cause sdrtrunk to fail to launch. Do the following to install the latest libusb and create a symbolic link and then use the nightly build which includes an updated usb4java native library for Tahoe with ARM processor. There may still be issue(s) with MacOS accessing your USB SDR tuners.
```
brew install libusb --HEAD
cd /opt
sudo mkdir local
cd local
sudo mkdir lib
```
Next, find where brew installed the libusb library, for example: ```/opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib``` Note: the folder "HEAD-9ceaa52" is the version stamp for HEAD when you installed from it.
Finally, create a symbolic link from the installed library to the place where usb4java is expecting to find libusb (/opt/local/lib/libusb-1.0.0.dylib)
```
sudo ln -s /opt/homebrew/Cellar/libusb/HEAD-9ceaa52/lib/libusb-1.0.0.dylib /opt/local/lib/libusb-1.0.0.dylib
```
## Download the Latest Release
All release versions of sdrtrunk are available from the [releases](https://github.com/DSheirer/sdrtrunk/releases) tab.

View File

@@ -213,6 +213,14 @@ def jvmArgsLinux =
'--enable-native-access=javafx.graphics', //JDK24 - suppress restricted java.lang.System calls
'--enable-native-access=ALL-UNNAMED'] //Suppress warnings for FFM API native calls (tuner libraries)
/**
* Startup splash screen image. The JVM shows it before any application code runs and closes it when the main window
* opens. The release launch scripts load it from the runtime image lib folder (see the runtime task below) and the
* gradle run task loads it from the resources folder. The JVM picks up the @2x image on HiDPI displays.
*/
def splashImages = ['sdrtrunk-splash.png', 'sdrtrunk-splash@2x.png']
def splashResourceDir = 'src/main/resources/images/sdrtrunk'
application {
mainClass = "io.github.dsheirer.gui.SDRTrunk"
@@ -224,6 +232,10 @@ application {
}
}
tasks.named('run') {
jvmArgs "-splash:${file(splashResourceDir + '/' + splashImages[0]).absolutePath}"
}
test {
if(os.isWindows()) {
jvmArgs = jvmArgsWindows
@@ -288,8 +300,8 @@ def jdk_download_windows_aarch64 = jdk_download_base + "windows-aarch64-full.zip
* @return configured task.
*/
def configure(RuntimeZipTask rt, List<String> jvmArgs) {
//Use the correct set of JVM arguments
rt.extension.launcherData.get().jvmArgs = jvmArgs
//Use the correct set of JVM arguments, plus the startup splash screen that the runtime task copies to lib
rt.extension.launcherData.get().jvmArgs = jvmArgs + ['-splash:{{BIN_DIR}}/../lib/sdrtrunk-splash.png']
//Additional modules to include with auto-detected modules.
//jdk.charsets - NXDN BIG5 encoding support
@@ -388,6 +400,22 @@ tasks.named('runtime') {rt ->
}
}
/**
* Copies the startup splash screen images into the lib folder of each runtime target image, where the launch scripts
* load them from (-splash:{{BIN_DIR}}/../lib/...).
*/
tasks.named('runtime') {rt ->
rt.doLast {
rt.targetPlatforms.get().keySet().each { target ->
def lib = new File(rt.imageDir.asFile, "${project.name}-${target}/lib")
splashImages.each { name ->
java.nio.file.Files.copy(file(splashResourceDir + '/' + name).toPath(), new File(lib, name).toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
}
}
}
/**
* Verifies that each runtime target image contains every module that the sdrtrunk jar requires, as reported by jdeps.
* This guards against the runtime plugin's module auto-detection silently missing modules (e.g. when it can't parse

View File

@@ -52,7 +52,9 @@ import org.slf4j.LoggerFactory;
* </ul>
*
* Only aliases whose only identifier is the radio are created or renamed. An alias that combines the radio with other
* identifiers (e.g. several radios or talkgroups) is left alone.
* identifiers (e.g. several radios or talkgroups) is left alone. The exception is a P25 radio's simple and fully
* qualified radio identifiers with the same radio ID: the second form decoded is added to the alias for the first
* form, including a user alias outside the managed group, instead of creating a second alias for the same radio.
*
* This class is thread safe. Talker aliases are received on decoder threads and the alias model is updated on the
* JavaFX application thread.
@@ -200,6 +202,21 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
AliasList aliasList = mAliasModel.getAliasList(mAliasListName);
Alias existing = findExactMatch(aliasList.getAliases(radio), aliasId);
if(existing == null)
{
existing = findCompanion(aliasList.aliases(), radio, aliasId);
if(existing != null)
{
//Add the radio to the alias for the same radio's other identifier form, then continue below to
//compare the talker alias with the alias name (only managed aliases are renamed).
existing.addAliasID(aliasId);
aliasList.updateAlias(existing);
mLog.info("Talker alias radio [" + aliasId + "] added to existing alias [" + existing.getName() +
"] in alias list [" + mAliasListName + "]");
}
}
if(existing == null)
{
Alias alias = new Alias(value);
@@ -408,22 +425,114 @@ public class TalkerAliasAutoAdder implements BiConsumer<RadioIdentifier,TalkerAl
}
/**
* Number of identifiers (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming.
* Finds the alias for the other identifier form of a P25 radio, so that a radio's simple and fully qualified
* identifiers share one alias instead of creating an alias for each. This includes user aliases outside the
* managed group, so that either identifier maps to the user's alias. The user alias is never renamed.
* <ul>
* <li>Fully qualified radio: the alias whose only identifier is the simple radio with the same radio
* ID. Only when the fully qualified radio isn't using a different local address (e.g. a roaming radio), since
* the radio ID then belongs to the home system and doesn't identify the radio on this system.</li>
* <li>Simple radio: the alias whose only identifier is a fully qualified radio with the same radio ID. None
* when more than one fully qualified radio alias matches.</li>
* </ul>
* @param aliases to search
* @param radio decoded radio identifier
* @param aliasId created from the decoded radio
* @return companion alias or null.
*/
private static int getIdentityCount(Alias alias)
@VisibleForTesting
static Alias findCompanion(List<Alias> aliases, RadioIdentifier radio, Radio aliasId)
{
int count = 0;
if(aliases == null || aliasId.getProtocol() != Protocol.APCO25)
{
return null;
}
boolean fullyQualified = aliasId instanceof P25FullyQualifiedRadio;
if(fullyQualified && !(radio instanceof FullyQualifiedRadioIdentifier fqri &&
fqri.getValue() != null && fqri.getValue() == fqri.getRadio()))
{
return null;
}
Alias match = null;
for(Alias alias: aliases)
{
if(getSoleIdentity(alias) instanceof Radio candidate &&
(candidate instanceof P25FullyQualifiedRadio) != fullyQualified &&
candidate.getProtocol() == Protocol.APCO25 && candidate.getValue() == aliasId.getValue())
{
if(match != null)
{
//Ambiguous - more than one candidate.
return null;
}
match = alias;
}
}
return match;
}
/**
* Identifier of an alias that has exactly one identifier, excluding audio settings.
* @return identifier or null if the alias has none or more than one.
*/
private static AliasID getSoleIdentity(Alias alias)
{
AliasID sole = null;
for(AliasID id: alias.getAliasIdentifiers())
{
if(!id.isAudioIdentifier())
{
count++;
if(sole != null)
{
return null;
}
sole = id;
}
}
return count;
return sole;
}
/**
* Number of identities (e.g. radios, talkgroups) in the alias, excluding audio settings like priority, record and
* streaming. A P25 radio's simple and fully qualified radio identifiers with the same radio ID count as one
* identity.
*/
private static int getIdentityCount(Alias alias)
{
List<AliasID> ids = alias.getAliasIdentifiers().stream().filter(id -> !id.isAudioIdentifier()).toList();
if(ids.size() == 2 && isRadioPair(ids.get(0), ids.get(1)))
{
return 1;
}
return ids.size();
}
/**
* Indicates if the identifiers are the simple and fully qualified forms of the same P25 radio ID.
*/
private static boolean isRadioPair(AliasID a, AliasID b)
{
if(a instanceof P25FullyQualifiedRadio)
{
AliasID swap = a;
a = b;
b = swap;
}
return a instanceof Radio simple && !(a instanceof P25FullyQualifiedRadio) &&
b instanceof P25FullyQualifiedRadio fqr && simple.getProtocol() == Protocol.APCO25 &&
simple.getValue() == fqr.getValue();
}
private static String getKey(Radio aliasId)

View File

@@ -42,6 +42,7 @@ public class ChannelDFTFactory
case VECTOR_SIMD_PREFERRED:
return new VectorChannelDFT(channelCount);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarChannelDFT(channelCount);
}

View File

@@ -42,6 +42,7 @@ public class DcRemovalFilterFactory
case VECTOR_SIMD_PREFERRED:
return new VectorDcRemovalFilter(gain);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarDcRemovalFilter(gain);
}

View File

@@ -52,6 +52,7 @@ public class FmDemodulatorFactory
case VECTOR_SIMD_512:
return new VectorFMDemodulator512();
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarFMDemodulator();
}

View File

@@ -44,6 +44,7 @@ public class ComplexGainFactory
return new VectorComplexGainControl();
}
case SCALAR:
case UNCALIBRATED:
default:
return new ComplexGainControl();
}
@@ -64,6 +65,7 @@ public class ComplexGainFactory
return new VectorComplexGain(gain);
}
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexGain(gain);
}

View File

@@ -52,6 +52,7 @@ public class MagnitudeFactory
case VECTOR_SIMD_512:
return new VectorMagnitudeCalculator512();
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarMagnitudeCalculator();
}

View File

@@ -49,6 +49,7 @@ public class ComplexMixerFactory
return new VectorComplexMixer(frequency, sampleRate);
}
case SCALAR:
case UNCALIBRATED:
{
return new ScalarComplexMixer(frequency, sampleRate);
}

View File

@@ -49,6 +49,7 @@ public class OscillatorFactory
case VECTOR_SIMD_PREFERRED:
return new VectorRealOscillator(frequency, sampleRate);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarRealOscillator(frequency, sampleRate);
}
@@ -69,6 +70,7 @@ public class OscillatorFactory
case VECTOR_SIMD_PREFERRED:
return new VectorComplexOscillator(frequency, sampleRate);
case SCALAR:
case UNCALIBRATED:
default:
return new ScalarComplexOscillator(frequency, sampleRate);
}

View File

@@ -45,7 +45,8 @@ public class DifferentialDemodulatorFactory
case VECTOR_SIMD_128 -> new DifferentialDemodulatorFloatVector128(sampleRate, symbolRate);
case VECTOR_SIMD_256 -> new DifferentialDemodulatorFloatVector256(sampleRate, symbolRate);
case VECTOR_SIMD_512 -> new DifferentialDemodulatorFloatVector512(sampleRate, symbolRate);
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate); //Includes SCALAR case
case SCALAR, UNCALIBRATED -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
default -> new DifferentialDemodulatorFloatScalar(sampleRate, symbolRate);
};
}
}

View File

@@ -0,0 +1,255 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui;
import java.awt.AWTEvent;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Taskbar;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.stage.Stage;
import javafx.stage.Window;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* sdrtrunk application icon for Swing frames and dialogs, JavaFX stages and the macOS Dock.
*
* Call installSwing() once at startup and installJavaFx() once the JavaFX toolkit is running. After that, each
* window that opens without its own icon gets the sdrtrunk icon, so individual windows don't have to set it.
*/
public final class ApplicationIcons
{
private static final Logger mLog = LoggerFactory.getLogger(ApplicationIcons.class);
private static final String RESOURCE_PATTERN = "/images/sdrtrunk/sdrtrunk-icon-%d.png";
private static final int[] SIZES = {16, 24, 32, 48, 64, 128, 256, 512};
private static final int TASKBAR_SIZE = 512;
private static List<Image> sAwtImages;
private static List<javafx.scene.image.Image> sFxImages;
private static boolean sSwingInstalled;
private static boolean sJavaFxInstalled;
private ApplicationIcons()
{
}
/**
* Application icon in each available size, smallest first, for Swing/AWT windows.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<Image> getAwtImages()
{
if(sAwtImages == null)
{
List<Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
Image image = ImageIO.read(in);
if(image != null)
{
images.add(image);
}
}
else
{
mLog.warn("Application icon resource not found [" + path + "]");
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sAwtImages = Collections.unmodifiableList(images);
}
return sAwtImages;
}
/**
* Application icon in each available size, smallest first, for JavaFX stages.
* @return images, or an empty list if the icon resources can't be loaded.
*/
public static synchronized List<javafx.scene.image.Image> getFxImages()
{
if(sFxImages == null)
{
List<javafx.scene.image.Image> images = new ArrayList<>();
for(int size: SIZES)
{
String path = String.format(RESOURCE_PATTERN, size);
try(InputStream in = ApplicationIcons.class.getResourceAsStream(path))
{
if(in != null)
{
javafx.scene.image.Image image = new javafx.scene.image.Image(in);
if(!image.isError())
{
images.add(image);
}
}
}
catch(IOException ioe)
{
mLog.warn("Unable to load application icon [" + path + "]", ioe);
}
}
sFxImages = Collections.unmodifiableList(images);
}
return sFxImages;
}
/**
* Sets the application icon on the Swing/AWT window if it doesn't already have one.
*/
public static void apply(java.awt.Window window)
{
if(window != null && window.getIconImages().isEmpty() && !getAwtImages().isEmpty())
{
window.setIconImages(getAwtImages());
}
}
/**
* Sets the application icon on the JavaFX stage if it doesn't already have one. Call on the FX thread.
*/
public static void apply(Stage stage)
{
if(stage != null && stage.getIcons().isEmpty() && !getFxImages().isEmpty())
{
stage.getIcons().setAll(getFxImages());
}
}
/**
* Sets the macOS Dock icon and gives each Swing frame and dialog that opens without an icon the application
* icon. Safe to call more than once. Does nothing in a headless environment.
*/
public static synchronized void installSwing()
{
if(sSwingInstalled || java.awt.GraphicsEnvironment.isHeadless())
{
return;
}
sSwingInstalled = true;
Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
if(event.getID() == WindowEvent.WINDOW_OPENED &&
(event.getSource() instanceof Frame || event.getSource() instanceof Dialog))
{
apply((java.awt.Window)event.getSource());
}
}, AWTEvent.WINDOW_EVENT_MASK);
//The Dock icon on macOS. Windows and Linux take the icon from each window instead.
try
{
if(Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE))
{
List<Image> images = getAwtImages();
for(int x = 0; x < SIZES.length && x < images.size(); x++)
{
if(SIZES[x] == TASKBAR_SIZE)
{
Taskbar.getTaskbar().setIconImage(images.get(x));
}
}
}
}
catch(Exception e)
{
mLog.debug("Unable to set taskbar icon", e);
}
}
/**
* Gives each JavaFX stage that shows without an icon the application icon, and closes the startup splash screen
* if a JavaFX window opens before the main window does. Safe to call more than once. The JavaFX toolkit must
* already be running.
*/
public static synchronized void installJavaFx()
{
if(sJavaFxInstalled)
{
return;
}
sJavaFxInstalled = true;
Platform.runLater(() -> {
for(Window window: Window.getWindows())
{
onFxWindowShown(window);
}
Window.getWindows().addListener((ListChangeListener<Window>)change -> {
while(change.next())
{
for(Window window: change.getAddedSubList())
{
onFxWindowShown(window);
}
}
});
});
}
/**
* Handles a JavaFX window that is showing.
*/
private static void onFxWindowShown(Window window)
{
//Only stages are top-level windows. JFXPanel content and popups (menus, tooltips) are other Window types.
if(window instanceof Stage stage)
{
apply(stage);
//A JavaFX window (e.g. an error dialog) that shows before the main window would sit behind the splash.
Splash.close();
}
}
}

View File

@@ -181,6 +181,7 @@ public class JavaFxWindowManager extends Application
{
mJFXPanel = new JFXPanel();
Platform.setImplicitExit(false);
ApplicationIcons.installJavaFx();
}
}

View File

@@ -144,12 +144,28 @@ public class SDRTrunk implements Listener<TunerEvent>
private String mTitle;
public SDRTrunk()
{
try
{
initialize();
}
catch(Throwable t)
{
startupFailed(t);
}
}
/**
* Creates and starts the application components and shows the main window.
*/
private void initialize()
{
if(!GraphicsEnvironment.isHeadless())
{
//Initialize the theme manager before any Swing components are realized so the chosen
//look-and-feel applies to the very first window that is created.
ThemeManager.getInstance().initialize(mUserPreferences);
ApplicationIcons.installSwing();
mMainGui = new JFrame();
}
@@ -273,6 +289,9 @@ public class SDRTrunk implements Listener<TunerEvent>
if(!GraphicsEnvironment.isHeadless())
{
mMainGui.setVisible(true);
//The JVM closes the splash when the first window shows. Close it here as well in case it didn't.
Splash.close();
Tuner tuner = tunerSpectralDisplayManager.showFirstTuner();
if(tuner != null)
@@ -311,7 +330,15 @@ public class SDRTrunk implements Listener<TunerEvent>
}
catch(Exception e)
{
e.printStackTrace();
if(mMainGui != null && !mMainGui.isVisible())
{
//The main window didn't open, so the user has no way to close the application.
startupFailed(e);
}
else
{
mLog.error("Error while starting the application", e);
}
}
});
}
@@ -361,6 +388,7 @@ public class SDRTrunk implements Listener<TunerEvent>
*/
mTitle = SystemProperties.getInstance().getApplicationName();
mMainGui.setTitle(mTitle);
ApplicationIcons.apply(mMainGui);
Point location = mUserPreferences.getSwingPreference().getLocation(WINDOW_FRAME_IDENTIFIER);
if(location != null)
@@ -967,11 +995,117 @@ public class SDRTrunk implements Listener<TunerEvent>
JOptionPane.showMessageDialog(mMainGui, message, "Duplicate Library Versions", JOptionPane.WARNING_MESSAGE);
}
/**
* Handles an error that stops the application from starting. Stops the tuners that already started, so that they
* are released for the next start, then reports the error and exits. Without this, the threads that the
* application started before the error keep the JVM running with no main window and the splash screen showing.
* @param t error
*/
private void startupFailed(Throwable t)
{
mLog.error("sdrtrunk failed to start", t);
if(mTunerManager != null)
{
try
{
mTunerManager.stop();
}
catch(Throwable t2)
{
mLog.error("Error stopping tuners after the startup error", t2);
}
}
String logsDirectory = null;
try
{
logsDirectory = mUserPreferences.getDirectoryPreference().getDirectoryApplicationLog().toString();
}
catch(Throwable t2)
{
//Not available - the dialog leaves out the log location
}
if(mApplicationLog != null)
{
mApplicationLog.stop();
}
exitAfterStartupError(t, logsDirectory);
}
/**
* Closes the splash screen, shows the startup error to the user and exits the JVM with a non-zero status.
* @param t error
* @param logsDirectory where the application log is, or null if not known.
*/
private static void exitAfterStartupError(Throwable t, String logsDirectory)
{
//The application log may not be running yet, so also write the error to the console.
System.err.println("sdrtrunk failed to start");
t.printStackTrace();
Splash.close();
if(!GraphicsEnvironment.isHeadless())
{
String message = "<html><body style='width: 450px'>" +
"<p>sdrtrunk couldn't start because of this error:</p><br>" +
"<p><b>" + escapeHtml(String.valueOf(t)) + "</b></p><br>" +
(logsDirectory != null ? "<p>The application log has the details:</p><p>" +
escapeHtml(logsDirectory) + "</p><br>" : "") +
"<p>See Help / Support on the sdrtrunk wiki for help.</p>" +
"</body></html>";
try
{
Runnable dialog = () -> JOptionPane.showMessageDialog(null, message, "sdrtrunk Startup Error",
JOptionPane.ERROR_MESSAGE);
if(EventQueue.isDispatchThread())
{
dialog.run();
}
else
{
EventQueue.invokeAndWait(dialog);
}
}
catch(Throwable t2)
{
t2.printStackTrace();
}
}
System.exit(1);
}
/**
* Escapes text for display in a Swing HTML label.
*/
private static String escapeHtml(String text)
{
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
}
/**
* Launch the application.
*/
public static void main(String[] args)
{
new SDRTrunk();
String version = SDRTrunk.class.getPackage().getImplementationVersion();
Splash.showVersion(version != null ? "v" + version : null);
try
{
new SDRTrunk();
}
catch(Throwable t)
{
//An error creating the SDRTrunk fields, before the constructor's own startup error handling runs.
exitAfterStartupError(t, null);
}
}
}

View File

@@ -0,0 +1,117 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.SplashScreen;
/**
* Startup splash screen.
*
* The JVM shows the splash image named by the -splash:path option (set by the launch scripts) before any application
* code runs, and closes it when the main window becomes visible. This class draws the version on the splash and lets
* the application close the splash early, for example when a dialog has to show before the main window.
*
* Headless operation: the java launcher doesn't show the splash when -Djava.awt.headless=true is on the command line
* (for example in JAVA_OPTS or SDR_TRUNK_OPTS), and there is nothing to show it on without a display. This class does
* nothing when headless.
*/
public final class Splash
{
//Splash image layout, in pixels of the 640 x 360 image. The version goes under the tagline.
private static final double IMAGE_WIDTH = 640.0;
private static final double VERSION_X = 214.0;
private static final double VERSION_Y = 232.0;
private static final double VERSION_FONT_SIZE = 13.0;
private static final Color VERSION_COLOR = new Color(0x2E, 0xE6, 0xA6);
private Splash()
{
}
/**
* Draws the version text on the splash screen, if a splash screen is showing.
* @param version to show, for example "v1.0.1", or null to leave the splash unchanged.
*/
public static void showVersion(String version)
{
if(version == null || version.isBlank() || GraphicsEnvironment.isHeadless())
{
return;
}
try
{
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash == null || !splash.isVisible())
{
return;
}
//Overlay coordinates are in the splash's size, which can differ from the image (HiDPI @2x image).
Dimension size = splash.getSize();
double scale = size.width / IMAGE_WIDTH;
Graphics2D g = splash.createGraphics();
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(VERSION_COLOR);
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, (int)Math.round(VERSION_FONT_SIZE * scale)));
g.drawString(version, (float)(VERSION_X * scale), (float)(VERSION_Y * scale));
g.dispose();
splash.update();
}
catch(Exception e)
{
//The splash is cosmetic. Never let it stop the application from starting.
}
}
/**
* Closes the splash screen if it is still showing.
*/
public static void close()
{
if(GraphicsEnvironment.isHeadless())
{
return;
}
try
{
SplashScreen splash = SplashScreen.getSplashScreen();
if(splash != null && splash.isVisible())
{
splash.close();
}
}
catch(Exception e)
{
//The splash is cosmetic. Never let it stop the application from starting.
}
}
}

View File

@@ -0,0 +1,678 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.SourceEvent;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.LongConsumer;
import javafx.animation.KeyFrame;
import javafx.animation.PauseTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.AccessibleRole;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.Duration;
/**
* Frequency display and tuning control that shows a frequency in MHz with six fractional digits (1 Hz).
*
* Mouse: hover over a digit to reveal its up/down halves. Click the upper half to increment the digit or the lower
* half to decrement it (hold the button to repeat), or use the scroll wheel over the digit. Steps carry into the
* higher digits and stop at the minimum/maximum frequency.
*
* Keyboard: left/right move the digit cursor, up/down (or +/-) step the digit under the cursor. Typing digits
* starts a calculator style entry (e.g. 851.0125) that is applied with Enter and cancelled with Escape. Shortcut-C
* and Shortcut-V copy and paste the frequency.
*
* The control only reports user requested frequencies to the listeners. {@link #setFrequency(long)} updates the
* display without notifying them, which is how the tuner reports its actual frequency back to the control.
*/
public class FrequencyControl extends HBox implements ISourceEventProcessor
{
private static final PseudoClass HOVER_UP = PseudoClass.getPseudoClass("hover-up");
private static final PseudoClass HOVER_DOWN = PseudoClass.getPseudoClass("hover-down");
private static final PseudoClass LEADING = PseudoClass.getPseudoClass("leading");
private static final PseudoClass CURSOR = PseudoClass.getPseudoClass("cursor");
private static final PseudoClass ENTRY = PseudoClass.getPseudoClass("entry");
private static final PseudoClass TYPED = PseudoClass.getPseudoClass("typed");
private static final PseudoClass INVALID = PseudoClass.getPseudoClass("invalid");
private static final Duration REPEAT_DELAY = Duration.millis(400);
private static final Duration REPEAT_INTERVAL = Duration.millis(70);
private final List<LongConsumer> mListeners = new CopyOnWriteArrayList<>();
private final Digit[] mDigits = new Digit[FrequencyEntry.DIGIT_COUNT];
private final FrequencyEntry.TypedEntry mTypedEntry = new FrequencyEntry.TypedEntry();
private final Text mProbe = new Text("0");
private final Label mUnitLabel = new Label("MHz");
private final Tooltip mTooltip = new Tooltip();
private final PauseTransition mInvalidFlash = new PauseTransition(Duration.millis(1200));
private final Timeline mRepeat = new Timeline();
private long mFrequency;
private long mMinimum = 1;
private long mMaximum = FrequencyEntry.MAXIMUM_DISPLAYABLE;
private int mCursorPosition = FrequencyEntry.FRACTION_DIGITS;
private double mScrollAccumulator;
/**
* Constructs an instance
*/
public FrequencyControl()
{
getStyleClass().add("frequency-control");
URL stylesheet = FrequencyControl.class.getResource("/frequency_control.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
setAlignment(Pos.CENTER_LEFT);
setFocusTraversable(true);
setAccessibleRole(AccessibleRole.SPINNER);
setMaxWidth(Region.USE_PREF_SIZE);
//Invisible probe text, styled like the digits, sizes every digit cell to the same width so that a
//proportional font doesn't make the display jitter as the digits change.
mProbe.getStyleClass().add("frequency-digit-text");
mProbe.setManaged(false);
mProbe.setVisible(false);
getChildren().add(mProbe);
for(int position = FrequencyEntry.DIGIT_COUNT - 1; position >= 0; position--)
{
Digit digit = new Digit(position);
mDigits[position] = digit;
getChildren().add(digit);
if(position == FrequencyEntry.FRACTION_DIGITS)
{
Text point = new Text(".");
point.getStyleClass().addAll("frequency-digit-text", "frequency-point");
getChildren().add(point);
}
else if(position % 3 == 0 && position > 0)
{
Region gap = new Region();
gap.getStyleClass().add("frequency-group-gap");
getChildren().add(gap);
}
}
mUnitLabel.getStyleClass().add("frequency-unit");
getChildren().add(mUnitLabel);
Tooltip.install(this, mTooltip);
updateTooltip();
mInvalidFlash.setOnFinished(e -> pseudoClassStateChanged(INVALID, false));
mRepeat.setCycleCount(Timeline.INDEFINITE);
addEventHandler(KeyEvent.KEY_PRESSED, this::keyPressed);
addEventHandler(KeyEvent.KEY_TYPED, this::keyTyped);
addEventHandler(MouseEvent.MOUSE_PRESSED, e -> requestFocus());
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
cancelEntry();
}
updateDigits();
});
disabledProperty().addListener((observable, wasDisabled, disabled) -> {
if(disabled)
{
stopRepeat();
cancelEntry();
}
});
setOnContextMenuRequested(e -> {
buildContextMenu().show(this, e.getScreenX(), e.getScreenY());
e.consume();
});
updateDigits();
}
/**
* Adds a listener to be notified of frequencies requested by the user. Listeners are invoked on the JavaFX
* application thread.
*/
public void addListener(LongConsumer listener)
{
if(listener != null && !mListeners.contains(listener))
{
mListeners.add(listener);
}
}
/**
* Removes the listener.
*/
public void removeListener(LongConsumer listener)
{
mListeners.remove(listener);
}
/**
* Removes all listeners.
*/
public void clearListeners()
{
mListeners.clear();
}
/**
* Current frequency in Hertz.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Sets the displayed frequency without notifying listeners. Safe to call from any thread.
* @param frequency in Hertz
*/
public void setFrequency(long frequency)
{
if(Platform.isFxApplicationThread())
{
mFrequency = Math.max(0, Math.min(FrequencyEntry.MAXIMUM_DISPLAYABLE, frequency));
updateDigits();
}
else
{
Platform.runLater(() -> setFrequency(frequency));
}
}
/**
* Sets the range of frequencies that the user can request.
* @param minimum frequency in Hertz
* @param maximum frequency in Hertz
*/
public void setRange(long minimum, long maximum)
{
mMinimum = Math.max(0, Math.min(minimum, maximum));
mMaximum = Math.min(FrequencyEntry.MAXIMUM_DISPLAYABLE, Math.max(minimum, maximum));
updateTooltip();
}
/**
* Minimum frequency that the user can request.
*/
public long getMinimum()
{
return mMinimum;
}
/**
* Maximum frequency that the user can request.
*/
public long getMaximum()
{
return mMaximum;
}
/**
* Receives tuner frequency change notifications and shows the new frequency. Requests are not re-broadcast.
*/
@Override
public void process(SourceEvent event)
{
if(event.getEvent() == SourceEvent.Event.NOTIFICATION_FREQUENCY_CHANGE && event.getValue() != null)
{
setFrequency(event.getValue().longValue());
}
}
/**
* Digit position under the keyboard cursor.
*/
public int getCursorPosition()
{
return mCursorPosition;
}
/**
* Steps the digit at the position and notifies listeners when the frequency changes.
* @param position of the digit (0 = 1 Hz)
* @param steps positive to increment, negative to decrement
*/
public void step(int position, int steps)
{
if(isDisabled() || steps == 0)
{
return;
}
cancelEntry();
long stepped = FrequencyEntry.step(mFrequency, position, steps, mMinimum, mMaximum);
request(stepped);
}
/**
* Requests the frequency on behalf of the user. An out of range frequency is rejected and flagged.
* @return true if the frequency was accepted.
*/
public boolean request(long frequency)
{
if(frequency < mMinimum || frequency > mMaximum)
{
flagInvalid();
return false;
}
if(frequency != mFrequency)
{
mFrequency = frequency;
updateDigits();
for(LongConsumer listener: mListeners)
{
listener.accept(frequency);
}
}
return true;
}
/**
* Indicates if a typed entry is in progress.
*/
public boolean isEntryActive()
{
return !mTypedEntry.isEmpty();
}
private void keyTyped(KeyEvent event)
{
if(isDisabled() || event.isShortcutDown() || event.isAltDown())
{
return;
}
String character = event.getCharacter();
if(character == null || character.length() != 1)
{
return;
}
char c = character.charAt(0);
if((c >= '0' && c <= '9') || c == '.' || c == ',')
{
mTypedEntry.type(c);
updateDigits();
event.consume();
}
else if(c == '+' || c == '=')
{
step(mCursorPosition, 1);
event.consume();
}
else if(c == '-')
{
step(mCursorPosition, -1);
event.consume();
}
}
private void keyPressed(KeyEvent event)
{
if(isDisabled())
{
return;
}
if(event.isShortcutDown())
{
if(event.getCode() == KeyCode.C)
{
copy();
event.consume();
}
else if(event.getCode() == KeyCode.V)
{
paste();
event.consume();
}
return;
}
switch(event.getCode())
{
case LEFT, KP_LEFT -> moveCursor(1);
case RIGHT, KP_RIGHT -> moveCursor(-1);
case HOME -> setCursorPosition(FrequencyEntry.DIGIT_COUNT - 1);
case END -> setCursorPosition(0);
case UP, KP_UP -> step(mCursorPosition, 1);
case DOWN, KP_DOWN -> step(mCursorPosition, -1);
case PAGE_UP -> step(mCursorPosition, 10);
case PAGE_DOWN -> step(mCursorPosition, -10);
case ENTER ->
{
if(!commitEntry())
{
return;
}
}
case ESCAPE ->
{
if(!isEntryActive())
{
return;
}
cancelEntry();
}
case BACK_SPACE ->
{
if(!isEntryActive())
{
return;
}
mTypedEntry.backspace();
updateDigits();
}
default ->
{
return;
}
}
event.consume();
}
/**
* Applies the typed entry.
* @return true if there was an entry to apply.
*/
private boolean commitEntry()
{
if(!isEntryActive())
{
return false;
}
long frequency = mTypedEntry.getFrequency();
mTypedEntry.clear();
if(!request(frequency))
{
updateDigits();
}
return true;
}
private void cancelEntry()
{
if(isEntryActive())
{
mTypedEntry.clear();
updateDigits();
}
}
private void moveCursor(int direction)
{
cancelEntry();
setCursorPosition(mCursorPosition + direction);
}
private void setCursorPosition(int position)
{
mCursorPosition = Math.max(0, Math.min(FrequencyEntry.DIGIT_COUNT - 1, position));
updateDigits();
}
private void copy()
{
ClipboardContent content = new ClipboardContent();
content.putString(FrequencyEntry.format(mFrequency));
Clipboard.getSystemClipboard().setContent(content);
}
private void paste()
{
Clipboard clipboard = Clipboard.getSystemClipboard();
if(clipboard.hasString())
{
Long frequency = FrequencyEntry.parse(clipboard.getString());
cancelEntry();
if(frequency != null)
{
request(frequency);
}
else
{
flagInvalid();
}
}
}
private ContextMenu buildContextMenu()
{
MenuItem copy = new MenuItem("Copy Frequency");
copy.setAccelerator(KeyCombination.keyCombination("Shortcut+C"));
copy.setOnAction(e -> copy());
MenuItem paste = new MenuItem("Paste Frequency");
paste.setAccelerator(KeyCombination.keyCombination("Shortcut+V"));
paste.setDisable(isDisabled() || !Clipboard.getSystemClipboard().hasString());
paste.setOnAction(e -> paste());
MenuItem minimum = new MenuItem("Tune to Minimum (" + FrequencyEntry.format(mMinimum) + " MHz)");
minimum.setDisable(isDisabled());
minimum.setOnAction(e -> request(mMinimum));
MenuItem maximum = new MenuItem("Tune to Maximum (" + FrequencyEntry.format(mMaximum) + " MHz)");
maximum.setDisable(isDisabled());
maximum.setOnAction(e -> request(mMaximum));
return new ContextMenu(copy, paste, new SeparatorMenuItem(), minimum, maximum);
}
private void flagInvalid()
{
pseudoClassStateChanged(INVALID, true);
mInvalidFlash.playFromStart();
}
private void updateTooltip()
{
mTooltip.setText("Tuning range " + FrequencyEntry.format(mMinimum) + " - " +
FrequencyEntry.format(mMaximum) + " MHz\n\n" +
"Hover over a digit and use the scroll wheel, or click its upper or lower half, to step it.\n" +
"Or type a frequency in MHz (e.g. 851.0125) and press Enter. Escape cancels.\n" +
"Arrow keys move between digits and step the selected digit.");
}
/**
* Refreshes every digit's value and state.
*/
private void updateDigits()
{
boolean entry = isEntryActive();
long shown = entry ? mTypedEntry.getFrequency() : mFrequency;
boolean focused = isFocused();
pseudoClassStateChanged(ENTRY, entry);
for(Digit digit: mDigits)
{
int position = digit.getPosition();
digit.setValue(FrequencyEntry.getDigit(shown, position));
digit.pseudoClassStateChanged(LEADING, FrequencyEntry.isLeadingZero(shown, position));
digit.pseudoClassStateChanged(TYPED, entry && mTypedEntry.isTyped(position));
digit.pseudoClassStateChanged(CURSOR, focused && !entry && position == mCursorPosition);
}
setAccessibleText(FrequencyEntry.format(mFrequency) + " MHz");
}
private void stopRepeat()
{
mRepeat.stop();
mRepeat.getKeyFrames().clear();
}
/**
* A single digit with up and down halves.
*/
private class Digit extends VBox
{
private final int mPosition;
private final Text mText = new Text("0");
private final Region mUpHalf = new Region();
private final Region mDownHalf = new Region();
Digit(int position)
{
mPosition = position;
getStyleClass().add("frequency-digit");
setAlignment(Pos.CENTER);
Region upArrow = new Region();
upArrow.getStyleClass().addAll("frequency-arrow", "frequency-arrow-up");
Region downArrow = new Region();
downArrow.getStyleClass().addAll("frequency-arrow", "frequency-arrow-down");
mText.getStyleClass().add("frequency-digit-text");
mUpHalf.getStyleClass().addAll("frequency-half", "frequency-half-up");
mDownHalf.getStyleClass().addAll("frequency-half", "frequency-half-down");
StackPane cell = new StackPane(mUpHalf, mDownHalf, mText);
cell.getStyleClass().add("frequency-digit-cell");
StackPane.setAlignment(mUpHalf, Pos.TOP_CENTER);
StackPane.setAlignment(mDownHalf, Pos.BOTTOM_CENTER);
mUpHalf.maxHeightProperty().bind(cell.heightProperty().divide(2));
mDownHalf.maxHeightProperty().bind(cell.heightProperty().divide(2));
cell.minWidthProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getWidth() + 4));
cell.prefWidthProperty().bind(cell.minWidthProperty());
//Arrow size follows the digit font size, so it scales with the user's GUI scale
upArrow.prefWidthProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getWidth() * 0.6));
upArrow.prefHeightProperty().bind(mProbe.layoutBoundsProperty().map(bounds -> bounds.getHeight() * 0.18));
upArrow.maxWidthProperty().bind(upArrow.prefWidthProperty());
upArrow.maxHeightProperty().bind(upArrow.prefHeightProperty());
downArrow.prefWidthProperty().bind(upArrow.prefWidthProperty());
downArrow.prefHeightProperty().bind(upArrow.prefHeightProperty());
downArrow.maxWidthProperty().bind(upArrow.prefWidthProperty());
downArrow.maxHeightProperty().bind(upArrow.prefHeightProperty());
getChildren().addAll(upArrow, cell, downArrow);
addEventHandler(MouseEvent.MOUSE_MOVED, e -> setHalf(e.getY() < getHeight() / 2 ? 1 : -1));
addEventHandler(MouseEvent.MOUSE_ENTERED, e -> setHalf(e.getY() < getHeight() / 2 ? 1 : -1));
addEventHandler(MouseEvent.MOUSE_EXITED, e -> {
setHalf(0);
stopRepeat();
});
addEventHandler(MouseEvent.MOUSE_PRESSED, this::pressed);
addEventHandler(MouseEvent.MOUSE_RELEASED, e -> stopRepeat());
addEventHandler(ScrollEvent.SCROLL, this::scrolled);
}
int getPosition()
{
return mPosition;
}
void setValue(int value)
{
mText.setText(String.valueOf(value));
}
private void setHalf(int half)
{
pseudoClassStateChanged(HOVER_UP, half > 0);
pseudoClassStateChanged(HOVER_DOWN, half < 0);
}
private void pressed(MouseEvent event)
{
if(event.getButton() != MouseButton.PRIMARY || isDisabled())
{
return;
}
requestFocus();
mCursorPosition = mPosition;
int direction = event.getY() < getHeight() / 2 ? 1 : -1;
setHalf(direction);
step(mPosition, direction);
stopRepeat();
mRepeat.getKeyFrames().add(new KeyFrame(REPEAT_INTERVAL, e -> step(mPosition, direction)));
mRepeat.setDelay(REPEAT_DELAY);
mRepeat.playFromStart();
event.consume();
}
private void scrolled(ScrollEvent event)
{
if(isDisabled() || event.getDeltaY() == 0)
{
return;
}
//Accumulate so that high resolution (touchpad) scrolling steps once per wheel notch
double notch = event.getMultiplierY() > 1 ? event.getMultiplierY() : 40;
mScrollAccumulator += event.getDeltaY() / notch;
int steps = (int)mScrollAccumulator;
if(steps != 0)
{
mScrollAccumulator -= steps;
mCursorPosition = mPosition;
step(mPosition, steps);
}
event.consume();
}
}
}

View File

@@ -0,0 +1,372 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import java.math.BigDecimal;
/**
* Frequency arithmetic for the {@link FrequencyControl}, kept free of JavaFX so that it can be unit tested.
*
* The control shows a frequency in MHz as a fixed number of digits: {@link #INTEGER_DIGITS} MHz digits and
* {@link #FRACTION_DIGITS} fractional digits, so the least significant digit is 1 Hz. Digit positions are
* numbered by their power of ten in Hertz: position 0 is the 1 Hz digit and position 9 is the 1000 MHz digit.
*/
public final class FrequencyEntry
{
/**
* Number of MHz (integer) digits.
*/
public static final int INTEGER_DIGITS = 4;
/**
* Number of fractional MHz digits (precision to 1 Hz).
*/
public static final int FRACTION_DIGITS = 6;
/**
* Total number of displayed digits.
*/
public static final int DIGIT_COUNT = INTEGER_DIGITS + FRACTION_DIGITS;
/**
* Largest frequency that fits the display: 9999.999999 MHz.
*/
public static final long MAXIMUM_DISPLAYABLE = 9_999_999_999L;
private FrequencyEntry()
{
}
/**
* Value of the digit at the position.
* @param frequency in Hertz
* @param position power of ten (0 = 1 Hz)
* @return digit 0-9
*/
public static int getDigit(long frequency, int position)
{
return (int)((Math.abs(frequency) / pow10(position)) % 10);
}
/**
* Indicates if the digit at the position is a leading zero, which the control shows dimmed. The 1 MHz digit is
* never a leading zero.
*/
public static boolean isLeadingZero(long frequency, int position)
{
return position > FRACTION_DIGITS && Math.abs(frequency) < pow10(position);
}
/**
* Steps the frequency by a number of units of the digit position, carrying into the higher digits, and clamps
* the result to the range. A step that would leave the range lands on the range limit.
* @param frequency current value in Hertz
* @param position power of ten for the digit being stepped
* @param steps positive to increment, negative to decrement
* @param minimum allowed frequency
* @param maximum allowed frequency
* @return stepped and clamped frequency
*/
public static long step(long frequency, int position, int steps, long minimum, long maximum)
{
long stepped = frequency + (steps * pow10(position));
return clamp(stepped, minimum, maximum);
}
/**
* Replaces the digit at the position with a new value, without carry.
*/
public static long setDigit(long frequency, int position, int digit)
{
long unit = pow10(position);
int current = getDigit(frequency, position);
return frequency + ((long)(digit - current) * unit);
}
/**
* Clamps the frequency to the range.
*/
public static long clamp(long frequency, long minimum, long maximum)
{
return Math.max(minimum, Math.min(maximum, frequency));
}
/**
* Parses a typed or pasted frequency. A bare number is in MHz (e.g. 851.0125) unless it is too large to be MHz
* for the display, in which case it is read as Hertz (e.g. 851012500). An optional unit suffix of Hz, kHz, MHz
* or GHz (any case, with or without a space) overrides that. Thousands separators (comma, underscore or space)
* are ignored.
* @param text to parse
* @return frequency in Hertz, or null if the text isn't a frequency or has more precision than 1 Hz.
*/
public static Long parse(String text)
{
if(text == null)
{
return null;
}
String value = text.trim().toLowerCase().replace(",", "").replace("_", "").replace(" ", "");
if(value.isEmpty())
{
return null;
}
BigDecimal multiplier = null;
if(value.endsWith("ghz"))
{
multiplier = BigDecimal.valueOf(1_000_000_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("mhz"))
{
multiplier = BigDecimal.valueOf(1_000_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("khz"))
{
multiplier = BigDecimal.valueOf(1_000L);
value = value.substring(0, value.length() - 3);
}
else if(value.endsWith("hz"))
{
multiplier = BigDecimal.ONE;
value = value.substring(0, value.length() - 2);
}
BigDecimal number;
try
{
number = new BigDecimal(value);
}
catch(NumberFormatException nfe)
{
return null;
}
if(number.signum() < 0)
{
return null;
}
if(multiplier == null)
{
//A whole number too large to be MHz on the display is taken as Hertz
boolean whole = number.stripTrailingZeros().scale() <= 0;
multiplier = (whole && number.compareTo(BigDecimal.valueOf(10_000)) >= 0) ? BigDecimal.ONE :
BigDecimal.valueOf(1_000_000L);
}
BigDecimal hertz = number.multiply(multiplier).stripTrailingZeros();
if(hertz.scale() > 0)
{
return null;
}
try
{
return hertz.longValueExact();
}
catch(ArithmeticException ae)
{
return null;
}
}
/**
* Formats the frequency in MHz with all six fractional digits, e.g. 851.012500
*/
public static String format(long frequency)
{
return BigDecimal.valueOf(frequency, FRACTION_DIGITS).toPlainString();
}
/**
* Ten raised to the power.
*/
public static long pow10(int power)
{
long value = 1;
for(int x = 0; x < power; x++)
{
value *= 10;
}
return value;
}
/**
* Calculator style typed entry. Digits typed before the decimal point fill the MHz digits from the right and
* digits typed after it fill the fractional digits from the left, so typing 851.0125 shows 851.012500.
*/
public static class TypedEntry
{
private final StringBuilder mIntegerPart = new StringBuilder();
private final StringBuilder mFractionPart = new StringBuilder();
private boolean mDecimal = false;
/**
* Adds a typed character.
* @param c digit or decimal point
* @return true if the character was accepted
*/
public boolean type(char c)
{
if(c == '.' || c == ',')
{
if(mDecimal)
{
return false;
}
mDecimal = true;
return true;
}
if(c < '0' || c > '9')
{
return false;
}
if(mDecimal)
{
if(mFractionPart.length() >= FRACTION_DIGITS)
{
return false;
}
mFractionPart.append(c);
return true;
}
//Ignore leading zeros so they don't use up the MHz digits
if(mIntegerPart.isEmpty() && c == '0')
{
return true;
}
if(mIntegerPart.length() >= INTEGER_DIGITS)
{
return false;
}
mIntegerPart.append(c);
return true;
}
/**
* Removes the last typed character.
* @return true if there is still something typed after the removal.
*/
public boolean backspace()
{
if(!mFractionPart.isEmpty())
{
mFractionPart.setLength(mFractionPart.length() - 1);
}
else if(mDecimal)
{
mDecimal = false;
}
else if(!mIntegerPart.isEmpty())
{
mIntegerPart.setLength(mIntegerPart.length() - 1);
}
return !isEmpty();
}
/**
* Indicates if nothing has been typed.
*/
public boolean isEmpty()
{
return mIntegerPart.isEmpty() && mFractionPart.isEmpty() && !mDecimal;
}
/**
* Number of fractional digits typed so far.
*/
public int getFractionDigitsTyped()
{
return mFractionPart.length();
}
/**
* Indicates if the decimal point has been typed.
*/
public boolean hasDecimal()
{
return mDecimal;
}
/**
* Number of MHz digits typed so far.
*/
public int getIntegerDigitsTyped()
{
return mIntegerPart.length();
}
/**
* Frequency for what has been typed so far.
*/
public long getFrequency()
{
long mhz = mIntegerPart.isEmpty() ? 0 : Long.parseLong(mIntegerPart.toString());
long fraction = 0;
if(!mFractionPart.isEmpty())
{
fraction = Long.parseLong(mFractionPart.toString()) * pow10(FRACTION_DIGITS - mFractionPart.length());
}
return (mhz * 1_000_000L) + fraction;
}
/**
* Indicates if the digit at the position has been typed, as opposed to an implied trailing zero.
*/
public boolean isTyped(int position)
{
if(position >= FRACTION_DIGITS)
{
return position - FRACTION_DIGITS < mIntegerPart.length();
}
return (FRACTION_DIGITS - 1 - position) < mFractionPart.length();
}
/**
* Clears the typed entry.
*/
public void clear()
{
mIntegerPart.setLength(0);
mFractionPart.setLength(0);
mDecimal = false;
}
}
}

View File

@@ -0,0 +1,111 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import java.util.function.LongPredicate;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
/**
* Text field for a frequency in MHz (to 1 Hz). The value is committed when the user presses Enter or leaves the
* field. A commit handler can reject the new value, which restores the previous value. Escape reverts the text.
*/
public class FrequencyField extends TextField
{
private long mFrequency;
private LongPredicate mCommitHandler;
/**
* Constructs an instance
* @param frequency initial value in Hertz
*/
public FrequencyField(long frequency)
{
getStyleClass().add("frequency-field");
setPrefColumnCount(11);
setFrequency(frequency);
setOnAction(e -> commit());
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
commit();
}
});
setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ESCAPE)
{
setText(FrequencyEntry.format(mFrequency));
e.consume();
}
});
}
/**
* Sets the handler for committed values. The handler returns false to reject the value.
*/
public void setCommitHandler(LongPredicate handler)
{
mCommitHandler = handler;
}
/**
* Current frequency in Hertz.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Sets the frequency without invoking the commit handler.
*/
public void setFrequency(long frequency)
{
mFrequency = frequency;
setText(FrequencyEntry.format(frequency));
}
private void commit()
{
Long parsed = FrequencyEntry.parse(getText());
if(parsed == null)
{
setText(FrequencyEntry.format(mFrequency));
return;
}
if(parsed == mFrequency)
{
setText(FrequencyEntry.format(mFrequency));
return;
}
long previous = mFrequency;
mFrequency = parsed;
setText(FrequencyEntry.format(parsed));
if(mCommitHandler != null && !mCommitHandler.test(parsed))
{
setFrequency(previous);
}
}
}

View File

@@ -1,195 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import java.awt.EventQueue;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
/**
* Swing text field control for entering frequency (MHz) values.
*/
public class FrequencyTextField extends JTextField
{
private static final Logger LOGGER = LoggerFactory.getLogger(FrequencyTextField.class);
//Value range: 0.000001 to 9999.999999
private static final String REGEX = "^[0-9]{0,4}[.]?[0-9]{0,6}$";
//This lets users start typing a really small number like 1 Hertz ... 0.00000
private static final String ZEROS_REGEX = "^0?([.]0{0,5})?$";
private double mMinimum;
private double mMaximum;
/**
* Constructs an instance
*
* @param minimum allowable frequency value in Hertz
* @param maximum allowable frequency value in Hertz
* @param current frequency value in Hertz
*/
public FrequencyTextField(long minimum, long maximum, long current)
{
super(8);
mMinimum = minimum / 1E6d;
mMaximum = maximum / 1E6d;
PlainDocument document = (PlainDocument)this.getDocument();
document.setDocumentFilter(new FrequencyFilter());
setFrequency(current);
}
/**
* Current frequency value
* @return frequency in Hertz
*/
public long getFrequency()
{
String value = getText();
if(value == null || value.isEmpty())
{
return 0;
}
try
{
return (long)(Double.parseDouble(getText()) * 1E6d);
}
catch(Exception e)
{
LOGGER.error("Unable to parse frequency value from text [" + value + "] " + e.getLocalizedMessage());
}
return 0;
}
/**
* Sets the current frequency value
* @param frequency in Hertz
*/
public void setFrequency(long frequency)
{
double frequencyMHz = frequency / 1E6d;
if(isValid(String.valueOf(frequencyMHz)))
{
setText(String.valueOf(frequencyMHz));
}
else
{
LOGGER.warn("Can't set frequency [" + frequency + "Hz / " + frequencyMHz + "MHz] with current minimum [" + mMinimum + "MHz] and maximum [" + mMaximum + "MHz] limits");
}
}
/**
* Indicates if the value is a valid double value that is between the minimum and maximum extents.
* @param value to test
* @return true if it is valid.
*/
private boolean isValid(String value)
{
if(value == null || value.isEmpty() || value.matches(ZEROS_REGEX))
{
return true;
}
if(value.matches(REGEX))
{
try
{
double frequency = Double.parseDouble(value);
return mMinimum <= frequency && frequency <= mMaximum;
}
catch(NumberFormatException e)
{
return false;
}
}
return false;
}
/**
* Input filter for user entered values.
*/
class FrequencyFilter extends DocumentFilter
{
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if(isValid(sb.toString()))
{
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if(isValid(sb.toString()))
{
super.replace(fb, offset, length, text, attrs);
}
}
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException
{
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
if(isValid(sb.toString()))
{
super.remove(fb, offset, length);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Frequency Control Test");
frame.setSize(300, 200);
FrequencyTextField ftf = new FrequencyTextField(1, 9_999_999_999l, 101_100_000);
frame.setLayout(new MigLayout());
frame.add(ftf);
EventQueue.invokeLater(() -> frame.setVisible(true));
}
}

View File

@@ -1,593 +0,0 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import io.github.dsheirer.source.ISourceEventProcessor;
import io.github.dsheirer.source.InvalidFrequencyException;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.source.SourceException;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* Custom frequency controller for displaying or editing frequency values in MHz.
*/
public class JFrequencyControl extends JPanel implements ISourceEventProcessor
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(JFrequencyControl.class);
private List<ISourceEventProcessor> mProcessors = new ArrayList<>();
private Color mHighlightColor = Color.YELLOW;
private long mFrequency;
private HashMap<Integer,Digit> mDigits = new HashMap<Integer,Digit>();
/**
* Constructor
*/
public JFrequencyControl()
{
init();
}
/**
* Initializes the control/layout.
*/
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[]0[]", ""));
Font font = new Font(Font.MONOSPACED, Font.BOLD, 30);
for(int x = 9; x >= 0; x--)
{
Digit digit = null;
try
{
digit = new Digit(x);
}
catch(ParseException e)
{
mLog.error("JFrequencyControl - parse exception constructing a digit - " + e);
}
if(digit != null)
{
mDigits.put(x, digit);
add(digit);
digit.setFont(font);
if(x == 6)
{
add(new JLabel(". "));
}
}
}
revalidate();
}
/**
* Enables or disables the control.
* @param enabled true if this component should be enabled, false otherwise
*/
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
for(Digit digit : mDigits.values())
{
digit.setEnabled(enabled);
}
}
/**
* Receives a frequency change event invoked by another control. We don't
* rebroadcast this event, just set the control to indicate the new frequency.
*/
@Override
public void process(SourceEvent event)
{
switch(event.getEvent())
{
case NOTIFICATION_FREQUENCY_CHANGE:
EventQueue.invokeLater(() -> setFrequency(event.getValue().longValue(), false));
break;
}
}
/**
* Loads the frequency into the display and optionally fires a change event
* to all registered listeners
*/
public void setFrequency(long frequency, boolean fireChangeEvent)
{
mFrequency = frequency;
for(Digit digit : mDigits.values())
{
digit.setFrequency(frequency, fireChangeEvent);
}
}
/**
* Current frequency value for the control.
* @return frequency
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Updates the frequency value according to the manually changed digit value.
*/
private void updateFrequency()
{
long frequency = 0;
for(Digit digit : mDigits.values())
{
frequency += digit.getFrequency();
}
mFrequency = frequency;
}
/**
* Fires a source changed event
* @throws SourceException of there's an error
*/
private void fireSourceChanged() throws SourceException
{
updateFrequency();
Iterator<ISourceEventProcessor> it = mProcessors.iterator();
SourceEvent event = SourceEvent.frequencyRequest(mFrequency);
while(it.hasNext())
{
it.next().process(event);
}
}
/**
* Adds the source event listener
* @param processor
*/
public void addListener(ISourceEventProcessor processor)
{
if(!mProcessors.contains(processor))
{
mProcessors.add(processor);
}
}
/**
* Remove all source event processors
*/
public void clearListeners()
{
mProcessors.clear();
}
/**
* Removes the source event processor
* @param processor
*/
public void removeListener(ISourceEventProcessor processor)
{
mProcessors.remove(processor);
}
/**
* Custom single digit value editor.
*/
public class Digit extends JTextField
{
private static final long serialVersionUID = 1L;
private int mPower = 0;
private long mValue = 0;
/**
* Constructor
* @param position of the digit where a position of 1 is the ones unit of MHz and a position of -1 is the tenths
* unit of MHz.
* @throws ParseException if there is an error
*/
private Digit(int position) throws ParseException
{
super("0");
setColumns(1);
mPower = position;
setToolTipText(getTooltip(mPower));
Listener listener = new Listener();
this.addKeyListener(listener);
this.addMouseListener(listener);
this.addMouseWheelListener(listener);
}
/**
* Generates a custom tooltip for the current hover-over digit.
* @param power of the digit in units of 10
* @return custom tooptip.
*/
private static String getTooltip(int power)
{
StringBuilder sb = new StringBuilder();
sb.append("Center frequency ");
switch(power)
{
case 0:
sb.append("1 Hertz");
break;
case 1:
sb.append("10 Hertz");
break;
case 2:
sb.append("100 Hertz");
break;
case 3:
sb.append("1 Kilohertz");
break;
case 4:
sb.append("10 Kilohertz");
break;
case 5:
sb.append("100 Kilohertz");
break;
case 6:
sb.append("1 Megahertz");
break;
case 7:
sb.append("10 Megahertz");
break;
case 8:
sb.append("100 Megahertz");
break;
case 9:
sb.append("1 Gigahertz");
break;
}
sb.append(" units. Type a number, use up/down arrows, or click the upper/lower digit control to adjust");
return sb.toString();
}
/**
* Sets this digit to the value of the column in frequency that corresponds
* to the power (ie column) set for this digit. Optionally, fires a
* value change event to all listeners.
*/
public void setFrequency(long frequency, boolean fireChangeEvent)
{
//Strip the digits higher than this one
long lower = frequency % (long)(FastMath.pow(10, mPower + 1));
//Set the value to int value of dividing by 10 to this power
long value = (long)(lower / (long)(FastMath.pow(10, mPower)));
set(value, fireChangeEvent);
}
/**
* Frequency value.
* @return frequency value.
*/
public long getFrequency()
{
return mValue * (long)FastMath.pow(10, mPower);
}
/**
* Increments the unit value and fires a change event
*/
public void increment()
{
increment(true);
}
/**
* Increments the unit value and fires a change event
* @param fireChangeEvent true to fire an event
*/
public void increment(boolean fireChangeEvent)
{
if(isEnabled())
{
set(mValue + 1, fireChangeEvent);
}
}
/**
* Decrements the unit value and fires a change event.
*/
public void decrement()
{
decrement(true);
}
/**
* Decrements the unit value and optionally fires a change event.
* @param fireChangeEvent set to true to fire an event
*/
public void decrement(boolean fireChangeEvent)
{
if(isEnabled())
{
set(mValue - 1, fireChangeEvent);
}
}
/**
* Convenience wrapper to change amount and fire change event
*/
private void set(long amount)
{
set(amount, true);
}
/**
* Changes the value and optionally fires change event to listeners
*/
private void set(long amount, boolean fireChangeEvent)
{
long previous = mValue;
boolean higherDigitIncremented = false;
boolean higherDigitDecremented = false;
mValue = amount;
while(mValue < 0)
{
mValue += 10;
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.decrement(false);
higherDigitDecremented = true;
}
}
while(mValue > 9)
{
mValue -= 10;
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.increment(false);
higherDigitIncremented = true;
}
}
if(fireChangeEvent)
{
try
{
fireSourceChanged();
}
catch(SourceException se)
{
mValue = previous;
if(higherDigitIncremented)
{
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.decrement(false);
}
}
if(higherDigitDecremented)
{
Digit nextHigherDigit = mDigits.get(mPower + 1);
if(nextHigherDigit != null)
{
nextHigherDigit.increment(false);
}
}
if(se instanceof InvalidFrequencyException ife)
{
JOptionPane.showMessageDialog(this, ife.getMessage() + " for this tuner.");
}
}
}
setText(String.valueOf(mValue));
repaint();
}
/**
* Multiple Listener interface implementation
*/
private class Listener implements KeyListener, MouseListener, MouseWheelListener
{
@Override
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
switch(key)
{
case KeyEvent.VK_0:
case KeyEvent.VK_NUMPAD0:
set(0);
Digit.this.transferFocus();
break;
case KeyEvent.VK_1:
case KeyEvent.VK_NUMPAD1:
set(1);
Digit.this.transferFocus();
break;
case KeyEvent.VK_2:
case KeyEvent.VK_NUMPAD2:
set(2);
Digit.this.transferFocus();
break;
case KeyEvent.VK_3:
case KeyEvent.VK_NUMPAD3:
set(3);
Digit.this.transferFocus();
break;
case KeyEvent.VK_4:
case KeyEvent.VK_NUMPAD4:
set(4);
Digit.this.transferFocus();
break;
case KeyEvent.VK_5:
case KeyEvent.VK_NUMPAD5:
set(5);
Digit.this.transferFocus();
break;
case KeyEvent.VK_6:
case KeyEvent.VK_NUMPAD6:
set(6);
Digit.this.transferFocus();
break;
case KeyEvent.VK_7:
case KeyEvent.VK_NUMPAD7:
set(7);
Digit.this.transferFocus();
break;
case KeyEvent.VK_8:
case KeyEvent.VK_NUMPAD8:
set(8);
Digit.this.transferFocus();
break;
case KeyEvent.VK_9:
case KeyEvent.VK_NUMPAD9:
set(9);
Digit.this.transferFocus();
break;
case KeyEvent.VK_LEFT:
Digit.this.transferFocusBackward();
break;
case KeyEvent.VK_RIGHT:
Digit.this.transferFocus();
break;
case KeyEvent.VK_UP:
increment();
break;
case KeyEvent.VK_DOWN:
decrement();
break;
case KeyEvent.VK_TAB:
break;
default:
set(mValue);
break;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void mouseClicked(MouseEvent e)
{
switch(e.getButton())
{
case MouseEvent.BUTTON1:
increment();
break;
case MouseEvent.BUTTON2:
break;
case MouseEvent.BUTTON3:
decrement();
break;
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e)
{
Color bg = UIManager.getColor("TextField.selectionBackground");
Color fg = UIManager.getColor("TextField.selectionForeground");
Digit.this.setBackground(bg != null ? bg : Color.YELLOW);
Digit.this.setForeground(fg != null ? fg : Color.BLACK);
repaint(); }
@Override
public void mouseExited(MouseEvent e)
{
Color bg = UIManager.getColor("TextField.background");
Color fg = UIManager.getColor("TextField.foreground");
Digit.this.setBackground(bg != null ? bg : Color.WHITE);
Digit.this.setForeground(fg != null ? fg : Color.BLACK);
repaint(); }
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
//Swing delivers mouse wheel events to disabled components, so check enabled state explicitly so that
//the wheel can't bypass the lock when the tuner is providing channels.
if(isEnabled())
{
set(mValue - e.getWheelRotation());
}
else if(getParent() != null)
{
//Pass the event up so that an enclosing scroll pane can still scroll while this control is locked
getParent().dispatchEvent(SwingUtilities.convertMouseEvent(Digit.this, e, getParent()));
}
}
}
}
}

View File

@@ -660,7 +660,7 @@ public class AliasConfigurationEditor extends SplitPane implements IAliasListRef
nameColumn.setPrefWidth(140);
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
groupColumn.setPrefWidth(140);

View File

@@ -1094,7 +1094,7 @@ public class AliasItemEditor extends Editor<Alias>
GridPane.setConstraints(getColorPicker(), 7, row);
mTextFieldPane.getChildren().add(getColorPicker());
Label groupLabel = new Label("Group");
Label groupLabel = new Label("Category");
groupLabel.setLabelFor(getGroupField());
GridPane.setHalignment(groupLabel, HPos.RIGHT);
GridPane.setConstraints(groupLabel, 0, ++row);

View File

@@ -243,7 +243,7 @@ public class AliasViewByIdentifierEditor extends VBox
aliasColumn.setPrefWidth(200);
TableColumn<AliasAndIdentifier, String> groupColumn = new TableColumn<>();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
groupColumn.setPrefWidth(200);

View File

@@ -241,7 +241,7 @@ public class AliasViewByRecordingEditor extends VBox
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(200);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
@@ -280,7 +280,7 @@ public class AliasViewByRecordingEditor extends VBox
nameColumn.setCellValueFactory(new PropertyValueFactory<Alias,String>("name"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(200);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));

View File

@@ -694,8 +694,8 @@ public abstract class ChannelConfigurationEditor extends Editor<Channel>
mAutoAddTalkerAliasesCheckBox = new CheckBox("Auto-Add Talker Aliases");
mAutoAddTalkerAliasesCheckBox.setDisable(true);
mAutoAddTalkerAliasesCheckBox.setTooltip(new Tooltip("Adds decoded talker aliases as radio aliases in " +
"the Talker Alias group. Only radio aliases in that group are automatically renamed; existing " +
"radio aliases outside the group are left unchanged. Move an alias out of the Talker Alias group " +
"the Talker Alias category. Only radio aliases in that category are automatically renamed; existing " +
"radio aliases outside the category are left unchanged. Move an alias out of the Talker Alias category " +
"to preserve a custom name. Applies when the channel is (re)started."));
mAutoAddTalkerAliasesCheckBox.setOnAction(event -> modifiedProperty().set(true));
}

View File

@@ -225,7 +225,7 @@ public class StreamAliasSelectionEditor extends VBox
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(150);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));
@@ -270,7 +270,7 @@ public class StreamAliasSelectionEditor extends VBox
aliasListNameColumn.setCellValueFactory(new PropertyValueFactory<>("aliasListName"));
TableColumn groupColumn = new TableColumn();
groupColumn.setText("Group");
groupColumn.setText("Category");
groupColumn.setPrefWidth(150);
groupColumn.setCellValueFactory(new PropertyValueFactory<>("group"));

View File

@@ -65,7 +65,7 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
SpectralDisplayModel model = getSpectralDisplay().getModel();
getSpectralDisplay().messageProperty().set(MESSAGE_NO_CHANNEL);
//Noise floor slider along the right edge, below the configuration panel tab
//Noise floor slider for the spectrum
mNoiseFloorSlider = new EdgeSlider("Floor", "Noise floor: moves the bottom of the spectrum's dB range. " +
"Higher settings show a deeper range and move the noise floor up the display.",
MINIMUM_SAMPLE_SIZE, MAXIMUM_SAMPLE_SIZE, 1, this::formatPlotBottom);
@@ -82,9 +82,10 @@ public class ChannelSpectralDisplay extends DftSpectralDisplay
model.binCountProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
model.noiseBandwidthProperty().addListener((ob, ov, nv) -> mNoiseFloorSlider.refreshLabel());
mNoiseFloorSlider.refreshLabel();
//Along the right edge of the spectrum section, below the configuration panel tab
StackPane.setAlignment(mNoiseFloorSlider, Pos.CENTER_RIGHT);
StackPane.setMargin(mNoiseFloorSlider, new Insets(44, 0, 8, 0));
getChildren().add(mNoiseFloorSlider);
getSpectralDisplay().addSectionOverlay(DisplaySection.SPECTRUM, mNoiseFloorSlider);
installConfigPanel();
}

View File

@@ -55,6 +55,8 @@ public abstract class DftSpectralDisplay extends StackPane
private static final String PEAK_HOLD = "peak.hold";
private static final String SPECTRUM_ENABLED = "spectrum.enabled";
private static final String WATERFALL_ENABLED = "waterfall.enabled";
private static final String WATERFALL_RANGE = "waterfall.range";
private static final String WATERFALL_AVERAGING = "waterfall.averaging";
private static final String DIVIDER_POSITION = "divider.position";
private static final String DECIBEL_SCALE = "decibel.scale";
private static final String CONFIG_PINNED = "config.pinned";
@@ -121,6 +123,9 @@ public abstract class DftSpectralDisplay extends StackPane
});
mSpectralDisplay.averagingProperty().addListener((ob, ov, nv) -> save(AVERAGING, nv.intValue()));
mSpectralDisplay.peakHoldProperty().addListener((ob, ov, nv) -> save(PEAK_HOLD, nv));
mSpectralDisplay.waterfallRangeProperty().addListener((ob, ov, nv) -> save(WATERFALL_RANGE, nv.intValue()));
mSpectralDisplay.waterfallAveragingProperty().addListener((ob, ov, nv) ->
save(WATERFALL_AVERAGING, nv.intValue()));
mSpectralDisplay.dividerPositionProperty().addListener((ob, ov, nv) ->
save(DIVIDER_POSITION, String.valueOf(nv.doubleValue())));
mDecibelLayer.visibleProperty().addListener((ob, ov, nv) -> save(DECIBEL_SCALE, nv));
@@ -205,6 +210,12 @@ public abstract class DftSpectralDisplay extends StackPane
mSpectralDisplay.averagingProperty().set(Math.max(SpectralDisplay.AVERAGING_MINIMUM,
Math.min(SpectralDisplay.AVERAGING_MAXIMUM, averaging)));
mSpectralDisplay.peakHoldProperty().set(properties.get(key(PEAK_HOLD), false));
mSpectralDisplay.waterfallRangeProperty().set(Math.max(WaterfallScaler.RANGE_MINIMUM,
Math.min(WaterfallScaler.RANGE_MAXIMUM, properties.get(key(WATERFALL_RANGE),
WaterfallScaler.RANGE_DEFAULT))));
mSpectralDisplay.waterfallAveragingProperty().set(Math.max(WaterfallScaler.AVERAGING_MINIMUM,
Math.min(WaterfallScaler.AVERAGING_MAXIMUM, properties.get(key(WATERFALL_AVERAGING),
WaterfallScaler.AVERAGING_DEFAULT))));
mDecibelLayer.visibleProperty().set(properties.get(key(DECIBEL_SCALE), true));
try

View File

@@ -42,6 +42,8 @@ import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Orientation;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
@@ -104,6 +106,10 @@ public class SpectralDisplay extends StackPane
private final SplitPane mSplitPane = new SplitPane();
private final CanvasPane mSpectrumPane = new CanvasPane(DisplaySection.SPECTRUM);
private final CanvasPane mWaterfallPane = new CanvasPane(DisplaySection.WATERFALL);
//Each section's canvas with overlay controls stacked on top
private final StackPane mSpectrumSection = new StackPane(mSpectrumPane);
private final StackPane mWaterfallSection = new StackPane(mWaterfallPane);
private final EdgeSlider mWaterfallRangeSlider;
private final StackPane mDisabledPane = new StackPane();
private final BooleanProperty mSpectrumEnabled = new SimpleBooleanProperty(true);
@@ -112,6 +118,8 @@ public class SpectralDisplay extends StackPane
private final IntegerProperty mAveraging = new SimpleIntegerProperty(AVERAGING_DEFAULT);
private final BooleanProperty mPeakHold = new SimpleBooleanProperty(false);
private final DoubleProperty mDividerPosition = new SimpleDoubleProperty(0.5);
private final IntegerProperty mWaterfallRange = new SimpleIntegerProperty(WaterfallScaler.RANGE_DEFAULT);
private final IntegerProperty mWaterfallAveraging = new SimpleIntegerProperty(WaterfallScaler.AVERAGING_DEFAULT);
private final StringProperty mMessage = new SimpleStringProperty();
//Values read on the DFT results thread
@@ -119,6 +127,7 @@ public class SpectralDisplay extends StackPane
private volatile boolean mWaterfallActive = true;
private volatile boolean mWaterfallPausedFlag = false;
private final SpectrumAverager mAverager = new SpectrumAverager();
private final WaterfallScaler mWaterfallScaler = new WaterfallScaler();
//Hand off from the DFT results thread to the JavaFX thread
private final AtomicReference<SpectrumAverager.Frame> mLatestSpectrum = new AtomicReference<>();
@@ -133,8 +142,10 @@ public class SpectralDisplay extends StackPane
private WritableImage[] mWaterfallTiles;
private int mWaterfallWidth;
private int mWaterfallHeight;
private byte[] mWaterfallIndexes;
private byte[] mWaterfallLevels;
private int[] mWaterfallPixels;
//ARGB color for each waterfall level code, for the current theme and range. Null when it needs to be rebuilt.
private int[] mWaterfallColors;
private int mWaterfallWriteRow = 0;
private double[] mPolygonX = new double[0];
private double[] mPolygonY = new double[0];
@@ -167,6 +178,37 @@ public class SpectralDisplay extends StackPane
themeChanged(disabledLabel);
getChildren().addAll(mDisabledPane, mSplitPane);
setMinSize(0, 0);
mSpectrumSection.setMinSize(0, 0);
mWaterfallSection.setMinSize(0, 0);
//Waterfall gain slider along the right edge of the waterfall. The slider value is inverted so that moving it
//up narrows the dB range, which raises the contrast of weak signals.
int rangeSum = WaterfallScaler.RANGE_MINIMUM + WaterfallScaler.RANGE_MAXIMUM;
mWaterfallRangeSlider = new EdgeSlider("Gain", "Waterfall gain: dB range from the noise floor to the top " +
"of the color palette. Higher settings use a smaller range, which gives weak signals more contrast " +
"against the noise and saturates strong signals sooner.", WaterfallScaler.RANGE_MINIMUM,
WaterfallScaler.RANGE_MAXIMUM, 1, value -> (rangeSum - Math.round(value)) + " dB");
mWaterfallRangeSlider.valueProperty().set(rangeSum - mWaterfallRange.get());
mWaterfallRangeSlider.valueProperty().addListener((ob, ov, nv) ->
mWaterfallRange.set(rangeSum - (int)Math.round(nv.doubleValue())));
mWaterfallRange.addListener((ob, ov, nv) -> {
int range = Math.max(WaterfallScaler.RANGE_MINIMUM, Math.min(WaterfallScaler.RANGE_MAXIMUM,
nv.intValue()));
if(range != nv.intValue())
{
mWaterfallRange.set(range);
return;
}
mWaterfallRangeSlider.valueProperty().set(rangeSum - range);
mWaterfallColors = null;
repaintWaterfallImage();
});
StackPane.setAlignment(mWaterfallRangeSlider, Pos.CENTER_RIGHT);
mWaterfallSection.getChildren().add(mWaterfallRangeSlider);
mWaterfallAveraging.addListener((ob, ov, nv) -> mWaterfallScaler.setAveraging(nv.intValue()));
mSpectrumEnabled.addListener((ob, ov, nv) -> updateSections());
mWaterfallEnabled.addListener((ob, ov, nv) -> updateSections());
@@ -261,6 +303,7 @@ public class SpectralDisplay extends StackPane
SpectralDisplayTheme theme = getTheme();
mDisabledPane.setBackground(new Background(new BackgroundFill(theme.getBackground(), null, null)));
disabledLabel.setTextFill(theme.getLine());
mWaterfallColors = null;
repaintWaterfallImage();
requestRender();
}
@@ -357,6 +400,42 @@ public class SpectralDisplay extends StackPane
return mPeakHold;
}
/**
* Waterfall dB range from the noise floor to the top of the color palette, from WaterfallScaler.RANGE_MINIMUM to
* RANGE_MAXIMUM. Smaller ranges give weak signals more contrast. JavaFX thread only.
*/
public IntegerProperty waterfallRangeProperty()
{
return mWaterfallRange;
}
/**
* Number of DFT frames averaged into each waterfall row, from WaterfallScaler.AVERAGING_MINIMUM to
* AVERAGING_MAXIMUM. Averaging steadies the noise floor so weak signals stand out, but the waterfall scrolls
* more slowly.
*/
public IntegerProperty waterfallAveragingProperty()
{
return mWaterfallAveraging;
}
/**
* Waterfall gain slider along the right edge of the waterfall section.
*/
public EdgeSlider getWaterfallRangeSlider()
{
return mWaterfallRangeSlider;
}
/**
* Adds a control on top of the spectrum or the waterfall section, for example an EdgeSlider. Set its StackPane
* alignment and margin before adding it. The control is hidden with its section.
*/
public void addSectionOverlay(DisplaySection section, javafx.scene.Node node)
{
(section == DisplaySection.SPECTRUM ? mSpectrumSection : mWaterfallSection).getChildren().add(node);
}
/**
* Divider position (0 - 1.0) between the spectrum and the waterfall when both are showing.
*/
@@ -395,6 +474,7 @@ public class SpectralDisplay extends StackPane
public void clear()
{
mAverager.reset();
mWaterfallScaler.reset();
mLatestSpectrum.set(null);
mWaterfallRows.clear();
@@ -412,10 +492,11 @@ public class SpectralDisplay extends StackPane
return;
}
//The first DFT results on startup can be NaN or infinite
//The first DFT results on startup can be NaN or infinite - drop them. Replacing them with zeros would add
//full scale (0 dBFS) values to the spectrum averaging and the waterfall floor tracking.
if(Float.isNaN(bins[0]) || Float.isInfinite(bins[0]))
{
bins = new float[bins.length];
return;
}
if(mSpectrumActive)
@@ -425,11 +506,16 @@ public class SpectralDisplay extends StackPane
if(mWaterfallActive && !mWaterfallPausedFlag)
{
mWaterfallRows.offer(toWaterfallRow(bins));
byte[] row = mWaterfallScaler.process(bins);
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
if(row != null)
{
mWaterfallRows.poll();
mWaterfallRows.offer(row);
while(mWaterfallRows.size() > WATERFALL_QUEUE_LIMIT)
{
mWaterfallRows.poll();
}
}
}
}
@@ -452,33 +538,7 @@ public class SpectralDisplay extends StackPane
mLatestSpectrum.set(null);
mWaterfallRows.clear();
mWaterfallTiles = null;
mWaterfallIndexes = null;
}
/**
* Converts the DFT results to a row of waterfall intensity indexes (0 - 255). Each bin is scaled relative to the
* average bin value so the noise floor stays at the bottom of the palette regardless of tuner gain.
*/
private static byte[] toWaterfallRow(float[] bins)
{
double sum = 0.0;
for(float bin: bins)
{
sum += bin;
}
float average = (float)(sum / bins.length) - 1.0f;
float scale = 256.0f / average;
byte[] row = new byte[bins.length];
for(int x = 0; x < bins.length; x++)
{
int value = (int)((average - bins[x]) * scale);
row[x] = (byte)Math.max(0, Math.min(255, value));
}
return row;
mWaterfallLevels = null;
}
/**
@@ -491,11 +551,11 @@ public class SpectralDisplay extends StackPane
mSpectrumActive = spectrum;
mWaterfallActive = waterfall;
List<Pane> items = new ArrayList<>();
List<StackPane> items = new ArrayList<>();
if(spectrum)
{
items.add(mSpectrumPane);
items.add(mSpectrumSection);
}
else
{
@@ -505,13 +565,16 @@ public class SpectralDisplay extends StackPane
if(waterfall)
{
items.add(mWaterfallPane);
items.add(mWaterfallSection);
}
else
{
mWaterfallRows.clear();
}
//Keep the waterfall slider below the configuration panel tab when the waterfall is at the top
StackPane.setMargin(mWaterfallRangeSlider, new Insets(spectrum ? 8 : 44, 0, 8, 0));
mSplitPane.getItems().setAll(items);
mSplitPane.setVisible(!items.isEmpty());
@@ -543,7 +606,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallTiles != null)
{
mWaterfallTiles = null;
mWaterfallIndexes = null;
mWaterfallLevels = null;
mWaterfallWriteRow = 0;
}
@@ -581,8 +644,8 @@ public class SpectralDisplay extends StackPane
/**
* Writes the row into the waterfall ring buffer. The newest row is at mWaterfallWriteRow and older rows follow
* it, wrapping around the end of the image. The intensity indexes are kept alongside the image so the history
* can be recolored when the theme changes.
* it, wrapping around the end of the image. The level codes are kept alongside the image so the history
* can be recolored when the theme or the waterfall range changes.
*/
private void writeWaterfallRow(byte[] row)
{
@@ -590,7 +653,7 @@ public class SpectralDisplay extends StackPane
if(mWaterfallTiles == null || mWaterfallWidth != row.length)
{
mWaterfallIndexes = new byte[row.length * rows];
mWaterfallLevels = new byte[row.length * rows];
createWaterfallTiles(row.length, rows);
mWaterfallWriteRow = 0;
repaintWaterfallImage();
@@ -602,7 +665,7 @@ public class SpectralDisplay extends StackPane
int width = row.length;
mWaterfallWriteRow = (mWaterfallWriteRow - 1 + mWaterfallHeight) % mWaterfallHeight;
System.arraycopy(row, 0, mWaterfallIndexes, mWaterfallWriteRow * width, width);
System.arraycopy(row, 0, mWaterfallLevels, mWaterfallWriteRow * width, width);
writeWaterfallPixels(mWaterfallWriteRow);
}
@@ -625,7 +688,7 @@ public class SpectralDisplay extends StackPane
}
/**
* Colors one row of the waterfall image tiles from the stored intensity indexes.
* Colors one row of the waterfall image tiles from the stored level codes.
*/
private void writeWaterfallPixels(int imageRow)
{
@@ -636,12 +699,12 @@ public class SpectralDisplay extends StackPane
mWaterfallPixels = new int[width];
}
SpectralDisplayTheme theme = getTheme();
int[] colors = getWaterfallColors();
int offset = imageRow * width;
for(int x = 0; x < width; x++)
{
mWaterfallPixels[x] = theme.getWaterfallColor(mWaterfallIndexes[offset + x]);
mWaterfallPixels[x] = colors[mWaterfallLevels[offset + x] & 0xFF];
}
for(int tile = 0; tile < mWaterfallTiles.length; tile++)
@@ -653,11 +716,33 @@ public class SpectralDisplay extends StackPane
}
/**
* Recolors the whole waterfall image from the stored intensity indexes using the current theme.
* ARGB color for each waterfall level code, for the current theme and range.
*/
private int[] getWaterfallColors()
{
if(mWaterfallColors == null)
{
SpectralDisplayTheme theme = getTheme();
int range = mWaterfallRange.get();
int[] colors = new int[256];
for(int level = 0; level < colors.length; level++)
{
colors[level] = theme.getWaterfallColor(WaterfallScaler.paletteIndex(level, range));
}
mWaterfallColors = colors;
}
return mWaterfallColors;
}
/**
* Recolors the whole waterfall image from the stored level codes using the current theme and range.
*/
private void repaintWaterfallImage()
{
if(mWaterfallTiles != null && mWaterfallIndexes != null)
if(mWaterfallTiles != null && mWaterfallLevels != null)
{
for(int y = 0; y < mWaterfallHeight; y++)
{
@@ -689,10 +774,10 @@ public class SpectralDisplay extends StackPane
for(int y = 0; y < previousHeight; y++)
{
int source = (mWaterfallWriteRow + y) % previousHeight;
System.arraycopy(mWaterfallIndexes, source * width, indexes, y * width, width);
System.arraycopy(mWaterfallLevels, source * width, indexes, y * width, width);
}
mWaterfallIndexes = indexes;
mWaterfallLevels = indexes;
createWaterfallTiles(width, rows);
mWaterfallWriteRow = 0;
repaintWaterfallImage();

View File

@@ -353,6 +353,27 @@ public class SpectralDisplayConfigPanel extends VBox
"falling slowly"));
row = addRow(grid, row, peakHold.label(), peakHold.control());
//Waterfall
grid.add(sectionLabel("Waterfall"), 0, row++, 2, 1);
ComboBox<Integer> waterfallAveraging = new ComboBox<>();
for(int frames = WaterfallScaler.AVERAGING_MINIMUM; frames <= WaterfallScaler.AVERAGING_MAXIMUM; frames++)
{
waterfallAveraging.getItems().add(frames);
}
waterfallAveraging.setMaxWidth(Double.MAX_VALUE);
waterfallAveraging.setConverter(converter(frames -> frames == 1 ? "Off" : frames + " frames"));
waterfallAveraging.setValue(mSpectralDisplay.waterfallAveragingProperty().get());
waterfallAveraging.valueProperty().addListener((ob, ov, nv) -> {
if(nv != null)
{
mSpectralDisplay.waterfallAveragingProperty().set(nv);
}
});
waterfallAveraging.setTooltip(new Tooltip("FFT frames averaged into each waterfall row. Averaging steadies " +
"the noise floor so weak signals stand out, but the waterfall scrolls more slowly."));
trackPopup(waterfallAveraging.showingProperty());
row = addRow(grid, row, "Averaging", waterfallAveraging);
//Layer settings
for(SpectralDisplayLayer layer: mSpectralDisplay.getLayers())
{

View File

@@ -33,44 +33,31 @@ public class WaterfallPalette
}
/**
* Palette of the original Swing waterfall: dark blue noise floor, a blue to yellow ramp, yellow fading to orange,
* then red.
* Palette based on the original Swing waterfall colors: a dark to bright blue ramp, a blue to yellow ramp, yellow
* fading to orange, then red. The blue ramp covers the bottom quarter of the palette, where the waterfall places
* the noise floor, so the noise stays blue and weak signals stand out from it.
*/
public static int[] classic()
{
int[] palette = new int[SIZE];
for(int x = 0; x < 16; x++)
for(int x = 0; x < 64; x++)
{
palette[x] = argb(0, 0, 127);
palette[x] = argb(0, 0, blend(64, 191, x / 63.0));
}
for(int x = 16; x < 32; x++)
for(int x = 64; x < 100; x++)
{
palette[x] = argb(0, 0, 191);
double t = (x - 64) / 36.0;
palette[x] = argb(blend(0, 255, t), blend(0, 255, t), blend(191, 0, t));
}
int r = 0;
int g = 0;
int b = 191;
for(int x = 32; x < 60; x++)
for(int x = 100; x < 220; x++)
{
palette[x] = argb(r, g, b);
r += 9;
g += 9;
b -= 6;
palette[x] = argb(255, blend(255, 0, (x - 100) / 120.0), 0);
}
g = 255;
for(int x = 60; x < 188; x++)
{
palette[x] = argb(255, g, 0);
g -= 2;
}
for(int x = 188; x < SIZE; x++)
for(int x = 220; x < SIZE; x++)
{
palette[x] = argb(255, 0, 0);
}
@@ -78,6 +65,11 @@ public class WaterfallPalette
return palette;
}
private static int blend(int from, int to, double fraction)
{
return (int)Math.round(from + (to - from) * fraction);
}
/**
* Palette that blends linearly between evenly spaced colors.
* @param colors web color strings (for example #440154), lowest intensity first

View File

@@ -0,0 +1,289 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import java.util.Arrays;
/**
* Converts DFT results in dB to rows of waterfall level codes, and level codes to palette indexes.
*
* Optionally averages several DFT frames (in linear power) into each row. Averaging reduces the random variation of
* the noise bins (about 5.6 dB for a single frame), which is the only thing that makes weak signals statistically
* easier to see, at the cost of fewer rows per second.
*
* The noise floor reference is a low percentile of the bins, so signals that fill much of the span don't raise it,
* smoothed across rows so the waterfall background doesn't flicker.
*
* Each row stores a level code per bin: the bin level relative to the floor reference in LEVEL_STEP_DB steps. The
* level codes are mapped to palette indexes over a dB range above the floor (see paletteIndex()) when the row is
* colored, so the range can change and the waterfall history can be recolored without the original DFT results.
*
* Not thread safe: process() on the DFT results thread only. reset() and setAveraging() are safe from any thread.
*/
public class WaterfallScaler
{
public static final int RANGE_MINIMUM = 20;
public static final int RANGE_MAXIMUM = 80;
public static final int RANGE_DEFAULT = 45;
public static final int AVERAGING_MINIMUM = 1;
public static final int AVERAGING_MAXIMUM = 4;
public static final int AVERAGING_DEFAULT = 2;
//Percentile of the bins used as the noise floor reference. Robust to signals in up to 75% of the bins.
static final double FLOOR_PERCENTILE = 0.25;
//Smoothing applied to the floor reference each row: about 5 rows. The percentile barely varies from row to row,
//so this mostly limits jumps from bursts of signals while still following tuner gain changes quickly.
static final float FLOOR_SMOOTHING = 0.2f;
//Floor reference changes larger than this jump straight to the new level instead of smoothing, for example when
//the first samples arrive after DFT frames of an empty buffer (-196 dB), or after a tuner or gain change.
static final float FLOOR_JUMP_DB = 10.0f;
//Level code resolution and the level code of the floor reference: codes cover -8 dB to +94 dB from the floor,
//which covers the palette at the maximum range.
static final float LEVEL_STEP_DB = 0.4f;
static final int FLOOR_LEVEL = 20;
//Palette index for the floor reference. Noise bins spread above the 25th percentile, so this places the noise in
//the lower part of the palette as texture with only the weakest noise bins at the background color.
static final float FLOOR_INDEX = 16.0f;
private static final float DB_TO_LN_POWER = (float)(Math.log(10.0) / 10.0);
private float mFloor = Float.NaN;
private volatile boolean mResetRequested;
private volatile int mAveraging = AVERAGING_DEFAULT;
private float[] mScratch = new float[0];
private float[] mPowerSum = new float[0];
private float[] mAverage = new float[0];
private int mFrameCount;
/**
* Restarts floor tracking and frame averaging on the next frame, for example after the source changes. Safe to
* call from any thread.
*/
public void reset()
{
mResetRequested = true;
}
/**
* Sets the number of DFT frames averaged into each waterfall row. Safe to call from any thread.
* @param frames from AVERAGING_MINIMUM to AVERAGING_MAXIMUM
*/
public void setAveraging(int frames)
{
mAveraging = Math.max(AVERAGING_MINIMUM, Math.min(AVERAGING_MAXIMUM, frames));
}
/**
* Current noise floor reference in dB, or NaN before the first row.
*/
public float getFloor()
{
return mFloor;
}
/**
* Adds the DFT results to the current row.
* @param bins in dB
* @return the row of level codes (unsigned bytes) when the row is complete, otherwise null
*/
public byte[] process(float[] bins)
{
if(mResetRequested)
{
mResetRequested = false;
mFloor = Float.NaN;
mFrameCount = 0;
}
int frames = mAveraging;
if(frames <= 1 && mFrameCount == 0)
{
return levels(bins);
}
if(mPowerSum.length != bins.length)
{
mPowerSum = new float[bins.length];
mAverage = new float[bins.length];
mFrameCount = 0;
}
if(mFrameCount == 0)
{
Arrays.fill(mPowerSum, 0.0f);
}
for(int x = 0; x < bins.length; x++)
{
mPowerSum[x] += (float)Math.exp(bins[x] * DB_TO_LN_POWER);
}
mFrameCount++;
//The averaging can drop below the frames already summed - complete the row with what has been summed
if(mFrameCount < frames)
{
return null;
}
float scale = 1.0f / mFrameCount;
for(int x = 0; x < bins.length; x++)
{
mAverage[x] = (float)(10.0 * Math.log10(mPowerSum[x] * scale));
}
mFrameCount = 0;
return levels(mAverage);
}
/**
* Updates the floor reference and converts the bins to level codes.
*/
private byte[] levels(float[] bins)
{
float percentile = percentile(bins);
if(Float.isNaN(mFloor) || Float.isInfinite(mFloor) || Math.abs(percentile - mFloor) > FLOOR_JUMP_DB)
{
mFloor = percentile;
}
else
{
mFloor += (percentile - mFloor) * FLOOR_SMOOTHING;
}
byte[] row = new byte[bins.length];
float floor = mFloor;
for(int x = 0; x < bins.length; x++)
{
int level = Math.round((bins[x] - floor) / LEVEL_STEP_DB) + FLOOR_LEVEL;
row[x] = (byte)Math.max(0, Math.min(255, level));
}
return row;
}
/**
* Palette index for a level code.
* @param level code (0 - 255)
* @param range in dB from the noise floor reference to the top of the palette. Smaller ranges give weak signals
* more contrast against the noise and saturate strong signals sooner.
* @return palette index (0 - 255)
*/
public static int paletteIndex(int level, double range)
{
double db = (level - FLOOR_LEVEL) * LEVEL_STEP_DB;
long index = Math.round(db * (WaterfallPalette.SIZE - 1) / range + FLOOR_INDEX);
return (int)Math.max(0, Math.min(WaterfallPalette.SIZE - 1, index));
}
/**
* Floor reference percentile of the bins, using quickselect on a scratch copy.
*/
private float percentile(float[] bins)
{
if(mScratch.length != bins.length)
{
mScratch = new float[bins.length];
}
System.arraycopy(bins, 0, mScratch, 0, bins.length);
return select(mScratch, (int)(FLOOR_PERCENTILE * (bins.length - 1)));
}
/**
* Quickselect: the k-th smallest value, partially reordering the array.
*/
static float select(float[] values, int k)
{
int left = 0;
int right = values.length - 1;
while(left < right)
{
//Median of three pivot
int middle = (left + right) >>> 1;
if(values[middle] < values[left])
{
swap(values, middle, left);
}
if(values[right] < values[left])
{
swap(values, right, left);
}
if(values[right] < values[middle])
{
swap(values, right, middle);
}
float pivot = values[middle];
int i = left;
int j = right;
while(i <= j)
{
while(values[i] < pivot)
{
i++;
}
while(values[j] > pivot)
{
j--;
}
if(i <= j)
{
swap(values, i, j);
i++;
j--;
}
}
if(k <= j)
{
right = j;
}
else if(k >= i)
{
left = i;
}
else
{
return values[k];
}
}
return values[k];
}
private static void swap(float[] values, int a, int b)
{
float temp = values[a];
values[a] = values[b];
values[b] = temp;
}
}

View File

@@ -52,6 +52,7 @@ public class DMRSoftSyncDetectorFactory
case VECTOR_SIMD_512:
return new DMRSoftSyncDetectorVector512();
case SCALAR:
case UNCALIBRATED:
default:
return new DMRSoftSyncDetectorScalar();
}

View File

@@ -51,6 +51,7 @@ public class NXDNSyncDetectorFactory
case VECTOR_SIMD_512:
return new NXDNSoftSyncDetectorVector512();
case SCALAR:
case UNCALIBRATED:
default:
return new NXDNSoftSyncDetectorScalar();
}

View File

@@ -52,6 +52,7 @@ public class P25P1SoftSyncDetectorFactory
case VECTOR_SIMD_512:
return new P25P1SoftSyncDetectorVector512();
case SCALAR:
case UNCALIBRATED:
default:
return new P25P1SoftSyncDetectorScalar();
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -23,50 +23,35 @@ import io.github.dsheirer.source.tuner.airspy.AirspyTunerController.Gain;
import io.github.dsheirer.source.tuner.airspy.AirspyTunerController.GainMode;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Region;
/**
* Airspy tuner editor/controller
* Airspy tuner editor
*/
public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfiguration>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(AirspyTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<AirspySampleRate> mSampleRateCombo;
private JComboBox<GainMode> mGainModeCombo;
private JSlider mMasterGainSlider;
private JLabel mMasterGainLabel;
private JLabel mMasterGainValueLabel;
private JSlider mIFGainSlider;
private JLabel mIFGainLabel;
private JLabel mIFGainValueLabel;
private JSlider mLNAGainSlider;
private JLabel mLNAGainValueLabel;
private JSlider mMixerGainSlider;
private JLabel mMixerGainValueLabel;
private JCheckBox mLNAAGCCheckBox;
private JCheckBox mMixerAGCCheckBox;
private JCheckBox mBiasTCheckBox;
private ComboBox<AirspySampleRate> mSampleRateCombo;
private ComboBox<GainMode> mGainModeCombo;
private GainSlider mMasterGainSlider;
private Label mMasterGainLabel;
private GainSlider mIFGainSlider;
private Label mIFGainLabel;
private GainSlider mLNAGainSlider;
private Label mLNAGainLabel;
private GainSlider mMixerGainSlider;
private Label mMixerGainLabel;
private CheckBox mLNAAGCCheckBox;
private CheckBox mMixerAGCCheckBox;
private CheckBox mBiasTCheckBox;
/**
* Constructs an instance
@@ -78,7 +63,7 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -93,125 +78,62 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return AirspyTunerController.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
TunerSection gain = addSection("Gain");
gain.addRow("Mode", getGainModeCombo());
mMasterGainLabel = gain.addRow("Master", getMasterGainSlider(), new Region());
mIFGainLabel = gain.addRow("IF", getIFGainSlider(), new Region());
mMixerGainLabel = gain.addRow("Mixer", getMixerGainSlider(), getMixerAGCCheckBox());
mLNAGainLabel = gain.addRow("LNA", getLNAGainSlider(), getLNAAGCCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getTunerInfoButton().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
getBiasTCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setSelected(hasTuner() && hasConfiguration() && getConfiguration().isBiasT());
updateGainComponents((hasTuner() && hasConfiguration()) ? getConfiguration().getGain() : null);
if(hasTuner())
{
List<AirspySampleRate> rates = getTuner().getController().getSampleRates();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new AirspySampleRate[rates.size()])));
getSampleRateCombo().getItems().setAll(rates);
if(hasConfiguration())
{
AirspySampleRate sampleRate = getSampleRate(getConfiguration().getSampleRate());
getSampleRateCombo().setSelectedItem(sampleRate);
getSampleRateCombo().setValue(getSampleRate(getConfiguration().getSampleRate()));
}
}
else
{
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
getSampleRateCombo().getItems().clear();
}
setLoading(false);
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel(""));
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Mode:"));
add(getGainModeCombo(), "wrap");
add(getMasterGainLabel());
add(getMasterGainSlider());
add(getMasterGainValueLabel());
add(getIFGainLabel());
add(getIFGainSlider());
add(getIFGainValueLabel());
add(getMixerAGCCheckBox());
add(getMixerGainSlider());
add(getMixerGainValueLabel());
add(getLNAAGCCheckBox());
add(getLNAGainSlider());
add(getLNAGainValueLabel());
updateSampleRateToolTip();
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private JCheckBox getBiasTCheckBox()
private CheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
{
try
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Bias-T", e1);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e1.getMessage());
}
save();
}
});
}
@@ -219,26 +141,19 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return mBiasTCheckBox;
}
private JCheckBox getLNAAGCCheckBox()
private CheckBox getLNAAGCCheckBox()
{
if(mLNAAGCCheckBox == null)
{
mLNAAGCCheckBox = new JCheckBox("AGC LNA:");
mLNAAGCCheckBox.setEnabled(false);
mLNAAGCCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
mLNAAGCCheckBox = new CheckBox("AGC");
mLNAAGCCheckBox.setTooltip(new Tooltip("Automatic LNA gain control"));
mLNAAGCCheckBox.setDisable(true);
mLNAAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("LNA AGC",
() -> getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected())))
{
try
{
getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected());
getLNAGainSlider().setEnabled(!getLNAAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting LNA AGC Enabled");
}
getLNAGainSlider().setDisable(getLNAAGCCheckBox().isSelected());
save();
}
});
}
@@ -246,26 +161,19 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return mLNAAGCCheckBox;
}
private JCheckBox getMixerAGCCheckBox()
private CheckBox getMixerAGCCheckBox()
{
if(mMixerAGCCheckBox == null)
{
mMixerAGCCheckBox = new JCheckBox("AGC Mixer:");
mMixerAGCCheckBox.setEnabled(false);
mMixerAGCCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
mMixerAGCCheckBox = new CheckBox("AGC");
mMixerAGCCheckBox.setTooltip(new Tooltip("Automatic mixer gain control"));
mMixerAGCCheckBox.setDisable(true);
mMixerAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("mixer AGC",
() -> getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected())))
{
try
{
getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected());
getMixerGainSlider().setEnabled(!getMixerAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Mixer AGC Enabled");
}
getMixerGainSlider().setDisable(getMixerAGCCheckBox().isSelected());
save();
}
});
}
@@ -273,93 +181,37 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return mMixerAGCCheckBox;
}
private JLabel getLNAGainValueLabel()
{
if(mLNAGainValueLabel == null)
{
mLNAGainValueLabel = new JLabel("0");
mLNAGainValueLabel.setEnabled(false);
}
return mLNAGainValueLabel;
}
private JSlider getLNAGainSlider()
private GainSlider getLNAGainSlider()
{
if(mLNAGainSlider == null)
{
mLNAGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.LNA_GAIN_MIN,
AirspyTunerController.LNA_GAIN_MAX, AirspyTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setEnabled(false);
mLNAGainSlider.setMajorTickSpacing(1);
mLNAGainSlider.setPaintTicks(true);
mLNAGainSlider.addChangeListener(event ->
{
int gain = mLNAGainSlider.getValue();
if(hasTuner() && !isLoading())
mLNAGainSlider = new GainSlider(AirspyTunerController.LNA_GAIN_MIN, AirspyTunerController.LNA_GAIN_MAX,
AirspyTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setDisable(true);
mLNAGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("LNA gain", () -> getTuner().getController().setLNAGain(gain)))
{
try
{
getTuner().getController().setLNAGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy LNA gain to:" + gain, e);
JOptionPane.showMessageDialog(mLNAGainSlider, "Couldn't set LNA gain value to " + gain);
}
save();
}
getLNAGainValueLabel().setText(String.valueOf(gain));
});
}
return mLNAGainSlider;
}
private JLabel getMixerGainValueLabel()
{
if(mMixerGainValueLabel == null)
{
mMixerGainValueLabel = new JLabel("0");
mMixerGainValueLabel.setEnabled(false);
}
return mMixerGainValueLabel;
}
private JSlider getMixerGainSlider()
private GainSlider getMixerGainSlider()
{
if(mMixerGainSlider == null)
{
mMixerGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.MIXER_GAIN_MIN,
mMixerGainSlider = new GainSlider(AirspyTunerController.MIXER_GAIN_MIN,
AirspyTunerController.MIXER_GAIN_MAX, AirspyTunerController.MIXER_GAIN_MIN);
mMixerGainSlider.setEnabled(false);
mMixerGainSlider.setMajorTickSpacing(1);
mMixerGainSlider.setPaintTicks(true);
mMixerGainSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent event)
mMixerGainSlider.setDisable(true);
mMixerGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("mixer gain", () -> getTuner().getController().setMixerGain(gain)))
{
int gain = mMixerGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy Mixer gain to:" + gain, e);
JOptionPane.showMessageDialog(mMixerGainSlider, "Couldn't set Mixer gain value to " + gain);
}
}
getMixerGainValueLabel().setText(String.valueOf(gain));
save();
}
});
}
@@ -367,134 +219,77 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return mMixerGainSlider;
}
private JLabel getIFGainLabel()
{
if(mIFGainLabel == null)
{
mIFGainLabel = new JLabel("IF:");
}
return mIFGainLabel;
}
private JLabel getIFGainValueLabel()
{
if(mIFGainValueLabel == null)
{
mIFGainValueLabel = new JLabel("0");
mIFGainValueLabel.setEnabled(false);
}
return mIFGainValueLabel;
}
private JSlider getIFGainSlider()
private GainSlider getIFGainSlider()
{
if(mIFGainSlider == null)
{
mIFGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.IF_GAIN_MIN,
AirspyTunerController.IF_GAIN_MAX, AirspyTunerController.IF_GAIN_MIN);
mIFGainSlider.setEnabled(false);
mIFGainSlider.setMajorTickSpacing(1);
mIFGainSlider.setPaintTicks(true);
mIFGainSlider.addChangeListener(event ->
{
int gain = mIFGainSlider.getValue();
if(hasTuner() && !isLoading())
mIFGainSlider = new GainSlider(AirspyTunerController.IF_GAIN_MIN, AirspyTunerController.IF_GAIN_MAX,
AirspyTunerController.IF_GAIN_MIN);
mIFGainSlider.setDisable(true);
mIFGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("IF gain", () -> getTuner().getController().setIFGain(gain)))
{
try
{
getTuner().getController().setIFGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy IF gain to:" + gain, e);
JOptionPane.showMessageDialog(mIFGainSlider, "Couldn't set IF gain value to " + gain);
}
save();
}
getIFGainValueLabel().setText(String.valueOf(gain));
});
}
return mIFGainSlider;
}
private JLabel getMasterGainLabel()
{
if(mMasterGainLabel == null)
{
mMasterGainLabel = new JLabel("Master:");
}
return mMasterGainLabel;
}
private JLabel getMasterGainValueLabel()
{
if(mMasterGainValueLabel == null)
{
mMasterGainValueLabel = new JLabel("0");
mMasterGainValueLabel.setEnabled(false);
}
return mMasterGainValueLabel;
}
private JSlider getMasterGainSlider()
private GainSlider getMasterGainSlider()
{
if(mMasterGainSlider == null)
{
mMasterGainSlider = new JSlider(JSlider.HORIZONTAL, AirspyTunerController.GAIN_MIN,
AirspyTunerController.GAIN_MAX, AirspyTunerController.GAIN_MIN);
mMasterGainSlider.setEnabled(false);
mMasterGainSlider.setMajorTickSpacing(1);
mMasterGainSlider.setPaintTicks(true);
mMasterGainSlider = new GainSlider(AirspyTunerController.GAIN_MIN, AirspyTunerController.GAIN_MAX,
AirspyTunerController.GAIN_MIN);
mMasterGainSlider.setDisable(true);
mMasterGainSlider.setOnChange(value -> {
Gain gain = Gain.getGain(getGainModeCombo().getValue(), value);
mMasterGainSlider.addChangeListener(event ->
{
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = mMasterGainSlider.getValue();
Gain gain = Gain.getGain(mode, value);
if(hasTuner() && !isLoading())
if(hasTuner() && !isLoading() && applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set airspy gain to:" + gain.name(), e);
JOptionPane.showMessageDialog(mMasterGainSlider, "Couldn't set gain value to " +
gain.getValue());
}
save();
}
getMasterGainValueLabel().setText(String.valueOf(value));
});
}
return mMasterGainSlider;
}
private JComboBox<GainMode> getGainModeCombo()
private ComboBox<GainMode> getGainModeCombo()
{
if(mGainModeCombo == null)
{
mGainModeCombo = new JComboBox<>(GainMode.values());
mGainModeCombo.setEnabled(false);
mGainModeCombo.addActionListener(e ->
{
mGainModeCombo = new ComboBox<>(FXCollections.observableArrayList(GainMode.values()));
mGainModeCombo.setMaxWidth(Double.MAX_VALUE);
mGainModeCombo.setDisable(true);
mGainModeCombo.setTooltip(new Tooltip("Linearity and sensitivity modes set all gains from the master " +
"gain. Custom mode sets each gain separately."));
mGainModeCombo.setOnAction(e -> {
if(hasTuner() && !isLoading())
{
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = getMasterGainSlider().getValue();
Gain gain = Gain.getGain(mode, value);
Gain gain = Gain.getGain(mGainModeCombo.getValue(), getMasterGainSlider().getValue());
setLoading(true);
updateGainComponents(gain);
setLoading(false);
applyToTuner("gain mode", () -> {
AirspyTunerController controller = getTuner().getController();
if(gain == Gain.CUSTOM)
{
controller.setMixerAGC(getMixerAGCCheckBox().isSelected());
controller.setLNAAGC(getLNAAGCCheckBox().isSelected());
controller.setIFGain(getIFGainSlider().getValue());
controller.setMixerGain(getMixerGainSlider().getValue());
controller.setLNAGain(getLNAGainSlider().getValue());
}
else
{
controller.setGain(gain);
}
});
save();
}
});
@@ -503,37 +298,23 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
return mGainModeCombo;
}
private JComboBox<AirspySampleRate> getSampleRateCombo()
private ComboBox<AirspySampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
AirspySampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(rate)))
{
if(hasTuner() && !isLoading())
{
AirspySampleRate rate = (AirspySampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(AirspyTunerEditor.this,
"Couldn't set sample rate to " + rate.getLabel());
mLog.error("Error setting airspy sample rate", e1);
}
}
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
});
}
@@ -542,48 +323,29 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
}
/**
* Hyperlink button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(AirspyTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
/**
* Updates the enabled state of each of the gain controls according to the
* specified gain mode. The master gain control is enabled for linearity
* and sensitivity and the individual gain controls are disabled, and
* vice-versa for custom mode.
* Updates the enabled state of each of the gain controls according to the specified gain mode. The master gain
* control is enabled for linearity and sensitivity and the individual gain controls are disabled, and vice-versa
* for custom mode.
*/
private void updateGainComponents(Gain gain)
{
if(hasTuner() && gain != null)
{
boolean isCustom = gain.equals(Gain.CUSTOM);
getGainModeCombo().setEnabled(true);
getGainModeCombo().setSelectedItem(gain.getGainMode());
getMasterGainLabel().setEnabled(!isCustom);
getMasterGainSlider().setEnabled(!isCustom);
getGainModeCombo().setDisable(false);
getGainModeCombo().setValue(gain.getGainMode());
mMasterGainLabel.setDisable(isCustom);
getMasterGainSlider().setDisable(isCustom);
getMasterGainSlider().setValue(gain.getValue());
getMasterGainValueLabel().setEnabled(!isCustom);
getIFGainLabel().setEnabled(isCustom);
getIFGainSlider().setEnabled(isCustom);
getIFGainValueLabel().setEnabled(isCustom);
getLNAAGCCheckBox().setEnabled(isCustom);
getLNAGainSlider().setEnabled(isCustom && !getConfiguration().isLNAAGC());
getLNAGainValueLabel().setEnabled(isCustom);
getMixerAGCCheckBox().setEnabled(isCustom);
getMixerGainSlider().setEnabled(isCustom && !getConfiguration().isMixerAGC());
getMixerGainValueLabel().setEnabled(isCustom);
mIFGainLabel.setDisable(!isCustom);
getIFGainSlider().setDisable(!isCustom);
mLNAGainLabel.setDisable(!isCustom);
getLNAAGCCheckBox().setDisable(!isCustom);
getLNAGainSlider().setDisable(!isCustom || getConfiguration().isLNAAGC());
mMixerGainLabel.setDisable(!isCustom);
getMixerAGCCheckBox().setDisable(!isCustom);
getMixerGainSlider().setDisable(!isCustom || getConfiguration().isMixerAGC());
if(isCustom)
{
getIFGainSlider().setValue(getConfiguration().getIFGain());
@@ -603,25 +365,23 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
}
else
{
getGainModeCombo().setEnabled(false);
getMasterGainLabel().setEnabled(false);
getMasterGainSlider().setEnabled(false);
getGainModeCombo().setDisable(true);
mMasterGainLabel.setDisable(true);
getMasterGainSlider().setDisable(true);
getMasterGainSlider().setValue(0);
getMasterGainValueLabel().setEnabled(false);
getIFGainLabel().setEnabled(false);
getIFGainSlider().setEnabled(false);
mIFGainLabel.setDisable(true);
getIFGainSlider().setDisable(true);
getIFGainSlider().setValue(0);
getIFGainValueLabel().setEnabled(false);
getLNAAGCCheckBox().setEnabled(false);
mLNAGainLabel.setDisable(true);
getLNAAGCCheckBox().setDisable(true);
getLNAAGCCheckBox().setSelected(false);
getLNAGainSlider().setEnabled(false);
getLNAGainSlider().setDisable(true);
getLNAGainSlider().setValue(0);
getLNAGainValueLabel().setEnabled(false);
getMixerAGCCheckBox().setEnabled(false);
mMixerGainLabel.setDisable(true);
getMixerAGCCheckBox().setDisable(true);
getMixerAGCCheckBox().setSelected(false);
getMixerGainSlider().setEnabled(false);
getMixerGainSlider().setDisable(true);
getMixerGainSlider().setValue(0);
getMixerGainValueLabel().setEnabled(false);
}
}
@@ -630,21 +390,21 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate(((AirspySampleRate)getSampleRateCombo().getSelectedItem()).getRate());
Gain gain = Gain.getGain((GainMode)mGainModeCombo.getSelectedItem(), getMasterGainSlider().getValue());
getConfiguration().setGain(gain);
getConfiguration().setIFGain(getIFGainSlider().getValue());
getConfiguration().setMixerGain(getMixerGainSlider().getValue());
getConfiguration().setLNAGain(getLNAGainSlider().getValue());
getConfiguration().setMixerAGC(getMixerAGCCheckBox().isSelected());
getConfiguration().setLNAAGC(getLNAAGCCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
AirspyTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
if(getSampleRateCombo().getValue() != null)
{
config.setSampleRate(getSampleRateCombo().getValue().getRate());
}
config.setGain(Gain.getGain(getGainModeCombo().getValue(), getMasterGainSlider().getValue()));
config.setIFGain(getIFGainSlider().getValue());
config.setMixerGain(getMixerGainSlider().getValue());
config.setLNAGain(getLNAGainSlider().getValue());
config.setMixerAGC(getMixerAGCCheckBox().isSelected());
config.setLNAAGC(getLNAAGCCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
@@ -668,7 +428,7 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
}
}
if(rates.size() > 0)
if(!rates.isEmpty())
{
return rates.get(0);
}
@@ -684,56 +444,32 @@ public class AirspyTunerEditor extends TunerEditor<AirspyTuner, AirspyTunerConfi
{
if(hasTuner() && getTuner().getController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
}
else
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
}
}
@Override
public void setTunerLockState(boolean locked)
protected void tunerLockStateUpdated(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setDisable(!hasTuner() || locked);
updateSampleRateToolTip();
}
private String getTunerInfo()
@Override
protected String getTunerInfo()
{
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
{
return getDiscoveredTuner().getErrorMessage();
}
if(hasTuner())
{
StringBuilder sb = new StringBuilder();
AirspyDeviceInformation info = getTuner().getController().getDeviceInfo();
sb.append("<html><h3>Airspy Tuner</h3>");
sb.append("<b>Serial: </b>");
sb.append(info.getSerialNumber());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
String[] firmware = info.getVersion().split(" ");
sb.append(firmware.length > 1 ? firmware[0] : info.getVersion());
sb.append("<br>");
sb.append("<b>Part: </b>");
sb.append(info.getPartNumber());
sb.append("<br>");
sb.append("<b>Board: </b>");
sb.append(info.getBoardName());
sb.append("<br>");
return sb.toString();
}
return null;
StringBuilder sb = new StringBuilder();
AirspyDeviceInformation info = getTuner().getController().getDeviceInfo();
sb.append("<html><h3>Airspy Tuner</h3>");
sb.append("<b>Serial: </b>").append(info.getSerialNumber()).append("<br>");
String[] firmware = info.getVersion().split(" ");
sb.append("<b>Firmware: </b>").append(firmware.length > 1 ? firmware[0] : info.getVersion()).append("<br>");
sb.append("<b>Part: </b>").append(info.getPartNumber()).append("<br>");
sb.append("<b>Board: </b>").append(info.getBoardName()).append("<br>");
return sb.toString();
}
}
}

View File

@@ -16,50 +16,40 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.airspy.hf;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
/**
* Tuner editor for Airspy HF+/Discovery tuners
* Airspy HF+ tuner editor
*/
public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(AirspyHfTunerEditor.class);
private JComboBox<AirspyHfSampleRate> mSampleRateCombo;
private JComboBox<Attenuation> mAttenuationCombo;
private JToggleButton mAgcToggleButton;
private JToggleButton mLnaToggleButton;
private JToggleButton mBiasTToggleButton;
private ComboBox<AirspyHfSampleRate> mSampleRateCombo;
private ComboBox<Attenuation> mAttenuationCombo;
private CheckBox mAgcCheckBox;
private CheckBox mLnaCheckBox;
private CheckBox mBiasTCheckBox;
/**
* Constructs an instance
*
* @param userPreferences
* @param tunerManager for requesting configuration saves.
* @param discoveredTuner
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
*/
public AirspyHfTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -76,61 +66,41 @@ public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTuner
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][grow]"));
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
TunerSection gain = addSection("Gain");
gain.addRow("Attenuation", getAttenuationCombo(), getAgcCheckBox());
gain.addControl(getLnaCheckBox());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JSeparator(), "span");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new MigLayout("insets 0", "[left]", ""));
buttonPanel.add(getAgcToggleButton());
buttonPanel.add(getLnaToggleButton());
buttonPanel.add(getBiasTToggleButton());
add(new JLabel(" "));
add(buttonPanel, "wrap");
add(new JLabel("Attenuation:"));
add(getAttenuationCombo(), "wrap");
@Override
protected String getTunerInfo()
{
AirspyHfTunerController controller = getTuner().getController();
return "<html><h3>Airspy HF+ Tuner</h3>" +
"<b>Board: </b>" + controller.getBoardId() + "<br>" +
"<b>Serial: </b>" + controller.getSerialNumber() + "<br>" +
"<b>Firmware: </b>" + controller.getFirmwareVersion() + "<br>";
}
@Override
protected void save()
{
if(hasConfiguration() && !isLoading())
if(hasConfiguration() && hasTuner() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((int)getTuner().getController().getSampleRate());
AirspyHfTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setSampleRate((int)getTuner().getController().getSampleRate());
config.setAttenuation(getAttenuationCombo().getValue());
config.setAgc(getAgcCheckBox().isSelected());
config.setLna(getLnaCheckBox().isSelected());
Attenuation attenuation = (Attenuation)getAttenuationCombo().getSelectedItem();
getConfiguration().setAttenuation(attenuation);
getConfiguration().setAgc(getAgcToggleButton().isSelected());
getConfiguration().setLna(getLnaToggleButton().isSelected());
//Only update bias-T when the device supports it, so the saved setting isn't lost on unsupported firmware.
if(getTuner().getController().isBiasTSupported())
{
getConfiguration().setBiasT(getBiasTToggleButton().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
}
saveConfiguration();
@@ -140,123 +110,80 @@ public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTuner
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
if(hasTuner())
{
getTunerIdLabel().setText("Airspy " + getTuner().getController().getBoardId() + " SER# " +
getTuner().getController().getSerialNumber() + " FW " + getTuner().getController().getFirmwareVersion());
getSampleRateCombo().setEnabled(!getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().removeAllItems();
for(AirspyHfSampleRate sampleRate: getTuner().getController().getAvailableSampleRates())
{
getSampleRateCombo().addItem(sampleRate);
}
getAgcToggleButton().setEnabled(true);
getAgcToggleButton().setSelected(getTuner().getController().getAgc());
getLnaToggleButton().setEnabled(true);
getLnaToggleButton().setSelected(getTuner().getController().getLna());
boolean biasTSupported = getTuner().getController().isBiasTSupported();
getBiasTToggleButton().setEnabled(biasTSupported);
getBiasTToggleButton().setSelected(biasTSupported && getTuner().getController().getBiasT());
getBiasTToggleButton().setToolTipText(biasTSupported ? "Enable Bias-T power output for active antennas" :
"Bias-T not supported by this device or firmware");
getSampleRateCombo().setSelectedItem(getTuner().getController().getCurrentAirspySampleRate());
getAttenuationCombo().setEnabled(!getTuner().getController().getAgc());
getAttenuationCombo().setSelectedItem(getTuner().getController().getAttenuation());
AirspyHfTunerController controller = getTuner().getController();
getSampleRateCombo().setDisable(controller.isLockedSampleRate());
getSampleRateCombo().getItems().setAll(controller.getAvailableSampleRates());
getSampleRateCombo().setValue(controller.getCurrentAirspySampleRate());
getAgcCheckBox().setDisable(false);
getAgcCheckBox().setSelected(controller.getAgc());
getLnaCheckBox().setDisable(false);
getLnaCheckBox().setSelected(controller.getLna());
boolean biasTSupported = controller.isBiasTSupported();
getBiasTCheckBox().setDisable(!biasTSupported);
getBiasTCheckBox().setSelected(biasTSupported && controller.getBiasT());
getBiasTCheckBox().setTooltip(new Tooltip(biasTSupported ? "Enable Bias-T power output for active " +
"antennas" : "Bias-T not supported by this device or firmware"));
getAttenuationCombo().setDisable(controller.getAgc());
getAttenuationCombo().setValue(controller.getAttenuation());
}
else
{
getTunerIdLabel().setText("Airspy HF+");
getAgcToggleButton().setEnabled(false);
getAgcToggleButton().setSelected(false);
getLnaToggleButton().setEnabled(false);
getLnaToggleButton().setSelected(false);
getBiasTToggleButton().setEnabled(false);
getBiasTToggleButton().setSelected(false);
getBiasTToggleButton().setToolTipText("No tuner available");
getSampleRateCombo().setEnabled(false);
getAttenuationCombo().setEnabled(false);
getAttenuationCombo().setSelectedItem(Attenuation.A0);
getAgcCheckBox().setDisable(true);
getAgcCheckBox().setSelected(false);
getLnaCheckBox().setDisable(true);
getLnaCheckBox().setSelected(false);
getBiasTCheckBox().setDisable(true);
getBiasTCheckBox().setSelected(false);
getBiasTCheckBox().setTooltip(new Tooltip("No tuner available"));
getSampleRateCombo().setDisable(true);
getAttenuationCombo().setDisable(true);
getAttenuationCombo().setValue(Attenuation.A0);
}
updateSampleRateToolTip();
setLoading(false);
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
getSampleRateCombo().setTooltip(new Tooltip("No tuner available"));
}
}
@Override
public void setTunerLockState(boolean locked)
protected void tunerLockStateUpdated(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setDisable(!hasTuner() || locked);
updateSampleRateToolTip();
}
/**
* Sample rate combo for selecting among available sample rates.
* @return sample rate combo
*/
private JComboBox<AirspyHfSampleRate> getSampleRateCombo()
private ComboBox<AirspyHfSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e ->
{
if(!isLoading())
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
AirspyHfSampleRate sampleRate = mSampleRateCombo.getValue();
if(!isLoading() && hasTuner() && sampleRate != null &&
applyToTuner("sample rate [" + sampleRate + "]",
() -> getTuner().getController().setSampleRate(sampleRate)))
{
AirspyHfSampleRate sampleRate = (AirspyHfSampleRate)mSampleRateCombo.getSelectedItem();
if(sampleRate != null)
{
try
{
getTuner().getController().setSampleRate(sampleRate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(sampleRate.getSampleRate());
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy Hf Sample Rate [" + sampleRate + "]", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy Tuner Controller - couldn't apply the sample rate setting [" +
sampleRate + "] " + se.getLocalizedMessage());
}
}
adjustForSampleRate(sampleRate.getSampleRate());
save();
}
});
}
@@ -264,33 +191,22 @@ public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTuner
return mSampleRateCombo;
}
/**
* Combobox with available attenuation items
* @return combo box
*/
private JComboBox<Attenuation> getAttenuationCombo()
private ComboBox<Attenuation> getAttenuationCombo()
{
if(mAttenuationCombo == null)
{
mAttenuationCombo = new JComboBox<>(Attenuation.values());
mAttenuationCombo.setToolTipText("Attenuation applies when the AGC is off");
mAttenuationCombo.setEnabled(false);
mAttenuationCombo.addActionListener(e -> {
if(!isLoading())
mAttenuationCombo = new ComboBox<>(FXCollections.observableArrayList(Attenuation.values()));
mAttenuationCombo.setMaxWidth(Double.MAX_VALUE);
mAttenuationCombo.setTooltip(new Tooltip("Attenuation applies when the AGC is off"));
mAttenuationCombo.setDisable(true);
mAttenuationCombo.setOnAction(e -> {
Attenuation selected = mAttenuationCombo.getValue();
if(!isLoading() && hasTuner() && selected != null &&
applyToTuner("attenuation [" + selected + "]",
() -> getTuner().getController().setAttenuation(selected)))
{
Attenuation selected = (Attenuation)mAttenuationCombo.getSelectedItem();
try
{
getTuner().getController().setAttenuation(selected);
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy Hf attenuation [" + selected + "]", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy Tuner Controller - couldn't apply attenuation setting [" +
selected + "] " + se.getLocalizedMessage());
}
save();
}
});
}
@@ -298,98 +214,67 @@ public class AirspyHfTunerEditor extends TunerEditor<AirspyHfTuner,AirspyHfTuner
return mAttenuationCombo;
}
/**
* Automatic Gain Control (AGC) toggle button
*/
private JToggleButton getAgcToggleButton()
private CheckBox getAgcCheckBox()
{
if(mAgcToggleButton == null)
if(mAgcCheckBox == null)
{
mAgcToggleButton = new JToggleButton("AGC");
mAgcToggleButton.setToolTipText("Automatic Gain Control");
mAgcToggleButton.setEnabled(false);
mAgcToggleButton.addActionListener(e -> {
if(!isLoading())
mAgcCheckBox = new CheckBox("AGC");
mAgcCheckBox.setTooltip(new Tooltip("Automatic gain control"));
mAgcCheckBox.setDisable(true);
mAgcCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() &&
applyToTuner("AGC", () -> getTuner().getController().setAgc(mAgcCheckBox.isSelected())))
{
try
{
getTuner().getController().setAgc(mAgcToggleButton.isSelected());
getAttenuationCombo().setEnabled(!mAgcToggleButton.isSelected());
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy HF AGC", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy HF Tuner Controller - couldn't change AGC setting" + se.getLocalizedMessage());
}
getAttenuationCombo().setDisable(mAgcCheckBox.isSelected());
save();
}
});
}
return mAgcToggleButton;
return mAgcCheckBox;
}
/**
* Low Noise Amplifier (LNA) toggle button
*/
private JToggleButton getLnaToggleButton()
private CheckBox getLnaCheckBox()
{
if(mLnaToggleButton == null)
if(mLnaCheckBox == null)
{
mLnaToggleButton = new JToggleButton("LNA");
mLnaToggleButton.setToolTipText("Low Noise Amplifier");
mLnaToggleButton.setEnabled(false);
mLnaToggleButton.addActionListener(e -> {
if(!isLoading())
mLnaCheckBox = new CheckBox("LNA (low noise amplifier)");
mLnaCheckBox.setTooltip(new Tooltip("Turn on the low noise amplifier"));
mLnaCheckBox.setDisable(true);
mLnaCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() &&
applyToTuner("LNA", () -> getTuner().getController().setLna(mLnaCheckBox.isSelected())))
{
try
{
getTuner().getController().setLna(mLnaToggleButton.isSelected());
save();
}
catch(SourceException se)
{
mLog.error("Error setting Airspy HF LNA", se);
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy HF Tuner Controller - couldn't change LNA setting" + se.getLocalizedMessage());
}
save();
}
});
}
return mLnaToggleButton;
return mLnaCheckBox;
}
/**
* Bias-T toggle button, enabled only when the device firmware supports a bias-T.
*/
private JToggleButton getBiasTToggleButton()
private CheckBox getBiasTCheckBox()
{
if(mBiasTToggleButton == null)
if(mBiasTCheckBox == null)
{
mBiasTToggleButton = new JToggleButton("Bias-T");
mBiasTToggleButton.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTToggleButton.setEnabled(false);
mBiasTToggleButton.addActionListener(e -> {
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading())
{
try
if(applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
{
getTuner().getController().setBiasT(mBiasTToggleButton.isSelected());
save();
}
catch(SourceException se)
else
{
mLog.error("Error setting Airspy HF Bias-T", se);
mBiasTToggleButton.setSelected(getTuner().getController().getBiasT());
JOptionPane.showMessageDialog(AirspyHfTunerEditor.this,
"Airspy HF Tuner Controller - couldn't change Bias-T setting " + se.getLocalizedMessage());
mBiasTCheckBox.setSelected(getTuner().getController().getBiasT());
}
}
});
}
return mBiasTToggleButton;
return mBiasTCheckBox;
}
}

View File

@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.bladerf;
import io.github.dsheirer.bladerf.GainMode;
@@ -25,41 +24,26 @@ import io.github.dsheirer.bladerf.Range;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import java.awt.Component;
import java.io.Serial;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.util.StringConverter;
/**
* bladeRF tuner editor
* bladeRF tuner editor. sdrtrunk uses the RX1 connector as a single tuner.
*/
public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerConfiguration>
{
@Serial
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(BladeRfTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<BladeRfSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JComboBox<GainModeInfo> mGainModeCombo;
private JSlider mGainSlider;
private JLabel mGainValueLabel;
private ComboBox<BladeRfSampleRate> mSampleRateCombo;
private CheckBox mBiasTCheckBox;
private ComboBox<GainModeInfo> mGainModeCombo;
private GainSlider mGainSlider;
private Label mGainLabel;
/**
* Constructs an instance
@@ -71,7 +55,7 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -90,78 +74,33 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]", "[][][][][][][][][][][][grow]"));
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
TunerSection gain = addSection("Gain");
gain.addRow("Mode", getGainModeCombo());
mGainLabel = gain.addRow("Gain", getGainSlider());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Mode:"));
add(getGainModeCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainSlider());
add(getGainValueLabel());
//Empty row that takes all extra vertical space so that the controls stay stacked at the top of the editor.
add(new JLabel(), "span,pushy");
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
boolean started = hasStartedTuner();
getTunerIdLabel().setText(started ? getTuner().getPreferredName() : getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(started);
if(started)
if(hasStartedTuner())
{
BladeRfTunerController controller = getTuner().getController();
List<BladeRfSampleRate> rates = controller.getSampleRates();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new BladeRfSampleRate[0])));
getSampleRateCombo().setSelectedItem(controller.getBladeRfSampleRate());
getSampleRateCombo().setEnabled(!controller.isLockedSampleRate());
getSampleRateCombo().getItems().setAll(rates);
getSampleRateCombo().setValue(controller.getBladeRfSampleRate());
getSampleRateCombo().setDisable(controller.isLockedSampleRate());
getBiasTCheckBox().setVisible(controller.isBiasTSupported());
getBiasTCheckBox().setEnabled(true);
getBiasTCheckBox().setDisable(false);
List<GainModeInfo> modes = controller.getGainModes();
getGainModeCombo().setModel(new DefaultComboBoxModel<>(modes.toArray(new GainModeInfo[0])));
getGainModeCombo().setEnabled(true);
getGainModeCombo().getItems().setAll(modes);
getGainModeCombo().setDisable(false);
Range range = controller.getGainRange();
getGainSlider().setMinimum((int)range.min());
getGainSlider().setMaximum((int)range.max());
getGainSlider().setRange((int)range.min(), (int)range.max());
if(hasConfiguration())
{
@@ -172,7 +111,7 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
{
if(mode.mode() == getConfiguration().getGainMode())
{
getGainModeCombo().setSelectedItem(mode);
getGainModeCombo().setValue(mode);
}
}
}
@@ -181,81 +120,50 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
}
else
{
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
getSampleRateCombo().setEnabled(false);
getBiasTCheckBox().setEnabled(false);
getSampleRateCombo().getItems().clear();
getSampleRateCombo().setDisable(true);
getBiasTCheckBox().setDisable(true);
getBiasTCheckBox().setSelected(false);
getGainModeCombo().setModel(new DefaultComboBoxModel<>());
getGainModeCombo().setEnabled(false);
getGainSlider().setEnabled(false);
getGainValueLabel().setEnabled(false);
getGainModeCombo().getItems().clear();
getGainModeCombo().setDisable(true);
getGainSlider().setDisable(true);
mGainLabel.setDisable(true);
}
setLoading(false);
}
/**
* Indicates if the tuner has finished starting, since a status update can arrive while it's starting or restarting.
* Indicates if the tuner is started, which is when the controller has the gain range.
*/
private boolean hasStartedTuner()
{
return hasTuner() && getTuner().getController().getGainRange() != null;
}
/**
* Enables the gain slider when the gain mode is manual and refreshes the gain value label.
*/
private void updateGainControls()
{
GainModeInfo mode = (GainModeInfo)getGainModeCombo().getSelectedItem();
GainModeInfo mode = getGainModeCombo().getValue();
boolean manual = hasTuner() && mode != null && mode.mode() == GainMode.MANUAL;
getGainSlider().setEnabled(manual);
getGainValueLabel().setEnabled(manual);
getGainValueLabel().setText(manual ? getGainSlider().getValue() + " dB" : "AGC");
getGainSlider().setDisable(!manual);
mGainLabel.setDisable(!manual);
getGainSlider().setFormatter(value -> manual ? value + " dB" : "AGC");
}
/**
* Button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(_ -> JOptionPane.showMessageDialog(BladeRfTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private JComboBox<BladeRfSampleRate> getSampleRateCombo()
private ComboBox<BladeRfSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setTooltip(new Tooltip("Select a sample rate for the tuner"));
mSampleRateCombo.setOnAction(e -> {
BladeRfSampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate + "]", () -> getTuner().getController().setSampleRate(rate)))
{
BladeRfSampleRate rate = (BladeRfSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
mLog.error("Error setting bladeRF sample rate", e1);
JOptionPane.showMessageDialog(BladeRfTunerEditor.this, "Couldn't set sample rate to " + rate);
}
adjustForSampleRate(rate.getRate());
save();
}
});
}
@@ -263,30 +171,19 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
return mSampleRateCombo;
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private JCheckBox getBiasTCheckBox()
private CheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas. Also powers the RX2 connector.");
mBiasTCheckBox.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas. Also powers the " +
"RX2 connector."));
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
{
try
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Bias-T", e1);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e1.getMessage());
}
save();
}
});
}
@@ -294,39 +191,36 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
return mBiasTCheckBox;
}
private JComboBox<GainModeInfo> getGainModeCombo()
private ComboBox<GainModeInfo> getGainModeCombo()
{
if(mGainModeCombo == null)
{
mGainModeCombo = new JComboBox<>();
mGainModeCombo.setEnabled(false);
mGainModeCombo.setRenderer(new DefaultListCellRenderer()
mGainModeCombo = new ComboBox<>();
mGainModeCombo.setMaxWidth(Double.MAX_VALUE);
mGainModeCombo.setDisable(true);
mGainModeCombo.setConverter(new StringConverter<>()
{
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean selected,
boolean focused)
public String toString(GainModeInfo mode)
{
Object label = value instanceof GainModeInfo mode ? mode.name() : value;
return super.getListCellRendererComponent(list, label, index, selected, focused);
return mode == null ? "" : mode.name();
}
@Override
public GainModeInfo fromString(String text)
{
return null;
}
});
mGainModeCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
GainModeInfo mode = (GainModeInfo)mGainModeCombo.getSelectedItem();
mGainModeCombo.setOnAction(e -> {
GainModeInfo mode = mGainModeCombo.getValue();
try
{
getTuner().getController().setGainMode(mode.mode());
updateGainControls();
save();
}
catch(Exception e1)
{
mLog.error("Error setting bladeRF gain mode", e1);
JOptionPane.showMessageDialog(mGainModeCombo, "Couldn't set gain mode to " + mode.name());
}
if(hasTuner() && !isLoading() && mode != null &&
applyToTuner("gain mode [" + mode.name() + "]",
() -> getTuner().getController().setGainMode(mode.mode())))
{
updateGainControls();
save();
}
});
}
@@ -334,107 +228,73 @@ public class BladeRfTunerEditor extends TunerEditor<BladeRfTuner, BladeRfTunerCo
return mGainModeCombo;
}
private JSlider getGainSlider()
private GainSlider getGainSlider()
{
if(mGainSlider == null)
{
mGainSlider = new JSlider(JSlider.HORIZONTAL, 0, 60, BladeRfTunerController.GAIN_DEFAULT);
mGainSlider.setEnabled(false);
mGainSlider.setMajorTickSpacing(5);
mGainSlider.setPaintTicks(true);
mGainSlider.addChangeListener(_ ->
{
int gain = mGainSlider.getValue();
if(hasTuner() && !isLoading())
mGainSlider = new GainSlider(0, 60, BladeRfTunerController.GAIN_DEFAULT);
mGainSlider.setDisable(true);
mGainSlider.setFormatter(value -> value + " dB");
mGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set bladeRF gain to:" + gain, e);
JOptionPane.showMessageDialog(mGainSlider, "Couldn't set gain value to " + gain);
}
save();
}
updateGainControls();
});
}
return mGainSlider;
}
private JLabel getGainValueLabel()
{
if(mGainValueLabel == null)
{
mGainValueLabel = new JLabel("0 dB");
mGainValueLabel.setEnabled(false);
}
return mGainValueLabel;
}
@Override
public void save()
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel)getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
BladeRfTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
if(getSampleRateCombo().getSelectedItem() instanceof BladeRfSampleRate rate)
if(getSampleRateCombo().getValue() instanceof BladeRfSampleRate rate)
{
getConfiguration().setSampleRate(rate.getRate());
config.setSampleRate(rate.getRate());
}
if(getGainModeCombo().getSelectedItem() instanceof GainModeInfo mode)
if(getGainModeCombo().getValue() instanceof GainModeInfo mode)
{
getConfiguration().setGainMode(mode.mode());
config.setGainMode(mode.mode());
}
getConfiguration().setGain(getGainSlider().getValue());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
config.setGain(getGainSlider().getValue());
config.setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
@Override
public void setTunerLockState(boolean locked)
protected void tunerLockStateUpdated(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setToolTipText(locked ? "Sample Rate is locked. Disable decoding channels to unlock." :
"Select a sample rate for the tuner");
getSampleRateCombo().setDisable(!hasStartedTuner() || locked);
getSampleRateCombo().setTooltip(new Tooltip(locked ? "Sample rate is locked. Disable decoding channels " +
"to unlock." : "Select a sample rate for the tuner"));
}
private String getTunerInfo()
@Override
protected String getTunerInfo()
{
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
if(!hasStartedTuner())
{
return getDiscoveredTuner().getErrorMessage();
return null;
}
if(hasTuner())
{
BladeRfDeviceInformation info = getTuner().getController().getDeviceInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>bladeRF Tuner</h3>");
sb.append("<b>Serial: </b>").append(info.serial()).append("<br>");
sb.append("<b>Board: </b>").append(info.board()).append("<br>");
sb.append("<b>Firmware: </b>").append(info.firmware()).append("<br>");
sb.append("<b>FPGA: </b>").append(info.fpga()).append("<br>");
sb.append("<b>USB Speed: </b>").append(info.speed()).append("<br>");
return sb.toString();
}
return null;
BladeRfDeviceInformation info = getTuner().getController().getDeviceInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>bladeRF Tuner</h3>");
sb.append("<b>Serial: </b>").append(info.serial()).append("<br>");
sb.append("<b>Board: </b>").append(info.board()).append("<br>");
sb.append("<b>Firmware: </b>").append(info.firmware()).append("<br>");
sb.append("<b>FPGA: </b>").append(info.fpga()).append("<br>");
sb.append("<b>USB Speed: </b>").append(info.speed()).append("<br>");
return sb.toString();
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,7 +19,6 @@
package io.github.dsheirer.source.tuner.fcd.proV1;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.fcd.FCDTuner;
import io.github.dsheirer.source.tuner.fcd.proV1.FCD1TunerController.LNAEnhance;
import io.github.dsheirer.source.tuner.fcd.proV1.FCD1TunerController.LNAGain;
@@ -27,34 +26,24 @@ import io.github.dsheirer.source.tuner.fcd.proV1.FCD1TunerController.MixerGain;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import java.text.DecimalFormat;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.Tooltip;
import javafx.util.StringConverter;
/**
* Funcube Dongle Pro tuner editor
*/
public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(FCD1TunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<LNAGain> mLnaGainCombo;
private JComboBox<LNAEnhance> mLnaEnhanceCombo;
private JComboBox<MixerGain> mMixerGainCombo;
private JCheckBox mBiasTCheckBox;
private ComboBox<LNAGain> mLnaGainCombo;
private ComboBox<LNAEnhance> mLnaEnhanceCombo;
private ComboBox<MixerGain> mMixerGainCombo;
private CheckBox mBiasTCheckBox;
private CorrectionSpinner mCorrectionDCI;
private CorrectionSpinner mCorrectionDCQ;
private CorrectionSpinner mGainCorrectionSpinner;
@@ -63,14 +52,14 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param tunerManager to save configuration
* @param discoveredTuner to control
* @param tunerManager for saving tuner configuration
* @param discoveredTuner for the optionally usable tuner and controller
*/
public FCD1TunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
private FCD1TunerController getController()
@@ -95,120 +84,64 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
return FCD1TunerController.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private void init()
{
TunerSection gain = addSection("Gain");
gain.addRow("LNA", getLnaGainCombo());
gain.addRow("LNA Enhance", getLnaEnhanceCombo());
gain.addRow("Mixer", getMixerGainCombo());
TunerSection correction = addSection("I/Q Correction");
correction.addRow("DC Inphase", getDcCorrectionSpinnerI());
correction.addRow("DC Quadrature", getDcCorrectionSpinnerQ());
correction.addRow("Gain", getGainCorrectionSpinner());
correction.addRow("Phase", getPhaseCorrectionSpinner());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(hasTuner());
if(hasTuner() && hasConfiguration())
{
getMixerGainCombo().setSelectedItem(getConfiguration().getMixerGain());
getLnaEnhanceCombo().setSelectedItem(getConfiguration().getLNAEnhance());
getLnaGainCombo().setSelectedItem(getConfiguration().getLNAGain());
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
getDcCorrectionSpinnerI().setValue(getConfiguration().getInphaseDCCorrection());
getDcCorrectionSpinnerQ().setValue(getConfiguration().getQuadratureDCCorrection());
getPhaseCorrectionSpinner().setValue(getConfiguration().getGainCorrection());
getGainCorrectionSpinner().setValue(getConfiguration().getPhaseCorrection());
FCD1TunerConfiguration config = getConfiguration();
getMixerGainCombo().setValue(config.getMixerGain());
getLnaEnhanceCombo().setValue(config.getLNAEnhance());
getLnaGainCombo().setValue(config.getLNAGain());
getBiasTCheckBox().setSelected(config.isBiasT());
getDcCorrectionSpinnerI().setCorrection(config.getInphaseDCCorrection());
getDcCorrectionSpinnerQ().setCorrection(config.getQuadratureDCCorrection());
getGainCorrectionSpinner().setCorrection(config.getGainCorrection());
getPhaseCorrectionSpinner().setCorrection(config.getPhaseCorrection());
}
getMixerGainCombo().setEnabled(hasTuner());
getLnaEnhanceCombo().setEnabled(hasTuner());
getLnaGainCombo().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
getDcCorrectionSpinnerI().setEnabled(hasTuner());
getDcCorrectionSpinnerQ().setEnabled(hasTuner());
getPhaseCorrectionSpinner().setEnabled(hasTuner());
getGainCorrectionSpinner().setEnabled(hasTuner());
setLoading(false);
getMixerGainCombo().setDisable(!hasTuner());
getLnaEnhanceCombo().setDisable(!hasTuner());
getLnaGainCombo().setDisable(!hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
getDcCorrectionSpinnerI().setDisable(!hasTuner());
getDcCorrectionSpinnerQ().setDisable(!hasTuner());
getPhaseCorrectionSpinner().setDisable(!hasTuner());
getGainCorrectionSpinner().setDisable(!hasTuner());
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain"), "span,align center");
add(new JLabel("LNA:"));
add(getLnaGainCombo(), "wrap");
add(new JLabel("Enhance:"));
add(getLnaEnhanceCombo(), "wrap");
add(new JLabel("Mixer:"));
add(getMixerGainCombo(), "wrap");
add(new JLabel(""));
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Correction"), "span,align center");
add(new JLabel("DC Inphase:"));
add(getDcCorrectionSpinnerI(), "wrap");
add(new JLabel("DC Quadrature:"));
add(getDcCorrectionSpinnerQ(), "wrap");
add(new JLabel("Gain:"));
add(getGainCorrectionSpinner(), "wrap");
add(new JLabel("Phase:"));
add(getPhaseCorrectionSpinner(), "wrap");
}
public JComboBox getLnaGainCombo()
private ComboBox<LNAGain> getLnaGainCombo()
{
if(mLnaGainCombo == null)
{
mLnaGainCombo = new JComboBox<>(LNAGain.values());
mLnaGainCombo.setEnabled(false);
mLnaGainCombo.setToolTipText("Adjust the low noise amplifier gain setting.");
mLnaGainCombo.addActionListener(arg0 ->
{
if(!isLoading())
mLnaGainCombo = new ComboBox<>(FXCollections.observableArrayList(LNAGain.values()));
mLnaGainCombo.setMaxWidth(Double.MAX_VALUE);
mLnaGainCombo.setDisable(true);
mLnaGainCombo.setTooltip(new Tooltip("Adjust the low noise amplifier gain setting."));
mLnaGainCombo.setOnAction(e -> {
LNAGain gain = mLnaGainCombo.getValue();
if(!isLoading() && hasTuner() && gain != null &&
applyToTuner("LNA gain [" + gain + "]", () -> getController().setLNAGain(gain)))
{
LNAGain gain = (LNAGain) mLnaGainCombo.getSelectedItem();
try
{
getController().setLNAGain(gain);
save();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCD Pro Tuner " +
"Controller - error setting LNA gain [" + gain + "]");
mLog.error("FuncubeDonglePro Controller - error setting gain [" + gain + "]", e);
}
save();
}
});
}
@@ -216,30 +149,18 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
return mLnaGainCombo;
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
public JCheckBox getBiasTCheckBox()
private CheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(event ->
{
if(hasTuner() && !isLoading())
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(event -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getController().setBiasT(mBiasTCheckBox.isSelected())))
{
try
{
getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set bias-T for FCD Pro", e);
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "Couldn't set Bias-T: " + e.getMessage());
}
save();
}
});
}
@@ -247,31 +168,21 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
return mBiasTCheckBox;
}
public JComboBox getLnaEnhanceCombo()
private ComboBox<LNAEnhance> getLnaEnhanceCombo()
{
if(mLnaEnhanceCombo == null)
{
mLnaEnhanceCombo = new JComboBox<>(LNAEnhance.values());
mLnaEnhanceCombo.setEnabled(false);
mLnaEnhanceCombo.setToolTipText("Adjust the LNA enhance setting. Default value is OFF");
mLnaEnhanceCombo.addActionListener(arg0 ->
{
if(!isLoading())
mLnaEnhanceCombo = new ComboBox<>(FXCollections.observableArrayList(LNAEnhance.values()));
mLnaEnhanceCombo.setMaxWidth(Double.MAX_VALUE);
mLnaEnhanceCombo.setDisable(true);
mLnaEnhanceCombo.setTooltip(new Tooltip("Adjust the LNA enhance setting. Default value is OFF"));
mLnaEnhanceCombo.setOnAction(e -> {
LNAEnhance enhance = mLnaEnhanceCombo.getValue();
if(!isLoading() && hasTuner() && enhance != null &&
applyToTuner("LNA enhance [" + enhance + "]", () -> getController().setLNAEnhance(enhance)))
{
LNAEnhance enhance = (LNAEnhance) mLnaEnhanceCombo.getSelectedItem();
try
{
getController().setLNAEnhance(enhance);
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCD Pro Tuner"
+ " error setting LNA enhance gain [" + enhance + "]");
mLog.error("FCDPro - error setting LNA enhance [" + enhance + "]", e1);
}
save();
}
});
}
@@ -279,31 +190,21 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
return mLnaEnhanceCombo;
}
public JComboBox getMixerGainCombo()
private ComboBox<MixerGain> getMixerGainCombo()
{
if(mMixerGainCombo == null)
{
mMixerGainCombo = new JComboBox<>(MixerGain.values());
mMixerGainCombo.setEnabled(false);
mMixerGainCombo.setToolTipText("Adjust mixer gain setting");
mMixerGainCombo.addActionListener(arg0 ->
{
if(!isLoading())
mMixerGainCombo = new ComboBox<>(FXCollections.observableArrayList(MixerGain.values()));
mMixerGainCombo.setMaxWidth(Double.MAX_VALUE);
mMixerGainCombo.setDisable(true);
mMixerGainCombo.setTooltip(new Tooltip("Adjust mixer gain setting"));
mMixerGainCombo.setOnAction(e -> {
MixerGain gain = mMixerGainCombo.getValue();
if(!isLoading() && hasTuner() && gain != null &&
applyToTuner("mixer gain [" + gain + "]", () -> getController().setMixerGain(gain)))
{
MixerGain gain = (MixerGain) mMixerGainCombo.getSelectedItem();
try
{
getController().setMixerGain(gain);
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCDPro - error setting"
+ " mixer gain [" + gain + "]");
mLog.error("FCDPro - error setting mixer gain [" + gain + "]", e1);
}
save();
}
});
}
@@ -311,102 +212,60 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
return mMixerGainCombo;
}
public CorrectionSpinner getDcCorrectionSpinnerQ()
private CorrectionSpinner getDcCorrectionSpinnerQ()
{
if(mCorrectionDCQ == null)
{
mCorrectionDCQ = new CorrectionSpinner(Correction.DC_QUADRATURE, 0.0, 0.00001, 5);
mCorrectionDCQ.setEnabled(false);
mCorrectionDCQ.setToolTipText("DC Bias Correction/Quadrature Component: valid values are -1.0 to 1.0 (default: 0.0)");
mCorrectionDCQ = new CorrectionSpinner(Correction.DC_QUADRATURE);
mCorrectionDCQ.setTooltip(new Tooltip("DC bias correction, quadrature component: -1.0 to 1.0 (default: 0.0)"));
}
return mCorrectionDCQ;
}
public CorrectionSpinner getDcCorrectionSpinnerI()
private CorrectionSpinner getDcCorrectionSpinnerI()
{
if(mCorrectionDCI == null)
{
mCorrectionDCI = new CorrectionSpinner(Correction.DC_INPHASE, 0.0, 0.00001, 5);
mCorrectionDCI.setEnabled(false);
mCorrectionDCI.setToolTipText("DC Bias Correction/Inphase Component: valid values are -1.0 to 1.0 (default: 0.0)");
mCorrectionDCI = new CorrectionSpinner(Correction.DC_INPHASE);
mCorrectionDCI.setTooltip(new Tooltip("DC bias correction, inphase component: -1.0 to 1.0 (default: 0.0)"));
}
return mCorrectionDCI;
}
public CorrectionSpinner getGainCorrectionSpinner()
private CorrectionSpinner getGainCorrectionSpinner()
{
if(mGainCorrectionSpinner == null)
{
mGainCorrectionSpinner = new CorrectionSpinner(Correction.GAIN, 0.0, 0.00001, 5);
mGainCorrectionSpinner.setEnabled(false);
mGainCorrectionSpinner.setToolTipText("Gain Correction: valid values are -1.0 to 1.0 (default: 0.0)");
mGainCorrectionSpinner = new CorrectionSpinner(Correction.GAIN);
mGainCorrectionSpinner.setTooltip(new Tooltip("Gain correction: -1.0 to 1.0 (default: 0.0)"));
}
return mGainCorrectionSpinner;
}
public CorrectionSpinner getPhaseCorrectionSpinner()
private CorrectionSpinner getPhaseCorrectionSpinner()
{
if(mPhaseCorrectionSpinner == null)
{
mPhaseCorrectionSpinner = new CorrectionSpinner(Correction.PHASE, 0.0, 0.00001, 5);
mPhaseCorrectionSpinner.setEnabled(false);
mPhaseCorrectionSpinner.setToolTipText("Phase Correction: valid values are -1.0 to 1.0 (default: 0.0)");
mPhaseCorrectionSpinner = new CorrectionSpinner(Correction.PHASE);
mPhaseCorrectionSpinner.setTooltip(new Tooltip("Phase correction: -1.0 to 1.0 (default: 0.0)"));
}
return mPhaseCorrectionSpinner;
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
}
public JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Tuner Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(FCD1TunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private String getTunerInfo()
protected String getTunerInfo()
{
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>Funcube Dongle Pro Tuner</h3>");
if(hasTuner())
{
sb.append("<b>USB ID: </b>");
sb.append(getController().getUSBID());
sb.append("<br>");
sb.append("<b>USB Address: </b>");
sb.append(getController().getUSBAddress());
sb.append("<br>");
sb.append("<b>USB Speed: </b>");
sb.append(getController().getUSBSpeed());
sb.append("<br>");
sb.append("<b>Cellular Band: </b>");
sb.append(getController().getConfiguration().getBandBlocking());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
sb.append(getController().getConfiguration().getFirmware());
sb.append("<br>");
}
sb.append("<b>USB ID: </b>").append(getController().getUSBID()).append("<br>");
sb.append("<b>USB Address: </b>").append(getController().getUSBAddress()).append("<br>");
sb.append("<b>USB Speed: </b>").append(getController().getUSBSpeed()).append("<br>");
sb.append("<b>Cellular Band: </b>").append(getController().getConfiguration().getBandBlocking()).append("<br>");
sb.append("<b>Firmware: </b>").append(getController().getConfiguration().getFirmware()).append("<br>");
return sb.toString();
}
@@ -415,88 +274,95 @@ public class FCD1TunerEditor extends TunerEditor<FCDTuner,FCD1TunerConfiguration
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setLNAEnhance((LNAEnhance) mLnaEnhanceCombo.getSelectedItem());
getConfiguration().setLNAGain((LNAGain) mLnaGainCombo.getSelectedItem());
getConfiguration().setMixerGain((MixerGain) mMixerGainCombo.getSelectedItem());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
double dci = ((SpinnerNumberModel)mCorrectionDCI.getModel()).getNumber().doubleValue();
getConfiguration().setInphaseDCCorrection(dci);
double dcq = ((SpinnerNumberModel)mCorrectionDCQ.getModel()).getNumber().doubleValue();
getConfiguration().setQuadratureDCCorrection(dcq);
double gain = ((SpinnerNumberModel) mGainCorrectionSpinner.getModel()).getNumber().doubleValue();
getConfiguration().setGainCorrection(gain);
double phase = ((SpinnerNumberModel) mPhaseCorrectionSpinner.getModel()).getNumber().doubleValue();
getConfiguration().setPhaseCorrection(phase);
FCD1TunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setLNAEnhance(getLnaEnhanceCombo().getValue());
config.setLNAGain(getLnaGainCombo().getValue());
config.setMixerGain(getMixerGainCombo().getValue());
config.setBiasT(getBiasTCheckBox().isSelected());
config.setInphaseDCCorrection(getDcCorrectionSpinnerI().getCorrection());
config.setQuadratureDCCorrection(getDcCorrectionSpinnerQ().getCorrection());
config.setGainCorrection(getGainCorrectionSpinner().getCorrection());
config.setPhaseCorrection(getPhaseCorrectionSpinner().getCorrection());
saveConfiguration();
}
}
public enum Correction {GAIN, PHASE, DC_INPHASE, DC_QUADRATURE};
public enum Correction {GAIN, PHASE, DC_INPHASE, DC_QUADRATURE}
public class CorrectionSpinner extends JSpinner
/**
* Spinner for a correction value in the range -1.0 to 1.0 with five decimal places.
*/
public class CorrectionSpinner extends Spinner<Double>
{
private static final long serialVersionUID = 1L;
private static final double MIN_VALUE = -1.0d;
private static final double MAX_VALUE = 1.0d;
private final Correction mCorrectionComponent;
private Correction mCorrectionComponent;
public CorrectionSpinner(Correction component, double initialValue, double step, int decimalPlaces)
public CorrectionSpinner(Correction component)
{
mCorrectionComponent = component;
SpinnerModel model = new SpinnerNumberModel(initialValue, MIN_VALUE, MAX_VALUE, step);
setModel(model);
JSpinner.NumberEditor editor = (JSpinner.NumberEditor)getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits(decimalPlaces);
editor.getTextField().setHorizontalAlignment(SwingConstants.CENTER);
addChangeListener(e ->
SpinnerValueFactory.DoubleSpinnerValueFactory factory =
new SpinnerValueFactory.DoubleSpinnerValueFactory(MIN_VALUE, MAX_VALUE, 0.0, 0.00001);
factory.setConverter(new StringConverter<>()
{
if(!isLoading())
@Override
public String toString(Double value)
{
double value = ((SpinnerNumberModel)getModel()).getNumber().doubleValue();
return value == null ? "" : String.format("%.5f", value);
}
@Override
public Double fromString(String text)
{
try
{
switch(mCorrectionComponent)
{
case DC_INPHASE:
getController().setDCCorrectionInPhase(value);
break;
case DC_QUADRATURE:
getController().setDCCorrectionQuadrature(value);
break;
case GAIN:
getController().setGainCorrection(value);
break;
case PHASE:
getController().setPhaseCorrection(value);
break;
}
save();
return Double.parseDouble(text.trim().replace(',', '.'));
}
catch(Exception e1)
catch(Exception e)
{
JOptionPane.showMessageDialog(FCD1TunerEditor.this, "FCDPro - error "
+ "applying " + mCorrectionComponent.toString() + " correction value [" + value + "]");
mLog.error("FCDPro - error applying " + mCorrectionComponent.toString() + " correction value [" +
value + "]", e1);
return factory.getValue();
}
}
});
setValueFactory(factory);
setEditable(true);
setDisable(true);
setMaxWidth(Double.MAX_VALUE);
focusedProperty().addListener((observable, wasFocused, focused) -> {
if(!focused)
{
increment(0);
}
});
valueProperty().addListener((observable, oldValue, value) -> {
if(!isLoading() && hasTuner() && value != null &&
applyToTuner(mCorrectionComponent + " correction [" + value + "]", () -> apply(value)))
{
save();
}
});
}
private void apply(double value) throws Exception
{
switch(mCorrectionComponent)
{
case DC_INPHASE -> getController().setDCCorrectionInPhase(value);
case DC_QUADRATURE -> getController().setDCCorrectionQuadrature(value);
case GAIN -> getController().setGainCorrection(value);
case PHASE -> getController().setPhaseCorrection(value);
}
}
public void setCorrection(double value)
{
getValueFactory().setValue(value);
}
public double getCorrection()
{
return getValue() != null ? getValue() : 0.0;
}
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,46 +19,38 @@
package io.github.dsheirer.source.tuner.fcd.proplusV2;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.fcd.FCDTuner;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tooltip;
/**
* Funcube Dongle Pro Plus tuner editor
*/
public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguration>
{
private final static Logger mLog = LoggerFactory.getLogger(FCD2TunerEditor.class);
private static final long serialVersionUID = 1L;
private JButton mTunerInfoButton;
private JCheckBox mLnaGainCheckBox;
private JCheckBox mMixerGainCheckBox;
private JCheckBox mBiasTCheckBox;
private CheckBox mLnaGainCheckBox;
private CheckBox mMixerGainCheckBox;
private CheckBox mBiasTCheckBox;
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param tunerManager to save configuration
* @param discoveredTuner to control
* @param tunerManager for saving tuner configuration
* @param discoveredTuner for the optionally usable tuner and controller
*/
public FCD2TunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection gain = addSection("Gain");
gain.addControl(getLnaGainCheckBox());
gain.addControl(getMixerGainCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
refresh();
}
private FCD2TunerController getController()
@@ -86,29 +78,9 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(hasTuner());
getLnaGainCheckBox().setEnabled(hasTuner());
getMixerGainCheckBox().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
getLnaGainCheckBox().setDisable(!hasTuner());
getMixerGainCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
if(hasTuner() && hasConfiguration())
{
@@ -116,69 +88,19 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
getMixerGainCheckBox().setSelected(getConfiguration().getGainMixer());
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
}
setLoading(false);
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JSeparator(), "span,growx,push");
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new MigLayout("insets 0", "[left][left][left]", ""));
checkBoxPanel.add(getLnaGainCheckBox());
checkBoxPanel.add(getMixerGainCheckBox());
checkBoxPanel.add(getBiasTCheckBox());
add(checkBoxPanel, "span,align left");
}
public JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Tuner Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(FCD2TunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
public JCheckBox getLnaGainCheckBox()
private CheckBox getLnaGainCheckBox()
{
if(mLnaGainCheckBox == null)
{
mLnaGainCheckBox = new JCheckBox("LNA Gain");
mLnaGainCheckBox.setEnabled(false);
mLnaGainCheckBox.addActionListener(event ->
{
if(!isLoading())
mLnaGainCheckBox = new CheckBox("LNA gain");
mLnaGainCheckBox.setDisable(true);
mLnaGainCheckBox.setOnAction(event -> {
if(!isLoading() && hasTuner() && applyToTuner("LNA gain",
() -> getController().setLNAGain(getLnaGainCheckBox().isSelected())))
{
try
{
getController().setLNAGain(getLnaGainCheckBox().isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set LNA gain for FCD2", e);
}
save();
}
});
}
@@ -186,25 +108,17 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
return mLnaGainCheckBox;
}
public JCheckBox getMixerGainCheckBox()
private CheckBox getMixerGainCheckBox()
{
if(mMixerGainCheckBox == null)
{
mMixerGainCheckBox = new JCheckBox("Mixer Gain");
mMixerGainCheckBox.setEnabled(false);
mMixerGainCheckBox.addActionListener(event ->
{
if(!isLoading())
mMixerGainCheckBox = new CheckBox("Mixer gain");
mMixerGainCheckBox.setDisable(true);
mMixerGainCheckBox.setOnAction(event -> {
if(!isLoading() && hasTuner() && applyToTuner("mixer gain",
() -> getController().setMixerGain(getMixerGainCheckBox().isSelected())))
{
try
{
getController().setMixerGain(getMixerGainCheckBox().isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set mixer gain for FCD2", e);
}
save();
}
});
}
@@ -212,30 +126,18 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
return mMixerGainCheckBox;
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
public JCheckBox getBiasTCheckBox()
private CheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(event ->
{
if(hasTuner() && !isLoading())
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(event -> {
if(hasTuner() && !isLoading() && applyToTuner("Bias-T",
() -> getController().setBiasT(getBiasTCheckBox().isSelected())))
{
try
{
getController().setBiasT(getBiasTCheckBox().isSelected());
save();
}
catch(SourceException e)
{
mLog.error("Couldn't set bias-T for FCD2", e);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e.getMessage());
}
save();
}
});
}
@@ -244,40 +146,15 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
}
private String getTunerInfo()
protected String getTunerInfo()
{
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>Funcube Dongle Pro Plus Tuner</h3>");
if(hasTuner())
{
sb.append("<b>USB ID: </b>");
sb.append(getController().getUSBID());
sb.append("<br>");
sb.append("<b>USB Address: </b>");
sb.append(getController().getUSBAddress());
sb.append("<br>");
sb.append("<b>USB Speed: </b>");
sb.append(getController().getUSBSpeed());
sb.append("<br>");
sb.append("<b>Cellular Band: </b>");
sb.append(getController().getConfiguration().getBandBlocking());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
sb.append(getController().getConfiguration().getFirmware());
sb.append("<br>");
}
sb.append("<b>USB ID: </b>").append(getController().getUSBID()).append("<br>");
sb.append("<b>USB Address: </b>").append(getController().getUSBAddress()).append("<br>");
sb.append("<b>USB Speed: </b>").append(getController().getUSBSpeed()).append("<br>");
sb.append("<b>Cellular Band: </b>").append(getController().getConfiguration().getBandBlocking()).append("<br>");
sb.append("<b>Firmware: </b>").append(getController().getConfiguration().getFirmware()).append("<br>");
return sb.toString();
}
@@ -286,16 +163,12 @@ public class FCD2TunerEditor extends TunerEditor<FCDTuner, FCD2TunerConfiguratio
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setGainLNA(getLnaGainCheckBox().isSelected());
getConfiguration().setGainMixer(getMixerGainCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
FCD2TunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setGainLNA(getLnaGainCheckBox().isSelected());
config.setGainMixer(getMixerGainCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
}
}

View File

@@ -20,50 +20,43 @@ package io.github.dsheirer.source.tuner.hackrf;
import io.github.dsheirer.hackrf.HackRf;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.HackRFLNAGain;
import io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.HackRFSampleRate;
import io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.HackRFVGAGain;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
/**
* HackRF Tuner Editor
* HackRF tuner editor
*/
public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfiguration>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(HackRFTunerEditor.class);
private JButton mTunerInfo;
private JComboBox<HackRFSampleRate> mSampleRateCombo;
private JToggleButton mAmplifier;
private JToggleButton mBiasT;
private JComboBox<HackRFLNAGain> mLnaGainCombo;
private JComboBox<HackRFVGAGain> mVgaGainCombo;
private ComboBox<HackRFSampleRate> mSampleRateCombo;
private CheckBox mAmplifierCheckBox;
private CheckBox mBiasTCheckBox;
private ComboBox<HackRFLNAGain> mLnaGainCombo;
private ComboBox<HackRFVGAGain> mVgaGainCombo;
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param tunerManager to save configuration
* @param discoveredTuner to control
* @param tunerManager for saving tuner configuration
* @param discoveredTuner for the optionally usable HackRF tuner and controller
*/
public HackRFTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -80,116 +73,55 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][grow]"));
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
TunerSection gain = addSection("Gain");
gain.addRow("LNA", getLnaGainCombo());
gain.addRow("VGA", getVgaGainCombo());
gain.addControl(getAmplifierCheckBox());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"));
add(getAmplifierToggle(), "wrap");
add(new JLabel("LNA:"));
add(getLnaGainCombo(), "wrap");
add(new JLabel("VGA:"));
add(getVgaGainCombo(), "wrap");
add(new JLabel("Bias-T:"));
add(getBiasTToggle(), "wrap");
//Empty filler row that grows to take up the remaining vertical space
add(new JLabel(), "span,grow,push");
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
updateSampleRateToolTip();
getTunerInfoButton().setEnabled(hasTuner());
getAmplifierToggle().setEnabled(hasTuner());
getBiasTToggle().setEnabled(hasTuner());
getLnaGainCombo().setEnabled(hasTuner());
getVgaGainCombo().setEnabled(hasTuner());
getAmplifierCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
getLnaGainCombo().setDisable(!hasTuner());
getVgaGainCombo().setDisable(!hasTuner());
if(hasConfiguration())
{
getSampleRateCombo().setSelectedItem(getConfiguration().getSampleRate());
getAmplifierToggle().setSelected(getConfiguration().getAmplifierEnabled());
getBiasTToggle().setSelected(getConfiguration().isBiasT());
getLnaGainCombo().setSelectedItem(getConfiguration().getLNAGain());
getVgaGainCombo().setSelectedItem(getConfiguration().getVGAGain());
getSampleRateCombo().setValue(getConfiguration().getSampleRate());
getAmplifierCheckBox().setSelected(getConfiguration().getAmplifierEnabled());
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
getLnaGainCombo().setValue(getConfiguration().getLNAGain());
getVgaGainCombo().setValue(getConfiguration().getVGAGain());
}
setLoading(false);
}
private JComboBox getVgaGainCombo()
private ComboBox<HackRFVGAGain> getVgaGainCombo()
{
if(mVgaGainCombo == null)
{
mVgaGainCombo = new JComboBox<HackRFVGAGain>(HackRFVGAGain.values());
mVgaGainCombo.setToolTipText("<html>VGA Gain. Adjust to set the baseband gain</html>");
mVgaGainCombo.setEnabled(false);
mVgaGainCombo.addActionListener(arg0 ->
{
if(!isLoading())
mVgaGainCombo = new ComboBox<>(FXCollections.observableArrayList(HackRFVGAGain.values()));
mVgaGainCombo.setMaxWidth(Double.MAX_VALUE);
mVgaGainCombo.setTooltip(new Tooltip("VGA gain. Adjust to set the baseband gain"));
mVgaGainCombo.setDisable(true);
mVgaGainCombo.setOnAction(e -> {
if(!isLoading() && hasTuner())
{
try
HackRFVGAGain vgaGain = mVgaGainCombo.getValue() != null ? mVgaGainCombo.getValue() :
HackRFVGAGain.GAIN_16;
if(applyToTuner("VGA gain", () -> getTuner().getController().setVGAGain(vgaGain)))
{
HackRFVGAGain vgaGain = (HackRFVGAGain) mVgaGainCombo.getSelectedItem();
if(vgaGain == null)
{
vgaGain = HackRFVGAGain.GAIN_16;
}
getTuner().getController().setVGAGain(vgaGain);
save();
}
catch(SourceException e)
{
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "HackRF Tuner Controller"
+ " - couldn't apply the VGA gain setting - " + e.getLocalizedMessage());
mLog.error("HackRF Tuner Controller - couldn't apply VGA gain setting", e);
}
}
});
}
@@ -197,35 +129,24 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return mVgaGainCombo;
}
private JComboBox getLnaGainCombo()
private ComboBox<HackRFLNAGain> getLnaGainCombo()
{
if(mLnaGainCombo == null)
{
mLnaGainCombo = new JComboBox<HackRFLNAGain>(HackRFLNAGain.values());
mLnaGainCombo.setToolTipText("<html>LNA Gain. Adjust to set the IF gain</html>");
mLnaGainCombo.setEnabled(false);
mLnaGainCombo.addActionListener(arg0 ->
{
if(!isLoading())
mLnaGainCombo = new ComboBox<>(FXCollections.observableArrayList(HackRFLNAGain.values()));
mLnaGainCombo.setMaxWidth(Double.MAX_VALUE);
mLnaGainCombo.setTooltip(new Tooltip("LNA gain. Adjust to set the IF gain"));
mLnaGainCombo.setDisable(true);
mLnaGainCombo.setOnAction(e -> {
if(!isLoading() && hasTuner())
{
try
HackRFLNAGain lnaGain = mLnaGainCombo.getValue() != null ? mLnaGainCombo.getValue() :
HackRFLNAGain.GAIN_16;
if(applyToTuner("LNA gain", () -> getTuner().getController().setLNAGain(lnaGain)))
{
HackRFLNAGain lnaGain = (HackRFLNAGain) mLnaGainCombo.getSelectedItem();
if(lnaGain == null)
{
lnaGain = HackRFLNAGain.GAIN_16;
}
getTuner().getController().setLNAGain(lnaGain);
save();
}
catch(SourceException e)
{
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "HackRF Tuner Controller"
+ " - couldn't apply the LNA gain setting - " + e.getLocalizedMessage());
mLog.error("HackRF Tuner Controller - couldn't apply LNA gain setting - ", e);
}
}
});
}
@@ -233,97 +154,61 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return mLnaGainCombo;
}
private JToggleButton getAmplifierToggle()
private CheckBox getAmplifierCheckBox()
{
if(mAmplifier == null)
if(mAmplifierCheckBox == null)
{
mAmplifier = new JToggleButton("Amplifier");
mAmplifier.setToolTipText("Enable or disable the gain amplifier");
mAmplifier.setEnabled(false);
mAmplifier.addActionListener(arg0 ->
{
if(!isLoading())
mAmplifierCheckBox = new CheckBox("RF amplifier");
mAmplifierCheckBox.setTooltip(new Tooltip("Enable or disable the RF gain amplifier"));
mAmplifierCheckBox.setDisable(true);
mAmplifierCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() && applyToTuner("amplifier",
() -> getTuner().getController().setAmplifierEnabled(mAmplifierCheckBox.isSelected())))
{
try
{
getTuner().getController().setAmplifierEnabled(mAmplifier.isSelected());
save();
}
catch(SourceException e)
{
mLog.error("couldn't enable/disable amplifier", e);
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "Couldn't change amplifier setting",
"Error changing amplifier setting", JOptionPane.ERROR_MESSAGE);
}
save();
}
});
}
return mAmplifier;
return mAmplifierCheckBox;
}
private JToggleButton getBiasTToggle()
private CheckBox getBiasTCheckBox()
{
if(mBiasT == null)
if(mBiasTCheckBox == null)
{
mBiasT = new JToggleButton("Disabled");
mBiasT.setToolTipText("Enable or disable Bias-T power (3.3V) on the antenna port for active antennas or LNAs");
mBiasT.setEnabled(false);
//Item listener also fires for programmatic setSelected() when the configuration loads
mBiasT.addItemListener(e -> mBiasT.setText(mBiasT.isSelected() ? "Enabled" : "Disabled"));
mBiasT.addActionListener(arg0 ->
{
if(!isLoading())
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setTooltip(new Tooltip("Enable or disable Bias-T power (3.3V) on the antenna port for " +
"active antennas or LNAs"));
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner() && applyToTuner("Bias-T",
() -> getTuner().getController().setBiasTEnabled(mBiasTCheckBox.isSelected())))
{
try
{
getTuner().getController().setBiasTEnabled(mBiasT.isSelected());
save();
}
catch(SourceException e)
{
mLog.error("couldn't enable/disable bias-t", e);
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "Couldn't change Bias-T setting",
"Error changing Bias-T setting", JOptionPane.ERROR_MESSAGE);
}
save();
}
});
}
return mBiasT;
return mBiasTCheckBox;
}
private JComboBox getSampleRateCombo()
private ComboBox<HackRFSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
HackRFSampleRate[] validRates = HackRFSampleRate.VALID_SAMPLE_RATES.toArray(new HackRFSampleRate[0]);
mSampleRateCombo = new JComboBox<>(validRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e ->
{
if(!isLoading())
mSampleRateCombo = new ComboBox<>(FXCollections.observableArrayList(HackRFSampleRate.VALID_SAMPLE_RATES));
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
HackRFSampleRate sampleRate = mSampleRateCombo.getValue();
if(!isLoading() && hasTuner() && sampleRate != null &&
applyToTuner("sample rate [" + sampleRate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(sampleRate)))
{
HackRFSampleRate sampleRate = (HackRFSampleRate)getSampleRateCombo().getSelectedItem();
try
{
getTuner().getController().setSampleRate(sampleRate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(sampleRate.getRate());
save();
}
catch(SourceException e2)
{
JOptionPane.showMessageDialog(HackRFTunerEditor.this, "HackRF Tuner Controller"
+ " - couldn't apply the sample rate setting [" + sampleRate.getLabel() +
"] " + e2.getLocalizedMessage());
mLog.error("HackRF Tuner Controller - couldn't apply sample rate setting [" +
sampleRate.getLabel() + "]", e);
}
adjustForSampleRate(sampleRate.getRate());
save();
}
});
}
@@ -331,47 +216,29 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return mSampleRateCombo;
}
private JButton getTunerInfoButton()
{
if(mTunerInfo == null)
{
mTunerInfo = new JButton("Tuner Info");
mTunerInfo.setToolTipText("Provides details and information about the tuner");
mTunerInfo.setEnabled(false);
mTunerInfo.addActionListener(e -> JOptionPane.showMessageDialog(HackRFTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfo;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getController().isLockedSampleRate())
{
mSampleRateCombo.setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
}
else
{
mSampleRateCombo.setToolTipText("Select a sample rate for the tuner");
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
}
}
@Override
public void setTunerLockState(boolean locked)
protected void tunerLockStateUpdated(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setDisable(!hasTuner() || locked);
updateSampleRateToolTip();
}
private String getTunerInfo()
@Override
protected String getTunerInfo()
{
HackRFTunerController controller = hasTuner() ? getTuner().getController() : null;
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>HackRF Tuner</h3>");
appendInfo(sb, "Board", controller != null ? controller.getBoardName() : null);
@@ -391,9 +258,6 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
return sb.toString();
}
/**
* Appends a labeled tuner info value, or Unknown when the value is not available.
*/
private static void appendInfo(StringBuilder sb, String label, String value)
{
sb.append("<b>").append(label).append(": </b>").append(value != null ? value : "Unknown").append("<br>");
@@ -404,18 +268,14 @@ public class HackRFTunerEditor extends TunerEditor<HackRFTuner,HackRFTunerConfig
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((HackRFSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setAmplifierEnabled(getAmplifierToggle().isSelected());
getConfiguration().setBiasT(getBiasTToggle().isSelected());
getConfiguration().setLNAGain((HackRFLNAGain)getLnaGainCombo().getSelectedItem());
getConfiguration().setVGAGain((HackRFVGAGain)getVgaGainCombo().getSelectedItem());
HackRFTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setSampleRate(getSampleRateCombo().getValue());
config.setAmplifierEnabled(getAmplifierCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
config.setLNAGain(getLnaGainCombo().getValue());
config.setVGAGain(getVgaGainCombo().getValue());
saveConfiguration();
}
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -23,50 +23,35 @@ import io.github.dsheirer.source.tuner.hydrasdr.HydraSdrTunerController.Gain;
import io.github.dsheirer.source.tuner.hydrasdr.HydraSdrTunerController.GainMode;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Region;
/**
* HydraSDR tuner editor/controller
* HydraSDR tuner editor
*/
public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTunerConfiguration>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(HydraSdrTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<HydraSdrSampleRate> mSampleRateCombo;
private JComboBox<GainMode> mGainModeCombo;
private JSlider mMasterGainSlider;
private JLabel mMasterGainLabel;
private JLabel mMasterGainValueLabel;
private JSlider mIFGainSlider;
private JLabel mIFGainLabel;
private JLabel mIFGainValueLabel;
private JSlider mLNAGainSlider;
private JLabel mLNAGainValueLabel;
private JSlider mMixerGainSlider;
private JLabel mMixerGainValueLabel;
private JCheckBox mLNAAGCCheckBox;
private JCheckBox mMixerAGCCheckBox;
private JCheckBox mBiasTCheckBox;
private ComboBox<HydraSdrSampleRate> mSampleRateCombo;
private ComboBox<GainMode> mGainModeCombo;
private GainSlider mMasterGainSlider;
private Label mMasterGainLabel;
private GainSlider mIFGainSlider;
private Label mIFGainLabel;
private GainSlider mLNAGainSlider;
private Label mLNAGainLabel;
private GainSlider mMixerGainSlider;
private Label mMixerGainLabel;
private CheckBox mLNAAGCCheckBox;
private CheckBox mMixerAGCCheckBox;
private CheckBox mBiasTCheckBox;
/**
* Constructs an instance
@@ -78,7 +63,7 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -93,182 +78,62 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
return HydraSdrTunerController.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private void init()
{
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
TunerSection gain = addSection("Gain");
gain.addRow("Mode", getGainModeCombo());
mMasterGainLabel = gain.addRow("Master", getMasterGainSlider(), new Region());
mIFGainLabel = gain.addRow("IF", getIFGainSlider(), new Region());
mMixerGainLabel = gain.addRow("Mixer", getMixerGainSlider(), getMixerAGCCheckBox());
mLNAGainLabel = gain.addRow("LNA", getLNAGainSlider(), getLNAAGCCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getTunerInfoButton().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
if(hasTuner() && hasConfiguration())
{
getBiasTCheckBox().setSelected(getConfiguration().isBiasT());
}
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
getBiasTCheckBox().setDisable(!hasTuner());
getBiasTCheckBox().setSelected(hasTuner() && hasConfiguration() && getConfiguration().isBiasT());
updateGainComponents((hasTuner() && hasConfiguration()) ? getConfiguration().getGain() : null);
if(hasTuner())
{
List<HydraSdrSampleRate> rates = getTuner().getController().getSampleRates();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new HydraSdrSampleRate[rates.size()])));
getSampleRateCombo().getItems().setAll(rates);
if(hasConfiguration())
{
HydraSdrSampleRate sampleRate = getSampleRate(getConfiguration().getSampleRate());
getSampleRateCombo().setSelectedItem(sampleRate);
getSampleRateCombo().setValue(getSampleRate(getConfiguration().getSampleRate()));
}
}
else
{
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
getSampleRateCombo().getItems().clear();
}
setLoading(false);
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Mode:"));
add(getGainModeCombo(), "wrap");
add(getMasterGainLabel());
add(getMasterGainSlider());
add(getMasterGainValueLabel());
add(getIFGainLabel());
add(getIFGainSlider());
add(getIFGainValueLabel());
add(getMixerAGCCheckBox());
add(getMixerGainSlider());
add(getMixerGainValueLabel());
add(getLNAAGCCheckBox());
add(getLNAGainSlider());
add(getLNAGainValueLabel());
}
private JCheckBox getLNAAGCCheckBox()
{
if(mLNAAGCCheckBox == null)
{
mLNAAGCCheckBox = new JCheckBox("AGC LNA:");
mLNAAGCCheckBox.setEnabled(false);
mLNAAGCCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected());
getLNAGainSlider().setEnabled(!getLNAAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting LNA AGC Enabled");
}
}
});
}
return mLNAAGCCheckBox;
}
private JCheckBox getMixerAGCCheckBox()
{
if(mMixerAGCCheckBox == null)
{
mMixerAGCCheckBox = new JCheckBox("AGC Mixer:");
mMixerAGCCheckBox.setEnabled(false);
mMixerAGCCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected());
getMixerGainSlider().setEnabled(!getMixerAGCCheckBox().isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Mixer AGC Enabled");
}
}
});
}
return mMixerAGCCheckBox;
updateSampleRateToolTip();
}
/**
* Checkbox to enable/disable Bias-T power for active antennas
*/
private JCheckBox getBiasTCheckBox()
private CheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.setToolTipText("Enable Bias-T power output for active antennas");
mBiasTCheckBox.addActionListener(e ->
{
if(hasTuner() && !isLoading())
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setTooltip(new Tooltip("Enable Bias-T power output for active antennas"));
mBiasTCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() &&
applyToTuner("Bias-T", () -> getTuner().getController().setBiasT(mBiasTCheckBox.isSelected())))
{
try
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(Exception e1)
{
mLog.error("Error setting Bias-T", e1);
JOptionPane.showMessageDialog(mBiasTCheckBox, "Couldn't set Bias-T: " + e1.getMessage());
}
save();
}
});
}
@@ -276,93 +141,77 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
return mBiasTCheckBox;
}
private JLabel getLNAGainValueLabel()
private CheckBox getLNAAGCCheckBox()
{
if(mLNAGainValueLabel == null)
if(mLNAAGCCheckBox == null)
{
mLNAGainValueLabel = new JLabel("0");
mLNAGainValueLabel.setEnabled(false);
mLNAAGCCheckBox = new CheckBox("AGC");
mLNAAGCCheckBox.setTooltip(new Tooltip("Automatic LNA gain control"));
mLNAAGCCheckBox.setDisable(true);
mLNAAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("LNA AGC",
() -> getTuner().getController().setLNAAGC(getLNAAGCCheckBox().isSelected())))
{
getLNAGainSlider().setDisable(getLNAAGCCheckBox().isSelected());
save();
}
});
}
return mLNAGainValueLabel;
return mLNAAGCCheckBox;
}
private JSlider getLNAGainSlider()
private CheckBox getMixerAGCCheckBox()
{
if(mMixerAGCCheckBox == null)
{
mMixerAGCCheckBox = new CheckBox("AGC");
mMixerAGCCheckBox.setTooltip(new Tooltip("Automatic mixer gain control"));
mMixerAGCCheckBox.setDisable(true);
mMixerAGCCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading() && applyToTuner("mixer AGC",
() -> getTuner().getController().setMixerAGC(getMixerAGCCheckBox().isSelected())))
{
getMixerGainSlider().setDisable(getMixerAGCCheckBox().isSelected());
save();
}
});
}
return mMixerAGCCheckBox;
}
private GainSlider getLNAGainSlider()
{
if(mLNAGainSlider == null)
{
mLNAGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.LNA_GAIN_MIN,
HydraSdrTunerController.LNA_GAIN_MAX, HydraSdrTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setEnabled(false);
mLNAGainSlider.setMajorTickSpacing(1);
mLNAGainSlider.setPaintTicks(true);
mLNAGainSlider.addChangeListener(event ->
{
int gain = mLNAGainSlider.getValue();
if(hasTuner() && !isLoading())
mLNAGainSlider = new GainSlider(HydraSdrTunerController.LNA_GAIN_MIN, HydraSdrTunerController.LNA_GAIN_MAX,
HydraSdrTunerController.LNA_GAIN_MIN);
mLNAGainSlider.setDisable(true);
mLNAGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("LNA gain", () -> getTuner().getController().setLNAGain(gain)))
{
try
{
getTuner().getController().setLNAGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR LNA gain to:" + gain, e);
JOptionPane.showMessageDialog(mLNAGainSlider, "Couldn't set LNA gain value to " + gain);
}
save();
}
getLNAGainValueLabel().setText(String.valueOf(gain));
});
}
return mLNAGainSlider;
}
private JLabel getMixerGainValueLabel()
{
if(mMixerGainValueLabel == null)
{
mMixerGainValueLabel = new JLabel("0");
mMixerGainValueLabel.setEnabled(false);
}
return mMixerGainValueLabel;
}
private JSlider getMixerGainSlider()
private GainSlider getMixerGainSlider()
{
if(mMixerGainSlider == null)
{
mMixerGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.MIXER_GAIN_MIN,
mMixerGainSlider = new GainSlider(HydraSdrTunerController.MIXER_GAIN_MIN,
HydraSdrTunerController.MIXER_GAIN_MAX, HydraSdrTunerController.MIXER_GAIN_MIN);
mMixerGainSlider.setEnabled(false);
mMixerGainSlider.setMajorTickSpacing(1);
mMixerGainSlider.setPaintTicks(true);
mMixerGainSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent event)
mMixerGainSlider.setDisable(true);
mMixerGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("mixer gain", () -> getTuner().getController().setMixerGain(gain)))
{
int gain = mMixerGainSlider.getValue();
if(hasTuner() && !isLoading())
{
try
{
getTuner().getController().setMixerGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR Mixer gain to:" + gain, e);
JOptionPane.showMessageDialog(mMixerGainSlider, "Couldn't set Mixer gain value to " + gain);
}
}
getMixerGainValueLabel().setText(String.valueOf(gain));
save();
}
});
}
@@ -370,134 +219,77 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
return mMixerGainSlider;
}
private JLabel getIFGainLabel()
{
if(mIFGainLabel == null)
{
mIFGainLabel = new JLabel("IF:");
}
return mIFGainLabel;
}
private JLabel getIFGainValueLabel()
{
if(mIFGainValueLabel == null)
{
mIFGainValueLabel = new JLabel("0");
mIFGainValueLabel.setEnabled(false);
}
return mIFGainValueLabel;
}
private JSlider getIFGainSlider()
private GainSlider getIFGainSlider()
{
if(mIFGainSlider == null)
{
mIFGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.IF_GAIN_MIN,
HydraSdrTunerController.IF_GAIN_MAX, HydraSdrTunerController.IF_GAIN_MIN);
mIFGainSlider.setEnabled(false);
mIFGainSlider.setMajorTickSpacing(1);
mIFGainSlider.setPaintTicks(true);
mIFGainSlider.addChangeListener(event ->
{
int gain = mIFGainSlider.getValue();
if(hasTuner() && !isLoading())
mIFGainSlider = new GainSlider(HydraSdrTunerController.IF_GAIN_MIN, HydraSdrTunerController.IF_GAIN_MAX,
HydraSdrTunerController.IF_GAIN_MIN);
mIFGainSlider.setDisable(true);
mIFGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("IF gain", () -> getTuner().getController().setIFGain(gain)))
{
try
{
getTuner().getController().setIFGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR IF gain to:" + gain, e);
JOptionPane.showMessageDialog(mIFGainSlider, "Couldn't set IF gain value to " + gain);
}
save();
}
getIFGainValueLabel().setText(String.valueOf(gain));
});
}
return mIFGainSlider;
}
private JLabel getMasterGainLabel()
{
if(mMasterGainLabel == null)
{
mMasterGainLabel = new JLabel("Master:");
}
return mMasterGainLabel;
}
private JLabel getMasterGainValueLabel()
{
if(mMasterGainValueLabel == null)
{
mMasterGainValueLabel = new JLabel("0");
mMasterGainValueLabel.setEnabled(false);
}
return mMasterGainValueLabel;
}
private JSlider getMasterGainSlider()
private GainSlider getMasterGainSlider()
{
if(mMasterGainSlider == null)
{
mMasterGainSlider = new JSlider(JSlider.HORIZONTAL, HydraSdrTunerController.GAIN_MIN,
HydraSdrTunerController.GAIN_MAX, HydraSdrTunerController.GAIN_MIN);
mMasterGainSlider.setEnabled(false);
mMasterGainSlider.setMajorTickSpacing(1);
mMasterGainSlider.setPaintTicks(true);
mMasterGainSlider = new GainSlider(HydraSdrTunerController.GAIN_MIN, HydraSdrTunerController.GAIN_MAX,
HydraSdrTunerController.GAIN_MIN);
mMasterGainSlider.setDisable(true);
mMasterGainSlider.setOnChange(value -> {
Gain gain = Gain.getGain(getGainModeCombo().getValue(), value);
mMasterGainSlider.addChangeListener(event ->
{
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = mMasterGainSlider.getValue();
Gain gain = Gain.getGain(mode, value);
if(hasTuner() && !isLoading())
if(hasTuner() && !isLoading() && applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set HydraSDR gain to:" + gain.name(), e);
JOptionPane.showMessageDialog(mMasterGainSlider, "Couldn't set gain value to " +
gain.getValue());
}
save();
}
getMasterGainValueLabel().setText(String.valueOf(value));
});
}
return mMasterGainSlider;
}
private JComboBox<GainMode> getGainModeCombo()
private ComboBox<GainMode> getGainModeCombo()
{
if(mGainModeCombo == null)
{
mGainModeCombo = new JComboBox<>(GainMode.values());
mGainModeCombo.setEnabled(false);
mGainModeCombo.addActionListener(e ->
{
mGainModeCombo = new ComboBox<>(FXCollections.observableArrayList(GainMode.values()));
mGainModeCombo.setMaxWidth(Double.MAX_VALUE);
mGainModeCombo.setDisable(true);
mGainModeCombo.setTooltip(new Tooltip("Linearity and sensitivity modes set all gains from the master " +
"gain. Custom mode sets each gain separately."));
mGainModeCombo.setOnAction(e -> {
if(hasTuner() && !isLoading())
{
GainMode mode = (GainMode)mGainModeCombo.getSelectedItem();
int value = getMasterGainSlider().getValue();
Gain gain = Gain.getGain(mode, value);
Gain gain = Gain.getGain(mGainModeCombo.getValue(), getMasterGainSlider().getValue());
setLoading(true);
updateGainComponents(gain);
setLoading(false);
applyToTuner("gain mode", () -> {
HydraSdrTunerController controller = getTuner().getController();
if(gain == Gain.CUSTOM)
{
controller.setMixerAGC(getMixerAGCCheckBox().isSelected());
controller.setLNAAGC(getLNAAGCCheckBox().isSelected());
controller.setIFGain(getIFGainSlider().getValue());
controller.setMixerGain(getMixerGainSlider().getValue());
controller.setLNAGain(getLNAGainSlider().getValue());
}
else
{
controller.setGain(gain);
}
});
save();
}
});
@@ -506,37 +298,23 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
return mGainModeCombo;
}
private JComboBox<HydraSdrSampleRate> getSampleRateCombo()
private ComboBox<HydraSdrSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
HydraSdrSampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(rate)))
{
if(hasTuner() && !isLoading())
{
HydraSdrSampleRate rate = (HydraSdrSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(HydraSdrTunerEditor.this,
"Couldn't set sample rate to " + rate.getLabel());
mLog.error("Error setting HydraSDR sample rate", e1);
}
}
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
});
}
@@ -545,48 +323,29 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
}
/**
* Hyperlink button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(HydraSdrTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
/**
* Updates the enabled state of each of the gain controls according to the
* specified gain mode. The master gain control is enabled for linearity
* and sensitivity and the individual gain controls are disabled, and
* vice-versa for custom mode.
* Updates the enabled state of each of the gain controls according to the specified gain mode. The master gain
* control is enabled for linearity and sensitivity and the individual gain controls are disabled, and vice-versa
* for custom mode.
*/
private void updateGainComponents(Gain gain)
{
if(hasTuner() && gain != null)
{
boolean isCustom = gain.equals(Gain.CUSTOM);
getGainModeCombo().setEnabled(true);
getGainModeCombo().setSelectedItem(gain.getGainMode());
getMasterGainLabel().setEnabled(!isCustom);
getMasterGainSlider().setEnabled(!isCustom);
getGainModeCombo().setDisable(false);
getGainModeCombo().setValue(gain.getGainMode());
mMasterGainLabel.setDisable(isCustom);
getMasterGainSlider().setDisable(isCustom);
getMasterGainSlider().setValue(gain.getValue());
getMasterGainValueLabel().setEnabled(!isCustom);
getIFGainLabel().setEnabled(isCustom);
getIFGainSlider().setEnabled(isCustom);
getIFGainValueLabel().setEnabled(isCustom);
getLNAAGCCheckBox().setEnabled(isCustom);
getLNAGainSlider().setEnabled(isCustom && !getConfiguration().isLNAAGC());
getLNAGainValueLabel().setEnabled(isCustom);
getMixerAGCCheckBox().setEnabled(isCustom);
getMixerGainSlider().setEnabled(isCustom && !getConfiguration().isMixerAGC());
getMixerGainValueLabel().setEnabled(isCustom);
mIFGainLabel.setDisable(!isCustom);
getIFGainSlider().setDisable(!isCustom);
mLNAGainLabel.setDisable(!isCustom);
getLNAAGCCheckBox().setDisable(!isCustom);
getLNAGainSlider().setDisable(!isCustom || getConfiguration().isLNAAGC());
mMixerGainLabel.setDisable(!isCustom);
getMixerAGCCheckBox().setDisable(!isCustom);
getMixerGainSlider().setDisable(!isCustom || getConfiguration().isMixerAGC());
if(isCustom)
{
getIFGainSlider().setValue(getConfiguration().getIFGain());
@@ -606,25 +365,23 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
}
else
{
getGainModeCombo().setEnabled(false);
getMasterGainLabel().setEnabled(false);
getMasterGainSlider().setEnabled(false);
getGainModeCombo().setDisable(true);
mMasterGainLabel.setDisable(true);
getMasterGainSlider().setDisable(true);
getMasterGainSlider().setValue(0);
getMasterGainValueLabel().setEnabled(false);
getIFGainLabel().setEnabled(false);
getIFGainSlider().setEnabled(false);
mIFGainLabel.setDisable(true);
getIFGainSlider().setDisable(true);
getIFGainSlider().setValue(0);
getIFGainValueLabel().setEnabled(false);
getLNAAGCCheckBox().setEnabled(false);
mLNAGainLabel.setDisable(true);
getLNAAGCCheckBox().setDisable(true);
getLNAAGCCheckBox().setSelected(false);
getLNAGainSlider().setEnabled(false);
getLNAGainSlider().setDisable(true);
getLNAGainSlider().setValue(0);
getLNAGainValueLabel().setEnabled(false);
getMixerAGCCheckBox().setEnabled(false);
mMixerGainLabel.setDisable(true);
getMixerAGCCheckBox().setDisable(true);
getMixerAGCCheckBox().setSelected(false);
getMixerGainSlider().setEnabled(false);
getMixerGainSlider().setDisable(true);
getMixerGainSlider().setValue(0);
getMixerGainValueLabel().setEnabled(false);
}
}
@@ -633,21 +390,21 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate(((HydraSdrSampleRate)getSampleRateCombo().getSelectedItem()).getRate());
Gain gain = Gain.getGain((GainMode)mGainModeCombo.getSelectedItem(), getMasterGainSlider().getValue());
getConfiguration().setGain(gain);
getConfiguration().setIFGain(getIFGainSlider().getValue());
getConfiguration().setMixerGain(getMixerGainSlider().getValue());
getConfiguration().setLNAGain(getLNAGainSlider().getValue());
getConfiguration().setMixerAGC(getMixerAGCCheckBox().isSelected());
getConfiguration().setLNAAGC(getLNAAGCCheckBox().isSelected());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
HydraSdrTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
if(getSampleRateCombo().getValue() != null)
{
config.setSampleRate(getSampleRateCombo().getValue().getRate());
}
config.setGain(Gain.getGain(getGainModeCombo().getValue(), getMasterGainSlider().getValue()));
config.setIFGain(getIFGainSlider().getValue());
config.setMixerGain(getMixerGainSlider().getValue());
config.setLNAGain(getLNAGainSlider().getValue());
config.setMixerAGC(getMixerAGCCheckBox().isSelected());
config.setLNAAGC(getLNAAGCCheckBox().isSelected());
config.setBiasT(getBiasTCheckBox().isSelected());
saveConfiguration();
}
}
@@ -671,7 +428,7 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
}
}
if(rates.size() > 0)
if(!rates.isEmpty())
{
return rates.get(0);
}
@@ -687,55 +444,31 @@ public class HydraSdrTunerEditor extends TunerEditor<HydraSdrTuner, HydraSdrTune
{
if(hasTuner() && getTuner().getController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
}
else
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
}
}
@Override
public void setTunerLockState(boolean locked)
protected void tunerLockStateUpdated(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setDisable(!hasTuner() || locked);
updateSampleRateToolTip();
}
private String getTunerInfo()
@Override
protected String getTunerInfo()
{
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
{
return getDiscoveredTuner().getErrorMessage();
}
if(hasTuner())
{
StringBuilder sb = new StringBuilder();
HydraSdrDeviceInformation info = getTuner().getController().getDeviceInfo();
sb.append("<html><h3>HydraSDR Tuner</h3>");
sb.append("<b>Serial: </b>");
sb.append(info.getSerialNumber());
sb.append("<br>");
sb.append("<b>Firmware: </b>");
sb.append(info.getVersion());
sb.append("<br>");
sb.append("<b>Part: </b>");
sb.append(info.getPartNumber());
sb.append("<br>");
sb.append("<b>Board: </b>");
sb.append(info.getBoardName());
sb.append("<br>");
return sb.toString();
}
return null;
StringBuilder sb = new StringBuilder();
HydraSdrDeviceInformation info = getTuner().getController().getDeviceInfo();
sb.append("<html><h3>HydraSDR Tuner</h3>");
sb.append("<b>Serial: </b>").append(info.getSerialNumber()).append("<br>");
sb.append("<b>Firmware: </b>").append(info.getVersion()).append("<br>");
sb.append("<b>Part: </b>").append(info.getPartNumber()).append("<br>");
sb.append("<b>Board: </b>").append(info.getBoardName()).append("<br>");
return sb.toString();
}
}

View File

@@ -16,42 +16,25 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.limesdr;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import java.io.Serial;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
/**
* LimeSDR tuner editor
*/
public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerConfiguration>
{
@Serial
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(LimeSdrTunerEditor.class);
private JButton mTunerInfoButton;
private JComboBox<LimeSdrSampleRate> mSampleRateCombo;
private JComboBox<String> mAntennaCombo;
private JSlider mGainSlider;
private JLabel mGainValueLabel;
private ComboBox<LimeSdrSampleRate> mSampleRateCombo;
private ComboBox<String> mAntennaCombo;
private GainSlider mGainSlider;
/**
* Constructs an instance
@@ -63,7 +46,7 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -82,142 +65,62 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]", "[][][][][][][][][][][grow]"));
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
getTuningSection().addRow("Antenna", getAntennaCombo());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Antenna:"));
add(getAntennaCombo(), "wrap");
add(new JSeparator(), "span,growx");
add(new JLabel("Gain:"));
add(getGainSlider());
add(getGainValueLabel());
//Empty row that takes all extra vertical space so that the controls stay stacked at the top of the editor.
add(new JLabel(), "span,pushy");
TunerSection gain = addSection("Gain");
gain.addRow("Gain", getGainSlider());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
boolean started = hasStartedTuner();
getTunerIdLabel().setText(started ? getTuner().getPreferredName() : getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(started);
if(started)
if(hasStartedTuner())
{
LimeSdrTunerController controller = getTuner().getController();
List<LimeSdrSampleRate> rates = controller.getSampleRates();
getSampleRateCombo().setModel(new DefaultComboBoxModel<>(rates.toArray(new LimeSdrSampleRate[0])));
getSampleRateCombo().setSelectedItem(controller.getLimeSdrSampleRate());
getSampleRateCombo().setEnabled(!controller.isLockedSampleRate());
List<String> antennas = controller.getAntennas();
getAntennaCombo().setModel(new DefaultComboBoxModel<>(antennas.toArray(new String[0])));
getAntennaCombo().setSelectedItem(controller.getAntenna());
getAntennaCombo().setEnabled(true);
getSampleRateCombo().getItems().setAll(controller.getSampleRates());
getSampleRateCombo().setValue(controller.getLimeSdrSampleRate());
getSampleRateCombo().setDisable(controller.isLockedSampleRate());
getAntennaCombo().getItems().setAll(controller.getAntennas());
getAntennaCombo().setValue(controller.getAntenna());
getAntennaCombo().setDisable(false);
getGainSlider().setValue(controller.getGain());
getGainSlider().setEnabled(true);
getGainValueLabel().setEnabled(true);
getGainSlider().setDisable(false);
}
else
{
getSampleRateCombo().setModel(new DefaultComboBoxModel<>());
getSampleRateCombo().setEnabled(false);
getAntennaCombo().setModel(new DefaultComboBoxModel<>());
getAntennaCombo().setEnabled(false);
getGainSlider().setEnabled(false);
getGainValueLabel().setEnabled(false);
getSampleRateCombo().getItems().clear();
getSampleRateCombo().setDisable(true);
getAntennaCombo().getItems().clear();
getAntennaCombo().setDisable(true);
getGainSlider().setDisable(true);
}
updateGainLabel();
setLoading(false);
}
/**
* Indicates if the tuner has finished starting, since a status update can arrive while it's starting or restarting.
* Indicates if the tuner is started, which is when the controller knows the selected antenna.
*/
private boolean hasStartedTuner()
{
return hasTuner() && getTuner().getController().getAntenna() != null;
}
private void updateGainLabel()
{
getGainValueLabel().setText(getGainSlider().getValue() + " dB");
}
/**
* Button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(_ -> JOptionPane.showMessageDialog(LimeSdrTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private JComboBox<LimeSdrSampleRate> getSampleRateCombo()
private ComboBox<LimeSdrSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setTooltip(new Tooltip("Select a sample rate for the tuner"));
mSampleRateCombo.setOnAction(e -> {
LimeSdrSampleRate rate = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && rate != null &&
applyToTuner("sample rate [" + rate + "]", () -> getTuner().getController().setSampleRate(rate)))
{
LimeSdrSampleRate rate = (LimeSdrSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(rate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(rate.getRate());
save();
}
catch(Exception e1)
{
mLog.error("Error setting LimeSDR sample rate", e1);
JOptionPane.showMessageDialog(LimeSdrTunerEditor.this, "Couldn't set sample rate to " + rate);
}
adjustForSampleRate(rate.getRate());
save();
}
});
}
@@ -225,29 +128,21 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
return mSampleRateCombo;
}
private JComboBox<String> getAntennaCombo()
private ComboBox<String> getAntennaCombo()
{
if(mAntennaCombo == null)
{
mAntennaCombo = new JComboBox<>();
mAntennaCombo.setEnabled(false);
mAntennaCombo.setToolTipText("Receive port: LNAW wideband (default), LNAL low band, LNAH high band");
mAntennaCombo.addActionListener(_ ->
{
if(hasTuner() && !isLoading())
{
String antenna = (String)mAntennaCombo.getSelectedItem();
mAntennaCombo = new ComboBox<>();
mAntennaCombo.setMaxWidth(Double.MAX_VALUE);
mAntennaCombo.setDisable(true);
mAntennaCombo.setTooltip(new Tooltip("Receive port: LNAW wideband (default), LNAL low band, LNAH high band"));
mAntennaCombo.setOnAction(e -> {
String antenna = mAntennaCombo.getValue();
try
{
getTuner().getController().setAntenna(antenna);
save();
}
catch(Exception e1)
{
mLog.error("Error setting LimeSDR antenna", e1);
JOptionPane.showMessageDialog(mAntennaCombo, "Couldn't set antenna to " + antenna);
}
if(hasTuner() && !isLoading() && antenna != null &&
applyToTuner("antenna [" + antenna + "]", () -> getTuner().getController().setAntenna(antenna)))
{
save();
}
});
}
@@ -255,109 +150,75 @@ public class LimeSdrTunerEditor extends TunerEditor<LimeSdrTuner, LimeSdrTunerCo
return mAntennaCombo;
}
private JSlider getGainSlider()
private GainSlider getGainSlider()
{
if(mGainSlider == null)
{
mGainSlider = new JSlider(JSlider.HORIZONTAL, LimeSdrTunerController.GAIN_MINIMUM,
LimeSdrTunerController.GAIN_MAXIMUM, LimeSdrTunerController.GAIN_DEFAULT);
mGainSlider.setEnabled(false);
mGainSlider.setMajorTickSpacing(5);
mGainSlider.setPaintTicks(true);
mGainSlider.addChangeListener(_ ->
{
int gain = mGainSlider.getValue();
if(hasTuner() && !isLoading())
mGainSlider = new GainSlider(LimeSdrTunerController.GAIN_MINIMUM, LimeSdrTunerController.GAIN_MAXIMUM,
LimeSdrTunerController.GAIN_DEFAULT);
mGainSlider.setDisable(true);
mGainSlider.setFormatter(value -> value + " dB");
mGainSlider.setOnChange(gain -> {
if(hasTuner() && !isLoading() &&
applyToTuner("gain", () -> getTuner().getController().setGain(gain)))
{
try
{
getTuner().getController().setGain(gain);
save();
}
catch(Exception e)
{
mLog.error("Couldn't set LimeSDR gain to:" + gain, e);
JOptionPane.showMessageDialog(mGainSlider, "Couldn't set gain value to " + gain);
}
save();
}
updateGainLabel();
});
}
return mGainSlider;
}
private JLabel getGainValueLabel()
{
if(mGainValueLabel == null)
{
mGainValueLabel = new JLabel("0 dB");
mGainValueLabel.setEnabled(false);
}
return mGainValueLabel;
}
@Override
public void save()
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel)getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
LimeSdrTunerConfiguration config = getConfiguration();
saveCommonSettings(config);
if(getSampleRateCombo().getSelectedItem() instanceof LimeSdrSampleRate rate)
if(getSampleRateCombo().getValue() instanceof LimeSdrSampleRate rate)
{
getConfiguration().setSampleRate(rate.getRate());
config.setSampleRate(rate.getRate());
}
if(getAntennaCombo().getSelectedItem() instanceof String antenna)
if(getAntennaCombo().getValue() instanceof String antenna)
{
getConfiguration().setAntenna(antenna);
config.setAntenna(antenna);
}
getConfiguration().setGain(getGainSlider().getValue());
config.setGain(getGainSlider().getValue());
saveConfiguration();
}
}
@Override
public void setTunerLockState(boolean locked)
protected void tunerLockStateUpdated(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
getSampleRateCombo().setToolTipText(locked ? "Sample Rate is locked. Disable decoding channels to unlock." :
"Select a sample rate for the tuner");
getSampleRateCombo().setDisable(!hasStartedTuner() || locked);
getSampleRateCombo().setTooltip(new Tooltip(locked ? "Sample rate is locked. Disable decoding channels " +
"to unlock." : "Select a sample rate for the tuner"));
}
private String getTunerInfo()
@Override
protected String getTunerInfo()
{
if(getDiscoveredTuner().getTunerStatus() == TunerStatus.ERROR)
if(!hasStartedTuner())
{
return getDiscoveredTuner().getErrorMessage();
return null;
}
if(hasTuner())
{
LimeSdrDeviceInformation info = getTuner().getController().getDeviceInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>LimeSDR Tuner</h3>");
sb.append("<b>Board: </b>").append(info.board()).append("<br>");
sb.append("<b>Serial: </b>").append(info.serial()).append("<br>");
sb.append("<b>Hardware: </b>").append(info.hardware()).append("<br>");
sb.append("<b>Firmware: </b>").append(info.firmware()).append("<br>");
sb.append("<b>Gateware: </b>").append(info.gateware()).append("<br>");
sb.append("<b>Connection: </b>").append(info.connection()).append("<br>");
sb.append("<b>LimeSuiteNG: </b>").append(info.library()).append("<br>");
return sb.toString();
}
return null;
LimeSdrDeviceInformation info = getTuner().getController().getDeviceInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>LimeSDR Tuner</h3>");
sb.append("<b>Board: </b>").append(info.board()).append("<br>");
sb.append("<b>Serial: </b>").append(info.serial()).append("<br>");
sb.append("<b>Hardware: </b>").append(info.hardware()).append("<br>");
sb.append("<b>Firmware: </b>").append(info.firmware()).append("<br>");
sb.append("<b>Gateware: </b>").append(info.gateware()).append("<br>");
sb.append("<b>Connection: </b>").append(info.connection()).append("<br>");
sb.append("<b>LimeSuiteNG: </b>").append(info.library()).append("<br>");
return sb.toString();
}
}

View File

@@ -18,165 +18,150 @@
*/
package io.github.dsheirer.source.tuner.network;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.dsheirer.gui.control.FrequencyEntry;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.configuration.TunerConfigurationManager;
import io.github.dsheirer.source.tuner.manager.DiscoveredNetworkTuner;
import io.github.dsheirer.source.tuner.ui.DiscoveredTunerModel;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Window;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Dialog for adding an rtl_tcp network tuner.
*/
public class AddNetworkTunerDialog extends Dialog<ButtonType> {
private static final Logger mLog = LoggerFactory.getLogger(AddNetworkTunerDialog.class);
private static final ButtonType ADD = new ButtonType("Add", ButtonBar.ButtonData.OK_DONE);
private final UserPreferences mUserPreferences;
private final DiscoveredTunerModel mDiscoveredTunerModel;
private final TunerConfigurationManager mTunerConfigurationManager;
private final ComboBox<String> mTypeComboBox = new ComboBox<>();
private final TextField mHostField = new TextField();
private final TextField mPortField = new TextField("1234");
private final TextField mFrequencyField = new TextField();
private final Label mValidationLabel = new Label();
public class AddNetworkTunerDialog extends JFrame {
private final static Logger mLog = LoggerFactory.getLogger(AddNetworkTunerDialog.class);
private UserPreferences mUserPreferences;
private DiscoveredTunerModel mDiscoveredTunerModel;
private TunerConfigurationManager mTunerConfigurationManager;
private JLabel mTypeLabel;
private JLabel mHostLabel;
private JLabel mPortLabel;
private JLabel mFrequencyLabel;
private JComboBox mTypeComboBox;
private JTextField mHostField;
private JTextField mPortField;
private JTextField mFrequencyField;
private JButton mAddButton;
private JButton mCancelButton;
public AddNetworkTunerDialog(UserPreferences userPreferences, DiscoveredTunerModel discoveredTunerModel,
public AddNetworkTunerDialog(Window owner, UserPreferences userPreferences, DiscoveredTunerModel discoveredTunerModel,
TunerConfigurationManager tunerConfigurationManager) {
Validate.notNull(userPreferences, "UserPreferences cannot be null");
Validate.notNull(discoveredTunerModel, "TunerModel cannot be null");
Validate.notNull(tunerConfigurationManager, "TunerConfigurationManager cannot be null");
mDiscoveredTunerModel = discoveredTunerModel;
mUserPreferences = userPreferences;
mTunerConfigurationManager = tunerConfigurationManager;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
initOwner(owner);
setTitle("Add Network Tuner");
setSize(new Dimension(500, 250));
setHeaderText("Add an rtl_tcp network tuner");
JPanel content = new JPanel();
content.setLayout(new MigLayout("", "[align right][][]", "[][][][][grow][]"));
mTypeComboBox.getItems().add("rtl-tcp");
mTypeComboBox.getSelectionModel().selectFirst();
mTypeComboBox.setMaxWidth(Double.MAX_VALUE);
mHostField.setPromptText("hostname or IP address");
mPortField.setPromptText("e.g. 1234");
mFrequencyField.setPromptText("e.g. 851.0125");
mValidationLabel.getStyleClass().add("tuner-validation");
mValidationLabel.setWrapText(true);
mValidationLabel.setStyle("-fx-text-fill: #d9443a;");
mTypeLabel = new JLabel("Type:");
content.add(mTypeLabel);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(8);
grid.setPadding(new Insets(10));
grid.addRow(0, new Label("Type"), mTypeComboBox);
grid.addRow(1, new Label("Host"), mHostField);
grid.addRow(2, new Label("Port"), mPortField);
grid.addRow(3, new Label("Frequency (MHz)"), mFrequencyField);
grid.add(mValidationLabel, 0, 4, 2, 1);
GridPane.setHgrow(mHostField, Priority.ALWAYS);
grid.setPrefWidth(420);
String[] options = { "rtl-tcp" };
mTypeComboBox = new JComboBox<>(options);
content.add(mTypeComboBox, "span2,grow,wrap");
getDialogPane().setContent(grid);
getDialogPane().getButtonTypes().addAll(ADD, ButtonType.CANCEL);
mHostLabel = new JLabel("Host:");
content.add(mHostLabel);
Node addButton = getDialogPane().lookupButton(ADD);
addButton.setDisable(true);
Runnable validate = () -> {
String error = getValidationError();
mValidationLabel.setText(error == null ? "" : error);
addButton.setDisable(error != null);
};
mHostField.textProperty().addListener((observable, oldValue, newValue) -> validate.run());
mPortField.textProperty().addListener((observable, oldValue, newValue) -> validate.run());
mFrequencyField.textProperty().addListener((observable, oldValue, newValue) -> validate.run());
validate.run();
mValidationLabel.setText("");
mHostField = new JTextField("");
mHostField.setToolTipText("Enter the hostname or IP address of the network tuner");
content.add(mHostField, "span2,grow,wrap");
mPortLabel = new JLabel("Port:");
content.add(mPortLabel);
mPortField = new JTextField("");
mHostField.setToolTipText("Enter the port number of the network tuner");
content.add(mPortField, "span2,grow,wrap");
mFrequencyLabel = new JLabel("Frequency (Hz):");
content.add(mFrequencyLabel);
mFrequencyField = new JTextField("");
mFrequencyField.setToolTipText("Enter the center frequency of the network tuner in Hertz (Hz)");
content.add(mFrequencyField, "span2,grow,wrap");
content.add(new JLabel(""), "wrap");
content.add(new JLabel(""));
mAddButton = new JButton("Add");
// mAddButton.setEnabled(false);
mAddButton.addActionListener(e -> {
long frequency = getFrequency();
if (frequency <= 0 || frequency > Integer.MAX_VALUE) {
JOptionPane.showMessageDialog(AddNetworkTunerDialog.this,
"Please provide a center frequency (1Hz to 2.14 GHz)",
"Center Frequency Required",
JOptionPane.ERROR_MESSAGE);
return;
setResultConverter(buttonType -> {
if (buttonType == ADD) {
addTuner();
}
mLog.info("Adding network tuner = frequency [" + frequency + "] host [" + getHost() + ":" + getPort() + "]");
try {
NetworkTunerConfiguration config = NetworkTunerConfiguration.create();
config.setFrequency(frequency);
config.setHost(getHost());
config.setPort(getPort());
mTunerConfigurationManager.addTunerConfiguration(config);
DiscoveredNetworkTuner discoveredNetworkTuner = new DiscoveredNetworkTuner(mUserPreferences, config);
mDiscoveredTunerModel.addDiscoveredTuner(discoveredNetworkTuner);
} catch (Exception ex) {
mLog.error("Error adding network tuner", ex);
}
AddNetworkTunerDialog.this.setVisible(false);
return buttonType;
});
content.add(mAddButton, "grow,push");
mCancelButton = new JButton("Cancel");
mCancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddNetworkTunerDialog.this.setVisible(false);
}
});
content.add(mCancelButton, "grow,push");
setContentPane(content);
Platform.runLater(mHostField::requestFocus);
}
private long getFrequency() {
String text = mFrequencyField.getText();
if (text != null && !text.isEmpty()) {
try {
return Long.parseLong(text);
} catch (Exception e) {
// Do nothing, we couldn't parse the frequency value
}
/**
* Validation error for the current entries, or null when they are valid.
*/
private String getValidationError() {
if (getHost().isEmpty()) {
return "Enter the host name or IP address of the rtl_tcp server";
}
return 0l;
if (getPort() <= 0) {
return "Enter a port number from 1 to " + Short.MAX_VALUE;
}
Long frequency = FrequencyEntry.parse(mFrequencyField.getText());
if (frequency == null || frequency <= 0 || frequency > Integer.MAX_VALUE) {
return "Enter a center frequency up to 2147.483647 MHz";
}
return null;
}
private void addTuner() {
long frequency = FrequencyEntry.parse(mFrequencyField.getText());
mLog.info("Adding network tuner = frequency [" + frequency + "] host [" + getHost() + ":" + getPort() + "]");
try {
NetworkTunerConfiguration config = NetworkTunerConfiguration.create();
config.setFrequency(frequency);
config.setHost(getHost());
config.setPort(getPort());
mTunerConfigurationManager.addTunerConfiguration(config);
DiscoveredNetworkTuner discoveredNetworkTuner = new DiscoveredNetworkTuner(mUserPreferences, config);
mDiscoveredTunerModel.addDiscoveredTuner(discoveredNetworkTuner);
} catch (Exception ex) {
mLog.error("Error adding network tuner", ex);
}
}
private String getHost() {
return mHostField.getText();
return mHostField.getText() == null ? "" : mHostField.getText().trim();
}
private short getPort() {
String text = mPortField.getText();
if (text != null && !text.isEmpty()) {
try {
return Short.parseShort(text);
} catch (Exception e) {
// Do nothing, we couldn't parse the port value
}
try {
return Short.parseShort(mPortField.getText().trim());
} catch (Exception e) {
return 0;
}
return 0;
}
}

View File

@@ -18,42 +18,30 @@
*/
package io.github.dsheirer.source.tuner.network;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.Label;
/**
* Minimal tuner editor for a network (rtl_tcp) tuner that has not been started. Mirrors
* RTL2832UnknownTunerEditor's pattern: only the id/status labels and the button panel are shown -
* no frequency/sample-rate/gain controls, since there's no live tuner to configure yet.
* Editor for a network tuner that is disabled or not connected. Shows the status and the enable switch only.
*/
public class NetworkTunerDisabledEditor extends TunerEditor<NetworkTuner, NetworkTunerConfiguration> {
private static final long serialVersionUID = 1L;
public NetworkTunerDisabledEditor(UserPreferences userPreferences, TunerManager tunerManager,
DiscoveredTuner discoveredTuner) {
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection section = addSection("Network Tuner");
Label message = new Label("Enable the tuner to connect to the rtl_tcp server and change its settings.");
message.setWrapText(true);
section.addFullRow(message);
refresh();
}
private void init() {
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]", "[][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
@Override
protected boolean hasTuningControls() {
return false;
}
@Override
@@ -75,20 +63,6 @@ public class NetworkTunerDisabledEditor extends TunerEditor<NetworkTuner, Networ
@Override
protected void tunerStatusUpdated() {
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if (getDiscoveredTuner().hasErrorMessage()) {
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
setLoading(false);
}
@Override
public void setTunerLockState(boolean locked) {
getFrequencyPanel().updateControls();
//No-op - the header shows the status
}
}

View File

@@ -18,53 +18,37 @@
*/
package io.github.dsheirer.source.tuner.network;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.rtl.RTL2832TunerController.SampleRate;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
import javafx.util.StringConverter;
/**
* Editor for an rtl_tcp network tuner.
*/
public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerConfiguration> {
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(NetworkTunerEditor.class);
private static final List<Integer> R820T_GAINS_TENTHS_DB = List.of(0, 9, 14, 27, 37, 77, 87, 125, 144, 157, 166,
197, 207, 229, 254, 280, 297, 328, 338, 364, 372, 386, 402, 421, 434, 439, 445, 480, 496);
//R820T total gain table (tenths of dB), from librtlsdr's rtlsdr_get_tuner_gains() - most rtl_tcp
//servers are backed by an R820T/R820T2 dongle and report this same gain table.
private static final Integer[] R820T_GAINS_TENTHS_DB = {0, 9, 14, 27, 37, 77, 87, 125, 144, 157, 166, 197, 207,
229, 254, 280, 297, 328, 338, 364, 372, 386, 402, 421, 434, 439, 445, 480, 496};
private JButton mTunerInfoButton;
private JToggleButton mBiasTButton;
private JComboBox<SampleRate> mSampleRateCombo;
private JCheckBox mGainAutoCheckBox;
private JComboBox<Integer> mGainCombo;
private JCheckBox mAutoReconnectCheckBox;
private CheckBox mBiasTCheckBox;
private ComboBox<SampleRate> mSampleRateCombo;
private CheckBox mGainAutoCheckBox;
private ComboBox<Integer> mGainCombo;
private CheckBox mAutoReconnectCheckBox;
public NetworkTunerEditor(UserPreferences userPreferences, TunerManager tunerManager,
DiscoveredTuner discoveredTuner) {
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
}
@Override
public void setTunerLockState(boolean locked) {
getFrequencyPanel().updateControls();
//Matches the USB RTL2832/R8x tuner pattern: sample rate can't change while channels are active. Gain and
//Bias-T don't affect channelizing, so they remain adjustable regardless of lock state.
getSampleRateCombo().setEnabled(hasTuner() && !locked);
refresh();
}
@Override
@@ -74,134 +58,92 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
@Override
public long getMaximumTunableFrequency() {
return 2200000000l;
return 2200000000L;
}
private void init() {
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
TunerSection gain = addSection("Gain");
gain.addRow("Gain", getGainCombo(), getGainAutoCheckBox());
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
options.addControl(getAutoReconnectCheckBox());
}
@Override
protected void tunerStatusUpdated() {
setLoading(true);
if (hasTuner()) {
getTunerIdLabel().setText(getTuner().getPreferredName());
} else {
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if (getDiscoveredTuner().hasErrorMessage()) {
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getTunerInfoButton().setEnabled(hasTuner());
getBiasTButton().setEnabled(hasTuner());
getSampleRateCombo().setEnabled(hasTuner());
getGainAutoCheckBox().setEnabled(hasTuner());
getAutoReconnectCheckBox().setEnabled(hasTuner());
getBiasTCheckBox().setDisable(!hasTuner());
getGainAutoCheckBox().setDisable(!hasTuner());
getAutoReconnectCheckBox().setDisable(!hasTuner());
updateSampleRateControl();
if (hasConfiguration()) {
getBiasTButton().setSelected(getConfiguration().isBiasTEnabled());
getSampleRateCombo().setSelectedItem(closestSampleRate(getConfiguration().getSampleRate()));
getBiasTCheckBox().setSelected(getConfiguration().isBiasTEnabled());
getSampleRateCombo().setValue(closestSampleRate(getConfiguration().getSampleRate()));
getGainAutoCheckBox().setSelected(getConfiguration().isGainAuto());
getGainCombo().setSelectedItem(closestGain(getConfiguration().getGain()));
getGainCombo().setEnabled(hasTuner() && !getConfiguration().isGainAuto());
getGainCombo().setValue(closestGain(getConfiguration().getGain()));
getGainCombo().setDisable(!hasTuner() || getConfiguration().isGainAuto());
getAutoReconnectCheckBox().setSelected(getConfiguration().isAutoReconnect());
} else {
getGainCombo().setDisable(true);
}
}
@Override
protected void tunerLockStateUpdated(boolean locked) {
updateSampleRateControl();
}
private void updateSampleRateControl() {
getSampleRateCombo().setDisable(!hasTuner() || getTuner().getTunerController().isLockedSampleRate());
}
@Override
protected String getTunerInfo() {
if (!hasConfiguration()) {
return null;
}
setLoading(false);
return "<html><h3>rtl_tcp Network Tuner</h3>" +
"<b>Host: </b>" + getConfiguration().getHost() + "<br>" +
"<b>Port: </b>" + getConfiguration().getPort() + "<br>" +
"<b>Tuner Type: </b>rtl_tcp<br>";
}
private void init() {
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]", "[][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
add(new JLabel("Status:"));
add(getTunerStatusLabel());
add(getBiasTButton(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainAutoCheckBox(), "split 2");
add(getGainCombo(), "wrap");
add(new JLabel("Auto-Reconnect:"));
add(getAutoReconnectCheckBox(), "wrap");
}
/**
* Bias-T toggle button, matching the USB RTL2832/R8x tuner editor's top-row placement.
*/
private JToggleButton getBiasTButton() {
if (mBiasTButton == null) {
mBiasTButton = new JToggleButton("Bias-T");
mBiasTButton.setEnabled(false);
mBiasTButton.addActionListener(e -> {
private CheckBox getBiasTCheckBox() {
if (mBiasTCheckBox == null) {
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setTooltip(new Tooltip("Ask the rtl_tcp server to provide DC power on the antenna connector"));
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setOnAction(e -> {
if (!isLoading()) {
boolean enabled = mBiasTButton.isSelected();
if (hasTuner()) {
getTuner().getTunerController().setBiasTEnabled(enabled);
getTuner().getTunerController().setBiasTEnabled(mBiasTCheckBox.isSelected());
}
save();
}
});
}
return mBiasTButton;
return mBiasTCheckBox;
}
/**
* Hyperlink-style button that shows the network tuner's connection details.
*/
private JButton getTunerInfoButton() {
if (mTunerInfoButton == null) {
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(NetworkTunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
private String getTunerInfo() {
StringBuilder sb = new StringBuilder();
sb.append("<html><h3>rtl_tcp Network Tuner</h3>");
sb.append("<b>Host: </b>").append(getConfiguration().getHost()).append("<br>");
sb.append("<b>Port: </b>").append(getConfiguration().getPort()).append("<br>");
sb.append("<b>Tuner Type: </b>rtl_tcp<br>");
return sb.toString();
}
private JComboBox<SampleRate> getSampleRateCombo() {
private ComboBox<SampleRate> getSampleRateCombo() {
if (mSampleRateCombo == null) {
mSampleRateCombo = new JComboBox<>(SampleRate.values());
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if (!isLoading()) {
SampleRate sampleRate = (SampleRate) mSampleRateCombo.getSelectedItem();
mSampleRateCombo = new ComboBox<>(FXCollections.observableArrayList(SampleRate.values()));
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
SampleRate sampleRate = mSampleRateCombo.getValue();
if (sampleRate != null) {
if (hasTuner()) {
getTuner().getTunerController().setSampleRate(sampleRate.getRate());
}
save();
if (!isLoading() && sampleRate != null) {
if (hasTuner()) {
getTuner().getTunerController().setSampleRate(sampleRate.getRate());
adjustForSampleRate(sampleRate.getRate());
}
save();
}
});
}
@@ -209,18 +151,18 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
return mSampleRateCombo;
}
private JCheckBox getGainAutoCheckBox() {
private CheckBox getGainAutoCheckBox() {
if (mGainAutoCheckBox == null) {
mGainAutoCheckBox = new JCheckBox("Auto");
mGainAutoCheckBox.addActionListener(e -> {
mGainAutoCheckBox = new CheckBox("Auto");
mGainAutoCheckBox.setTooltip(new Tooltip("Let the rtl_tcp server's tuner set the gain automatically"));
mGainAutoCheckBox.setOnAction(e -> {
boolean gainAuto = mGainAutoCheckBox.isSelected();
getGainCombo().setEnabled(hasTuner() && !gainAuto);
getGainCombo().setDisable(!hasTuner() || gainAuto);
if (!isLoading()) {
if (hasTuner()) {
getTuner().getTunerController().setGainAuto(gainAuto);
}
save();
}
});
@@ -229,22 +171,31 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
return mGainAutoCheckBox;
}
private JComboBox<Integer> getGainCombo() {
private ComboBox<Integer> getGainCombo() {
if (mGainCombo == null) {
mGainCombo = new JComboBox<>(R820T_GAINS_TENTHS_DB);
mGainCombo.setEnabled(false);
mGainCombo.setToolTipText("Gain in tenths of dB. Uncheck Auto to enable manual gain.");
mGainCombo.addActionListener(e -> {
if (!isLoading()) {
Integer gain = (Integer) mGainCombo.getSelectedItem();
mGainCombo = new ComboBox<>(FXCollections.observableArrayList(R820T_GAINS_TENTHS_DB));
mGainCombo.setMaxWidth(Double.MAX_VALUE);
mGainCombo.setDisable(true);
mGainCombo.setTooltip(new Tooltip("Manual gain. Uncheck Auto to enable manual gain."));
mGainCombo.setConverter(new StringConverter<>() {
@Override
public String toString(Integer gain) {
return gain == null ? "" : String.format("%.1f dB", gain / 10.0);
}
if (gain != null) {
if (hasTuner()) {
getTuner().getTunerController().setGain(gain);
}
@Override
public Integer fromString(String text) {
return null;
}
});
mGainCombo.setOnAction(e -> {
Integer gain = mGainCombo.getValue();
save();
if (!isLoading() && gain != null) {
if (hasTuner()) {
getTuner().getTunerController().setGain(gain);
}
save();
}
});
}
@@ -252,18 +203,16 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
return mGainCombo;
}
private JCheckBox getAutoReconnectCheckBox() {
private CheckBox getAutoReconnectCheckBox() {
if (mAutoReconnectCheckBox == null) {
mAutoReconnectCheckBox = new JCheckBox();
mAutoReconnectCheckBox.setToolTipText("Automatically reconnect if the connection to the rtl_tcp server is lost");
mAutoReconnectCheckBox.addActionListener(e -> {
mAutoReconnectCheckBox = new CheckBox("Auto-reconnect");
mAutoReconnectCheckBox.setTooltip(new Tooltip("Automatically reconnect if the connection to the rtl_tcp " +
"server is lost"));
mAutoReconnectCheckBox.setOnAction(e -> {
if (!isLoading()) {
boolean autoReconnect = mAutoReconnectCheckBox.isSelected();
if (hasTuner()) {
getTuner().getTunerController().setAutoReconnect(autoReconnect);
getTuner().getTunerController().setAutoReconnect(mAutoReconnectCheckBox.isSelected());
}
save();
}
});
@@ -272,9 +221,6 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
return mAutoReconnectCheckBox;
}
/**
* Finds the SampleRate enum value closest to the specified sample rate (Hz).
*/
private static SampleRate closestSampleRate(long sampleRate) {
SampleRate closest = SampleRate.values()[0];
@@ -287,11 +233,8 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
return closest;
}
/**
* Finds the R820T gain table entry closest to the specified gain value (tenths of dB).
*/
private static int closestGain(int gain) {
int closest = R820T_GAINS_TENTHS_DB[0];
int closest = R820T_GAINS_TENTHS_DB.get(0);
for (int candidate : R820T_GAINS_TENTHS_DB) {
if (Math.abs(candidate - gain) < Math.abs(closest - gain)) {
@@ -306,23 +249,21 @@ public class NetworkTunerEditor extends TunerEditor<NetworkTuner, NetworkTunerCo
public void save() {
if (hasConfiguration() && !isLoading()) {
NetworkTunerConfiguration config = getConfiguration();
config.setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
saveCommonSettings(config);
SampleRate sampleRate = getSampleRateCombo().getValue();
SampleRate sampleRate = (SampleRate) getSampleRateCombo().getSelectedItem();
if (sampleRate != null) {
config.setSampleRate(sampleRate.getRate());
}
config.setGainAuto(getGainAutoCheckBox().isSelected());
Integer gain = getGainCombo().getValue();
Integer gain = (Integer) getGainCombo().getSelectedItem();
if (gain != null) {
config.setGain(gain);
}
config.setBiasTEnabled(getBiasTButton().isSelected());
config.setBiasTEnabled(getBiasTCheckBox().isSelected());
config.setAutoReconnect(getAutoReconnectCheckBox().isSelected());
saveConfiguration();
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,246 +16,227 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.recording;
import io.github.dsheirer.gui.control.FrequencyEntry;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.configuration.TunerConfigurationManager;
import io.github.dsheirer.source.tuner.manager.DiscoveredRecordingTuner;
import io.github.dsheirer.source.tuner.ui.DiscoveredTunerModel;
import io.github.dsheirer.source.wave.SDRSharpIQRecording;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.miginfocom.swing.MigLayout;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* Dialog to select a recording and specify a center frequency for use in adding a Recording Tuner
* Dialog for adding a recording tuner that replays a baseband recording file.
*/
public class AddRecordingTunerDialog extends JFrame
public class AddRecordingTunerDialog extends Dialog<ButtonType>
{
private final static Logger mLog = LoggerFactory.getLogger(AddRecordingTunerDialog.class);
private static final String SELECT_A_FILE = "Please select a recording file";
private static final String SELECT_A_FILE = "No recording selected";
private static final String LAST_FILE_BROWSE_LOCATION_KEY = "AddRecordingTunerDialog.lastBrowseLocation";
private UserPreferences mUserPreferences;
private DiscoveredTunerModel mDiscoveredTunerModel;
private TunerConfigurationManager mTunerConfigurationManager;
private JButton mSelectFileButton;
private File mSelectedRecording;
private JLabel mRecordingFileLabel;
private JLabel mFrequencyLabel;
private JTextField mFrequencyTextField;
private JButton mAddButton;
private JButton mCancelButton;
private static final ButtonType ADD = new ButtonType("Add", ButtonBar.ButtonData.OK_DONE);
private static final Pattern TUNER_RECORDING_PATTERN = Pattern.compile(".*_(\\d*)_baseband_\\d{8}_\\d{6}\\.wav");
private final UserPreferences mUserPreferences;
private final DiscoveredTunerModel mDiscoveredTunerModel;
private final TunerConfigurationManager mTunerConfigurationManager;
private final Label mRecordingFileLabel = new Label(SELECT_A_FILE);
private final TextField mFrequencyField = new TextField();
private final Label mValidationLabel = new Label();
private File mSelectedRecording;
private Node mAddButton;
public AddRecordingTunerDialog(UserPreferences userPreferences, DiscoveredTunerModel discoveredTunerModel,
/**
* Constructs an instance
* @param owner window for the dialog
* @param userPreferences for the default recording directory
* @param discoveredTunerModel to add the recording tuner to
* @param tunerConfigurationManager to add the recording tuner configuration to
*/
public AddRecordingTunerDialog(Window owner, UserPreferences userPreferences, DiscoveredTunerModel discoveredTunerModel,
TunerConfigurationManager tunerConfigurationManager)
{
Validate.notNull(userPreferences, "UserPreferences cannot be null");
Validate.notNull(discoveredTunerModel, "TunerModel cannot be null");
Validate.notNull(tunerConfigurationManager, "TunerConfigurationManager cannot be null");
mDiscoveredTunerModel = discoveredTunerModel;
mUserPreferences = userPreferences;
mTunerConfigurationManager = tunerConfigurationManager;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("Select Recording File");
setSize(new Dimension(500, 250));
initOwner(owner);
setTitle("Add Recording Tuner");
setHeaderText("Replay a baseband recording (.wav or SDR# .iq) as a tuner");
JPanel content = new JPanel();
content.setLayout(new MigLayout("", "[align right][][]", "[][][grow][]"));
Button selectFileButton = new Button("Select ...");
selectFileButton.setOnAction(e -> selectFile());
mRecordingFileLabel.setWrapText(true);
mFrequencyField.setPromptText("e.g. 851.0125");
mValidationLabel.setWrapText(true);
mValidationLabel.setStyle("-fx-text-fill: #d9443a;");
mSelectFileButton = new JButton("Select ...");
mSelectFileButton.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
String lastBrowsedDirectory = SystemProperties.getInstance().get(LAST_FILE_BROWSE_LOCATION_KEY, "");
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(8);
grid.setPadding(new Insets(10));
grid.addRow(0, selectFileButton, mRecordingFileLabel);
grid.addRow(1, new Label("Frequency (MHz)"), mFrequencyField);
grid.add(mValidationLabel, 0, 2, 2, 1);
GridPane.setHgrow(mFrequencyField, Priority.ALWAYS);
grid.setPrefWidth(460);
File browseDirectory;
getDialogPane().setContent(grid);
getDialogPane().getButtonTypes().addAll(ADD, ButtonType.CANCEL);
mAddButton = getDialogPane().lookupButton(ADD);
mAddButton.setDisable(true);
mFrequencyField.textProperty().addListener((observable, oldValue, newValue) -> validate());
if(lastBrowsedDirectory != null && !lastBrowsedDirectory.isEmpty())
setResultConverter(buttonType -> {
if(buttonType == ADD)
{
browseDirectory = new File(lastBrowsedDirectory);
addTuner();
}
else
{
browseDirectory = mUserPreferences.getDirectoryPreference().getDefaultRecordingDirectory().toFile();
}
fileChooser.setCurrentDirectory(browseDirectory);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter basebandFilter = new FileNameExtensionFilter("Baseband Recordings (*.wav, *.iq)",
"wav", SDRSharpIQRecording.FILE_EXTENSION);
fileChooser.addChoosableFileFilter(basebandFilter);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Wave Recordings (*.wav)", "wav"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("SDRSharp I/Q Recordings (*.iq)",
SDRSharpIQRecording.FILE_EXTENSION));
fileChooser.setFileFilter(basebandFilter);
int returnVal = fileChooser.showOpenDialog(AddRecordingTunerDialog.this);
File lastDirectory = fileChooser.getCurrentDirectory();
if(lastDirectory != null)
{
SystemProperties.getInstance().set(LAST_FILE_BROWSE_LOCATION_KEY, lastDirectory.getAbsolutePath());
}
if(returnVal == JFileChooser.APPROVE_OPTION)
{
mSelectedRecording = fileChooser.getSelectedFile();
if(SDRSharpIQRecording.hasIQExtension(mSelectedRecording))
{
SDRSharpIQRecording iqRecording = SDRSharpIQRecording.parse(mSelectedRecording);
if(iqRecording == null)
{
JOptionPane.showMessageDialog(AddRecordingTunerDialog.this,
"<html>Unable to determine the sample rate and center frequency from the I/Q recording " +
"file name.<br>Expected format: <i>yyyyMMdd-HHmmss_label_TUNER_123456789Hz_10MSps.iq</i></html>",
"Unsupported I/Q Recording",
JOptionPane.ERROR_MESSAGE);
mSelectedRecording = null;
}
else
{
mLog.info("Selected " + iqRecording);
if(mFrequencyTextField.getText() == null || mFrequencyTextField.getText().isEmpty())
{
mFrequencyTextField.setText(String.valueOf(iqRecording.getCenterFrequency()));
}
}
}
else if(mSelectedRecording != null &&
(mFrequencyTextField.getText() == null || mFrequencyTextField.getText().isEmpty()))
{
Matcher m = TUNER_RECORDING_PATTERN.matcher(mSelectedRecording.getName());
if(m.matches())
{
mFrequencyTextField.setText(m.group(1));
}
}
mAddButton.setEnabled(mSelectedRecording != null);
}
else
{
mSelectedRecording = null;
}
mRecordingFileLabel.setText(mSelectedRecording != null ? mSelectedRecording.getName() : SELECT_A_FILE);
return buttonType;
});
content.add(mSelectFileButton);
mRecordingFileLabel = new JLabel(SELECT_A_FILE);
content.add(mRecordingFileLabel, "span 2,wrap");
mFrequencyLabel = new JLabel("Frequency (Hz):");
content.add(mFrequencyLabel);
mFrequencyTextField = new JTextField("");
mFrequencyTextField.setToolTipText("Center frequency for the recording in Hertz (Hz)");
content.add(mFrequencyTextField, "span 2,grow,wrap");
content.add(new JLabel(""), "wrap");
content.add(new JLabel(""));
mAddButton = new JButton("Add");
mAddButton.setEnabled(false);
mAddButton.addActionListener(e -> {
if(mSelectedRecording == null)
{
JOptionPane.showMessageDialog(AddRecordingTunerDialog.this,
"Please select a recording file",
"Select a Recording File",
JOptionPane.ERROR_MESSAGE);
return;
}
long frequency = getFrequency();
if(frequency <= 0 || frequency > Integer.MAX_VALUE)
{
JOptionPane.showMessageDialog(AddRecordingTunerDialog.this,
"Please provide a recording center frequency (1 Hz to 2.14 GHz)",
"Center Frequency Required",
JOptionPane.ERROR_MESSAGE);
return;
}
mLog.info("Adding recording tuner = frequency [" + frequency +
"] recording [" + mSelectedRecording.getAbsolutePath() + "]");
try
{
RecordingTunerConfiguration config = RecordingTunerConfiguration.create();
config.setFrequency(frequency);
config.setPath(mSelectedRecording.getAbsolutePath());
mTunerConfigurationManager.addTunerConfiguration(config);
DiscoveredRecordingTuner discoveredRecordingTuner = new DiscoveredRecordingTuner(mUserPreferences, config);
mDiscoveredTunerModel.addDiscoveredTuner(discoveredRecordingTuner);
}
catch(Exception ex)
{
mLog.error("Error adding recording tuner", ex);
}
AddRecordingTunerDialog.this.setVisible(false);
});
content.add(mAddButton, "grow,push");
mCancelButton = new JButton("Cancel");
mCancelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
AddRecordingTunerDialog.this.setVisible(false);
}
});
content.add(mCancelButton, "grow,push");
setContentPane(content);
}
private long getFrequency()
private void selectFile()
{
String text = mFrequencyTextField.getText();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Recording File");
String lastBrowsedDirectory = SystemProperties.getInstance().get(LAST_FILE_BROWSE_LOCATION_KEY, "");
File browseDirectory = (lastBrowsedDirectory != null && !lastBrowsedDirectory.isEmpty()) ?
new File(lastBrowsedDirectory) : mUserPreferences.getDirectoryPreference().getDefaultRecordingDirectory().toFile();
if(text != null && !text.isEmpty())
if(browseDirectory.isDirectory())
{
try
fileChooser.setInitialDirectory(browseDirectory);
}
FileChooser.ExtensionFilter basebandFilter = new FileChooser.ExtensionFilter("Baseband Recordings (*.wav, *.iq)",
"*.wav", "*." + SDRSharpIQRecording.FILE_EXTENSION);
fileChooser.getExtensionFilters().addAll(basebandFilter,
new FileChooser.ExtensionFilter("Wave Recordings (*.wav)", "*.wav"),
new FileChooser.ExtensionFilter("SDRSharp I/Q Recordings (*.iq)", "*." + SDRSharpIQRecording.FILE_EXTENSION));
fileChooser.setSelectedExtensionFilter(basebandFilter);
File selected = fileChooser.showOpenDialog(getDialogPane().getScene().getWindow());
if(selected == null)
{
return;
}
if(selected.getParentFile() != null)
{
SystemProperties.getInstance().set(LAST_FILE_BROWSE_LOCATION_KEY, selected.getParentFile().getAbsolutePath());
}
mSelectedRecording = selected;
if(SDRSharpIQRecording.hasIQExtension(selected))
{
SDRSharpIQRecording iqRecording = SDRSharpIQRecording.parse(selected);
if(iqRecording == null)
{
return Long.parseLong(text);
Alert alert = new Alert(Alert.AlertType.ERROR, "Unable to determine the sample rate and center " +
"frequency from the I/Q recording file name.\n\nExpected format: " +
"yyyyMMdd-HHmmss_label_TUNER_123456789Hz_10MSps.iq");
alert.initOwner(getDialogPane().getScene().getWindow());
alert.setTitle("Unsupported I/Q Recording");
alert.setHeaderText(null);
alert.showAndWait();
mSelectedRecording = null;
}
catch(Exception e)
else
{
//Do nothing, we couldn't parse the frequency value
mLog.info("Selected " + iqRecording);
if(mFrequencyField.getText() == null || mFrequencyField.getText().isEmpty())
{
mFrequencyField.setText(FrequencyEntry.format(iqRecording.getCenterFrequency()));
}
}
}
else if(mFrequencyField.getText() == null || mFrequencyField.getText().isEmpty())
{
Matcher m = TUNER_RECORDING_PATTERN.matcher(selected.getName());
if(m.matches() && !m.group(1).isEmpty())
{
try
{
mFrequencyField.setText(FrequencyEntry.format(Long.parseLong(m.group(1))));
}
catch(NumberFormatException nfe)
{
//Leave the frequency for the user to enter
}
}
}
return 0l;
mRecordingFileLabel.setText(mSelectedRecording != null ? mSelectedRecording.getName() : SELECT_A_FILE);
validate();
}
private void validate()
{
String error = null;
if(mSelectedRecording == null)
{
error = "Select a recording file";
}
else
{
Long frequency = FrequencyEntry.parse(mFrequencyField.getText());
if(frequency == null || frequency <= 0 || frequency > Integer.MAX_VALUE)
{
error = "Enter the recording's center frequency, up to 2147.483647 MHz";
}
}
mValidationLabel.setText(error == null ? "" : error);
mAddButton.setDisable(error != null);
}
private void addTuner()
{
long frequency = FrequencyEntry.parse(mFrequencyField.getText());
mLog.info("Adding recording tuner = frequency [" + frequency + "] recording [" +
mSelectedRecording.getAbsolutePath() + "]");
try
{
RecordingTunerConfiguration config = RecordingTunerConfiguration.create();
config.setFrequency(frequency);
config.setPath(mSelectedRecording.getAbsolutePath());
mTunerConfigurationManager.addTunerConfiguration(config);
DiscoveredRecordingTuner discoveredRecordingTuner = new DiscoveredRecordingTuner(mUserPreferences, config);
mDiscoveredTunerModel.addDiscoveredTuner(discoveredRecordingTuner);
}
catch(Exception ex)
{
mLog.error("Error adding recording tuner", ex);
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -22,39 +22,28 @@ import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javafx.scene.control.Label;
/**
* Recording tuner configuration editor
* Recording tuner editor. Shows the recording file and the frequency of the recording.
*/
public class RecordingTunerEditor extends TunerEditor<RecordingTuner,RecordingTunerConfiguration>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(RecordingTunerEditor.class);
private JLabel mRecordingPath;
private final Label mRecordingPath = new Label();
/**
* Constructs an instance
* @param userPreferences for wide-band recordings
* @param userPreferences for settings
* @param tunerManager for saving configurations
* @param discoveredTuner for this configuration
* @param discoveredTuner to edit
*/
public RecordingTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
mRecordingPath.setWrapText(true);
mRecordingPath.getStyleClass().add("tuner-value-label");
getTuningSection().addRow("File", mRecordingPath);
refresh();
}
@Override
@@ -72,62 +61,7 @@ public class RecordingTunerEditor extends TunerEditor<RecordingTuner,RecordingTu
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(null);
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
if(hasConfiguration())
{
getRecordingPath().setText(getConfiguration().getPath());
}
setLoading(false);
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill]",
"[][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(new JLabel("File:"));
add(getRecordingPath(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
}
private JLabel getRecordingPath()
{
if(mRecordingPath == null)
{
mRecordingPath = new JLabel();
}
return mRecordingPath;
mRecordingPath.setText(hasConfiguration() ? getConfiguration().getPath() : "");
}
@Override
@@ -137,9 +71,9 @@ public class RecordingTunerEditor extends TunerEditor<RecordingTuner,RecordingTu
{
RecordingTunerConfiguration config = getConfiguration();
config.setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
config.setMinimumFrequency(getMinimumFrequencyField().getFrequency());
config.setMaximumFrequency(getMaximumFrequencyField().getFrequency());
saveConfiguration();
}
}
}
}

View File

@@ -19,7 +19,6 @@
package io.github.dsheirer.source.tuner.rtl;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.TunerType;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
@@ -27,17 +26,12 @@ import io.github.dsheirer.source.tuner.rtl.RTL2832TunerController.SampleRate;
import io.github.dsheirer.source.tuner.rtl.e4k.E4KTunerConfiguration;
import io.github.dsheirer.source.tuner.rtl.r8x.R8xTunerConfiguration;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
/**
* RTL-2832 tuner editor for all supported embedded tuner types (E4000, FC0012, FC0013, FC2580, R820T and R828D).
@@ -47,15 +41,12 @@ import org.slf4j.LoggerFactory;
*/
public class RTL2832TunerEditor extends TunerEditor<RTL2832Tuner, RTL2832TunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(RTL2832TunerEditor.class);
private static final long serialVersionUID = 1L;
private JButton mTunerInfoButton;
private JToggleButton mBiasTButton;
private JComboBox<SampleRate> mSampleRateCombo;
private JToggleButton mAgcToggleButton;
private JComboBox<Gain> mGainCombo;
private JLabel mIFGainLabel;
private JComboBox<Integer> mIFGainCombo;
private ComboBox<SampleRate> mSampleRateCombo;
private CheckBox mBiasTCheckBox;
private CheckBox mAgcCheckBox;
private ComboBox<Gain> mGainCombo;
private Label mIFGainLabel;
private ComboBox<Integer> mIFGainCombo;
/**
* Constructs an instance
@@ -67,7 +58,7 @@ public class RTL2832TunerEditor extends TunerEditor<RTL2832Tuner, RTL2832TunerCo
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
refresh();
}
@Override
@@ -92,11 +83,6 @@ public class RTL2832TunerEditor extends TunerEditor<RTL2832Tuner, RTL2832TunerCo
return R8xTunerConfiguration.MAXIMUM_TUNABLE_FREQUENCY_HZ;
}
private String getLogPrefix()
{
return (hasTuner() ? getTuner().getController().getTunerType().getLabel() : "RTL-2832") + " Tuner Controller - ";
}
/**
* Indicates if the tuner has an E4000 embedded tuner, which supports IF gain control.
*/
@@ -107,338 +93,18 @@ public class RTL2832TunerEditor extends TunerEditor<RTL2832Tuner, RTL2832TunerCo
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
add(new JLabel("Tuner:"));
add(getTunerIdLabel());
add(getTunerInfoButton());
TunerSection gain = addSection("Gain");
gain.addRow("Gain", getGainCombo(), getAgcCheckBox());
mIFGainLabel = gain.addRow("IF Gain (dB)", getIFGainCombo());
add(new JLabel("Status:"));
add(getTunerStatusLabel());
add(getBiasTButton(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Gain Control"), "wrap");
add(new JLabel("Gain:"));
add(getGainCombo());
add(getAgcToggleButton(), "wrap");
add(getIFGainLabel());
add(getIFGainCombo(), "wrap");
TunerSection options = addSection("Options");
options.addControl(getBiasTCheckBox());
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
if(hasTuner())
{
getTunerIdLabel().setText(getTuner().getPreferredName());
}
else
{
getTunerIdLabel().setText(getDiscoveredTuner().getId());
}
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
DefaultComboBoxModel<Gain> gainModel = new DefaultComboBoxModel<>();
if(hasTuner())
{
RTL2832TunerController controller = getTuner().getController();
if(controller.hasGainControl())
{
for(int gain : controller.getTunerGains())
{
gainModel.addElement(new Gain(gain));
}
}
}
getGainCombo().setModel(gainModel);
boolean e4k = isE4K();
getIFGainLabel().setVisible(e4k);
getIFGainCombo().setVisible(e4k);
if(hasTuner() && hasConfiguration())
{
RTL2832TunerConfiguration config = getConfiguration();
getBiasTButton().setEnabled(true);
getBiasTButton().setSelected(config.isBiasT());
getTunerInfoButton().setEnabled(true);
getSampleRateCombo().setEnabled(true);
getSampleRateCombo().setSelectedItem(config.getSampleRate());
RTL2832TunerController controller = getTuner().getController();
//The FC2580 always uses its internal AGC and the FC0012 doesn't support AGC
boolean agc = controller.hasGainControl() ? controller.hasTunerAGC() && config.isAGC() : true;
getAgcToggleButton().setEnabled(controller.hasTunerAGC());
getAgcToggleButton().setSelected(agc);
getAgcToggleButton().setToolTipText(getAgcToolTip(controller));
getGainCombo().setEnabled(!agc && gainModel.getSize() > 0);
getGainCombo().setSelectedItem(new Gain(getTuner().getController().getClosestTunerGain(config.getGain())));
if(e4k && config instanceof E4KTunerConfiguration e4kConfig)
{
getIFGainCombo().setEnabled(true);
getIFGainCombo().setSelectedItem(e4kConfig.getIFGainDb());
}
}
else
{
getBiasTButton().setEnabled(false);
getBiasTButton().setSelected(false);
getTunerInfoButton().setEnabled(false);
getSampleRateCombo().setEnabled(false);
getAgcToggleButton().setEnabled(false);
getGainCombo().setEnabled(false);
getIFGainCombo().setEnabled(false);
}
updateSampleRateToolTip();
setLoading(false);
}
/**
* Bias-T toggle button
*/
private JToggleButton getBiasTButton()
{
if(mBiasTButton == null)
{
mBiasTButton = new JToggleButton("Bias-T");
mBiasTButton.setEnabled(false);
mBiasTButton.addActionListener(e -> {
if(!isLoading())
{
getTuner().getController().setBiasT(mBiasTButton.isSelected());
save();
}
});
}
return mBiasTButton;
}
/**
* Button that provides tuner information
*/
private JButton getTunerInfoButton()
{
if(mTunerInfoButton == null)
{
mTunerInfoButton = new JButton("Info");
mTunerInfoButton.setEnabled(false);
mTunerInfoButton.addActionListener(e -> JOptionPane.showMessageDialog(RTL2832TunerEditor.this,
getTunerInfo(), "Tuner Info", JOptionPane.INFORMATION_MESSAGE));
}
return mTunerInfoButton;
}
/**
* Applies the current AGC and gain settings to the tuner and saves the configuration.
*/
private void applyGain()
{
if(isLoading() || !hasTuner())
{
return;
}
boolean agc = getAgcToggleButton().isSelected();
Gain gain = (Gain)getGainCombo().getSelectedItem();
getGainCombo().setEnabled(!agc && getGainCombo().getItemCount() > 0);
try
{
getTuner().getController().setGain(agc, gain != null ? gain.value() : getConfiguration().getGain());
save();
}
catch(SourceException se)
{
JOptionPane.showMessageDialog(RTL2832TunerEditor.this, getLogPrefix() +
"couldn't apply the gain setting - " + se.getLocalizedMessage());
mLog.error(getLogPrefix() + "couldn't apply gain setting", se);
}
}
/**
* Tool tip for the AGC button that explains when the tuner doesn't support switching AGC.
*/
private static String getAgcToolTip(RTL2832TunerController controller)
{
if(!controller.hasGainControl())
{
return "The " + controller.getTunerType().getLabel() + " tuner always uses its automatic gain control (AGC)";
}
else if(!controller.hasTunerAGC())
{
return "The " + controller.getTunerType().getLabel() + " tuner doesn't support automatic gain control (AGC)";
}
return "Turn on the tuner's automatic gain control (AGC)";
}
private JToggleButton getAgcToggleButton()
{
if(mAgcToggleButton == null)
{
mAgcToggleButton = new JToggleButton("AGC");
mAgcToggleButton.setEnabled(false);
mAgcToggleButton.setToolTipText("Turn on the tuner's automatic gain control (AGC)");
mAgcToggleButton.addActionListener(e -> applyGain());
}
return mAgcToggleButton;
}
private JComboBox<Gain> getGainCombo()
{
if(mGainCombo == null)
{
mGainCombo = new JComboBox<>();
mGainCombo.setEnabled(false);
mGainCombo.setToolTipText("Tuner gain. Turn off AGC to enable adjustment.");
mGainCombo.addActionListener(e -> applyGain());
}
return mGainCombo;
}
private JLabel getIFGainLabel()
{
if(mIFGainLabel == null)
{
mIFGainLabel = new JLabel("IF Gain (dB):");
}
return mIFGainLabel;
}
private JComboBox<Integer> getIFGainCombo()
{
if(mIFGainCombo == null)
{
mIFGainCombo = new JComboBox<>();
for(int gain = RTL2832TunerController.E4K_IF_GAIN_MINIMUM; gain <= RTL2832TunerController.E4K_IF_GAIN_MAXIMUM; gain++)
{
mIFGainCombo.addItem(gain);
}
mIFGainCombo.setEnabled(false);
mIFGainCombo.setToolTipText("E4000 IF gain, distributed across the six IF gain stages");
mIFGainCombo.addActionListener(e ->
{
Integer gain = (Integer)mIFGainCombo.getSelectedItem();
if(!isLoading() && hasTuner() && gain != null)
{
try
{
getTuner().getController().setE4KIFGain(gain);
save();
}
catch(SourceException se)
{
JOptionPane.showMessageDialog(RTL2832TunerEditor.this, getLogPrefix() +
"couldn't apply the IF gain setting - " + se.getLocalizedMessage());
mLog.error(getLogPrefix() + "couldn't apply IF gain setting", se);
}
}
});
}
return mIFGainCombo;
}
private JComboBox<SampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>(SampleRate.values());
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e ->
{
if(!isLoading())
{
SampleRate sampleRate = (SampleRate) mSampleRateCombo.getSelectedItem();
try
{
getTuner().getController().setSampleRate(sampleRate);
//Adjust the min/max values for the sample rate.
adjustForSampleRate(sampleRate.getRate());
save();
}
catch(SourceException se)
{
JOptionPane.showMessageDialog(RTL2832TunerEditor.this,
getLogPrefix() + "couldn't apply the sample rate setting [" +
sampleRate.getLabel() + "] " + se.getLocalizedMessage());
mLog.error(getLogPrefix() + "couldn't apply sample rate setting [" + sampleRate.getLabel() +
"]", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
private String getTunerInfo()
protected String getTunerInfo()
{
StringBuilder sb = new StringBuilder();
RTL2832TunerController.Descriptor descriptor = getTuner().getController().getDescriptor();
@@ -463,28 +129,242 @@ public class RTL2832TunerEditor extends TunerEditor<RTL2832Tuner, RTL2832TunerCo
return sb.toString();
}
@Override
protected void tunerStatusUpdated()
{
getGainCombo().getItems().clear();
if(hasTuner())
{
RTL2832TunerController controller = getTuner().getController();
if(controller.hasGainControl())
{
for(int gain : controller.getTunerGains())
{
getGainCombo().getItems().add(new Gain(gain));
}
}
}
boolean e4k = isE4K();
mIFGainLabel.setVisible(e4k);
getIFGainCombo().setVisible(e4k);
if(hasTuner() && hasConfiguration())
{
RTL2832TunerConfiguration config = getConfiguration();
RTL2832TunerController controller = getTuner().getController();
getBiasTCheckBox().setDisable(false);
getBiasTCheckBox().setSelected(config.isBiasT());
getSampleRateCombo().setValue(config.getSampleRate());
//The FC2580 always uses its internal AGC and the FC0012 doesn't support AGC
boolean agc = controller.hasGainControl() ? controller.hasTunerAGC() && config.isAGC() : true;
getAgcCheckBox().setDisable(!controller.hasTunerAGC());
getAgcCheckBox().setSelected(agc);
getAgcCheckBox().setTooltip(new Tooltip(getAgcToolTip(controller)));
getGainCombo().setDisable(agc || getGainCombo().getItems().isEmpty());
getGainCombo().setValue(new Gain(controller.getClosestTunerGain(config.getGain())));
if(e4k && config instanceof E4KTunerConfiguration e4kConfig)
{
getIFGainCombo().setDisable(false);
getIFGainCombo().setValue(e4kConfig.getIFGainDb());
}
}
else
{
getBiasTCheckBox().setDisable(true);
getBiasTCheckBox().setSelected(false);
getAgcCheckBox().setDisable(true);
getGainCombo().setDisable(true);
getIFGainCombo().setDisable(true);
}
updateSampleRateControl();
}
@Override
protected void tunerLockStateUpdated(boolean locked)
{
updateSampleRateControl();
}
/**
* Updates the sample rate combo's enabled state and tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateControl()
{
boolean locked = hasTuner() && getTuner().getTunerController().isLockedSampleRate();
getSampleRateCombo().setDisable(!hasTuner() || !hasConfiguration() || locked);
if(locked)
{
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
}
else if(hasTuner())
{
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
}
else
{
getSampleRateCombo().setTooltip(new Tooltip("No tuner available"));
}
}
private CheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new CheckBox("Bias-T");
mBiasTCheckBox.setTooltip(new Tooltip("Provide DC power on the antenna connector (e.g. for an LNA)"));
mBiasTCheckBox.setDisable(true);
mBiasTCheckBox.setOnAction(e -> {
if(!isLoading() && hasTuner())
{
getTuner().getController().setBiasT(mBiasTCheckBox.isSelected());
save();
}
});
}
return mBiasTCheckBox;
}
/**
* Applies the current AGC and gain settings to the tuner and saves the configuration.
*/
private void applyGain()
{
if(isLoading() || !hasTuner())
{
return;
}
boolean agc = getAgcCheckBox().isSelected();
Gain gain = getGainCombo().getValue();
getGainCombo().setDisable(agc || getGainCombo().getItems().isEmpty());
if(applyToTuner("gain", () -> getTuner().getController().setGain(agc,
gain != null ? gain.value() : getConfiguration().getGain())))
{
save();
}
}
/**
* Tool tip for the AGC control that explains when the tuner doesn't support switching AGC.
*/
private static String getAgcToolTip(RTL2832TunerController controller)
{
if(!controller.hasGainControl())
{
return "The " + controller.getTunerType().getLabel() + " tuner always uses its automatic gain control (AGC)";
}
else if(!controller.hasTunerAGC())
{
return "The " + controller.getTunerType().getLabel() + " tuner doesn't support automatic gain control (AGC)";
}
return "Turn on the tuner's automatic gain control (AGC)";
}
private CheckBox getAgcCheckBox()
{
if(mAgcCheckBox == null)
{
mAgcCheckBox = new CheckBox("AGC");
mAgcCheckBox.setDisable(true);
mAgcCheckBox.setTooltip(new Tooltip("Turn on the tuner's automatic gain control (AGC)"));
mAgcCheckBox.setOnAction(e -> applyGain());
}
return mAgcCheckBox;
}
private ComboBox<Gain> getGainCombo()
{
if(mGainCombo == null)
{
mGainCombo = new ComboBox<>();
mGainCombo.setMaxWidth(Double.MAX_VALUE);
mGainCombo.setDisable(true);
mGainCombo.setTooltip(new Tooltip("Tuner gain. Turn off AGC to enable adjustment."));
mGainCombo.setOnAction(e -> applyGain());
}
return mGainCombo;
}
private ComboBox<Integer> getIFGainCombo()
{
if(mIFGainCombo == null)
{
mIFGainCombo = new ComboBox<>();
mIFGainCombo.setMaxWidth(Double.MAX_VALUE);
for(int gain = RTL2832TunerController.E4K_IF_GAIN_MINIMUM; gain <= RTL2832TunerController.E4K_IF_GAIN_MAXIMUM; gain++)
{
mIFGainCombo.getItems().add(gain);
}
mIFGainCombo.setDisable(true);
mIFGainCombo.setTooltip(new Tooltip("E4000 IF gain, distributed across the six IF gain stages"));
mIFGainCombo.setOnAction(e -> {
Integer gain = mIFGainCombo.getValue();
if(!isLoading() && hasTuner() && gain != null &&
applyToTuner("IF gain", () -> getTuner().getController().setE4KIFGain(gain)))
{
save();
}
});
}
return mIFGainCombo;
}
private ComboBox<SampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>(FXCollections.observableArrayList(SampleRate.values()));
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
SampleRate sampleRate = mSampleRateCombo.getValue();
if(!isLoading() && hasTuner() && sampleRate != null &&
applyToTuner("sample rate [" + sampleRate.getLabel() + "]",
() -> getTuner().getController().setSampleRate(sampleRate)))
{
//Adjust the min/max values for the sample rate.
adjustForSampleRate(sampleRate.getRate());
save();
}
});
}
return mSampleRateCombo;
}
@Override
public void save()
{
if(hasConfiguration() && !isLoading())
{
RTL2832TunerConfiguration config = getConfiguration();
saveCommonSettings(config);
config.setBiasT(getTuner().getController().isBiasT());
config.setFrequency(getFrequencyControl().getFrequency());
config.setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
config.setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel)getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
config.setFrequencyCorrection(value);
config.setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
config.setSampleRate((SampleRate)getSampleRateCombo().getSelectedItem());
config.setAGC(getAgcToggleButton().isSelected());
config.setSampleRate(getSampleRateCombo().getValue());
config.setAGC(getAgcCheckBox().isSelected());
if(getGainCombo().getSelectedItem() instanceof Gain gain)
if(getGainCombo().getValue() instanceof Gain gain)
{
config.setGain(gain.value());
}
if(config instanceof E4KTunerConfiguration e4k && getIFGainCombo().getSelectedItem() instanceof Integer ifGain)
if(config instanceof E4KTunerConfiguration e4k && getIFGainCombo().getValue() instanceof Integer ifGain)
{
e4k.setIFGainDb(ifGain);
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.rtl;
import io.github.dsheirer.preference.UserPreferences;
@@ -24,46 +23,32 @@ import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.rtl.r8x.R8xTunerConfiguration;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.Label;
/**
* Tuner editor for RTL2832 tuner that has not been started, or for an unknown tuner type
* Editor for an RTL-2832 with an embedded tuner type that sdrtrunk doesn't support. Only shows the tuner status.
*/
public class RTL2832UnknownTunerEditor extends TunerEditor<RTL2832Tuner, RTL2832TunerConfiguration>
{
/**
* Constructs an instance
*
* @param userPreferences for starting wide-band recorders
* @param tunerManager for requesting configuration saves.
* @param discoveredTuner that is not started, or that doesn't have a recognized tuner type
*/
private final Label mUniqueIdLabel = new Label();
public RTL2832UnknownTunerEditor(UserPreferences userPreferences, TunerManager tunerManager,
DiscoveredTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection section = addSection("Unsupported Tuner");
Label message = new Label("This RTL-2832 device has an embedded tuner type that isn't supported.");
message.setWrapText(true);
section.addFullRow(message);
section.addRow("ID", mUniqueIdLabel);
refresh();
}
private void init()
@Override
protected boolean hasTuningControls()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
return false;
}
@Override
@@ -89,22 +74,6 @@ public class RTL2832UnknownTunerEditor extends TunerEditor<RTL2832Tuner, RTL2832
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId() + (hasTuner() ? " ID:" + getTuner().getUniqueID() : ""));
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
setLoading(false);
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
mUniqueIdLabel.setText(hasTuner() ? getTuner().getUniqueID() : getDiscoveredTuner().getId());
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,59 +16,82 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.sdrplay.Tuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.ui.GainSlider;
import io.github.dsheirer.source.tuner.ui.TunerEditor;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import io.github.dsheirer.util.ThreadPool;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import net.miginfocom.swing.MigLayout;
import javafx.css.PseudoClass;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToggleButton;
/**
* Abstract RSP tuner editor
* Base SDRPlay RSP tuner editor. Provides the sample rate control, the gain section (LNA state, IF gain reduction,
* IF AGC, gain readout and overload indicator) and helpers for binding the model specific option check boxes and
* choices to the device.
*/
public abstract class RspTunerEditor<C extends RspTunerConfiguration> extends TunerEditor<RspTuner,C> implements ITunerStatusListener
public abstract class RspTunerEditor<C extends RspTunerConfiguration> extends TunerEditor<RspTuner,C>
implements ITunerStatusListener
{
private Logger mLog = LoggerFactory.getLogger(RspTunerEditor.class);
protected static final String MANUAL = "Manual";
protected static final String AUTOMATIC = "Automatic";
private JToggleButton mAgcButton;
private JLabel mGainValueLabel;
private LnaSlider mLNASlider;
private IfGainSlider mIfGainSlider;
private JButton mGainOverloadButton;
private JPanel mGainPanel;
private AtomicBoolean mGainOverloadAlert = new AtomicBoolean();
private static final Logger mLog = LoggerFactory.getLogger(RspTunerEditor.class);
private static final PseudoClass OVERLOAD = PseudoClass.getPseudoClass("overload");
private static final int IF_GAIN_SLIDER_MAX = 39;
private ComboBox<RspSampleRate> mSampleRateCombo;
private CheckBox mAgcCheckBox;
private Label mGainValueLabel;
private Label mGainOverloadLabel;
private GainSlider mLNASlider;
private GainSlider mIfGainSlider;
private Label mLnaLabel;
private Label mIfGainLabel;
private boolean mGainOverloadAlert;
private final List<Option> mOptions = new ArrayList<>();
private final List<Choice<?>> mChoices = new ArrayList<>();
/**
* Constructs an instance
* @param userPreferences for preference settings
* @param tunerManager to notify for state changes
* @param discoveredTuner to be edited.
* Constructs an instance. Implementations add their own sections and then call {@link #refresh()}.
*/
public RspTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
getTuningSection().addRow("Sample Rate", getSampleRateCombo());
TunerSection gain = addSection("Gain");
HBox readout = new HBox(getGainValueLabel(), getGainOverloadLabel());
readout.getStyleClass().add("tuner-flow-row");
gain.addRow("Gain", readout);
mLnaLabel = gain.addRow("LNA", getLNASlider(), new Region());
mIfGainLabel = gain.addRow("IF", getIfGainSlider(), getAgcCheckBox());
}
private RspTunerController getTunerController()
/**
* Discovered RSP tuner
*/
protected DiscoveredRspTuner getDiscoveredRspTuner()
{
return (RspTunerController) getTuner().getTunerController();
return (DiscoveredRspTuner)getDiscoveredTuner();
}
/**
* Device control for the tuner. Only use when the editor has a tuner.
*/
protected IControlRsp getControlRsp()
{
return getTuner().getRspTunerController().getControlRsp();
}
@Override
@@ -84,92 +107,201 @@ public abstract class RspTunerEditor<C extends RspTunerConfiguration> extends Tu
}
/**
* Gain controls panel
* @return gain panel
* Sample rates to offer. Defaults to the single tuner sample rates.
*/
protected JPanel getGainPanel()
protected Collection<RspSampleRate> getSampleRates()
{
if(mGainPanel == null)
{
mGainPanel = new JPanel();
mGainPanel.setLayout(new MigLayout("insets 0","[][][grow,fill][][]",""));
mGainPanel.add(getGainValueLabel());
mGainPanel.add(getGainOverloadButton());
mGainPanel.add(new JLabel()); //empty label to grow to fill space
mGainPanel.add(new JLabel("IF Gain Mode:"));
mGainPanel.add(getAgcButton());
}
return mGainPanel;
return RspSampleRate.SINGLE_TUNER_SAMPLE_RATES;
}
/**
* Label for displaying current gain index value
* Indicates if the user can change the sample rate (when it isn't locked by active channels). Defaults to true.
*/
protected JLabel getGainValueLabel()
protected boolean isSampleRateChangeable()
{
return true;
}
/**
* Implementation specific updates after the common RSP controls are refreshed. Invoked while loading.
*/
protected void rspTunerStatusUpdated()
{
}
@Override
protected final void tunerStatusUpdated()
{
getSampleRateCombo().getItems().setAll(hasTuner() ? getSampleRates() : List.of());
getSampleRateCombo().setValue(hasTuner() ? getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateControl();
getAgcCheckBox().setDisable(!hasTuner());
if(hasTuner())
{
RspAgcMode current = getControlRsp().getAgcMode();
getAgcCheckBox().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getLNASlider().setRange(0, getControlRsp().getMaximumLNASetting());
setLNA(getControlRsp().getLNA());
setGainReduction(getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
else
{
getGainValueLabel().setText("");
}
getLNASlider().setDisable(!hasTuner());
mLnaLabel.setDisable(!hasTuner());
boolean ifManual = hasTuner() && !getAgcCheckBox().isSelected();
getIfGainSlider().setDisable(!ifManual);
mIfGainLabel.setDisable(!ifManual);
getGainValueLabel().setDisable(!hasTuner());
for(Option option: mOptions)
{
option.refresh();
}
for(Choice<?> choice: mChoices)
{
choice.refresh();
}
rspTunerStatusUpdated();
}
@Override
protected void tunerLockStateUpdated(boolean locked)
{
updateSampleRateControl();
}
private void updateSampleRateControl()
{
boolean locked = hasTuner() && getTuner().getTunerController().isLockedSampleRate();
getSampleRateCombo().setDisable(!hasTuner() || !isSampleRateChangeable() || locked);
if(locked)
{
getSampleRateCombo().setTooltip(new Tooltip("Sample rate is locked. Disable decoding channels to unlock."));
}
else if(!hasTuner())
{
getSampleRateCombo().setTooltip(new Tooltip("No tuner available"));
}
else if(!isSampleRateChangeable())
{
getSampleRateCombo().setTooltip(new Tooltip("The sample rate is set by the master tuner"));
}
else
{
getSampleRateCombo().setTooltip(new Tooltip("Select a sample rate for the tuner"));
}
}
/**
* Sample rate selection
*/
protected ComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new ComboBox<>();
mSampleRateCombo.setMaxWidth(Double.MAX_VALUE);
mSampleRateCombo.setDisable(true);
mSampleRateCombo.setOnAction(e -> {
RspSampleRate selected = mSampleRateCombo.getValue();
if(hasTuner() && !isLoading() && selected != null &&
applyToTuner("sample rate [" + selected + "]",
() -> getTuner().getRspTunerController().setSampleRate(selected)))
{
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
});
}
return mSampleRateCombo;
}
/**
* Copies the common RSP settings (sample rate and gain) and the base settings to the configuration.
*/
protected void saveRspSettings(C config)
{
saveCommonSettings(config);
if(getSampleRateCombo().getValue() != null)
{
config.setSampleRate(getSampleRateCombo().getValue());
}
config.setLNA(getLNA());
config.setBasebandGainReduction(getGainReduction());
config.setAgcMode(getAgcCheckBox().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
}
private Label getGainValueLabel()
{
if(mGainValueLabel == null)
{
mGainValueLabel = new JLabel("0");
mGainValueLabel.setEnabled(false);
mGainValueLabel = new Label();
mGainValueLabel.getStyleClass().add("tuner-value-label");
mGainValueLabel.setTooltip(new Tooltip("Current overall gain"));
}
return mGainValueLabel;
}
/**
* IF AGC mode (enable/disable) toggle button
*/
protected JToggleButton getAgcButton()
private Label getGainOverloadLabel()
{
if(mAgcButton == null)
if(mGainOverloadLabel == null)
{
mAgcButton = new JToggleButton(MANUAL);
mAgcButton.setEnabled(false);
mAgcButton.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setAgcMode(mAgcButton.isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
updateGainLabel();
}
catch(RspException se)
{
mLog.error("Error setting AGC mode on RSP device");
}
save();
}
getIfGainSlider().setEnabled(!getAgcButton().isSelected());
if(mAgcButton.isSelected())
{
getAgcButton().setText(AUTOMATIC);
}
else
{
getAgcButton().setText(MANUAL);
}
});
mGainOverloadLabel = new Label("Overload");
mGainOverloadLabel.getStyleClass().add("tuner-overload-indicator");
mGainOverloadLabel.setTooltip(new Tooltip("Lights when the manual gain is set too high and the signal " +
"overloads the tuner. Reduce the gain when this flashes."));
}
return mAgcButton;
return mGainOverloadLabel;
}
/**
* Gain overload button. Used in a disabled state to indicate (e.g. flashing color) that gain overload is detected.
* IF automatic gain control
*/
protected JButton getGainOverloadButton()
protected CheckBox getAgcCheckBox()
{
if(mGainOverloadButton == null)
if(mAgcCheckBox == null)
{
mGainOverloadButton = new JButton("Gain Overload");
mGainOverloadButton.setToolTipText("Notification that manual gain is set too high and causing power overload. Reduce manual gain when this flashes.");
mGainOverloadButton.setEnabled(false);
mAgcCheckBox = new CheckBox("AGC");
mAgcCheckBox.setTooltip(new Tooltip("Automatic IF gain control. Turn off to set the IF gain manually."));
mAgcCheckBox.setDisable(true);
mAgcCheckBox.setOnAction(e -> {
boolean agc = mAgcCheckBox.isSelected();
if(hasTuner() && !isLoading())
{
if(applyToTuner("AGC mode",
() -> getControlRsp().setAgcMode(agc ? RspAgcMode.ENABLE : RspAgcMode.DISABLE)))
{
updateGainLabel();
}
save();
}
getIfGainSlider().setDisable(agc);
mIfGainLabel.setDisable(agc);
});
}
return mGainOverloadButton;
return mAgcCheckBox;
}
@Override
@@ -177,210 +309,292 @@ public abstract class RspTunerEditor<C extends RspTunerConfiguration> extends Tu
{
if(hasTuner() && getTuner().getRspTunerController().getSdrplayTuner() == tuner)
{
//Set overload alert
EventQueue.invokeLater(() -> setGainOverloadAlert(true));
//Schedule a reset to happen 1 second later
ThreadPool.SCHEDULED.schedule((Runnable) () -> setGainOverloadAlert(false), 600, TimeUnit.MILLISECONDS);
runOnFxThread(() -> setGainOverloadAlert(true));
ThreadPool.SCHEDULED.schedule(() -> runOnFxThread(() -> setGainOverloadAlert(false)), 600,
TimeUnit.MILLISECONDS);
}
}
@Override
public void frequencyUpdated()
{
updateLnaSlider();
runOnFxThread(this::updateLnaSlider);
}
/**
* Toggles the alert styling of the disabled gain overload button to indicate an alert condition or a normal
* operating condition.
* @param alert true to apply alert styling or false to reset.
*/
private void setGainOverloadAlert(boolean alert)
{
if(alert && mGainOverloadAlert.compareAndSet(false, true))
if(alert != mGainOverloadAlert)
{
getGainOverloadButton().setEnabled(true);
getGainOverloadButton().setForeground(Color.YELLOW);
getGainOverloadButton().setBackground(Color.RED);
}
else if(!alert && mGainOverloadAlert.compareAndSet(true, false))
{
getGainOverloadButton().setEnabled(false);
getGainOverloadButton().setForeground(getForeground());
getGainOverloadButton().setBackground(getBackground());
mGainOverloadAlert = alert;
getGainOverloadLabel().pseudoClassStateChanged(OVERLOAD, alert);
}
}
/**
* Updates the LNA slider with the number of LNA states available for the current frequency.
* Updates the LNA slider range for the current frequency, since the number of LNA states depends on the band.
*/
protected void updateLnaSlider()
{
if(hasTuner())
{
int max = getTunerController().getControlRsp().getMaximumLNASetting();
if(max != getLNASlider().getMaximum())
int max = getControlRsp().getMaximumLNASetting();
GainSlider slider = getLNASlider();
if(max != (int)slider.getSlider().getMax())
{
EventQueue.invokeLater(() -> {
setLoading(true);
//Adjust the value if it's less than max
getLNASlider().setValue(Math.min(getLNASlider().getValue(), max));
getLNASlider().setMaximum(max);
setLoading(false);
});
boolean wasLoading = isLoading();
setLoading(true);
int lna = Math.min(getLNA(), max);
slider.setRange(0, max);
setLNA(lna);
setLoading(wasLoading);
}
}
}
/**
* LNA Gain Slider
* LNA state slider. The slider is inverted so that moving it right increases the gain: LNA state 0 is the
* highest gain.
*/
protected LnaSlider getLNASlider()
protected GainSlider getLNASlider()
{
if(mLNASlider == null)
{
mLNASlider = new LnaSlider();
mLNASlider.setEnabled(true);
mLNASlider.setMajorTickSpacing(1);
mLNASlider.setPaintTicks(true);
mLNASlider.addChangeListener(event ->
{
JSlider source = (JSlider)event.getSource();
if(!source.getValueIsAdjusting())
{
updateGain();
}
});
mLNASlider = new GainSlider(0, 9, 9);
mLNASlider.setApplyOnRelease(true);
mLNASlider.setTooltip("LNA gain. Move right for more gain.");
mLNASlider.setFormatter(value -> "State " + ((int)mLNASlider.getSlider().getMax() - value));
mLNASlider.setOnChange(value -> updateGain());
}
return mLNASlider;
}
/**
* Updates the gain settings when the LNA or Baseband gain value is changed by the user.
* IF gain slider. The slider is inverted gain reduction, so that moving it right increases the gain.
*/
private void updateGain()
{
int lna = getLNASlider().getLNA();
int gr = getIfGainSlider().getGR();
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setGain(lna, gr);
save();
updateGainLabel();
}
catch(Exception e)
{
mLog.error("Couldn't set RSP gain to LNA:" + lna + " Gain Reduction:" + gr, e);
JOptionPane.showMessageDialog(mIfGainSlider, "Couldn't set RSP gain value to LNA:" + lna + " Gain Reduction:" + gr);
}
}
}
protected void updateGainLabel()
{
try
{
float currentGain = getTunerController().getControlRsp().getCurrentGain();
getGainValueLabel().setText((int)currentGain + " dB");
}
catch(RspException se)
{
mLog.error("Error accessing current gain value from RSP tuner", se);
}
}
/**
* IF Gain Slider
*/
protected IfGainSlider getIfGainSlider()
protected GainSlider getIfGainSlider()
{
if(mIfGainSlider == null)
{
mIfGainSlider = new IfGainSlider();
mIfGainSlider.setEnabled(true);
mIfGainSlider.setMajorTickSpacing(1);
mIfGainSlider.setPaintTicks(true);
mIfGainSlider.addChangeListener(event ->
{
JSlider source = (JSlider)event.getSource();
if(!source.getValueIsAdjusting())
{
updateGain();
}
});
mIfGainSlider = new GainSlider(0, IF_GAIN_SLIDER_MAX, 30);
mIfGainSlider.setApplyOnRelease(true);
mIfGainSlider.setTooltip("IF gain. Move right for more gain. Turn off AGC to adjust.");
mIfGainSlider.setFormatter(value -> (IF_GAIN_SLIDER_MAX - value + 20) + " dB GR");
mIfGainSlider.setOnChange(value -> updateGain());
}
return mIfGainSlider;
}
/**
* JSlider implementation that inverts the scale to support LNA values.
* Current LNA state from the slider
*/
public class LnaSlider extends JSlider
protected int getLNA()
{
/**
* Constructs an instance
*/
public LnaSlider()
{
super(JSlider.HORIZONTAL, 0,9,9);
}
return (int)getLNASlider().getSlider().getMax() - getLNASlider().getValue();
}
/**
* Slider value converted to the LNA scale.
* @return lna value.
*/
public int getLNA()
{
return getMaximum() - getValue();
}
private void setLNA(int lna)
{
getLNASlider().setValue((int)getLNASlider().getSlider().getMax() - lna);
}
/**
* Sets the slider with the value converted from the provided LNA value.
* @param lna value to apply
*/
public void setLNA(int lna)
/**
* Current baseband gain reduction from the IF gain slider
*/
protected int getGainReduction()
{
return IF_GAIN_SLIDER_MAX - getIfGainSlider().getValue() + 20;
}
private void setGainReduction(int gainReduction)
{
getIfGainSlider().setValue(IF_GAIN_SLIDER_MAX - (gainReduction - 20));
}
private void updateGain()
{
int lna = getLNA();
int gr = getGainReduction();
if(hasTuner() && !isLoading() &&
applyToTuner("gain (LNA " + lna + ", gain reduction " + gr + ")", () -> getControlRsp().setGain(lna, gr)))
{
setValue(getMaximum() - lna);
save();
updateGainLabel();
}
}
/**
* JSlider implementation that inverts the scale to support IF Gain (aka Gain Reduction) values.
* Updates the overall gain readout
*/
public class IfGainSlider extends JSlider
protected void updateGainLabel()
{
/**
* Constructs an instance
*/
public IfGainSlider()
try
{
super(JSlider.HORIZONTAL, 0, 39, 30);
getGainValueLabel().setText((int)getControlRsp().getCurrentGain() + " dB");
}
catch(Exception se)
{
mLog.error("Error accessing current gain value from RSP tuner", se);
}
}
/**
* Reads a device setting
*/
@FunctionalInterface
protected interface RspGetter<T>
{
T get() throws Exception;
}
/**
* Applies a device setting
*/
@FunctionalInterface
protected interface RspSetter<T>
{
void set(T value) throws Exception;
}
/**
* Adds a check box option to the section that's bound to a device setting. The check box is refreshed from the
* device when the editor refreshes, and changes are applied to the device and then saved.
* @param section to add to
* @param text for the check box
* @param tooltip or null
* @param getter reads the device setting
* @param setter applies the device setting
* @return the check box
*/
protected CheckBox addOption(TunerSection section, String text, String tooltip, RspGetter<Boolean> getter,
RspSetter<Boolean> setter)
{
Option option = new Option(text, getter, setter);
if(tooltip != null)
{
option.mCheckBox.setTooltip(new Tooltip(tooltip));
}
/**
* Slider value converted to the gain reduction scale.
* @return gain reduction value.
*/
public int getGR()
mOptions.add(option);
section.addControl(option.mCheckBox);
return option.mCheckBox;
}
/**
* Adds a choice (combo box) to the section that's bound to a device setting.
* @param section to add to
* @param label for the row
* @param values to choose from
* @param getter reads the device setting
* @param setter applies the device setting
* @return the combo box
*/
protected <T> ComboBox<T> addChoice(TunerSection section, String label, Collection<T> values, RspGetter<T> getter,
RspSetter<T> setter)
{
Choice<T> choice = new Choice<>(label, values, getter, setter);
mChoices.add(choice);
section.addRow(label, choice.mComboBox);
return choice.mComboBox;
}
/**
* Check box bound to a device setting
*/
private class Option
{
private final CheckBox mCheckBox;
private final String mText;
private final RspGetter<Boolean> mGetter;
Option(String text, RspGetter<Boolean> getter, RspSetter<Boolean> setter)
{
return getIfGainSlider().getMaximum() - getIfGainSlider().getValue() + 20;
mText = text;
mGetter = getter;
mCheckBox = new CheckBox(text);
mCheckBox.setDisable(true);
mCheckBox.setOnAction(e -> {
if(hasTuner() && !isLoading())
{
boolean selected = mCheckBox.isSelected();
if(applyToTuner(mText, () -> setter.set(selected)))
{
save();
}
else
{
refresh();
}
}
});
}
/**
* Sets the slider with the value converted from the provided gain reduction value.
* @param gainReduction value to apply
*/
public void setGR(int gainReduction)
void refresh()
{
setValue(getMaximum() - (gainReduction - 20));
mCheckBox.setDisable(!hasTuner());
try
{
mCheckBox.setSelected(hasTuner() && mGetter.get());
}
catch(Exception e)
{
mLog.error("Error reading RSP setting [" + mText + "]", e);
}
}
}
/**
* Combo box bound to a device setting
*/
private class Choice<T>
{
private final ComboBox<T> mComboBox;
private final String mLabel;
private final RspGetter<T> mGetter;
Choice(String label, Collection<T> values, RspGetter<T> getter, RspSetter<T> setter)
{
mLabel = label;
mGetter = getter;
mComboBox = new ComboBox<>();
mComboBox.getItems().addAll(values);
mComboBox.setMaxWidth(Double.MAX_VALUE);
mComboBox.setDisable(true);
mComboBox.setOnAction(e -> {
T selected = mComboBox.getValue();
if(hasTuner() && !isLoading() && selected != null)
{
if(applyToTuner(mLabel.toLowerCase() + " [" + selected + "]", () -> setter.set(selected)))
{
save();
}
else
{
refresh();
}
}
});
}
void refresh()
{
mComboBox.setDisable(!hasTuner());
try
{
mComboBox.setValue(hasTuner() ? mGetter.get() : null);
}
catch(Exception e)
{
mLog.error("Error reading RSP setting [" + mLabel + "]", e);
}
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,138 +16,28 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rsp1;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
/**
* RSP1 Tuner Editor
* RSP1 tuner editor
*/
public class Rsp1TunerEditor extends RspTunerEditor<Rsp1TunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(Rsp1TunerEditor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public Rsp1TunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
}
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
}
/**
* Access tuner controller
*/
private Rsp1TunerController getTunerController()
{
if(hasTuner())
{
return (Rsp1TunerController)getTuner().getTunerController();
}
return null;
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
setLoading(false);
refresh();
}
@Override
@@ -155,70 +45,8 @@ public class Rsp1TunerEditor extends RspTunerEditor<Rsp1TunerConfiguration>
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
saveRspSettings(getConfiguration());
saveConfiguration();
}
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
RspSampleRate[] rspSampleRates = RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.toArray(new RspSampleRate[RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.size()]);
mSampleRateCombo = new JComboBox<>(rspSampleRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSP1A tuner", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,179 +16,46 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rsp1a;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.CheckBox;
/**
* RSP1A Tuner Editor
* RSP1A tuner editor
*/
public class Rsp1aTunerEditor extends RspTunerEditor<Rsp1aTunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(Rsp1aTunerEditor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JCheckBox mRfDabNotchCheckBox;
private JCheckBox mRfNotchCheckBox;
private final CheckBox mBiasTCheckBox;
private final CheckBox mRfNotchCheckBox;
private final CheckBox mRfDabNotchCheckBox;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public Rsp1aTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection options = addSection("Options");
mBiasTCheckBox = addOption(options, "Bias-T power", "Provide DC power on the antenna connector",
() -> control().isBiasT(), enabled -> control().setBiasT(enabled));
mRfNotchCheckBox = addOption(options, "FM broadcast band filter (77-115 MHz)", null,
() -> control().isRfNotch(), enabled -> control().setRfNotch(enabled));
mRfDabNotchCheckBox = addOption(options, "DAB broadcast band filter (160-235 MHz)", null,
() -> control().isRfDabNotch(), enabled -> control().setRfDabNotch(enabled));
refresh();
}
private void init()
private IControlRsp1a control()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JLabel());
add(getRfNotchCheckBox(), "wrap");
add(new JLabel());
add(getRfDabNotchCheckBox(), "wrap");
}
/**
* Access tuner controller
*/
private Rsp1aTunerController getTunerController()
{
if(hasTuner())
{
return (Rsp1aTunerController)getTuner().getTunerController();
}
return null;
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
try
{
getBiasTCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isBiasT());
}
catch(RspException se)
{
mLog.error("Error setting Bias-T enabled state in editor");
}
getRfDabNotchCheckBox().setEnabled(hasTuner());
try
{
getRfDabNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfDabNotch());
}
catch(RspException se)
{
mLog.error("Error setting RF DAB Notch enabled state in editor");
}
getRfNotchCheckBox().setEnabled(hasTuner());
try
{
getRfNotchCheckBox().setSelected(hasTuner() ? getTunerController().getControlRsp().isRfNotch() : false);
}
catch(RspException se)
{
mLog.error("Error setting RF Notch enabled state in editor");
}
setLoading(false);
return (IControlRsp1a)getControlRsp();
}
@Override
@@ -196,159 +63,12 @@ public class Rsp1aTunerEditor extends RspTunerEditor<Rsp1aTunerConfiguration>
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setRfNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setRfDabNotch(getRfDabNotchCheckBox().isSelected());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
Rsp1aTunerConfiguration config = getConfiguration();
saveRspSettings(config);
config.setBiasT(mBiasTCheckBox.isSelected());
config.setRfNotch(mRfNotchCheckBox.isSelected());
config.setRfDabNotch(mRfDabNotchCheckBox.isSelected());
saveConfiguration();
}
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
RspSampleRate[] rspSampleRates = RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.toArray(new RspSampleRate[RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.size()]);
mSampleRateCombo = new JComboBox<>(rspSampleRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSP1A tuner", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Checkbox control for Bias-T
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T Power");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP1A Bias-T enabled to " + mBiasTCheckBox.isSelected(), se);
}
}
});
}
return mBiasTCheckBox;
}
/**
* Checkbox control for RF DAB notch
*/
private JCheckBox getRfDabNotchCheckBox()
{
if(mRfDabNotchCheckBox == null)
{
mRfDabNotchCheckBox = new JCheckBox("DAB Broadcast Band Filter (160-235 MHz)");
mRfDabNotchCheckBox.setEnabled(false);
mRfDabNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfDabNotch(mRfDabNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP1A RF DAB notch enabled to " + mRfDabNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfDabNotchCheckBox;
}
/**
* Checkbox control for RF notch
*/
private JCheckBox getRfNotchCheckBox()
{
if(mRfNotchCheckBox == null)
{
mRfNotchCheckBox = new JCheckBox("FM Broadcast Band Filter (77-115 MHz)");
mRfNotchCheckBox.setEnabled(false);
mRfNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfNotch(mRfNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP1A RF notch enabled to " + mRfNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfNotchCheckBox;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,178 +16,46 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rsp1b;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import javafx.scene.control.CheckBox;
/**
* RSP1B Tuner Editor
* RSP1B tuner editor
*/
public class Rsp1bTunerEditor extends RspTunerEditor<Rsp1bTunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(Rsp1bTunerEditor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JCheckBox mRfDabNotchCheckBox;
private JCheckBox mRfNotchCheckBox;
private final CheckBox mBiasTCheckBox;
private final CheckBox mRfNotchCheckBox;
private final CheckBox mRfDabNotchCheckBox;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public Rsp1bTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection options = addSection("Options");
mBiasTCheckBox = addOption(options, "Bias-T power", "Provide DC power on the antenna connector",
() -> control().isBiasT(), enabled -> control().setBiasT(enabled));
mRfNotchCheckBox = addOption(options, "FM broadcast band filter (77-115 MHz)", null,
() -> control().isRfNotch(), enabled -> control().setRfNotch(enabled));
mRfDabNotchCheckBox = addOption(options, "DAB broadcast band filter (160-235 MHz)", null,
() -> control().isRfDabNotch(), enabled -> control().setRfDabNotch(enabled));
refresh();
}
private void init()
private IControlRsp1b control()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JLabel());
add(getRfNotchCheckBox(), "wrap");
add(new JLabel());
add(getRfDabNotchCheckBox(), "wrap");
}
/**
* Access tuner controller
*/
private Rsp1bTunerController getTunerController()
{
if(hasTuner())
{
return (Rsp1bTunerController)getTuner().getTunerController();
}
return null;
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
try
{
getBiasTCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isBiasT());
}
catch(RspException se)
{
mLog.error("Error setting Bias-T enabled state in editor");
}
getRfDabNotchCheckBox().setEnabled(hasTuner());
try
{
getRfDabNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfDabNotch());
}
catch(RspException se)
{
mLog.error("Error setting RF DAB Notch enabled state in editor");
}
getRfNotchCheckBox().setEnabled(hasTuner());
try
{
getRfNotchCheckBox().setSelected(hasTuner() ? getTunerController().getControlRsp().isRfNotch() : false);
}
catch(RspException se)
{
mLog.error("Error setting RF Notch enabled state in editor");
}
setLoading(false);
return (IControlRsp1b)getControlRsp();
}
@Override
@@ -195,158 +63,12 @@ public class Rsp1bTunerEditor extends RspTunerEditor<Rsp1bTunerConfiguration>
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setRfNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setRfDabNotch(getRfDabNotchCheckBox().isSelected());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
Rsp1bTunerConfiguration config = getConfiguration();
saveRspSettings(config);
config.setBiasT(mBiasTCheckBox.isSelected());
config.setRfNotch(mRfNotchCheckBox.isSelected());
config.setRfDabNotch(mRfDabNotchCheckBox.isSelected());
saveConfiguration();
}
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
RspSampleRate[] rspSampleRates = RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.toArray(new RspSampleRate[RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.size()]);
mSampleRateCombo = new JComboBox<>(rspSampleRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSP1A tuner", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Checkbox control for Bias-T
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T Power");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP1B Bias-T enabled to " + mBiasTCheckBox.isSelected(), se);
}
}
});
}
return mBiasTCheckBox;
}
/**
* Checkbox control for RF DAB notch
*/
private JCheckBox getRfDabNotchCheckBox()
{
if(mRfDabNotchCheckBox == null)
{
mRfDabNotchCheckBox = new JCheckBox("DAB Broadcast Band Filter (160-235 MHz)");
mRfDabNotchCheckBox.setEnabled(false);
mRfDabNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfDabNotch(mRfDabNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP1B RF DAB notch enabled to " + mRfDabNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfDabNotchCheckBox;
}
/**
* Checkbox control for RF notch
*/
private JCheckBox getRfNotchCheckBox()
{
if(mRfNotchCheckBox == null)
{
mRfNotchCheckBox = new JCheckBox("FM Broadcast Band Filter (77-115 MHz)");
mRfNotchCheckBox.setEnabled(false);
mRfNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfNotch(mRfNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP1B RF notch enabled to " + mRfNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfNotchCheckBox;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,192 +16,51 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rsp2;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.List;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
/**
* RSP2 Tuner Editor
* RSP2 tuner editor
*/
public class Rsp2TunerEditor extends RspTunerEditor<Rsp2TunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(Rsp2TunerEditor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JCheckBox mExternalReferenceOutputCheckBox;
private JCheckBox mRfNotchCheckBox;
private JComboBox<Rsp2AntennaSelection> mAntennaSelectionCombo;
private final ComboBox<Rsp2AntennaSelection> mAntennaCombo;
private final CheckBox mBiasTCheckBox;
private final CheckBox mExternalReferenceOutputCheckBox;
private final CheckBox mRfNotchCheckBox;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public Rsp2TunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection options = addSection("Options");
mAntennaCombo = addChoice(options, "Antenna", List.of(Rsp2AntennaSelection.values()),
() -> control().getAntennaSelection(), selection -> control().setAntennaSelection(selection));
mBiasTCheckBox = addOption(options, "ANT B Bias-T power", "Provide DC power on the ANT B connector",
() -> control().isBiasT(), enabled -> control().setBiasT(enabled));
mRfNotchCheckBox = addOption(options, "FM broadcast band filter (77-115 MHz)", null,
() -> control().isRfNotch(), enabled -> control().setRfNotch(enabled));
mExternalReferenceOutputCheckBox = addOption(options, "External reference output", null,
() -> control().isExternalReferenceOutput(), enabled -> control().setExternalReferenceOutput(enabled));
refresh();
}
private void init()
private IControlRsp2 control()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JLabel());
add(getExternalReferenceOutputCheckBox(), "wrap");
add(new JLabel());
add(getRfNotchCheckBox(), "wrap");
add(new JLabel());
add(getAntennaSelectionCombo(), "wrap");
}
/**
* Access tuner controller
*/
private Rsp2TunerController getTunerController()
{
if(hasTuner())
{
return (Rsp2TunerController) getTuner().getTunerController();
}
return null;
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
try
{
getBiasTCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isBiasT());
}
catch(RspException se)
{
mLog.error("Error setting Bias-T enabled state in editor");
}
getExternalReferenceOutputCheckBox().setEnabled(hasTuner());
try
{
getExternalReferenceOutputCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isExternalReferenceOutput());
}
catch(RspException se)
{
mLog.error("Error setting RF DAB Notch enabled state in editor");
}
getRfNotchCheckBox().setEnabled(hasTuner());
try
{
getRfNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfNotch());
}
catch(RspException se)
{
mLog.error("Error setting RF Notch enabled state in editor");
}
getAntennaSelectionCombo().setEnabled(hasTuner());
try
{
getAntennaSelectionCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getAntennaSelection() : null);
}
catch(RspException se)
{
mLog.error("Error setting antenna selection in editor");
}
setLoading(false);
return (IControlRsp2)getControlRsp();
}
@Override
@@ -209,188 +68,18 @@ public class Rsp2TunerEditor extends RspTunerEditor<Rsp2TunerConfiguration>
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setRfNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setAntennaSelection((Rsp2AntennaSelection)getAntennaSelectionCombo().getSelectedItem());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
Rsp2TunerConfiguration config = getConfiguration();
saveRspSettings(config);
config.setBiasT(mBiasTCheckBox.isSelected());
config.setRfNotch(mRfNotchCheckBox.isSelected());
config.setExternalReferenceOutput(mExternalReferenceOutputCheckBox.isSelected());
if(mAntennaCombo.getValue() != null)
{
config.setAntennaSelection(mAntennaCombo.getValue());
}
saveConfiguration();
}
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
RspSampleRate[] rspSampleRates = RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.toArray(new RspSampleRate[RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.size()]);
mSampleRateCombo = new JComboBox<>(rspSampleRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSP2 tuner", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Checkbox control for Bias-T
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("ANT B Bias-T Power");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP2 Bias-T enabled to " + mBiasTCheckBox.isSelected(), se);
}
}
});
}
return mBiasTCheckBox;
}
/**
* Checkbox control for RF notch
*/
private JCheckBox getRfNotchCheckBox()
{
if(mRfNotchCheckBox == null)
{
mRfNotchCheckBox = new JCheckBox("FM Broadcast Band Filter (77-115 MHz)");
mRfNotchCheckBox.setEnabled(false);
mRfNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfNotch(mRfNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP2 RF notch enabled to " + mRfNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfNotchCheckBox;
}
/**
* Checkbox control for External Reference Output
*/
private JCheckBox getExternalReferenceOutputCheckBox()
{
if(mExternalReferenceOutputCheckBox == null)
{
mExternalReferenceOutputCheckBox = new JCheckBox("External Reference Output");
mExternalReferenceOutputCheckBox.setEnabled(false);
mExternalReferenceOutputCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setExternalReferenceOutput(mExternalReferenceOutputCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP2 external reference output notch enabled to " +
mExternalReferenceOutputCheckBox.isSelected(), se);
}
}
});
}
return mExternalReferenceOutputCheckBox;
}
/**
* Antenna selection combobox control
*/
private JComboBox<Rsp2AntennaSelection> getAntennaSelectionCombo()
{
if(mAntennaSelectionCombo == null)
{
mAntennaSelectionCombo = new JComboBox<>(Rsp2AntennaSelection.values());
mAntennaSelectionCombo.setEnabled(false);
mAntennaSelectionCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
Rsp2AntennaSelection selected = (Rsp2AntennaSelection)mAntennaSelectionCombo.getSelectedItem();
try
{
getTunerController().getControlRsp().setAntennaSelection(selected);
save();
}
catch(RspException se)
{
mLog.error("Error setting Antenna selection for RSP2", se);
}
}
});
}
return mAntennaSelectionCombo;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,7 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rspDuo;
import io.github.dsheirer.eventbus.MyEventBus;
@@ -27,209 +26,71 @@ import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import java.util.EnumSet;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.Collection;
import java.util.List;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tooltip;
/**
* RSPduo Tuner 1 Editor
* RSPduo tuner 1 editor
*/
public class RspDuoTuner1Editor extends RspTunerEditor<RspDuoTuner1Configuration>
{
private static final Logger mLog = LoggerFactory.getLogger(RspDuoTuner1Editor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
private JCheckBox mRfDabNotchCheckBox;
private JCheckBox mRfNotchCheckBox;
private JCheckBox mAmNotchCheckBox;
private JCheckBox mExternalReferenceOutputCheckBox;
private JComboBox<RspDuoAmPortSelection> mAmPortCombo;
private JButton mTunerPreferencesButton;
private final CheckBox mExternalReferenceOutputCheckBox;
private final CheckBox mAmNotchCheckBox;
private final CheckBox mRfDabNotchCheckBox;
private final CheckBox mRfNotchCheckBox;
private final ComboBox<RspDuoAmPortSelection> mAmPortCombo;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public RspDuoTuner1Editor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
}
addHeaderNode(createPreferencesButton());
private void init()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
JPanel labelAndButtonPanel = new JPanel();
labelAndButtonPanel.setLayout(new MigLayout("insets 0"));
labelAndButtonPanel.add(getTunerIdLabel());
labelAndButtonPanel.add(getTunerPreferencesButton());
add(labelAndButtonPanel, "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getExternalReferenceOutputCheckBox(), "wrap");
add(new JLabel());
add(getAmNotchCheckBox(), "wrap");
add(new JLabel());
add(getRfDabNotchCheckBox(), "wrap");
add(new JLabel());
add(getRfNotchCheckBox(), "wrap");
add(new JLabel("AM Port:"));
add(getAmPortCombo(), "wrap");
TunerSection options = addSection("Options");
mAmPortCombo = addChoice(options, "AM Port", List.of(RspDuoAmPortSelection.values()),
() -> control().getAmPort(), port -> control().setAmPort(port));
mRfNotchCheckBox = addOption(options, "FM broadcast band filter (78-114 MHz)", null,
() -> control().isRfNotch(), enabled -> control().setRfNotch(enabled));
mRfDabNotchCheckBox = addOption(options, "DAB broadcast band filter (157-235 MHz)", null,
() -> control().isRfDabNotch(), enabled -> control().setRfDabNotch(enabled));
mAmNotchCheckBox = addOption(options, "AM broadcast band filter (415-1640 kHz)", null,
() -> control().isAmNotch(), enabled -> control().setAmNotch(enabled));
mExternalReferenceOutputCheckBox = addOption(options, "External reference output", null,
() -> control().isExternalReferenceOutput(), enabled -> control().setExternalReferenceOutput(enabled));
refresh();
}
/**
* Access tuner controller
* Button that opens the RSPduo (tuner) preferences, where the RSPduo dual tuner mode is chosen.
*/
private RspDuoTuner1Controller getTunerController()
static Button createPreferencesButton()
{
if(hasTuner())
{
return (RspDuoTuner1Controller) getTuner().getTunerController();
}
Button button = new Button("RSPduo Preferences");
button.setTooltip(new Tooltip("Choose how sdrtrunk uses the RSPduo's two tuners"));
button.setOnAction(e -> MyEventBus.getGlobalEventBus()
.post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.SOURCE_TUNERS)));
return button;
}
return null;
private IControlRspDuoTuner1 control()
{
return (IControlRspDuoTuner1)getControlRsp();
}
@Override
public void setTunerLockState(boolean locked)
protected Collection<RspSampleRate> getSampleRates()
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
clearSampleRates();
if(hasTuner())
{
setSampleRates(getTunerController().getControlRsp().getSupportedSampleRates());
}
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
getAmPortCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
try
{
getAmPortCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getAmPort() : null);
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 1 AM Port in editor");
}
getRfDabNotchCheckBox().setEnabled(hasTuner());
try
{
getRfDabNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfDabNotch());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 1 RF DAB Notch enabled state in editor");
}
getRfNotchCheckBox().setEnabled(hasTuner());
try
{
getRfNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfNotch());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 1 RF Notch enabled state in editor");
}
getAmNotchCheckBox().setEnabled(hasTuner());
try
{
getAmNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isAmNotch());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 1 AM Notch enabled state in editor");
}
getExternalReferenceOutputCheckBox().setEnabled(hasTuner());
try
{
getExternalReferenceOutputCheckBox()
.setSelected(hasTuner() && getTunerController().getControlRsp().isExternalReferenceOutput());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 1 external reference output enabled state in editor");
}
setLoading(false);
return control().getSupportedSampleRates();
}
@Override
@@ -237,256 +98,14 @@ public class RspDuoTuner1Editor extends RspTunerEditor<RspDuoTuner1Configuration
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setAmNotch(getAmNotchCheckBox().isSelected());
getConfiguration().setAmPort(getAmPortCombo().getSelectedItem() != null ? (RspDuoAmPortSelection)getAmPortCombo().getSelectedItem() : null);
getConfiguration().setExternalReferenceOutput(getExternalReferenceOutputCheckBox().isSelected());
getConfiguration().setRfDabNotch(getRfDabNotchCheckBox().isSelected());
getConfiguration().setRfNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
RspDuoTuner1Configuration config = getConfiguration();
saveRspSettings(config);
config.setAmNotch(mAmNotchCheckBox.isSelected());
config.setAmPort(mAmPortCombo.getValue());
config.setExternalReferenceOutput(mExternalReferenceOutputCheckBox.isSelected());
config.setRfDabNotch(mRfDabNotchCheckBox.isSelected());
config.setRfNotch(mRfNotchCheckBox.isSelected());
saveConfiguration();
}
}
/**
* Updates the sample rates listed in the combobox.
* @param sampleRates to use.
*/
private void setSampleRates(EnumSet<RspSampleRate> sampleRates)
{
if(!sampleRates.isEmpty())
{
for(RspSampleRate sampleRate: sampleRates)
{
getSampleRateCombo().addItem(sampleRate);
}
}
}
/**
* Removes all sample rate options from the combo box.
*/
private void clearSampleRates()
{
getSampleRateCombo().removeAllItems();
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSPduo tuner 1", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* AM port selection combobox control
*/
private JComboBox<RspDuoAmPortSelection> getAmPortCombo()
{
if(mAmPortCombo == null)
{
mAmPortCombo = new JComboBox<>(RspDuoAmPortSelection.values());
mAmPortCombo.setEnabled(false);
mAmPortCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspDuoAmPortSelection selected = (RspDuoAmPortSelection)mAmPortCombo.getSelectedItem();
try
{
getTunerController().getControlRsp().setAmPort(selected);
save();
}
catch(RspException se)
{
mLog.error("Error setting AM port for RSPduo tuner 1", se);
}
}
});
}
return mAmPortCombo;
}
/**
* Checkbox control for RF DAB notch
*/
private JCheckBox getRfDabNotchCheckBox()
{
if(mRfDabNotchCheckBox == null)
{
mRfDabNotchCheckBox = new JCheckBox("DAB Broadcast Band Filter (157-235 MHz)");
mRfDabNotchCheckBox.setEnabled(false);
mRfDabNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfDabNotch(mRfDabNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 1 RF DAB notch enabled to " + mRfDabNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfDabNotchCheckBox;
}
/**
* Checkbox control for RF notch
*/
private JCheckBox getRfNotchCheckBox()
{
if(mRfNotchCheckBox == null)
{
mRfNotchCheckBox = new JCheckBox("FM Broadcast Band Filter (78-114 MHz)");
mRfNotchCheckBox.setEnabled(false);
mRfNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfNotch(mRfNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 1 RF notch enabled to " + mRfNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfNotchCheckBox;
}
/**
* Checkbox control for AM notch
*/
private JCheckBox getAmNotchCheckBox()
{
if(mAmNotchCheckBox == null)
{
mAmNotchCheckBox = new JCheckBox("AM Broadcast Band Filter (415-1640 kHz)");
mAmNotchCheckBox.setEnabled(false);
mAmNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setAmNotch(mAmNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 1 AM notch enabled to " + mAmNotchCheckBox.isSelected(), se);
}
}
});
}
return mAmNotchCheckBox;
}
/**
* Checkbox control for External Reference Output
*/
private JCheckBox getExternalReferenceOutputCheckBox()
{
if(mExternalReferenceOutputCheckBox == null)
{
mExternalReferenceOutputCheckBox = new JCheckBox("External Reference Output");
mExternalReferenceOutputCheckBox.setEnabled(false);
mExternalReferenceOutputCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setExternalReferenceOutput(mExternalReferenceOutputCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 1 external reference output notch enabled to " +
mExternalReferenceOutputCheckBox.isSelected(), se);
}
}
});
}
return mExternalReferenceOutputCheckBox;
}
/**
* Button to launch the User Preferences editor to show the RSPduo tuner preference selection.
* @return constructed button.
*/
private JButton getTunerPreferencesButton()
{
if(mTunerPreferencesButton == null)
{
mTunerPreferencesButton = new JButton("RSPduo Preferences");
mTunerPreferencesButton.addActionListener(e -> MyEventBus.getGlobalEventBus()
.post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.SOURCE_TUNERS)));
}
return mTunerPreferencesButton;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,121 +16,60 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rspDuo;
import io.github.dsheirer.eventbus.MyEventBus;
import io.github.dsheirer.gui.preference.PreferenceEditorType;
import io.github.dsheirer.gui.preference.ViewUserPreferenceEditorRequest;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import java.util.EnumSet;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.Collection;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tooltip;
/**
* RSPduo Tuner 2 Editor
* RSPduo tuner 2 editor. In master/slave mode, tuner 2 is the slave: its sample rate and external reference output
* follow the master (tuner 1) and it is enabled or disabled with the master.
*/
public class RspDuoTuner2Editor extends RspTunerEditor<RspDuoTuner2Configuration>
{
private static final Logger mLog = LoggerFactory.getLogger(RspDuoTuner2Editor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JCheckBox mExternalReferenceOutputCheckBox;
private JCheckBox mRfDabNotchCheckBox;
private JCheckBox mRfNotchCheckBox;
private JButton mTunerPreferencesButton;
private final CheckBox mExternalReferenceOutputCheckBox;
private final CheckBox mBiasTCheckBox;
private final CheckBox mRfDabNotchCheckBox;
private final CheckBox mRfNotchCheckBox;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public RspDuoTuner2Editor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
addHeaderNode(RspDuoTuner1Editor.createPreferencesButton());
TunerSection options = addSection("Options");
mBiasTCheckBox = addOption(options, "Bias-T power", "Provide DC power on the tuner 2 antenna connector",
() -> control().isBiasT(), enabled -> control().setBiasT(enabled));
mRfNotchCheckBox = addOption(options, "FM broadcast band filter (78-114 MHz)", null,
() -> control().isRfNotch(), enabled -> control().setRfNotch(enabled));
mRfDabNotchCheckBox = addOption(options, "DAB broadcast band filter (157-235 MHz)", null,
() -> control().isRfDabNotch(), enabled -> control().setRfDabNotch(enabled));
mExternalReferenceOutputCheckBox = addOption(options, "External reference output", null,
() -> !isSlaveMode() && control().isExternalReferenceOutput(),
enabled -> control().setExternalReferenceOutput(enabled));
refresh();
}
private void init()
private IControlRspDuoTuner2 control()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
JPanel labelAndButtonPanel = new JPanel();
labelAndButtonPanel.setLayout(new MigLayout("insets 0"));
labelAndButtonPanel.add(getTunerIdLabel());
labelAndButtonPanel.add(getTunerPreferencesButton());
add(labelAndButtonPanel, "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getExternalReferenceOutputCheckBox(), "wrap");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JLabel());
add(getRfDabNotchCheckBox(), "wrap");
add(new JLabel());
add(getRfNotchCheckBox(), "wrap");
}
private DiscoveredRspTuner getDiscoveredRspTuner()
{
return (DiscoveredRspTuner)getDiscoveredTuner();
return (IControlRspDuoTuner2)getControlRsp();
}
/**
* Access tuner controller
*/
private RspDuoTuner2Controller getTunerController()
{
if(hasTuner())
{
return (RspDuoTuner2Controller) getTuner().getTunerController();
}
return null;
}
/**
* Indicates if this editor has a tuner and the tuner is configured for slave mode.
* Indicates if the tuner is configured as the slave in master/slave mode.
*/
private boolean isSlaveMode()
{
@@ -138,106 +77,28 @@ public class RspDuoTuner2Editor extends RspTunerEditor<RspDuoTuner2Configuration
}
@Override
public void setTunerLockState(boolean locked)
protected Collection<RspSampleRate> getSampleRates()
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
return control().getSupportedSampleRates();
}
@Override
protected void tunerStatusUpdated()
protected boolean isSampleRateChangeable()
{
setLoading(true);
return !isSlaveMode();
}
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
//If master/slave configuration, disable the slave's enable/disable button - user can disable
//the tuner via the master device.
@Override
protected void rspTunerStatusUpdated()
{
if(isSlaveMode())
{
getEnabledButton().setEnabled(false);
//The user disables the slave by disabling the master tuner
getEnabledSwitch().setDisable(true);
getEnabledSwitch().setTooltip(new Tooltip("Enable or disable the RSPduo with tuner 1 (master)"));
mExternalReferenceOutputCheckBox.setDisable(true);
mExternalReferenceOutputCheckBox.setTooltip(new Tooltip("Set by tuner 1 (master)"));
}
getFrequencyPanel().updateControls();
clearSampleRates();
if(hasTuner())
{
setSampleRates(getTunerController().getControlRsp().getSupportedSampleRates());
}
getSampleRateCombo().setEnabled(hasTuner() && !isSlaveMode() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
getRfDabNotchCheckBox().setEnabled(hasTuner());
try
{
getRfDabNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfDabNotch());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 2 RF DAB Notch enabled state in editor");
}
getRfNotchCheckBox().setEnabled(hasTuner());
try
{
getRfNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfNotch());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 2 RF Notch enabled state in editor");
}
getBiasTCheckBox().setEnabled(hasTuner());
try
{
getBiasTCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isBiasT());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 2 Bias-T enabled state in editor");
}
getExternalReferenceOutputCheckBox().setEnabled(hasTuner() && !isSlaveMode());
try
{
getExternalReferenceOutputCheckBox()
.setSelected(hasTuner() && !isSlaveMode() && getTunerController().getControlRsp().isExternalReferenceOutput());
}
catch(RspException se)
{
mLog.error("Error setting RSPduo tuner 2 external reference output enabled state in editor");
}
setLoading(false);
}
@Override
@@ -245,231 +106,18 @@ public class RspDuoTuner2Editor extends RspTunerEditor<RspDuoTuner2Configuration
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
if(getSampleRateCombo().getSelectedItem() != null)
{
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
}
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
RspDuoTuner2Configuration config = getConfiguration();
saveRspSettings(config);
config.setBiasT(mBiasTCheckBox.isSelected());
if(hasTuner() && !isSlaveMode())
{
getConfiguration().setExternalReferenceOutput(getExternalReferenceOutputCheckBox().isSelected());
config.setExternalReferenceOutput(mExternalReferenceOutputCheckBox.isSelected());
}
getConfiguration().setRfDabNotch(getRfDabNotchCheckBox().isSelected());
getConfiguration().setRfNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
config.setRfDabNotch(mRfDabNotchCheckBox.isSelected());
config.setRfNotch(mRfNotchCheckBox.isSelected());
saveConfiguration();
}
}
/**
* Updates the sample rates listed in the combobox.
* @param sampleRates to use.
*/
private void setSampleRates(EnumSet<RspSampleRate> sampleRates)
{
if(!sampleRates.isEmpty())
{
for(RspSampleRate sampleRate: sampleRates)
{
getSampleRateCombo().addItem(sampleRate);
}
}
}
/**
* Removes all sample rate options from the combo box.
*/
private void clearSampleRates()
{
getSampleRateCombo().removeAllItems();
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
mSampleRateCombo = new JComboBox<>();
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSPduo tuner 2", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Checkbox control for RF DAB notch
*/
private JCheckBox getRfDabNotchCheckBox()
{
if(mRfDabNotchCheckBox == null)
{
mRfDabNotchCheckBox = new JCheckBox("DAB Broadcast Band Filter (157-235 MHz)");
mRfDabNotchCheckBox.setEnabled(false);
mRfDabNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfDabNotch(mRfDabNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 2 RF DAB notch enabled to " + mRfDabNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfDabNotchCheckBox;
}
/**
* Checkbox control for RF notch
*/
private JCheckBox getRfNotchCheckBox()
{
if(mRfNotchCheckBox == null)
{
mRfNotchCheckBox = new JCheckBox("FM Broadcast Band Filter (78-114 MHz)");
mRfNotchCheckBox.setEnabled(false);
mRfNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfNotch(mRfNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 2 RF notch enabled to " + mRfNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfNotchCheckBox;
}
/**
* Checkbox control for Bias-T
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("Bias-T Power");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 2 AM notch enabled to " + mBiasTCheckBox.isSelected(), se);
}
}
});
}
return mBiasTCheckBox;
}
/**
* Checkbox control for External Reference Output
*/
private JCheckBox getExternalReferenceOutputCheckBox()
{
if(mExternalReferenceOutputCheckBox == null)
{
mExternalReferenceOutputCheckBox = new JCheckBox("External Reference Output");
mExternalReferenceOutputCheckBox.setEnabled(false);
mExternalReferenceOutputCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setExternalReferenceOutput(mExternalReferenceOutputCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPduo tuner 2 external reference output notch enabled to " +
mExternalReferenceOutputCheckBox.isSelected(), se);
}
}
});
}
return mExternalReferenceOutputCheckBox;
}
/**
* Button to launch the User Preferences editor to show the RSPduo tuner preference selection.
* @return constructed button.
*/
private JButton getTunerPreferencesButton()
{
if(mTunerPreferencesButton == null)
{
mTunerPreferencesButton = new JButton("RSPduo Preferences");
mTunerPreferencesButton.addActionListener(e -> MyEventBus.getGlobalEventBus()
.post(new ViewUserPreferenceEditorRequest(PreferenceEditorType.SOURCE_TUNERS)));
}
return mTunerPreferencesButton;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2024 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,210 +16,60 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.sdrplay.rspDx;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.sdrplay.DiscoveredRspTuner;
import io.github.dsheirer.source.tuner.sdrplay.RspSampleRate;
import io.github.dsheirer.source.tuner.sdrplay.RspTunerEditor;
import io.github.dsheirer.source.tuner.sdrplay.RspException;
import io.github.dsheirer.source.tuner.sdrplay.RspAgcMode;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SpinnerNumberModel;
import io.github.dsheirer.source.tuner.ui.TunerSection;
import java.util.List;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
/**
* RSPdx Tuner Editor
* RSPdx tuner editor
*/
public class RspDxTunerEditor extends RspTunerEditor<RspDxTunerConfiguration>
{
private static final Logger mLog = LoggerFactory.getLogger(RspDxTunerEditor.class);
private JComboBox<RspSampleRate> mSampleRateCombo;
private JCheckBox mBiasTCheckBox;
private JCheckBox mRfDabNotchCheckBox;
private JCheckBox mRfNotchCheckBox;
private JComboBox<RspDxAntennaSelection> mAntennaCombo;
private JCheckBox mHdrModeCheckBox;
private JComboBox<HdrModeBandwidth> mHdrModeBandwidthCombo;
private final ComboBox<RspDxAntennaSelection> mAntennaCombo;
private final CheckBox mBiasTCheckBox;
private final CheckBox mRfNotchCheckBox;
private final CheckBox mRfDabNotchCheckBox;
private final CheckBox mHdrModeCheckBox;
private final ComboBox<HdrModeBandwidth> mHdrModeBandwidthCombo;
/**
* Constructs an instance
* @param userPreferences for settings
* @param tunerManager for state updates
* @param discoveredTuner to edit or control.
* @param userPreferences for preference settings
* @param tunerManager for saving tuner configurations
* @param discoveredTuner to edit
*/
public RspDxTunerEditor(UserPreferences userPreferences, TunerManager tunerManager, DiscoveredRspTuner discoveredTuner)
{
super(userPreferences, tunerManager, discoveredTuner);
init();
tunerStatusUpdated();
TunerSection options = addSection("Options");
mAntennaCombo = addChoice(options, "Antenna", List.of(RspDxAntennaSelection.values()),
() -> control().getAntenna(), selection -> control().setAntenna(selection));
mBiasTCheckBox = addOption(options, "ANT B Bias-T power", "Provide DC power on the ANT B connector",
() -> control().isBiasT(), enabled -> control().setBiasT(enabled));
mRfNotchCheckBox = addOption(options, "FM broadcast band filter (77-115 MHz)", null,
() -> control().isRfNotch(), enabled -> control().setRfNotch(enabled));
mRfDabNotchCheckBox = addOption(options, "DAB broadcast band filter (155-235 MHz)", null,
() -> control().isRfDabNotch(), enabled -> control().setRfDabNotch(enabled));
TunerSection hdr = addSection("High Dynamic Range");
mHdrModeCheckBox = addOption(hdr, "HDR mode (1 kHz - 2 MHz)", "High dynamic range mode for " +
"frequencies below 2 MHz", () -> control().isHighDynamicRange(),
enabled -> control().setHighDynamicRange(enabled));
mHdrModeBandwidthCombo = addChoice(hdr, "Bandwidth", HdrModeBandwidth.VALID,
() -> control().getHdrModeBandwidth(), bandwidth -> control().setHdrModeBandwidth(bandwidth));
refresh();
}
private void init()
private IControlRspDx control()
{
setLayout(new MigLayout("fill,wrap 3", "[right][grow,fill][fill]",
"[][][][][][][][][][][][][][][][][][grow]"));
add(new JLabel("Tuner:"));
add(getTunerIdLabel(), "wrap");
add(new JLabel("Status:"));
add(getTunerStatusLabel(), "wrap");
add(getButtonPanel(), "span,align left");
add(new JSeparator(), "span,growx,push");
add(new JLabel("Frequency (MHz):"));
add(getFrequencyPanel(), "wrap");
add(new JLabel("Sample Rate:"));
add(getSampleRateCombo(), "wrap");
add(new JLabel("Gain:"));
add(getGainPanel(), "wrap");
add(new JLabel("LNA:"));
add(getLNASlider(), "wrap");
add(new JLabel("IF:"));
add(getIfGainSlider(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getAntennaCombo(), "wrap");
add(new JLabel());
add(getBiasTCheckBox(), "wrap");
add(new JLabel());
add(getRfDabNotchCheckBox(), "wrap");
add(new JLabel());
add(getRfNotchCheckBox(), "wrap");
add(new JSeparator(), "span,growx,push");
add(new JLabel());
add(getHdrModeCheckBox(), "wrap");
add(new JLabel("HDR Mode Bandwidth"));
add(getHdrModeBandwidthCombo(), "wrap");
}
/**
* Access tuner controller
*/
private RspDxTunerController getTunerController()
{
if(hasTuner())
{
return (RspDxTunerController) getTuner().getTunerController();
}
return null;
}
@Override
public void setTunerLockState(boolean locked)
{
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(!locked);
updateSampleRateToolTip();
}
@Override
protected void tunerStatusUpdated()
{
setLoading(true);
getTunerIdLabel().setText(getDiscoveredTuner().getId());
String status = getDiscoveredTuner().getTunerStatus().toString();
if(getDiscoveredTuner().hasErrorMessage())
{
status += " - " + getDiscoveredTuner().getErrorMessage();
}
getTunerStatusLabel().setText(status);
getButtonPanel().updateControls();
getFrequencyPanel().updateControls();
getSampleRateCombo().setEnabled(hasTuner() && !getTuner().getTunerController().isLockedSampleRate());
getSampleRateCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getSampleRateEnumeration() : null);
updateSampleRateToolTip();
getAgcButton().setEnabled(hasTuner());
if(hasTuner())
{
RspAgcMode current = getTunerController().getControlRsp().getAgcMode();
getAgcButton().setSelected(current == null || current.equals(RspAgcMode.ENABLE));
getAgcButton().setText((current == null || current.equals(RspAgcMode.ENABLE)) ? AUTOMATIC : MANUAL);
getLNASlider().setLNA(getTunerController().getControlRsp().getLNA());
getIfGainSlider().setGR(getTunerController().getControlRsp().getBasebandGainReduction());
//Register to receive gain overload notifications
getTunerController().getControlRsp().setGainOverloadListener(this);
updateGainLabel();
}
getLNASlider().setEnabled(hasTuner());
getIfGainSlider().setEnabled(hasTuner() && getTunerController().getControlRsp().getAgcMode() != RspAgcMode.ENABLE);
getGainValueLabel().setEnabled(hasTuner());
getBiasTCheckBox().setEnabled(hasTuner());
try
{
getBiasTCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isBiasT());
}
catch(RspException se)
{
mLog.error("Error setting Bias-T enabled state in editor");
}
getHdrModeCheckBox().setEnabled(hasTuner());
try
{
getHdrModeCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isHighDynamicRange());
}
catch(RspException se)
{
mLog.error("Error setting HDR mode enabled state in editor");
}
getRfNotchCheckBox().setEnabled(hasTuner());
try
{
getRfNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfNotch());
}
catch(RspException se)
{
mLog.error("Error setting RF Notch enabled state in editor");
}
getRfDabNotchCheckBox().setEnabled(hasTuner());
try
{
getRfDabNotchCheckBox().setSelected(hasTuner() && getTunerController().getControlRsp().isRfDabNotch());
}
catch(RspException se)
{
mLog.error("Error setting RF DAB Notch enabled state in editor");
}
getAntennaCombo().setEnabled(hasTuner());
try
{
getAntennaCombo().setSelectedItem(hasTuner() ? getTunerController().getControlRsp().getAntenna() : null);
}
catch(RspException se)
{
mLog.error("Error setting antenna selection in editor");
}
setLoading(false);
return (IControlRspDx)getControlRsp();
}
@Override
@@ -227,247 +77,24 @@ public class RspDxTunerEditor extends RspTunerEditor<RspDxTunerConfiguration>
{
if(hasConfiguration() && !isLoading())
{
getConfiguration().setFrequency(getFrequencyControl().getFrequency());
getConfiguration().setMinimumFrequency(getMinimumFrequencyTextField().getFrequency());
getConfiguration().setMaximumFrequency(getMaximumFrequencyTextField().getFrequency());
double value = ((SpinnerNumberModel) getFrequencyCorrectionSpinner().getModel()).getNumber().doubleValue();
getConfiguration().setFrequencyCorrection(value);
getConfiguration().setAutoPPMCorrectionEnabled(getAutoPPMCheckBox().isSelected());
getConfiguration().setSampleRate((RspSampleRate)getSampleRateCombo().getSelectedItem());
getConfiguration().setBiasT(getBiasTCheckBox().isSelected());
getConfiguration().setHdrMode(getHdrModeCheckBox().isSelected());
getConfiguration().setRfDabNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setRfNotch(getRfNotchCheckBox().isSelected());
getConfiguration().setAntenna((RspDxAntennaSelection) getAntennaCombo().getSelectedItem());
getConfiguration().setLNA(getLNASlider().getLNA());
getConfiguration().setBasebandGainReduction(getIfGainSlider().getGR());
getConfiguration().setAgcMode(getAgcButton().isSelected() ? RspAgcMode.ENABLE : RspAgcMode.DISABLE);
RspDxTunerConfiguration config = getConfiguration();
saveRspSettings(config);
config.setBiasT(mBiasTCheckBox.isSelected());
config.setHdrMode(mHdrModeCheckBox.isSelected());
config.setRfDabNotch(mRfDabNotchCheckBox.isSelected());
config.setRfNotch(mRfNotchCheckBox.isSelected());
if(mAntennaCombo.getValue() != null)
{
config.setAntenna(mAntennaCombo.getValue());
}
if(mHdrModeBandwidthCombo.getValue() != null)
{
config.setHdrModeBandwidth(mHdrModeBandwidthCombo.getValue());
}
saveConfiguration();
}
}
/**
* Sample rate selection combobox control
*/
private JComboBox<RspSampleRate> getSampleRateCombo()
{
if(mSampleRateCombo == null)
{
RspSampleRate[] rspSampleRates = RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.toArray(new RspSampleRate[RspSampleRate.SINGLE_TUNER_SAMPLE_RATES.size()]);
mSampleRateCombo = new JComboBox<>(rspSampleRates);
mSampleRateCombo.setEnabled(false);
mSampleRateCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspSampleRate selected = (RspSampleRate)mSampleRateCombo.getSelectedItem();
try
{
getTunerController().setSampleRate(selected);
//Adjust the min/max values for the sample rate.
adjustForSampleRate((int)selected.getSampleRate());
save();
}
catch(RspException se)
{
mLog.error("Error setting sample rate for RSP2 tuner", se);
}
}
});
}
return mSampleRateCombo;
}
/**
* Checkbox control for Bias-T
*/
private JCheckBox getBiasTCheckBox()
{
if(mBiasTCheckBox == null)
{
mBiasTCheckBox = new JCheckBox("ANT B Bias-T Power");
mBiasTCheckBox.setEnabled(false);
mBiasTCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setBiasT(mBiasTCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP2 Bias-T enabled to " + mBiasTCheckBox.isSelected(), se);
}
}
});
}
return mBiasTCheckBox;
}
/**
* Checkbox control for HDR mode
*/
private JCheckBox getHdrModeCheckBox()
{
if(mHdrModeCheckBox == null)
{
mHdrModeCheckBox = new JCheckBox("HDR Mode (1 kHz - 2 MHz)");
mHdrModeCheckBox.setEnabled(false);
mHdrModeCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setHighDynamicRange(mHdrModeCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPd HDR mode enabled to " + mHdrModeCheckBox.isSelected(), se);
}
}
});
}
return mHdrModeCheckBox;
}
/**
* Checkbox control for RF notch
*/
private JCheckBox getRfNotchCheckBox()
{
if(mRfNotchCheckBox == null)
{
mRfNotchCheckBox = new JCheckBox("FM Broadcast Band Filter (77-115 MHz)");
mRfNotchCheckBox.setEnabled(false);
mRfNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfNotch(mRfNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSP2 RF notch enabled to " + mRfNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfNotchCheckBox;
}
/**
* Checkbox control for RF DAB notch
*/
private JCheckBox getRfDabNotchCheckBox()
{
if(mRfDabNotchCheckBox == null)
{
mRfDabNotchCheckBox = new JCheckBox("DAB Broadcast Band Filter (155-235 MHz)");
mRfDabNotchCheckBox.setEnabled(false);
mRfDabNotchCheckBox.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
try
{
getTunerController().getControlRsp().setRfDabNotch(mRfDabNotchCheckBox.isSelected());
save();
}
catch(RspException se)
{
mLog.error("Unable to set RSPdx RF DAB notch enabled to " + mRfDabNotchCheckBox.isSelected(), se);
}
}
});
}
return mRfDabNotchCheckBox;
}
/**
* Antenna selection combobox control
*/
private JComboBox<RspDxAntennaSelection> getAntennaCombo()
{
if(mAntennaCombo == null)
{
mAntennaCombo = new JComboBox<>(RspDxAntennaSelection.values());
mAntennaCombo.setEnabled(false);
mAntennaCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
RspDxAntennaSelection selected = (RspDxAntennaSelection) mAntennaCombo.getSelectedItem();
try
{
getTunerController().getControlRsp().setAntenna(selected);
save();
}
catch(RspException se)
{
mLog.error("Error setting Antenna selection for RSPdx", se);
}
}
});
}
return mAntennaCombo;
}
/**
* HDR mode bandwidth selection combobox control
*/
private JComboBox<HdrModeBandwidth> getHdrModeBandwidthCombo()
{
if(mHdrModeBandwidthCombo == null)
{
mHdrModeBandwidthCombo = new JComboBox<>(HdrModeBandwidth.VALID.toArray(new HdrModeBandwidth[0]));
mHdrModeBandwidthCombo.setEnabled(false);
mHdrModeBandwidthCombo.addActionListener(e -> {
if(hasTuner() && !isLoading())
{
HdrModeBandwidth selected = (HdrModeBandwidth) mHdrModeBandwidthCombo.getSelectedItem();
try
{
getTunerController().getControlRsp().setHdrModeBandwidth(selected);
save();
}
catch(RspException se)
{
mLog.error("Error setting HDR mode bandwidth for RSPdx", se);
}
}
});
}
return mHdrModeBandwidthCombo;
}
/**
* Updates the sample rate tooltip according to the tuner controller's lock state.
*/
private void updateSampleRateToolTip()
{
if(hasTuner() && getTuner().getTunerController().isLockedSampleRate())
{
getSampleRateCombo().setToolTipText("Sample Rate is locked. Disable decoding channels to unlock.");
}
else if(hasTuner())
{
getSampleRateCombo().setToolTipText("Select a sample rate for the tuner");
}
else
{
getSampleRateCombo().setToolTipText("No tuner available");
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,35 +16,33 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import io.github.dsheirer.gui.editor.Editor;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.TunerFactory;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.IDiscoveredTunerStatusListener;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import net.miginfocom.swing.MigLayout;
import javafx.application.Platform;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.StackPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
* Editor for Discovered Tuners that displays custom tuner editor for the selected discovered tuner
* Hosts the tuner editor for the selected discovered tuner, and replaces the editor when the tuner's status changes,
* since the tuner (and therefore the editor's controls) can change with the status.
*/
public class DiscoveredTunerEditor extends Editor<DiscoveredTuner> implements IDiscoveredTunerStatusListener
public class DiscoveredTunerEditor extends StackPane implements IDiscoveredTunerStatusListener
{
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(DiscoveredTunerEditor.class);
private UserPreferences mUserPreferences;
private TunerManager mTunerManager;
private JPanel mEmptyEditor = new EmptyTunerEditor();
private JPanel mEditor = mEmptyEditor;
private JScrollPane mEditorScroller;
private final UserPreferences mUserPreferences;
private final TunerManager mTunerManager;
private final EmptyTunerEditor mEmptyEditor = new EmptyTunerEditor();
private final ScrollPane mScrollPane = new ScrollPane();
private DiscoveredTuner mDiscoveredTuner;
private TunerEditor<?,?> mEditor;
/**
* Constructs an instance
@@ -55,83 +53,81 @@ public class DiscoveredTunerEditor extends Editor<DiscoveredTuner> implements ID
{
mUserPreferences = userPreferences;
mTunerManager = tunerManager;
init();
getStyleClass().add("discovered-tuner-editor");
mScrollPane.setFitToWidth(true);
mScrollPane.getStyleClass().add("tuner-editor-scroll");
mScrollPane.setContent(mEmptyEditor);
getChildren().add(mScrollPane);
}
/**
* Updates the lock state of the tuner editor so that lockable controls are updated
* @param locked true if the tuner is locked and the controls should be locked.
* Discovered tuner shown in the editor, or null.
*/
public void setTunerLockState(boolean locked)
public DiscoveredTuner getItem()
{
if(mEditor instanceof TunerEditor tunerEditor)
{
tunerEditor.setTunerLockState(locked);
}
return mDiscoveredTuner;
}
public void init()
/**
* Indicates if the editor shows a tuner.
*/
public boolean hasItem()
{
setLayout(new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]"));
mEditorScroller = new JScrollPane(mEditor);
add(mEditorScroller);
return mDiscoveredTuner != null;
}
@Override
public void save()
/**
* Current tuner editor, or null.
*/
public TunerEditor<?,?> getEditor()
{
//Unused
return mEditor;
}
@Override
public void setItem(DiscoveredTuner tuner)
/**
* Shows the editor for the discovered tuner, or the empty editor when the tuner is null.
*/
public void setItem(DiscoveredTuner discoveredTuner)
{
if(hasItem())
if(mDiscoveredTuner != null)
{
getItem().removeTunerStatusListener(this);
mDiscoveredTuner.removeTunerStatusListener(this);
}
//Cleanup previously selected tuner
if(hasItem() && mEditor instanceof TunerEditor tunerEditor)
if(mEditor != null)
{
tunerEditor.dispose();
mEditor.dispose();
mEditor = null;
}
super.setItem(tuner);
mDiscoveredTuner = discoveredTuner;
mEditorScroller.remove(mEditor);
if(discoveredTuner != null)
{
try
{
mEditor = TunerFactory.getEditor(mUserPreferences, discoveredTuner, mTunerManager);
}
catch(Exception e)
{
mLog.error("Error creating tuner editor for " + discoveredTuner.getId(), e);
}
if(hasItem())
{
mEditor = TunerFactory.getEditor(mUserPreferences, getItem(), mTunerManager);
getItem().addTunerStatusListener(this);
}
else
{
mEditor = mEmptyEditor;
discoveredTuner.addTunerStatusListener(this);
}
remove(mEditorScroller);
mEditorScroller = new JScrollPane(mEditor);
add(mEditorScroller);
revalidate();
repaint();
mScrollPane.setContent(mEditor != null ? mEditor : mEmptyEditor);
}
@Override
public void tunerStatusUpdated(DiscoveredTuner discoveredTuner, TunerStatus previous, TunerStatus current)
{
//If this is the currently displayed tuner, set it again to re-render the editor
if(hasItem() && getItem().equals(discoveredTuner))
{
if(current == TunerStatus.REMOVED)
Platform.runLater(() -> {
//If this is the currently displayed tuner, set it again to re-create the editor
if(mDiscoveredTuner != null && mDiscoveredTuner.equals(discoveredTuner))
{
setItem(null);
setItem(current == TunerStatus.REMOVED ? null : discoveredTuner);
}
else
{
setItem(discoveredTuner);
}
}
});
}
}
}

View File

@@ -28,8 +28,6 @@ import io.github.dsheirer.source.tuner.manager.IDiscoveredTunerStatusListener;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.sdrplay.rspDuo.DiscoveredRspDuoTuner1;
import io.github.dsheirer.source.tuner.sdrplay.rspDuo.DiscoveredRspDuoTuner2;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -39,29 +37,18 @@ import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.table.AbstractTableModel;
/**
* Model for discovered tuners
*/
public class DiscoveredTunerModel extends AbstractTableModel implements Listener<TunerEvent>,
public class DiscoveredTunerModel implements Listener<TunerEvent>,
IDiscoveredTunerStatusListener
{
private static final long serialVersionUID = 1L;
private static final Logger mLog = LoggerFactory.getLogger(DiscoveredTunerModel.class);
//Model columns
public static final int COLUMN_TUNER_STATUS = 0;
public static final int COLUMN_TUNER_CLASS = 1;
public static final int COLUMN_TUNER_TYPE = 2;
public static final int COLUMN_FREQUENCY = 3;
public static final int COLUMN_CHANNEL_COUNT = 4;
private static final String MHZ = " MHz";
private static final String[] COLUMN_HEADERS = {"Status","Class", "Type", "Frequency", "Channels"};
private List<DiscoveredTuner> mDiscoveredTuners = new CopyOnWriteArrayList<>();
private List<Listener<TunerEvent>> mTunerEventListeners = new ArrayList<>();
private DecimalFormat mFrequencyFormat = new DecimalFormat("0.00000");
private List<ModelListener> mModelListeners = new CopyOnWriteArrayList<>();
private Lock mLock = new ReentrantLock();
private TunerConfigurationManager mTunerConfigurationManager;
@@ -177,8 +164,7 @@ public class DiscoveredTunerModel extends AbstractTableModel implements Listener
if(!mDiscoveredTuners.contains(discoveredTuner))
{
mDiscoveredTuners.add(discoveredTuner);
int index = mDiscoveredTuners.indexOf(discoveredTuner);
EventQueue.invokeLater(() -> fireTableRowsInserted(index, index));
notifyAdded(discoveredTuner);
if(discoveredTuner.hasTuner())
{
discoveredTuner.getTuner().addTunerEventListener(this);
@@ -204,7 +190,11 @@ public class DiscoveredTunerModel extends AbstractTableModel implements Listener
try
{
mDiscoveredTuners.clear();
fireTableDataChanged();
for(DiscoveredTuner discoveredTuner: discoveredTuners)
{
notifyRemoved(discoveredTuner);
}
}
finally
{
@@ -230,34 +220,8 @@ public class DiscoveredTunerModel extends AbstractTableModel implements Listener
{
if(mDiscoveredTuners.contains(discoveredTuner))
{
int index = mDiscoveredTuners.indexOf(discoveredTuner);
mDiscoveredTuners.remove(discoveredTuner);
if(EventQueue.isDispatchThread())
{
try
{
fireTableRowsDeleted(index, index);
}
catch(Exception e)
{
mLog.info("Exception firing table rows deleted for index [" + index + "] on calling event dispatch thread", e);
}
}
else
{
EventQueue.invokeLater(() ->
{
try
{
fireTableRowsDeleted(index, index);
}
catch(Exception e)
{
mLog.info("Exception firing table rows deleted for index [" + index + "]", e);
}
});
}
notifyRemoved(discoveredTuner);
discoveredTuner.stop();
}
}
@@ -366,14 +330,12 @@ public class DiscoveredTunerModel extends AbstractTableModel implements Listener
if(current == TunerStatus.ENABLED && discoveredTuner.hasTuner())
{
discoveredTuner.getTuner().addTunerEventListener(this);
int row = mDiscoveredTuners.indexOf(discoveredTuner);
EventQueue.invokeLater(() -> fireTableRowsUpdated(row, row));
notifyUpdated(discoveredTuner);
return;
}
else if(current == TunerStatus.DISABLED)
else if(current == TunerStatus.DISABLED || current == TunerStatus.ERROR)
{
int row = mDiscoveredTuners.indexOf(discoveredTuner);
EventQueue.invokeLater(() -> fireTableRowsUpdated(row, row));
notifyUpdated(discoveredTuner);
return;
}
@@ -429,20 +391,17 @@ public class DiscoveredTunerModel extends AbstractTableModel implements Listener
try
{
DiscoveredTuner matchingTuner = getDiscoveredTuner(event.getTuner());
int index = mDiscoveredTuners.indexOf(matchingTuner);
if(index >= 0)
if(matchingTuner != null)
{
switch(event.getEvent())
{
case UPDATE_CHANNEL_COUNT:
EventQueue.invokeLater(() -> fireTableCellUpdated(index, COLUMN_CHANNEL_COUNT));
break;
case UPDATE_FREQUENCY:
EventQueue.invokeLater(() -> fireTableCellUpdated(index, COLUMN_FREQUENCY));
break;
case UPDATE_LOCK_STATE:
case UPDATE_SAMPLE_RATE:
case NOTIFICATION_ERROR_STATE:
EventQueue.invokeLater(() -> fireTableRowsUpdated(index, index));
notifyUpdated(matchingTuner);
break;
case UPDATE_FREQUENCY_ERROR:
if(mTunerConfigurationManager != null)
@@ -468,77 +427,77 @@ public class DiscoveredTunerModel extends AbstractTableModel implements Listener
broadcast(event);
}
@Override
public int getRowCount()
/**
* Snapshot of the discovered tuners.
*/
public List<DiscoveredTuner> getDiscoveredTuners()
{
return mDiscoveredTuners.size();
}
@Override
public int getColumnCount()
{
return COLUMN_HEADERS.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if(rowIndex < mDiscoveredTuners.size())
{
DiscoveredTuner discoveredTuner = mDiscoveredTuners.get(rowIndex);
switch(columnIndex)
{
case COLUMN_TUNER_STATUS:
return discoveredTuner.getTunerStatus();
case COLUMN_TUNER_CLASS:
return discoveredTuner.getTunerClass().toString();
case COLUMN_TUNER_TYPE:
if(discoveredTuner.hasTuner())
{
return discoveredTuner.getTuner().getTunerType().getLabel();
}
else
{
return "";
}
case COLUMN_FREQUENCY:
if(discoveredTuner.hasTuner())
{
long frequency = discoveredTuner.getTuner().getTunerController().getFrequency();
return mFrequencyFormat.format(frequency / 1E6D) + MHZ;
}
else
{
return "";
}
case COLUMN_CHANNEL_COUNT:
if(discoveredTuner.hasTuner())
{
int channelCount = discoveredTuner.getTuner().getChannelSourceManager().getTunerChannelCount();
return channelCount + " (" + (discoveredTuner.getTuner().getTunerController().isLockedSampleRate() ? "LOCKED)" : "UNLOCKED)");
}
else
{
return "";
}
default:
break;
}
}
return null;
}
@Override
public String getColumnName(int columnIndex)
{
return COLUMN_HEADERS[columnIndex];
return new ArrayList<>(mDiscoveredTuners);
}
/**
* Generates a diagnostic report for all discovered tuners.
* Adds a listener for tuners added to, removed from or updated in the model. Listeners are invoked on the
* calling thread, which can be any thread.
*/
public void addModelListener(ModelListener listener)
{
mModelListeners.add(listener);
}
/**
* Removes the model listener
*/
public void removeModelListener(ModelListener listener)
{
mModelListeners.remove(listener);
}
private void notifyAdded(DiscoveredTuner discoveredTuner)
{
for(ModelListener listener: mModelListeners)
{
listener.tunerAdded(discoveredTuner);
}
}
private void notifyRemoved(DiscoveredTuner discoveredTuner)
{
for(ModelListener listener: mModelListeners)
{
listener.tunerRemoved(discoveredTuner);
}
}
private void notifyUpdated(DiscoveredTuner discoveredTuner)
{
for(ModelListener listener: mModelListeners)
{
listener.tunerUpdated(discoveredTuner);
}
}
/**
* Listener for changes to the discovered tuners in the model.
*/
public interface ModelListener
{
/**
* A tuner was added to the model
*/
void tunerAdded(DiscoveredTuner discoveredTuner);
/**
* A tuner was removed from the model
*/
void tunerRemoved(DiscoveredTuner discoveredTuner);
/**
* A tuner's status, frequency, sample rate, channel count or lock state changed
*/
void tunerUpdated(DiscoveredTuner discoveredTuner);
}
public String getDiagnosticReport()
{
StringBuilder sb = new StringBuilder();

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2022 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,27 +16,25 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
/**
* Empty tuner editor panel
* Placeholder shown when no tuner is selected.
*/
public class EmptyTunerEditor extends JPanel
public class EmptyTunerEditor extends VBox
{
private static final long serialVersionUID = 1L;
/**
* Constructs an instance
*/
public EmptyTunerEditor()
{
setLayout(new MigLayout("insets 0 0 0 0", "[center,grow]", "[center,grow]"));
add(new JLabel("No tuner selected"), "wrap");
getStyleClass().add("empty-tuner-editor");
setAlignment(Pos.CENTER);
Label title = new Label("No tuner selected");
title.getStyleClass().add("empty-tuner-title");
Label hint = new Label("Select a tuner in the list to view and change its settings.");
hint.setWrapText(true);
getChildren().addAll(title, hint);
}
}

View File

@@ -0,0 +1,172 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
/**
* Integer slider with a value label, for gain settings. The change handler is invoked each time the user moves the
* slider to a different whole value, but not when the value is set with {@link #setValue(int)}.
*/
public class GainSlider extends HBox
{
private final Slider mSlider;
private final Label mValueLabel = new Label();
private IntConsumer mChangeHandler;
private IntFunction<String> mFormatter = String::valueOf;
private boolean mUpdating = false;
private boolean mApplyOnRelease = false;
private int mValue;
/**
* Constructs an instance
* @param minimum value
* @param maximum value
* @param value initial value
*/
public GainSlider(int minimum, int maximum, int value)
{
getStyleClass().add("gain-slider");
setAlignment(Pos.CENTER_LEFT);
mSlider = new Slider(minimum, maximum, value);
mSlider.setBlockIncrement(1);
mSlider.setMajorTickUnit(1);
mSlider.setMinorTickCount(0);
mSlider.setShowTickMarks(maximum - minimum <= 30);
mSlider.setSnapToTicks(true);
mSlider.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(mSlider, Priority.ALWAYS);
mValueLabel.getStyleClass().add("gain-slider-value");
mValue = value;
updateLabel();
mSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
int rounded = (int)Math.round(newValue.doubleValue());
if(rounded != mValue)
{
mValue = rounded;
updateLabel();
if(!mUpdating && mChangeHandler != null && !(mApplyOnRelease && mSlider.isValueChanging()))
{
mChangeHandler.accept(rounded);
}
}
});
mSlider.valueChangingProperty().addListener((observable, wasChanging, changing) -> {
if(mApplyOnRelease && !changing && !mUpdating && mChangeHandler != null)
{
mChangeHandler.accept(mValue);
}
});
getChildren().addAll(mSlider, mValueLabel);
}
/**
* Sets the handler for user changes.
*/
public void setOnChange(IntConsumer handler)
{
mChangeHandler = handler;
}
/**
* When true, a drag of the slider thumb invokes the change handler once, when the thumb is released, instead of
* at each whole value along the way.
*/
public void setApplyOnRelease(boolean applyOnRelease)
{
mApplyOnRelease = applyOnRelease;
}
/**
* Sets the formatter for the value label, e.g. to append dB.
*/
public void setFormatter(IntFunction<String> formatter)
{
mFormatter = formatter;
updateLabel();
}
/**
* Sets the value without invoking the change handler.
*/
public void setValue(int value)
{
mUpdating = true;
mValue = value;
mSlider.setValue(value);
updateLabel();
mUpdating = false;
}
/**
* Current value.
*/
public int getValue()
{
return mValue;
}
/**
* Changes the slider range without invoking the change handler.
*/
public void setRange(int minimum, int maximum)
{
mUpdating = true;
mSlider.setMin(minimum);
mSlider.setMax(maximum);
mSlider.setShowTickMarks(maximum - minimum <= 30);
mValue = (int)Math.round(mSlider.getValue());
updateLabel();
mUpdating = false;
}
/**
* Sets the tooltip on the slider.
*/
public void setTooltip(String text)
{
mSlider.setTooltip(new Tooltip(text));
}
/**
* Wrapped slider.
*/
public Slider getSlider()
{
return mSlider;
}
private void updateLabel()
{
mValueLabel.setText(mFormatter.apply(mValue));
}
}

View File

@@ -0,0 +1,200 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Window;
/**
* Shows tuner information that the tuner editors describe with a small subset of HTML: an optional h3 heading
* followed by lines separated by br, where a line is either "<b>Key: </b>value" or plain text.
*/
public class TunerInfoDialog
{
private TunerInfoDialog()
{
}
/**
* A parsed line of tuner information.
* @param key bold key text, or null for a plain line
* @param value text
*/
public record Line(String key, String value)
{
}
/**
* Parsed tuner information.
* @param heading text or null
* @param lines of information
*/
public record Info(String heading, List<Line> lines)
{
/**
* Plain text version for copying to the clipboard.
*/
public String toText()
{
StringBuilder sb = new StringBuilder();
if(heading != null)
{
sb.append(heading).append("\n");
}
for(Line line: lines)
{
if(line.key() != null)
{
sb.append(line.key()).append(": ");
}
sb.append(line.value()).append("\n");
}
return sb.toString();
}
}
/**
* Parses the tuner information HTML.
*/
public static Info parse(String html)
{
String text = html == null ? "" : html.replaceAll("(?i)</?html>", "");
String heading = null;
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("(?is)<h3>(.*?)</h3>").matcher(text);
if(matcher.find())
{
heading = strip(matcher.group(1));
text = text.substring(0, matcher.start()) + text.substring(matcher.end());
}
List<Line> lines = new ArrayList<>();
for(String part: text.split("(?i)<br\\s*/?>|\\n"))
{
java.util.regex.Matcher keyed = java.util.regex.Pattern.compile("(?is)^\\s*<b>(.*?)</b>(.*)$").matcher(part);
if(keyed.matches())
{
String key = strip(keyed.group(1)).trim();
if(key.endsWith(":"))
{
key = key.substring(0, key.length() - 1).trim();
}
lines.add(new Line(key, strip(keyed.group(2)).trim()));
}
else
{
String plain = strip(part).trim();
if(!plain.isEmpty())
{
lines.add(new Line(null, plain));
}
}
}
return new Info(heading, lines);
}
private static String strip(String text)
{
return text.replaceAll("<[^>]+>", "").replace("&nbsp;", " ").replace("&amp;", "&")
.replace("&lt;", "<").replace("&gt;", ">");
}
/**
* Creates the content node for the information.
*/
public static Node createContent(Info info)
{
GridPane grid = new GridPane();
grid.getStyleClass().add("tuner-info-grid");
grid.setHgap(12);
grid.setVgap(4);
int row = 0;
for(Line line: info.lines())
{
Label value = new Label(line.value());
value.setWrapText(true);
if(line.key() != null)
{
Label key = new Label(line.key());
key.setStyle("-fx-font-weight: bold;");
grid.add(key, 0, row);
grid.add(value, 1, row);
}
else
{
grid.add(value, 0, row, 2, 1);
}
row++;
}
VBox box = new VBox(8, grid);
box.setMinWidth(320);
return box;
}
/**
* Shows the tuner information dialog.
* @param owner window or null
* @param html tuner information
*/
public static void show(Window owner, String html)
{
Info info = parse(html);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.initOwner(owner);
alert.setTitle("Tuner Info");
alert.setHeaderText(info.heading() != null ? info.heading() : "Tuner Info");
alert.getDialogPane().setContent(createContent(info));
ButtonType copy = new ButtonType("Copy", ButtonBar.ButtonData.LEFT);
alert.getButtonTypes().add(copy);
alert.getDialogPane().lookupButton(copy).addEventFilter(javafx.event.ActionEvent.ACTION, e -> {
ClipboardContent content = new ClipboardContent();
content.putString(info.toText());
Clipboard.getSystemClipboard().setContent(content);
e.consume();
});
alert.show();
}
}

View File

@@ -0,0 +1,182 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
/**
* Titled card in a tuner editor that lays out labelled controls in rows: a label column, a control column that
* grows, and an optional trailing column (e.g. a value label or a button).
*/
public class TunerSection extends VBox
{
private final Label mTitle;
private final GridPane mGrid = new GridPane();
private int mRow = 0;
/**
* Constructs an instance
* @param title for the section
*/
public TunerSection(String title)
{
getStyleClass().add("tuner-section");
mTitle = new Label(title);
mTitle.getStyleClass().add("tuner-section-title");
mGrid.getStyleClass().add("tuner-section-grid");
ColumnConstraints labels = new ColumnConstraints();
labels.setHalignment(HPos.LEFT);
labels.setMinWidth(Label.USE_PREF_SIZE);
ColumnConstraints controls = new ColumnConstraints();
controls.setHgrow(Priority.ALWAYS);
controls.setFillWidth(true);
ColumnConstraints trailing = new ColumnConstraints();
trailing.setMinWidth(Label.USE_PREF_SIZE);
mGrid.getColumnConstraints().addAll(labels, controls, trailing);
getChildren().addAll(mTitle, mGrid);
}
/**
* Title label of the section.
*/
public Label getTitleLabel()
{
return mTitle;
}
/**
* Adds a row with a text label and a control.
* @return the label that was created, so that it can be hidden along with the control
*/
public Label addRow(String label, Node control)
{
Label labelNode = createLabel(label);
addRow(labelNode, control, null);
return labelNode;
}
/**
* Adds a row with a text label, a control and a trailing node.
* @return the label that was created
*/
public Label addRow(String label, Node control, Node trailing)
{
Label labelNode = createLabel(label);
addRow(labelNode, control, trailing);
return labelNode;
}
/**
* Adds a row with a label node (may be null), a control and an optional trailing node.
*/
public void addRow(Node label, Node control, Node trailing)
{
if(label != null)
{
GridPane.setValignment(label, VPos.CENTER);
mGrid.add(label, 0, mRow);
bindManaged(label);
}
if(control != null)
{
if(trailing == null)
{
mGrid.add(control, 1, mRow, 2, 1);
}
else
{
mGrid.add(control, 1, mRow);
}
bindManaged(control);
}
if(trailing != null)
{
mGrid.add(trailing, 2, mRow);
bindManaged(trailing);
}
mRow++;
}
/**
* Adds a control (e.g. a check box) without a label, aligned with the other controls.
*/
public void addControl(Node control)
{
addRow((Node)null, control, null);
}
/**
* Adds a node that spans the full width of the section.
*/
public void addFullRow(Node node)
{
mGrid.add(node, 0, mRow, 3, 1);
bindManaged(node);
mRow++;
}
/**
* Adds a row of nodes laid out left to right, under the control column.
*/
public HBox addFlowRow(Node... nodes)
{
HBox box = new HBox(nodes);
box.getStyleClass().add("tuner-flow-row");
box.setAlignment(Pos.CENTER_LEFT);
addRow((Node)null, box, null);
return box;
}
/**
* Creates a row label.
*/
public static Label createLabel(String text)
{
Label label = new Label(text);
label.getStyleClass().add("tuner-row-label");
return label;
}
/**
* Hides nodes from the layout when they are not visible.
*/
private static void bindManaged(Node node)
{
if(!node.managedProperty().isBound())
{
node.managedProperty().bind(node.visibleProperty());
}
}
}

View File

@@ -0,0 +1,368 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import io.github.dsheirer.gui.control.FrequencyEntry;
import io.github.dsheirer.gui.table.ColumnConfigurationButton;
import io.github.dsheirer.gui.table.TableColumnMonitor;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.source.tuner.configuration.TunerConfigurationManager;
import io.github.dsheirer.source.tuner.manager.DiscoveredNetworkTuner;
import io.github.dsheirer.source.tuner.manager.DiscoveredRecordingTuner;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.network.AddNetworkTunerDialog;
import io.github.dsheirer.source.tuner.recording.AddRecordingTunerDialog;
import io.github.dsheirer.util.ThreadPool;
import java.net.URL;
import java.util.function.Function;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.css.PseudoClass;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tuners tab: the list of discovered tuners on the left and the editor for the selected tuner on the right.
*/
public class TunerView extends SplitPane implements DiscoveredTunerModel.ModelListener
{
private static final Logger mLog = LoggerFactory.getLogger(TunerView.class);
private static final String TABLE_KEY = "tuner.view";
private static final String SWING_TABLE_KEY = "tuner.view.panel";
private static final PseudoClass STATUS_ENABLED = PseudoClass.getPseudoClass("enabled");
private static final PseudoClass STATUS_DISABLED = PseudoClass.getPseudoClass("disabled-tuner");
private static final PseudoClass STATUS_ERROR = PseudoClass.getPseudoClass("error");
private static final PseudoClass STATUS_REMOVED = PseudoClass.getPseudoClass("removed");
private final UserPreferences mUserPreferences;
private final DiscoveredTunerModel mDiscoveredTunerModel;
private final TunerConfigurationManager mTunerConfigurationManager;
private final DiscoveredTunerEditor mDiscoveredTunerEditor;
private final ObservableList<DiscoveredTuner> mTuners = FXCollections.observableArrayList();
private final TableView<DiscoveredTuner> mTableView = new TableView<>();
private final TableColumnMonitor<DiscoveredTuner> mTableColumnMonitor;
private final Button mRemoveButton = new Button("Remove");
/**
* Constructs an instance. Must be invoked on the JavaFX application thread.
* @param tunerManager for tuners
* @param userPreferences for tuner editors and column settings
*/
public TunerView(TunerManager tunerManager, UserPreferences userPreferences)
{
mUserPreferences = userPreferences;
mDiscoveredTunerModel = tunerManager.getDiscoveredTunerModel();
mTunerConfigurationManager = tunerManager.getTunerConfigurationManager();
mDiscoveredTunerEditor = new DiscoveredTunerEditor(userPreferences, tunerManager);
getStyleClass().add("tuner-view");
URL stylesheet = TunerView.class.getResource("/tuner_editor.css");
if(stylesheet != null)
{
getStylesheets().add(stylesheet.toExternalForm());
}
createColumns();
mTableColumnMonitor = new TableColumnMonitor<>(mTableView, TABLE_KEY, userPreferences.getSwingPreference(),
SWING_TABLE_KEY);
mTableView.setItems(mTuners);
mTableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
mTableView.setPlaceholder(new Label("No tuners discovered"));
mTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN);
mTableView.getSelectionModel().selectedItemProperty().addListener((observable, oldTuner, tuner) -> {
if(tuner != mDiscoveredTunerEditor.getItem())
{
mDiscoveredTunerEditor.setItem(tuner);
}
updateRemoveButton();
});
mTableView.setRowFactory(table -> {
TableRow<DiscoveredTuner> row = new TableRow<>();
row.contextMenuProperty().bind(row.itemProperty().map(this::createContextMenu));
return row;
});
VBox.setVgrow(mTableView, Priority.ALWAYS);
VBox listPane = new VBox(createToolbar(), mTableView);
listPane.getStyleClass().add("tuner-list-pane");
listPane.setMinWidth(260);
getItems().addAll(listPane, mDiscoveredTunerEditor);
setOrientation(Orientation.HORIZONTAL);
setDividerPositions(0.42);
SplitPane.setResizableWithParent(listPane, false);
mDiscoveredTunerModel.addModelListener(this);
mTuners.setAll(mDiscoveredTunerModel.getDiscoveredTuners());
mTableView.sort();
}
private HBox createToolbar()
{
MenuItem addRecording = new MenuItem("Recording Tuner ...");
addRecording.setOnAction(e -> new AddRecordingTunerDialog(getScene().getWindow(), mUserPreferences,
mDiscoveredTunerModel, mTunerConfigurationManager).show());
MenuItem addNetwork = new MenuItem("Network Tuner (rtl_tcp) ...");
addNetwork.setOnAction(e -> new AddNetworkTunerDialog(getScene().getWindow(), mUserPreferences,
mDiscoveredTunerModel, mTunerConfigurationManager).show());
MenuButton addButton = new MenuButton("Add Tuner", null, addRecording, addNetwork);
addButton.setTooltip(new Tooltip("Add a recording tuner that replays a baseband recording, or an rtl_tcp " +
"network tuner"));
mRemoveButton.setTooltip(new Tooltip("Remove the selected recording or network tuner"));
mRemoveButton.setDisable(true);
mRemoveButton.setOnAction(e -> removeTuner(mTableView.getSelectionModel().getSelectedItem()));
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
HBox toolbar = new HBox(addButton, mRemoveButton, spacer,
new ColumnConfigurationButton(mTableColumnMonitor, "Tuner Columns"));
toolbar.getStyleClass().add("tuner-list-toolbar");
toolbar.setAlignment(Pos.CENTER_LEFT);
return toolbar;
}
private void createColumns()
{
TableColumn<DiscoveredTuner,TunerStatus> status = new TableColumn<>("Status");
status.setId("status");
status.setCellValueFactory(cell -> new ReadOnlyObjectWrapper<>(cell.getValue().getTunerStatus()));
status.setCellFactory(column -> new StatusCell());
status.setPrefWidth(90);
TableColumnMonitor.setLegacyIndex(status, 0);
TableColumn<DiscoveredTuner,String> tunerClass = textColumn("tunerClass", "Class",
tuner -> tuner.getTunerClass().toString(), 1);
tunerClass.setPrefWidth(120);
TableColumn<DiscoveredTuner,String> type = textColumn("type", "Type",
tuner -> tuner.hasTuner() ? tuner.getTuner().getTunerType().getLabel() : "", 2);
type.setPrefWidth(120);
TableColumn<DiscoveredTuner,Long> frequency = new TableColumn<>("Frequency");
frequency.setId("frequency");
frequency.setCellValueFactory(cell -> new ReadOnlyObjectWrapper<>(cell.getValue().hasTuner() ?
cell.getValue().getTuner().getTunerController().getFrequency() : null));
frequency.setCellFactory(column -> new TableCell<>()
{
@Override
protected void updateItem(Long item, boolean empty)
{
super.updateItem(item, empty);
setText(empty || item == null ? null : FrequencyEntry.format(item) + " MHz");
}
});
frequency.getStyleClass().add("tuner-frequency-column");
frequency.setPrefWidth(130);
TableColumnMonitor.setLegacyIndex(frequency, 3);
TableColumn<DiscoveredTuner,String> channels = textColumn("channels", "Channels", tuner -> {
if(!tuner.hasTuner())
{
return "";
}
int count = tuner.getTuner().getChannelSourceManager().getTunerChannelCount();
boolean locked = tuner.getTuner().getTunerController().isLockedSampleRate();
return count + (locked ? " (locked)" : "");
}, 4);
mTableView.getColumns().addAll(status, tunerClass, type, frequency, channels);
mTableView.getSortOrder().add(type);
}
private static TableColumn<DiscoveredTuner,String> textColumn(String id, String title,
Function<DiscoveredTuner,String> value, int legacyIndex)
{
TableColumn<DiscoveredTuner,String> column = new TableColumn<>(title);
column.setId(id);
column.setCellValueFactory(cell -> new ReadOnlyObjectWrapper<>(value.apply(cell.getValue())));
TableColumnMonitor.setLegacyIndex(column, legacyIndex);
return column;
}
private ContextMenu createContextMenu(DiscoveredTuner tuner)
{
if(tuner == null)
{
return null;
}
MenuItem logState = new MenuItem("Log Tuner State");
logState.setOnAction(e -> tuner.logState());
MenuItem remove = new MenuItem("Remove Tuner");
remove.setDisable(!isRemovable(tuner));
remove.setOnAction(e -> removeTuner(tuner));
return new ContextMenu(logState, remove);
}
private static boolean isRemovable(DiscoveredTuner tuner)
{
return tuner instanceof DiscoveredRecordingTuner || tuner instanceof DiscoveredNetworkTuner;
}
private void updateRemoveButton()
{
DiscoveredTuner selected = mTableView.getSelectionModel().getSelectedItem();
mRemoveButton.setDisable(selected == null || !isRemovable(selected));
}
private void removeTuner(DiscoveredTuner selected)
{
if(selected != null && isRemovable(selected))
{
mLog.info("Removing Tuner: " + selected);
if(selected == mDiscoveredTunerEditor.getItem())
{
mDiscoveredTunerEditor.setItem(null);
}
//Stopping a tuner can block, so do it off of the JavaFX thread
ThreadPool.CACHED.submit(() -> {
selected.stop();
mTunerConfigurationManager.removeTunerConfiguration(selected.getTunerConfiguration());
mDiscoveredTunerModel.removeDiscoveredTuner(selected);
});
}
}
@Override
public void tunerAdded(DiscoveredTuner discoveredTuner)
{
Platform.runLater(() -> {
if(!mTuners.contains(discoveredTuner))
{
mTuners.add(discoveredTuner);
mTableView.sort();
}
});
}
@Override
public void tunerRemoved(DiscoveredTuner discoveredTuner)
{
Platform.runLater(() -> {
mTuners.remove(discoveredTuner);
if(mDiscoveredTunerEditor.getItem() == discoveredTuner)
{
mDiscoveredTunerEditor.setItem(null);
}
});
}
@Override
public void tunerUpdated(DiscoveredTuner discoveredTuner)
{
Platform.runLater(() -> {
mTableView.refresh();
updateRemoveButton();
});
}
/**
* Selects the tuner in the list, e.g. for a request to show a tuner's settings.
*/
public void select(DiscoveredTuner discoveredTuner)
{
mTableView.getSelectionModel().select(discoveredTuner);
}
/**
* Discovered tuner editor, for testing.
*/
DiscoveredTunerEditor getDiscoveredTunerEditor()
{
return mDiscoveredTunerEditor;
}
/**
* Table view, for testing.
*/
TableView<DiscoveredTuner> getTableView()
{
return mTableView;
}
/**
* Status column cell that shows the status as a colored pill.
*/
private static class StatusCell extends TableCell<DiscoveredTuner,TunerStatus>
{
private final Label mPill = new Label();
StatusCell()
{
mPill.getStyleClass().add("tuner-status-chip");
setAlignment(Pos.CENTER_LEFT);
}
@Override
protected void updateItem(TunerStatus status, boolean empty)
{
super.updateItem(status, empty);
setText(null);
if(empty || status == null)
{
setGraphic(null);
setTooltip(null);
return;
}
mPill.setText(status.toString());
mPill.pseudoClassStateChanged(STATUS_ENABLED, status == TunerStatus.ENABLED);
mPill.pseudoClassStateChanged(STATUS_DISABLED, status == TunerStatus.DISABLED);
mPill.pseudoClassStateChanged(STATUS_ERROR, status == TunerStatus.ERROR);
mPill.pseudoClassStateChanged(STATUS_REMOVED, status == TunerStatus.REMOVED);
setGraphic(mPill);
DiscoveredTuner tuner = getTableRow() != null ? getTableRow().getItem() : null;
setTooltip(tuner != null && tuner.hasErrorMessage() ? new Tooltip(tuner.getErrorMessage()) : null);
}
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -16,65 +16,20 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import com.jidesoft.swing.JideSplitPane;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.swing.JTableColumnWidthMonitor;
import io.github.dsheirer.source.tuner.configuration.TunerConfigurationManager;
import io.github.dsheirer.source.tuner.manager.DiscoveredNetworkTuner;
import io.github.dsheirer.source.tuner.manager.DiscoveredRecordingTuner;
import io.github.dsheirer.source.tuner.manager.DiscoveredTuner;
import io.github.dsheirer.source.tuner.manager.TunerManager;
import io.github.dsheirer.source.tuner.manager.TunerStatus;
import io.github.dsheirer.source.tuner.network.AddNetworkTunerDialog;
import io.github.dsheirer.source.tuner.recording.AddRecordingTunerDialog;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
/**
* Panel containing a discovered tuners table and a tuner editor for a selected tuner.
* Swing host for the JavaFX Tuners tab.
*/
public class TunerViewPanel extends JPanel
public class TunerViewPanel extends JFXPanel
{
private static final long serialVersionUID = 1L;
private final static Logger mLog = LoggerFactory.getLogger(TunerViewPanel.class);
private static final String TABLE_PREFERENCE_KEY = "tuner.view.panel";
private UserPreferences mUserPreferences;
private DiscoveredTunerModel mDiscoveredTunerModel;
private DiscoveredTunerEditor mDiscoveredTunerEditor;
private TunerConfigurationManager mTunerConfigurationManager;
private JTable mTunerTable;
private JTableColumnWidthMonitor mColumnWidthMonitor;
private TableRowSorter<DiscoveredTunerModel> mRowSorter;
private JideSplitPane mSplitPane;
private JButton mAddRecordingButton;
private JButton mRemoveTunerButton;
private JButton mAddNetworkButton;
/**
* Constructs an instance
* @param tunerManager for tuners
@@ -82,234 +37,13 @@ public class TunerViewPanel extends JPanel
*/
public TunerViewPanel(TunerManager tunerManager, UserPreferences userPreferences)
{
mDiscoveredTunerModel = tunerManager.getDiscoveredTunerModel();
mDiscoveredTunerEditor = new DiscoveredTunerEditor(userPreferences, tunerManager);
mTunerConfigurationManager = tunerManager.getTunerConfigurationManager();
mUserPreferences = userPreferences;
init();
}
Platform.setImplicitExit(false);
ThemeManager.getInstance().registerSwing(this);
private void init()
{
setLayout(new MigLayout("insets 0 0 0 0", "[fill,grow]", "[fill,grow]"));
mRowSorter = new TableRowSorter<>(mDiscoveredTunerModel);
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
sortKeys.add(new RowSorter.SortKey(DiscoveredTunerModel.COLUMN_TUNER_TYPE, SortOrder.ASCENDING));
mRowSorter.setSortKeys(sortKeys);
mTunerTable = new JTable(mDiscoveredTunerModel);
mTunerTable.setRowSorter(mRowSorter);
mTunerTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mTunerTable.getSelectionModel().addListSelectionListener(event ->
{
getRemoveTunerButton().setEnabled(false);
if(!event.getValueIsAdjusting())
{
int row = mTunerTable.getSelectedRow();
if(row >= 0)
{
int modelRow = mTunerTable.convertRowIndexToModel(row);
DiscoveredTuner selected = mDiscoveredTunerModel.getDiscoveredTuner(modelRow);
mDiscoveredTunerEditor.setItem(selected);
getRemoveTunerButton().setEnabled(selected instanceof DiscoveredRecordingTuner || selected instanceof DiscoveredNetworkTuner);
}
}
Platform.runLater(() -> {
Scene scene = new Scene(new TunerView(tunerManager, userPreferences));
ThemeManager.getInstance().register(scene);
setScene(scene);
});
//Add support for right-click context menu to the tuner table
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem logStateMenuItem = new JMenuItem("Log Tuner State");
logStateMenuItem.addActionListener(e -> {
int viewRow = mTunerTable.getSelectedRow();
DiscoveredTuner selected = null;
if(viewRow >= 0)
{
int modelRow = mTunerTable.convertRowIndexToModel(viewRow);
selected = mDiscoveredTunerModel.getDiscoveredTuner(modelRow);
}
if(selected != null)
{
selected.logState();
}
else
{
mLog.error("Can't log state - tuner not selected");
}
});
popupMenu.add(logStateMenuItem);
mTunerTable.setComponentPopupMenu(popupMenu);
//Monitor for tuner removal events so we can update the editor when our selected tuner is removed
mDiscoveredTunerModel.addTableModelListener(e ->
{
//Detect when status is for the currently selected tuner
if(e.getType() == TableModelEvent.DELETE &&
mDiscoveredTunerEditor.hasItem() &&
!mDiscoveredTunerModel.hasTuner(mDiscoveredTunerEditor.getItem()))
{
mDiscoveredTunerEditor.setItem(null);
}
});
mDiscoveredTunerModel.addListener(tunerEvent ->
{
switch(tunerEvent.getEvent())
{
case UPDATE_LOCK_STATE:
if(tunerEvent.getTuner() != null)
{
int row = mTunerTable.getSelectedRow();
if(row >= 0)
{
int modelRow = mTunerTable.convertRowIndexToModel(row);
DiscoveredTuner selectedTuner = mDiscoveredTunerModel.getDiscoveredTuner(modelRow);
if(selectedTuner != null && selectedTuner.hasTuner() && tunerEvent.getTuner() == selectedTuner.getTuner())
{
mDiscoveredTunerEditor.setTunerLockState(selectedTuner.getTuner().getTunerController().isLockedSampleRate());
}
}
}
break;
}
});
TableCellRenderer errorCellRenderer = new TunerStatusCellRenderer();
mTunerTable.getColumnModel().getColumn(DiscoveredTunerModel.COLUMN_TUNER_STATUS).setCellRenderer(errorCellRenderer);
mColumnWidthMonitor = new JTableColumnWidthMonitor(mUserPreferences, mTunerTable, TABLE_PREFERENCE_KEY);
JScrollPane tunerTableScroller = new JScrollPane(mTunerTable);
JPanel tunerTablePanel = new JPanel();
tunerTablePanel.setLayout(new MigLayout("insets 0", "[fill,grow,align center]", "[fill,grow][]"));
tunerTablePanel.add(tunerTableScroller, "span");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new MigLayout("insets 0 1 3 0", "", ""));
buttonPanel.add(getAddRecordingButton());
buttonPanel.add(getAddNetworkButton());
buttonPanel.add(getRemoveTunerButton());
tunerTablePanel.add(buttonPanel);
tunerTablePanel.setPreferredSize(new Dimension(200,200));
JScrollPane editorScroller = new JScrollPane(mDiscoveredTunerEditor);
editorScroller.setPreferredSize(new Dimension(200, 200));
mSplitPane = new JideSplitPane();
mSplitPane.setOrientation(JideSplitPane.HORIZONTAL_SPLIT);
mSplitPane.add(tunerTablePanel);
mSplitPane.add(editorScroller);
mSplitPane.setProportionalLayout(true);
mSplitPane.setProportions(new double[]{0.5});
add(mSplitPane);
}
private JButton getAddRecordingButton()
{
if(mAddRecordingButton == null)
{
mAddRecordingButton = new JButton("Add Recording Tuner");
mAddRecordingButton.addActionListener(e ->
{
AddRecordingTunerDialog dialog = new AddRecordingTunerDialog(mUserPreferences, mDiscoveredTunerModel,
mTunerConfigurationManager);
dialog.setLocationRelativeTo(TunerViewPanel.this);
EventQueue.invokeLater(() -> dialog.setVisible(true));
});
}
return mAddRecordingButton;
}
private JButton getRemoveTunerButton()
{
if(mRemoveTunerButton == null)
{
mRemoveTunerButton = new JButton("Remove Tuner");
mRemoveTunerButton.setEnabled(false);
mRemoveTunerButton.addActionListener(e -> {
int[] indexes = mTunerTable.getSelectionModel().getSelectedIndices();
//With single selection mode this should always be length one
if(indexes.length == 1)
{
int modelIndex = mTunerTable.convertRowIndexToModel(indexes[0]);
DiscoveredTuner selected = mDiscoveredTunerModel.getDiscoveredTuner(modelIndex);
if(selected instanceof DiscoveredRecordingTuner || selected instanceof DiscoveredNetworkTuner)
{
mLog.info("Removing Tuner: " + selected);
selected.stop();
mTunerConfigurationManager.removeTunerConfiguration(selected.getTunerConfiguration());
EventQueue.invokeLater(() -> mDiscoveredTunerModel.removeDiscoveredTuner(selected));
}
}
});
}
return mRemoveTunerButton;
}
private JButton getAddNetworkButton()
{
if (mAddNetworkButton == null)
{
mAddNetworkButton = new JButton("Add Network Tuner");
mAddNetworkButton.addActionListener(e ->
{
AddNetworkTunerDialog dialog = new AddNetworkTunerDialog(mUserPreferences, mDiscoveredTunerModel, mTunerConfigurationManager);
dialog.setLocationRelativeTo(TunerViewPanel.this);
EventQueue.invokeLater(() -> dialog.setVisible(true));
});
}
return mAddNetworkButton;
}
/**
* Custom cell renderer for the TunerStatus enumeration column
*/
public class TunerStatusCellRenderer extends DefaultTableCellRenderer
{
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column)
{
Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(value instanceof TunerStatus tunerStatus)
{
if(tunerStatus == TunerStatus.ERROR)
{
component.setForeground(Color.RED);
}
else if(tunerStatus == TunerStatus.DISABLED)
{
//Use the LAF's disabled-foreground colour so the row reads correctly on any
//theme - DARK_GRAY is invisible on dark backgrounds.
Color disabled = javax.swing.UIManager.getColor("Label.disabledForeground");
component.setForeground(disabled != null ? disabled : table.getForeground());
}
else
{
component.setForeground(table.getForeground());
}
}
else
{
component.setForeground(table.getForeground());
}
return component;
}
}
}

View File

@@ -0,0 +1,162 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
/* Frequency control. All colors are derived from the theme's looked-up colors (-fx-control-inner-background,
-fx-text-base-color, -fx-accent) so the control follows every application theme. */
.frequency-control
{
-fc-face: derive(-fx-control-inner-background, -5%);
-fc-edge: derive(-fx-control-inner-background, -28%);
-fc-digit: -fx-text-base-color;
-fc-dim: ladder(-fc-face, derive(-fc-face, 42%) 49%, derive(-fc-face, -30%) 50%);
-fc-hover: -fx-accent;
-fx-background-color: -fc-edge, -fc-face;
-fx-background-insets: 0, 1;
-fx-background-radius: 7, 6;
-fx-padding: 0 10 0 8;
-fx-spacing: 0;
-fx-effect: innershadow(gaussian, rgba(0, 0, 0, 0.30), 6, 0, 0, 1);
}
.frequency-control:focused
{
-fx-background-color: -fx-focus-color, -fc-face;
-fx-background-insets: 0, 2;
}
.frequency-control:entry
{
-fx-background-color: -fx-accent, -fc-face;
-fx-background-insets: 0, 2;
}
.frequency-control:invalid
{
-fx-background-color: #d9443a, -fc-face;
-fx-background-insets: 0, 2;
}
.frequency-control:disabled
{
-fx-opacity: 0.55;
}
.frequency-control .frequency-digit-text
{
-fx-font-size: 2.15em;
-fx-font-weight: bold;
-fx-fill: -fc-digit;
}
.frequency-control .frequency-point
{
-fx-fill: -fc-digit;
}
.frequency-control .frequency-group-gap
{
-fx-min-width: 6;
-fx-pref-width: 6;
}
.frequency-control .frequency-unit
{
-fx-text-fill: derive(-fc-digit, -25%);
-fx-font-size: 1.05em;
-fx-padding: 0.9em 0 0 6;
}
/* Leading zeros are dimmed so the significant part of the frequency stands out */
.frequency-control .frequency-digit:leading .frequency-digit-text
{
-fx-fill: -fc-dim;
}
/* Typed entry: typed digits use the accent color, implied digits are dimmed */
.frequency-control:entry .frequency-digit .frequency-digit-text
{
-fx-fill: -fc-dim;
}
.frequency-control:entry .frequency-digit:typed .frequency-digit-text
{
-fx-fill: -fx-accent;
}
.frequency-control .frequency-digit-cell
{
-fx-background-radius: 3;
}
/* Up/down halves revealed while the mouse is over a digit */
.frequency-control .frequency-half
{
-fx-background-color: -fc-hover;
-fx-background-radius: 3;
-fx-opacity: 0;
}
.frequency-control .frequency-digit:hover-up .frequency-half-up,
.frequency-control .frequency-digit:hover-down .frequency-half-down
{
-fx-opacity: 0.22;
}
.frequency-control .frequency-arrow
{
-fx-background-color: -fc-hover;
-fx-scale-shape: true;
-fx-opacity: 0;
}
.frequency-control .frequency-arrow-up
{
-fx-shape: "M0,10 L10,0 L20,10 Z";
-fx-translate-y: 2;
}
.frequency-control .frequency-arrow-down
{
-fx-shape: "M0,0 L20,0 L10,10 Z";
-fx-translate-y: -2;
}
.frequency-control .frequency-digit:hover .frequency-arrow
{
-fx-opacity: 0.35;
}
.frequency-control .frequency-digit:hover-up .frequency-arrow-up,
.frequency-control .frequency-digit:hover-down .frequency-arrow-down
{
-fx-opacity: 1.0;
}
.frequency-control .frequency-digit:hover
{
-fx-cursor: hand;
}
/* Keyboard cursor digit */
.frequency-control .frequency-digit:cursor .frequency-digit-cell
{
-fx-border-color: transparent transparent -fx-accent transparent;
-fx-border-width: 0 0 2 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 663 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

View File

@@ -0,0 +1,292 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
/* Tuners tab and tuner editors. Colors are derived from the theme's looked-up colors so they follow every
application theme. */
.tuner-view
{
-fx-background-color: -fx-background;
}
.tuner-list-pane
{
-fx-spacing: 6;
-fx-padding: 6 0 0 6;
}
.tuner-list-toolbar
{
-fx-spacing: 6;
}
.tuner-frequency-column
{
-fx-alignment: center-right;
}
/* Editor */
.tuner-editor
{
-fx-padding: 12 14 16 14;
-fx-spacing: 12;
-fx-max-width: 760;
}
.tuner-editor-scroll,
.tuner-editor-scroll > .viewport
{
-fx-background-color: -fx-background;
-fx-background-insets: 0;
}
.tuner-header
{
-fx-spacing: 8;
}
.tuner-title-row,
.tuner-header-extras
{
-fx-spacing: 8;
}
.tuner-titles
{
-fx-spacing: 1;
}
.tuner-title
{
-fx-font-size: 1.45em;
-fx-font-weight: bold;
}
.tuner-subtitle
{
-fx-opacity: 0.7;
}
.tuner-status-row
{
-fx-spacing: 10;
}
.tuner-actions
{
-fx-hgap: 6;
-fx-vgap: 6;
}
.tuner-error
{
-fx-text-fill: #d9443a;
}
.tuner-recording-status
{
-fx-text-fill: #d9443a;
-fx-font-size: 0.95em;
}
.tuner-record-button:selected
{
-fx-base: #c0392b;
-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
-fx-text-fill: white;
}
.tuner-record-button:selected .text
{
-fx-fill: white;
}
.tuner-restart-button
{
-fx-base: #d9822b;
}
/* Status chip used in the editor header and the tuner list */
.tuner-status-chip
{
-fx-padding: 1 9 1 9;
-fx-background-radius: 10;
-fx-border-radius: 10;
-fx-font-size: 0.92em;
-fx-font-weight: bold;
-fx-background-color: derive(-fx-background, -12%);
-fx-text-fill: -fx-text-base-color;
}
.tuner-status-chip:enabled
{
-fx-background-color: #2e9e5b;
-fx-text-fill: white;
}
.tuner-status-chip:error
{
-fx-background-color: #d9443a;
-fx-text-fill: white;
}
.tuner-status-chip:removed
{
-fx-background-color: #888888;
-fx-text-fill: white;
}
.tuner-status-chip:enabled .text,
.tuner-status-chip:error .text,
.tuner-status-chip:removed .text
{
-fx-fill: white;
}
/* Sections */
.tuner-sections
{
-fx-spacing: 12;
}
.tuner-section
{
-fx-background-color: derive(-fx-background, -10%), ladder(-fx-background, derive(-fx-background, 4%) 49%, derive(-fx-background, 45%) 50%);
-fx-background-insets: 0, 1;
-fx-background-radius: 8, 7;
-fx-padding: 10 14 12 14;
-fx-spacing: 8;
}
.tuner-section-embedded
{
-fx-background-color: transparent;
-fx-padding: 4 0 4 0;
}
.tuner-section-title
{
-fx-font-weight: bold;
-fx-font-size: 0.95em;
-fx-text-fill: -fx-accent;
}
.tuner-section-title .text
{
-fx-fill: -fx-accent;
}
.tuner-section-grid
{
-fx-hgap: 12;
-fx-vgap: 8;
}
.tuner-row-label
{
-fx-min-width: 90;
}
.tuner-flow-row
{
-fx-spacing: 12;
}
.tuner-frequency-row
{
-fx-padding: 2 0 4 0;
}
.tuner-hint
{
-fx-opacity: 0.75;
-fx-font-size: 0.95em;
}
.tuner-value-label
{
-fx-opacity: 0.85;
}
.tuner-locked-notice
{
-fx-padding: 4 10 4 10;
-fx-background-radius: 6;
-fx-background-color: derive(#d9a62b, 55%);
-fx-text-fill: #5c4300;
}
.tuner-locked-notice .text
{
-fx-fill: #5c4300;
}
.tuner-limits-pane > .content
{
-fx-padding: 4 14 8 14;
}
/* Gain slider */
.gain-slider
{
-fx-spacing: 10;
}
.gain-slider-value
{
-fx-min-width: 5.5em;
}
/* RSP gain overload indicator, which lights when the tuner reports an overload */
.tuner-overload-indicator
{
-fx-padding: 1 8 1 8;
-fx-background-radius: 4;
-fx-background-color: derive(-fx-background, -8%);
-fx-opacity: 0.55;
}
.tuner-overload-indicator:overload
{
-fx-background-color: #d9443a;
-fx-text-fill: #ffeb3b;
-fx-opacity: 1.0;
}
.tuner-overload-indicator:overload .text
{
-fx-fill: #ffeb3b;
}
/* Placeholder when no tuner is selected */
.empty-tuner-editor
{
-fx-padding: 40;
-fx-spacing: 6;
-fx-opacity: 0.75;
}
.empty-tuner-title
{
-fx-font-size: 1.3em;
-fx-font-weight: bold;
}

View File

@@ -255,6 +255,118 @@ public class TalkerAliasAutoAdderTest
assertNull(alias(RADIO), "local radio with the same value isn't aliased");
}
/**
* Fully qualified form of RADIO, with a local address that matches the radio ID.
*/
private static final RadioIdentifier QUALIFIED = APCO25FullyQualifiedRadioIdentifier.createFrom(1234, 0xBEE00,
0x123, 1234);
private void assertSingleAliasForBothForms(String name)
{
assertEquals(1, aliases().size(), "one alias for both radio identifier forms");
Alias alias = aliases().get(0);
assertEquals(name, alias.getName());
assertEquals(2, alias.getAliasIdentifiers().size());
AliasList aliasList = mAliasModel.getAliasList(LIST);
assertEquals(List.of(alias), aliasList.getAliases(RADIO), "alias list finds the simple radio");
assertEquals(List.of(alias), aliasList.getAliases(QUALIFIED), "alias list finds the fully qualified radio");
}
@Test
public void fullyQualifiedRadioAddedToSimpleRadioAlias()
{
decode(RADIO, "ENGINE 12");
decode(QUALIFIED, "ENGINE 12");
assertSingleAliasForBothForms("ENGINE 12");
decode(QUALIFIED, "ENGINE 12");
decode(RADIO, "ENGINE 12");
assertSingleAliasForBothForms("ENGINE 12");
}
@Test
public void simpleRadioAddedToFullyQualifiedRadioAlias()
{
decode(QUALIFIED, "ENGINE 12");
decode(RADIO, "ENGINE 12");
assertSingleAliasForBothForms("ENGINE 12");
}
@Test
public void mergedAliasIsStillRenamed()
{
decode(RADIO, "ENGINE 1");
decode(QUALIFIED, "ENGINE 12 OFFICER");
assertSingleAliasForBothForms("ENGINE 12 OFFICER");
decode(RADIO, "LADDER 3");
decode(RADIO, "LADDER 3");
assertSingleAliasForBothForms("LADDER 3");
decode(QUALIFIED, "RESCUE 5");
decode(QUALIFIED, "RESCUE 5");
assertSingleAliasForBothForms("RESCUE 5");
}
@Test
public void roamingRadioIsNotAddedToHomeRadioIdAlias()
{
RadioIdentifier home = APCO25RadioIdentifier.createFrom(777);
decode(home, "LOCAL 777");
decode(APCO25FullyQualifiedRadioIdentifier.createFrom(1234, 0xBEE00, 0x123, 777), "ROAMER");
assertEquals(2, aliases().size());
assertEquals("LOCAL 777", alias(home).getName());
assertEquals(1, alias(home).getAliasIdentifiers().size());
}
@Test
public void simpleRadioIsNotAddedToAmbiguousFullyQualifiedAliases()
{
decode(QUALIFIED, "ENGINE 12");
decode(APCO25FullyQualifiedRadioIdentifier.createFrom(1234, 0xBEE01, 0x456, 1234), "OTHER 12");
decode(RADIO, "ENGINE 12");
assertEquals(3, aliases().size());
assertEquals(1, alias(RADIO).getAliasIdentifiers().size());
}
private Alias userAlias(Radio radio)
{
Alias alias = new Alias("Custom Name");
alias.setAliasListName(LIST);
alias.setGroup("Apparatus");
alias.addAliasID(radio);
mAliasModel.addAlias(alias);
return alias;
}
@Test
public void userAliasIsGivenFullyQualifiedRadio()
{
Alias alias = userAlias(new Radio(Protocol.APCO25, 1234));
decode(QUALIFIED, "ENGINE 12");
decode(QUALIFIED, "ENGINE 12");
assertSingleAliasForBothForms("Custom Name");
assertEquals("Apparatus", alias.getGroup());
}
@Test
public void userAliasIsGivenSimpleRadio()
{
Alias alias = userAlias(new P25FullyQualifiedRadio(0xBEE00, 0x123, 1234));
decode(RADIO, "ENGINE 12");
decode(RADIO, "ENGINE 12");
assertSingleAliasForBothForms("Custom Name");
assertEquals("Apparatus", alias.getGroup());
}
@Test
public void multiIdentifierUserAliasIsNotGivenFullyQualifiedRadio()
{
Alias alias = userAlias(new Radio(Protocol.APCO25, 1234));
alias.addAliasID(new Talkgroup(Protocol.APCO25, 100));
mAliasModel.getAliasList(LIST).updateAlias(alias);
decode(QUALIFIED, "ENGINE 12");
assertEquals(2, aliases().size());
assertEquals(2, alias.getAliasIdentifiers().size());
}
@Test
public void decide()
{

View File

@@ -0,0 +1,206 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import io.github.dsheirer.source.SourceEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.StackPane;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the frequency control's keyboard and scroll wheel interaction.
*/
public class FrequencyControlTest
{
@BeforeAll
public static void startToolkit() throws Exception
{
//Run without a display
System.setProperty("glass.platform", "Headless");
System.setProperty("prism.order", "sw");
CompletableFuture<Void> started = new CompletableFuture<>();
try
{
Platform.startup(() -> started.complete(null));
}
catch(IllegalStateException e)
{
started.complete(null); //Already started
}
started.get(10, TimeUnit.SECONDS);
}
private static <T> T onFx(java.util.concurrent.Callable<T> callable) throws Exception
{
CompletableFuture<T> future = new CompletableFuture<>();
Platform.runLater(() -> {
try
{
future.complete(callable.call());
}
catch(Throwable t)
{
future.completeExceptionally(t);
}
});
return future.get(10, TimeUnit.SECONDS);
}
private static FrequencyControl createControl(List<Long> requests)
{
FrequencyControl control = new FrequencyControl();
control.setRange(24_000_000, 1_766_000_000);
control.setFrequency(851_012_500);
control.addListener(requests::add);
Scene scene = new Scene(new StackPane(control), 400, 120);
scene.snapshot(null);
return control;
}
private static void type(Node node, String text)
{
for(char c: text.toCharArray())
{
node.fireEvent(new KeyEvent(KeyEvent.KEY_TYPED, String.valueOf(c), "", KeyCode.UNDEFINED, false, false,
false, false));
}
}
private static void press(Node node, KeyCode code)
{
node.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", code, false, false, false, false));
}
@Test
public void typedEntryAppliedWithEnter() throws Exception
{
List<Long> requests = new ArrayList<>();
long frequency = onFx(() -> {
FrequencyControl control = createControl(requests);
type(control, "462.5625");
assertTrue(control.isEntryActive());
assertEquals(851_012_500L, control.getFrequency(), "not applied until Enter");
press(control, KeyCode.ENTER);
return control.getFrequency();
});
assertEquals(462_562_500L, frequency);
assertEquals(List.of(462_562_500L), requests);
}
@Test
public void typedEntryCancelledWithEscape() throws Exception
{
List<Long> requests = new ArrayList<>();
long frequency = onFx(() -> {
FrequencyControl control = createControl(requests);
type(control, "155.0");
press(control, KeyCode.ESCAPE);
return control.getFrequency();
});
assertEquals(851_012_500L, frequency);
assertTrue(requests.isEmpty());
}
@Test
public void outOfRangeEntryRejected() throws Exception
{
List<Long> requests = new ArrayList<>();
long frequency = onFx(() -> {
FrequencyControl control = createControl(requests);
type(control, "2000");
press(control, KeyCode.ENTER);
return control.getFrequency();
});
assertEquals(851_012_500L, frequency);
assertTrue(requests.isEmpty());
}
@Test
public void arrowKeysMoveCursorAndStep() throws Exception
{
List<Long> requests = new ArrayList<>();
long frequency = onFx(() -> {
FrequencyControl control = createControl(requests);
//Cursor starts on the 1 MHz digit: move right to the 100 kHz digit and step up twice
assertEquals(6, control.getCursorPosition());
press(control, KeyCode.RIGHT);
press(control, KeyCode.UP);
press(control, KeyCode.UP);
//Move left twice to the 10 MHz digit and step down once
press(control, KeyCode.LEFT);
press(control, KeyCode.LEFT);
press(control, KeyCode.DOWN);
return control.getFrequency();
});
assertEquals(841_212_500L, frequency);
assertEquals(List.of(851_112_500L, 851_212_500L, 841_212_500L), requests);
}
@Test
public void scrollWheelStepsDigitUnderMouse() throws Exception
{
List<Long> requests = new ArrayList<>();
long frequency = onFx(() -> {
FrequencyControl control = createControl(requests);
//Digits are in order from the 1000 MHz digit (position 9) to the 1 Hz digit (position 0)
Node digit = control.lookupAll(".frequency-digit").stream().toList().get(9 - 3); //1 kHz digit
var bounds = digit.localToScene(digit.getLayoutBounds());
//Two wheel notches up, as JFXPanel reports them: 40 per notch with a multiplier of 40
digit.fireEvent(new ScrollEvent(ScrollEvent.SCROLL, bounds.getCenterX(), bounds.getCenterY(),
bounds.getCenterX(), bounds.getCenterY(), false, false, false, false, false, false, 0, 80, 0, 80,
40, 40, ScrollEvent.HorizontalTextScrollUnits.NONE, 0, ScrollEvent.VerticalTextScrollUnits.NONE,
0, 0, null));
return control.getFrequency();
});
assertEquals(851_014_500L, frequency);
assertEquals(List.of(851_014_500L), requests, "one request for both notches");
}
@Test
public void tunerNotificationUpdatesWithoutRequest() throws Exception
{
List<Long> requests = new ArrayList<>();
FrequencyControl control = onFx(() -> createControl(requests));
control.process(SourceEvent.frequencyChange(null, 155_250_000L));
long frequency = onFx(control::getFrequency);
assertEquals(155_250_000L, frequency);
assertTrue(requests.isEmpty());
}
}

View File

@@ -0,0 +1,131 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.control;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the frequency control's digit arithmetic, parsing and typed entry.
*/
public class FrequencyEntryTest
{
@Test
public void digits()
{
long frequency = 851_012_500L;
assertEquals(0, FrequencyEntry.getDigit(frequency, 0));
assertEquals(5, FrequencyEntry.getDigit(frequency, 2));
assertEquals(1, FrequencyEntry.getDigit(frequency, 4));
assertEquals(1, FrequencyEntry.getDigit(frequency, 6));
assertEquals(8, FrequencyEntry.getDigit(frequency, 8));
assertEquals(0, FrequencyEntry.getDigit(frequency, 9));
assertTrue(FrequencyEntry.isLeadingZero(frequency, 9));
assertFalse(FrequencyEntry.isLeadingZero(frequency, 8));
assertFalse(FrequencyEntry.isLeadingZero(0, 6), "1 MHz digit is never a leading zero");
}
@Test
public void stepCarriesAndClamps()
{
assertEquals(852_000_000L, FrequencyEntry.step(851_900_000L, 5, 1, 1, 2_000_000_000L), "carry into MHz");
assertEquals(850_900_000L, FrequencyEntry.step(851_000_000L, 5, -1, 1, 2_000_000_000L), "borrow from MHz");
assertEquals(1_766_000_000L, FrequencyEntry.step(1_765_500_000L, 6, 3, 24_000_000L, 1_766_000_000L),
"clamp at maximum");
assertEquals(24_000_000L, FrequencyEntry.step(25_000_000L, 7, -1, 24_000_000L, 1_766_000_000L),
"clamp at minimum");
}
@Test
public void setDigit()
{
assertEquals(861_012_500L, FrequencyEntry.setDigit(851_012_500L, 7, 6));
assertEquals(851_012_509L, FrequencyEntry.setDigit(851_012_500L, 0, 9));
}
@Test
public void parse()
{
assertEquals(851_012_500L, FrequencyEntry.parse("851.0125"));
assertEquals(851_012_500L, FrequencyEntry.parse(" 851.012500 MHz "));
assertEquals(851_012_500L, FrequencyEntry.parse("851012500"), "large whole number is Hertz");
assertEquals(851_012_500L, FrequencyEntry.parse("851,012,500 Hz"));
assertEquals(162_550_000L, FrequencyEntry.parse("162550 kHz"));
assertEquals(1_296_000_000L, FrequencyEntry.parse("1.296GHz"));
assertEquals(9_999_000_000L, FrequencyEntry.parse("9999"), "4 digit whole number is MHz");
assertNull(FrequencyEntry.parse("851.0125005"), "finer than 1 Hz");
assertNull(FrequencyEntry.parse("abc"));
assertNull(FrequencyEntry.parse("-5"));
assertNull(FrequencyEntry.parse(""));
assertNull(FrequencyEntry.parse(null));
}
@Test
public void format()
{
assertEquals("851.012500", FrequencyEntry.format(851_012_500L));
assertEquals("0.000001", FrequencyEntry.format(1));
assertEquals("1296.000000", FrequencyEntry.format(1_296_000_000L));
}
@Test
public void typedEntry()
{
FrequencyEntry.TypedEntry entry = new FrequencyEntry.TypedEntry();
assertTrue(entry.isEmpty());
for(char c: "0851.0125".toCharArray())
{
assertTrue(entry.type(c));
}
assertEquals(851_012_500L, entry.getFrequency());
assertTrue(entry.isTyped(8), "100 MHz digit typed");
assertFalse(entry.isTyped(9), "leading zero isn't counted");
assertTrue(entry.isTyped(2), "100 Hz digit typed");
assertFalse(entry.isTyped(1), "10 Hz digit implied");
assertFalse(entry.type('.'), "second decimal point");
assertTrue(entry.backspace());
assertEquals(851_012_000L, entry.getFrequency());
entry.clear();
for(char c: "12345".toCharArray())
{
entry.type(c);
}
assertEquals(1234_000_000L, entry.getFrequency(), "fifth MHz digit is rejected");
entry.clear();
for(char c: ".1234567".toCharArray())
{
entry.type(c);
}
assertEquals(123_456L, entry.getFrequency(), "seventh fractional digit is rejected");
}
}

View File

@@ -76,8 +76,8 @@ public class HistoryTableViewTest
table.getSelectionModel().select(0);
table.getSelectionModel().select(2);
//The copy shortcut is Cmd-C (meta) on macOS and Ctrl-C elsewhere
boolean mac = System.getProperty("os.name", "").toLowerCase().startsWith("mac");
//The copy shortcut is Cmd-C on macOS and Ctrl-C elsewhere
boolean mac = System.getProperty("os.name", "").toLowerCase().contains("mac");
Clipboard.getSystemClipboard().clear();
Event.fireEvent(table, new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.C, false,
!mac, false, mac));

View File

@@ -39,15 +39,25 @@ public class SpectralDisplayThemeTest
}
@Test
void classicPaletteMatchesTheOriginalWaterfall()
void classicPaletteUsesTheOriginalWaterfallColors()
{
int[] palette = WaterfallPalette.classic();
assertEquals(0xFF00007F, palette[0]);
assertEquals(0xFF0000BF, palette[16]);
assertEquals(0xFFFFFF00, palette[60]);
assertEquals(0xFF0000BF, palette[63]);
assertEquals(0xFFFFFF00, palette[100]);
assertEquals(0xFFFF0000, palette[255]);
}
@Test
void classicPaletteHasDistinctColorsNearTheNoiseFloor()
{
int[] palette = WaterfallPalette.classic();
for(int index = 1; index < 64; index++)
{
assertTrue((palette[index] & 0xFF) > (palette[index - 1] & 0xFF), "index " + index);
}
}
@Test
void everyThemeHasAnOpaqueWaterfallAndALabel()
{

View File

@@ -0,0 +1,312 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.spectrum;
import java.util.Arrays;
import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the waterfall noise floor tracking and dB to palette index mapping.
*/
public class WaterfallScalerTest
{
private static final int BINS = 4096;
/**
* Noise bins in dB: exponentially distributed power with the given mean power in dB.
*/
private static float[] noise(Random random, float meanDb)
{
float[] bins = new float[BINS];
for(int x = 0; x < BINS; x++)
{
double power = -Math.log(1.0 - random.nextDouble());
bins[x] = (float)(meanDb + 10.0 * Math.log10(power));
}
return bins;
}
private static int index(byte value)
{
return WaterfallScaler.paletteIndex(value & 0xFF, WaterfallScaler.RANGE_DEFAULT);
}
/**
* Scaler with one DFT frame per row.
*/
private static WaterfallScaler single()
{
WaterfallScaler scaler = new WaterfallScaler();
scaler.setAveraging(1);
return scaler;
}
private static double medianIndex(byte[] row, int from, int to)
{
int[] values = new int[to - from];
for(int x = from; x < to; x++)
{
values[x - from] = index(row[x]);
}
Arrays.sort(values);
return values[values.length / 2];
}
@Test
void selectFindsTheKthSmallestValue()
{
Random random = new Random(1);
float[] values = new float[1001];
for(int x = 0; x < values.length; x++)
{
values[x] = random.nextFloat() * 100 - 50;
}
float[] sorted = values.clone();
Arrays.sort(sorted);
for(int k: new int[]{0, 1, 250, 500, 999, 1000})
{
assertEquals(sorted[k], WaterfallScaler.select(values.clone(), k), "k " + k);
}
}
@Test
void contrastDoesNotDependOnTheAbsoluteNoiseFloorLevel()
{
for(float floor: new float[]{-60, -100, -140})
{
WaterfallScaler scaler = single();
float[] bins = noise(new Random(2), floor);
//A 6 dB signal across bins 1000 - 1199
for(int x = 1000; x < 1200; x++)
{
bins[x] = floor + 6.0f;
}
byte[] row = scaler.process(bins);
double noiseMedian = medianIndex(row, 0, 1000);
double signal = index(row[1100]);
//Noise median sits in the lower part of the palette, above the background
assertTrue(noiseMedian > 25 && noiseMedian < 50, "floor " + floor + " noise median " + noiseMedian);
//6 dB signal is 7.6 dB above the noise median (1.6 dB below mean power): about 43 palette steps
assertEquals(43.0, signal - noiseMedian, 3.0, "floor " + floor);
}
}
/**
* Strong signals in a fraction of the bins move the 25th percentile up the noise distribution: about 1.5 dB at
* 25% occupancy and 3.8 dB (the noise median) at 50% occupancy. A mean of the dB values would move 5 and 10 dB.
*/
@Test
void signalsInMuchOfTheSpanBarelyRaiseTheFloor()
{
float[] noise = noise(new Random(3), -100);
WaterfallScaler empty = single();
empty.process(noise);
assertEquals(1.5, occupiedFloor(noise, 0.25) - empty.getFloor(), 0.5);
assertEquals(3.8, occupiedFloor(noise, 0.5) - empty.getFloor(), 0.5);
}
private static float occupiedFloor(float[] noise, double occupancy)
{
float[] bins = noise.clone();
for(int x = 0; x < (int)(BINS * occupancy); x++)
{
bins[x] += 20.0f;
}
WaterfallScaler scaler = single();
scaler.process(bins);
return scaler.getFloor();
}
@Test
void floorIsSmoothedAcrossRowsJumpsLargeStepsAndResets()
{
WaterfallScaler scaler = single();
Random random = new Random(4);
scaler.process(noise(random, -100));
float initial = scaler.getFloor();
//A 5 dB step moves the floor only part way on the next row
scaler.process(noise(random, -95));
float stepped = scaler.getFloor() - initial;
assertTrue(stepped > 0.5 && stepped < 1.5, "stepped " + stepped);
//A 20 dB step jumps straight to the new level
scaler.process(noise(random, -80));
assertEquals(initial + 20.0, scaler.getFloor(), 1.0);
//Reset restarts from the next row
scaler.reset();
scaler.process(noise(random, -100));
assertEquals(initial, scaler.getFloor(), 1.0);
}
@Test
void averagingCompletesARowEveryNFramesWithTheMeanPower()
{
WaterfallScaler scaler = new WaterfallScaler();
scaler.setAveraging(2);
float[] low = new float[BINS];
float[] high = new float[BINS];
java.util.Arrays.fill(low, -100.0f);
java.util.Arrays.fill(high, -100.0f);
//One bin at -100 dB then -90 dB: mean power is 10 * log10((1 + 10) / 2) = 7.4 dB above -100 dB
low[10] = -100.0f;
high[10] = -90.0f;
assertNull(scaler.process(low));
byte[] row = scaler.process(high);
assertNotNull(row);
float level = ((row[10] & 0xFF) - WaterfallScaler.FLOOR_LEVEL) * WaterfallScaler.LEVEL_STEP_DB;
assertEquals(7.4, level, WaterfallScaler.LEVEL_STEP_DB);
assertNull(scaler.process(low));
assertNotNull(scaler.process(low));
}
/**
* Averaging two frames should cut the noise spread (about 5.6 dB for one frame) to about 3.5 dB, so a weak signal
* stands further out of the noise.
*/
@Test
void averagingSeparatesWeakSignalsFromTheNoise()
{
double single = separation(1);
double averaged = separation(2);
assertTrue(averaged > single * 1.1, "single " + single + " averaged " + averaged);
}
/**
* Mean level difference between a 3 dB signal and the noise, relative to the noise level spread, in level codes.
*/
private static double separation(int frames)
{
WaterfallScaler scaler = new WaterfallScaler();
scaler.setAveraging(frames);
Random random = new Random(6);
byte[] row = null;
while(row == null)
{
float[] bins = noise(random, -100);
for(int x = 0; x < BINS / 2; x++)
{
double power = -Math.log(1.0 - random.nextDouble()) + Math.pow(10, 0.3);
bins[x] = (float)(-100 + 10.0 * Math.log10(power));
}
row = scaler.process(bins);
}
double[] signal = stats(row, 0, BINS / 2);
double[] noise = stats(row, BINS / 2, BINS);
return (signal[0] - noise[0]) / noise[1];
}
private static double[] stats(byte[] row, int from, int to)
{
double sum = 0;
double squares = 0;
for(int x = from; x < to; x++)
{
int level = row[x] & 0xFF;
sum += level;
squares += level * level;
}
double mean = sum / (to - from);
return new double[]{mean, Math.sqrt(squares / (to - from) - mean * mean)};
}
@Test
void smallerRangesGiveMoreContrast()
{
int level6dB = WaterfallScaler.FLOOR_LEVEL + Math.round(6.0f / WaterfallScaler.LEVEL_STEP_DB);
int floor = WaterfallScaler.paletteIndex(WaterfallScaler.FLOOR_LEVEL, WaterfallScaler.RANGE_DEFAULT);
assertEquals(WaterfallScaler.FLOOR_INDEX, floor, 0.5);
int wide = WaterfallScaler.paletteIndex(level6dB, WaterfallScaler.RANGE_MAXIMUM) - floor;
int normal = WaterfallScaler.paletteIndex(level6dB, WaterfallScaler.RANGE_DEFAULT) - floor;
int narrow = WaterfallScaler.paletteIndex(level6dB, WaterfallScaler.RANGE_MINIMUM) - floor;
assertTrue(wide < normal && normal < narrow, wide + " " + normal + " " + narrow);
assertEquals(6.0 * 255 / WaterfallScaler.RANGE_DEFAULT, normal, 1.0);
//The level codes reach the top of the palette at the widest range
assertEquals(255, WaterfallScaler.paletteIndex(255, WaterfallScaler.RANGE_MAXIMUM));
}
/**
* At startup the DFT runs on an empty sample buffer, which converts to -196 dB in every bin. The first rows of
* real noise must not show as strong signals while the floor reference catches up.
*/
@Test
void silentStartupFramesDoNotFlashTheFirstNoiseRows()
{
WaterfallScaler scaler = single();
float[] silence = new float[BINS];
Arrays.fill(silence, -196.0f);
for(int x = 0; x < 3; x++)
{
scaler.process(silence);
}
Random random = new Random(7);
for(int x = 0; x < 3; x++)
{
double median = medianIndex(scaler.process(noise(random, -100)), 0, BINS);
assertTrue(median > 25 && median < 50, "row " + x + " noise median index " + median);
}
}
@Test
void indexesClampToThePalette()
{
WaterfallScaler scaler = single();
float[] bins = noise(new Random(5), -100);
bins[0] = 0.0f;
bins[1] = -300.0f;
byte[] row = scaler.process(bins);
assertEquals(255, index(row[0]));
assertEquals(0, index(row[1]));
}
}

View File

@@ -0,0 +1,53 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.ui;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests parsing the simple HTML tuner information that tuner editors provide.
*/
public class TunerInfoDialogTest
{
@Test
public void parsesHeadingAndKeyValueLines()
{
TunerInfoDialog.Info info = TunerInfoDialog.parse("<html><h3>RTL-2832 with R820T Tuner</h3>" +
"<b>USB ID: </b>0bda:2838<br><b>Serial: </b>00000001<br>No EEPROM Descriptor Available");
assertEquals("RTL-2832 with R820T Tuner", info.heading());
assertEquals(List.of(new TunerInfoDialog.Line("USB ID", "0bda:2838"),
new TunerInfoDialog.Line("Serial", "00000001"),
new TunerInfoDialog.Line(null, "No EEPROM Descriptor Available")), info.lines());
assertEquals("RTL-2832 with R820T Tuner\nUSB ID: 0bda:2838\nSerial: 00000001\nNo EEPROM Descriptor Available\n",
info.toText());
}
@Test
public void handlesMissingHeading()
{
TunerInfoDialog.Info info = TunerInfoDialog.parse("<b>Host: </b>localhost<br>");
assertEquals(null, info.heading());
assertEquals(List.of(new TunerInfoDialog.Line("Host", "localhost")), info.lines());
}
}