HackRF - final check-in. Changed all tuners to use the low-level API of the usb4java library to resolve limitation in high-level API that constrains maximum sample rate to ~2.0 MHz. Added console logging to logback.

This commit is contained in:
dennis.sheirer
2014-10-20 23:09:50 +00:00
parent 8d60397547
commit 5f4e7652bd
29 changed files with 2297 additions and 1971 deletions

View File

@@ -17,4 +17,14 @@
<appender-ref ref="FILE" /> <appender-ref ref="FILE" />
</root> </root>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-16(%d{HH:mm:ss.SSS} [%thread]) %-5level %logger{30} - %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration> </configuration>

View File

@@ -6,6 +6,9 @@ import decode.Decoder;
import decode.DecoderType; import decode.DecoderType;
import dsp.am.AMDemodulator; import dsp.am.AMDemodulator;
import dsp.filter.DCRemovalFilter2; import dsp.filter.DCRemovalFilter2;
import dsp.filter.FilterFactory;
import dsp.filter.FloatFIRFilter;
import dsp.filter.Window.WindowType;
public class AMDecoder extends Decoder public class AMDecoder extends Decoder
{ {
@@ -13,10 +16,11 @@ public class AMDecoder extends Decoder
* This value determines how quickly the DC remove filter responds to * This value determines how quickly the DC remove filter responds to
* changes in frequency. * changes in frequency.
*/ */
private static final double DC_REMOVAL_RATIO = 0.000003; private static final double DC_REMOVAL_RATIO = 0.003;
private AMDemodulator mDemodulator; private AMDemodulator mDemodulator;
private DCRemovalFilter2 mDCRemovalFilter; private DCRemovalFilter2 mDCRemovalFilter;
private FloatFIRFilter mLowPassFilter;
public AMDecoder( SampleType sampleType ) public AMDecoder( SampleType sampleType )
{ {
@@ -50,7 +54,14 @@ public class AMDecoder extends Decoder
* Route the demodulated, filtered samples back to this class to send * Route the demodulated, filtered samples back to this class to send
* to all registered listeners * to all registered listeners
*/ */
mDCRemovalFilter.setListener( this.getFloatReceiver() );
mLowPassFilter = new FloatFIRFilter(
FilterFactory.getLowPass( 48000, 3000, 31,
WindowType.COSINE ), 100.0 );
mDCRemovalFilter.setListener( mLowPassFilter );
mLowPassFilter.setListener( this.getFloatReceiver() );
} }
} }

View File

@@ -14,7 +14,7 @@ public class AMDemodulator implements Listener<ComplexSample>
public AMDemodulator() public AMDemodulator()
{ {
this( FilterFactory.getLowPass( 48000, 2000, 73, WindowType.HAMMING ), this( FilterFactory.getLowPass( 48000, 3000, 73, WindowType.HAMMING ),
1000.0 ); 1000.0 );
} }
@@ -53,8 +53,8 @@ public class AMDemodulator implements Listener<ComplexSample>
public void receive( ComplexSample sample ) public void receive( ComplexSample sample )
{ {
float demodulated = (float)Math.abs( float demodulated = (float)Math.abs(
Math.sqrt( ( sample.real() * sample.real() ) + Math.sqrt( ( sample.real() * sample.real() ) +
( sample.imaginery() * sample.imaginery() ) ) ); ( sample.imaginery() * sample.imaginery() ) ) );
mBroadcaster.broadcast( demodulated * 30.0f ); mBroadcaster.broadcast( demodulated * 30.0f );
} }

View File

@@ -138,7 +138,7 @@ public class JFrequencyControl extends JPanel implements FrequencyChangeListener
{ {
if( event.getAttribute() == Attribute.FREQUENCY ) if( event.getAttribute() == Attribute.FREQUENCY )
{ {
setFrequency( (int)event.getValue(), false ); setFrequency( (long)event.getValue(), false );
} }
} }
@@ -202,7 +202,7 @@ public class JFrequencyControl extends JPanel implements FrequencyChangeListener
{ {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private int mPower = 0; private int mPower = 0;
private int mValue = 0; private long mValue = 0;
private Digit( int position ) throws ParseException private Digit( int position ) throws ParseException
{ {
@@ -225,17 +225,17 @@ public class JFrequencyControl extends JPanel implements FrequencyChangeListener
public void setFrequency( long frequency, boolean fireChangeEvent ) public void setFrequency( long frequency, boolean fireChangeEvent )
{ {
//Strip the digits higher than this one //Strip the digits higher than this one
long lower = frequency % (int)( Math.pow( 10, mPower + 1) ); long lower = frequency % (long)( Math.pow( 10, mPower + 1) );
//Set the value to int value of dividing by 10 to this power //Set the value to int value of dividing by 10 to this power
int value = (int)( lower / (int)( Math.pow( 10, mPower ) ) ); long value = (long)( lower / (long)( Math.pow( 10, mPower ) ) );
set( value, fireChangeEvent ); set( value, fireChangeEvent );
} }
public long getFrequency() public long getFrequency()
{ {
return mValue * (int)Math.pow( 10, mPower ); return mValue * (long)Math.pow( 10, mPower );
} }
public void increment() public void increment()
@@ -261,7 +261,7 @@ public class JFrequencyControl extends JPanel implements FrequencyChangeListener
/** /**
* Convenience wrapper to change amount and fire change event * Convenience wrapper to change amount and fire change event
*/ */
private void set( int amount ) private void set( long amount )
{ {
set( amount, true ); set( amount, true );
} }
@@ -269,7 +269,7 @@ public class JFrequencyControl extends JPanel implements FrequencyChangeListener
/** /**
* Changes the value and optionally fires change event to listeners * Changes the value and optionally fires change event to listeners
*/ */
private void set( int amount, boolean fireChangeEvent ) private void set( long amount, boolean fireChangeEvent )
{ {
mValue = amount; mValue = amount;

View File

@@ -197,6 +197,11 @@ public class MixerManager
mLog.info( sb.toString() ); mLog.info( sb.toString() );
} }
public HashMap<String,MixerTunerDataLine> getMixerTuners()
{
return mMixerTuners;
}
private TargetDataLine getTargetDataLine( Mixer.Info mixerInfo, AudioFormat format ) private TargetDataLine getTargetDataLine( Mixer.Info mixerInfo, AudioFormat format )
{ {
TargetDataLine retVal = null; TargetDataLine retVal = null;

View File

@@ -17,7 +17,6 @@
******************************************************************************/ ******************************************************************************/
package source.mixer; package source.mixer;
import source.Source.SampleType;
/* /*
* Adapter to convert byte data received from a data stream into float[] * Adapter to convert byte data received from a data stream into float[]

View File

@@ -38,7 +38,7 @@ public class FrequencyController
public FrequencyController( Tunable tunable, public FrequencyController( Tunable tunable,
long minFrequency, long minFrequency,
long maxFrequency, long maxFrequency,
double frequencyCorrection ) throws SourceException double frequencyCorrection )
{ {
mTunable = tunable; mTunable = tunable;
mMinimumFrequency = minFrequency; mMinimumFrequency = minFrequency;
@@ -148,7 +148,7 @@ public class FrequencyController
*/ */
private long getCorrectedFrequency( long tunedFrequency ) private long getCorrectedFrequency( long tunedFrequency )
{ {
return (int)( (double)tunedFrequency / return (long)( (double)tunedFrequency /
( 1.0 - ( mFrequencyCorrection / 1000000.0 ) ) ); ( 1.0 - ( mFrequencyCorrection / 1000000.0 ) ) );
} }

View File

@@ -21,6 +21,9 @@ import java.util.ArrayList;
import javax.sound.sampled.TargetDataLine; import javax.sound.sampled.TargetDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener; import sample.Listener;
import sample.complex.ComplexSampleListListener; import sample.complex.ComplexSampleListListener;
import source.mixer.MixerSource; import source.mixer.MixerSource;
@@ -28,6 +31,9 @@ import source.mixer.SampleAdapter;
public abstract class MixerTuner extends Tuner public abstract class MixerTuner extends Tuner
{ {
private final static Logger mLog =
LoggerFactory.getLogger( MixerTuner.class );
private TargetDataLine mTargetDataLine; private TargetDataLine mTargetDataLine;
protected MixerTunerType mMixerTunerType; protected MixerTunerType mMixerTunerType;
protected MixerSource mMixerSource; protected MixerSource mMixerSource;

View File

@@ -48,6 +48,13 @@ public abstract class Tuner implements FrequencyChangeBroadcaster,
mName = name; mName = name;
} }
public String toString()
{
return mName;
}
public abstract void dispose();
public void setName( String name ) public void setName( String name )
{ {
mName = name; mName = name;

View File

@@ -51,7 +51,6 @@ public abstract class TunerController implements Tunable
* class, tuning a frequency, or setting the bandwidth * class, tuning a frequency, or setting the bandwidth
*/ */
public TunerController( long minimumFrequency, long maximumFrequency ) public TunerController( long minimumFrequency, long maximumFrequency )
throws SourceException
{ {
mFrequencyController = new FrequencyController( this, mFrequencyController = new FrequencyController( this,
minimumFrequency, minimumFrequency,

View File

@@ -23,20 +23,17 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
import javax.usb.UsbDevice;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbServices;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceList;
import org.usb4java.LibUsb;
import source.Source; import source.Source;
import source.SourceException; import source.SourceException;
import source.config.SourceConfigTuner; import source.config.SourceConfigTuner;
import source.mixer.MixerManager; import source.mixer.MixerManager;
import source.tuner.ettus.B100Tuner;
import source.tuner.fcd.FCDTuner; import source.tuner.fcd.FCDTuner;
import source.tuner.fcd.proV1.FCD1TunerController; import source.tuner.fcd.proV1.FCD1TunerController;
import source.tuner.fcd.proplusV2.FCD2TunerController; import source.tuner.fcd.proplusV2.FCD2TunerController;
@@ -46,28 +43,35 @@ import source.tuner.rtl.RTL2832Tuner;
import source.tuner.rtl.RTL2832TunerController; import source.tuner.rtl.RTL2832TunerController;
import source.tuner.rtl.e4k.E4KTunerController; import source.tuner.rtl.e4k.E4KTunerController;
import source.tuner.rtl.r820t.R820TTunerController; import source.tuner.rtl.r820t.R820TTunerController;
import source.tuner.usb.USBTunerDevice;
import controller.ResourceManager; import controller.ResourceManager;
import controller.channel.ProcessingChain; import controller.channel.ProcessingChain;
public class TunerManager public class TunerManager
{ {
private final static Logger mLog = private final static Logger mLog =
LoggerFactory.getLogger( TunerManager.class ); LoggerFactory.getLogger( TunerManager.class );
private static final String sLOADED = "\t[LOADED]\t";
private static final String sNOT_LOADED = "\t[NOT LOADED]\t";
private ResourceManager mResourceManager; private ResourceManager mResourceManager;
private ArrayList<Tuner> mTuners = new ArrayList<Tuner>(); private ArrayList<Tuner> mTuners = new ArrayList<Tuner>();
public TunerManager( ResourceManager resourceManager ) public TunerManager( ResourceManager resourceManager )
{ {
mResourceManager = resourceManager; mResourceManager = resourceManager;
loadTuners();
/* initialize mixers */
MixerManager.getInstance();
initTuners();
} }
/**
* Performs cleanup of USB related issues
*/
public void dispose()
{
LibUsb.exit( null );
}
/** /**
* Iterates current tuners to get a tuner channel source for the frequency * Iterates current tuners to get a tuner channel source for the frequency
* specified in the channel config's source config object * specified in the channel config's source config object
@@ -121,127 +125,103 @@ public class TunerManager
/** /**
* Loads all USB tuners and USB/Mixer tuner devices * Loads all USB tuners and USB/Mixer tuner devices
*/ */
private void loadTuners() private void initTuners()
{ {
mTuners.clear(); DeviceList deviceList = new DeviceList();
//Get list of attached USB tuner devices int result = LibUsb.init( null );
ArrayList<USBTunerDevice> devices = getUSBTunerDevices();
StringBuilder sb = new StringBuilder(); if( result != LibUsb.SUCCESS )
sb.append( "discovered and using [" + devices.size() +
"] available tuner devices\n" );
mLog.info( "inspecting [" + devices.size() + "] available usb tuner devices" );
int counter = 0;
for( USBTunerDevice device: devices )
{ {
counter++; mLog.error( "unable to initialize libusb [" +
LibUsb.errorName( result ) + "]" );
}
else
{
mLog.info( "LibUSB API Version: " + LibUsb.getApiVersion() );
mLog.info( "LibUSB Version: " + LibUsb.getVersion() );
mLog.info( "inspecting usb device [" + counter + "] tuner class: " result = LibUsb.getDeviceList( null, deviceList );
+ device.getTunerClass().toString() );
String status = sNOT_LOADED; if( result < 0 )
String name = "Unknown"; {
String reason = "No device driver class available"; mLog.error( "unable to get device list from libusb [" + result + " / " +
LibUsb.errorName( result ) + "]" );
}
else
{
mLog.info( "discovered [" + result + "] attached USB devices" );
}
}
TunerClass tunerClass = device.getTunerClass(); for( Device device: deviceList )
{
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor( device, descriptor );
if( result != LibUsb.SUCCESS )
{
mLog.error( "unable to read device descriptor [" +
LibUsb.errorName( result ) + "]" );
}
else
{
TunerInitStatus status = initTuner( device, descriptor );
StringBuilder sb = new StringBuilder();
sb.append( "usb device [" );
sb.append( String.format( "%04X", descriptor.idVendor() ) );
sb.append( ":" );
sb.append( String.format( "%04X", descriptor.idProduct() ) );
if( status.isLoaded() )
{
Tuner tuner = status.getTuner();
sb.append( "] LOADED: " );
sb.append( tuner.toString() );
mTuners.add( tuner );
}
else
{
sb.append( "] NOT LOADED: " );
sb.append( status.getInfo() );
}
mLog.info( sb.toString() );
}
}
LibUsb.freeDeviceList( deviceList, true );
}
private TunerInitStatus initTuner( Device device,
DeviceDescriptor descriptor )
{
if( device != null && descriptor != null )
{
TunerClass tunerClass = TunerClass.valueOf( descriptor.idVendor(),
descriptor.idProduct() );
switch( tunerClass ) switch( tunerClass )
{ {
case ETTUS_USRP_B100:
return initEttusB100Tuner( device, descriptor );
case FUNCUBE_DONGLE_PRO: case FUNCUBE_DONGLE_PRO:
//Locate the matching mixer tuner dataline return initFuncubeProTuner( device, descriptor );
MixerTunerDataLine fcd1Dataline =
getMixerTunerDataLine( tunerClass.getTunerType() );
if( fcd1Dataline != null )
{
FCD1TunerController fcd1Controller;
try
{
fcd1Controller = new FCD1TunerController( device );
FCDTuner fcd1Tuner =
new FCDTuner( fcd1Dataline, fcd1Controller );
TunerConfiguration config =
getTunerConfiguration( fcd1Tuner );
if( config != null )
{
fcd1Tuner.apply( config );
}
mTuners.add( fcd1Tuner );
name = fcd1Tuner.getName();
status = sLOADED;
reason = null;
}
catch ( SourceException e )
{
reason = "Controller Source Exception: " +
e.getLocalizedMessage();
}
}
else
{
reason = "Couldn't locate matching mixer/sound card device";
}
break;
case FUNCUBE_DONGLE_PRO_PLUS: case FUNCUBE_DONGLE_PRO_PLUS:
//Locate the matching mixer tuner dataline return initFuncubeProPlusTuner( device, descriptor );
MixerTunerDataLine fcd2Dataline = case HACKRF_ONE:
getMixerTunerDataLine( tunerClass.getTunerType() ); return initHackRFTuner( device, descriptor );
if( fcd2Dataline != null )
{
FCD2TunerController fcd2Controller;
try
{
fcd2Controller = new FCD2TunerController( device );
FCDTuner fcd2Tuner =
new FCDTuner( fcd2Dataline, fcd2Controller );
TunerConfiguration config =
getTunerConfiguration( fcd2Tuner );
if( config != null )
{
fcd2Tuner.apply( config );
}
mTuners.add( fcd2Tuner );
status = sLOADED;
name = fcd2Tuner.getName();
reason = null;
}
catch ( SourceException e )
{
reason = "Controller Source Exception: " +
e.getLocalizedMessage();
}
}
else
{
reason = "Couldn't locate matching mixer/sound card device";
}
break;
case GENERIC_2832:
case COMPRO_VIDEOMATE_U620F: case COMPRO_VIDEOMATE_U620F:
case COMPRO_VIDEOMATE_U650F: case COMPRO_VIDEOMATE_U650F:
case COMPRO_VIDEOMATE_U680F: case COMPRO_VIDEOMATE_U680F:
case GENERIC_2832:
case GENERIC_2838:
case DEXATEK_5217_DVBT: case DEXATEK_5217_DVBT:
case DEXATEK_DIGIVOX_MINI_II_REV3: case DEXATEK_DIGIVOX_MINI_II_REV3:
case DEXATEK_LOGILINK_VG002A: case DEXATEK_LOGILINK_VG002A:
case GENERIC_2838:
case GIGABYTE_GTU7300: case GIGABYTE_GTU7300:
case GTEK_T803: case GTEK_T803:
case LIFEVIEW_LV5T_DELUXE: case LIFEVIEW_LV5T_DELUXE:
@@ -259,254 +239,333 @@ public class TunerManager
case TERRATEC_T_STICK_PLUS: case TERRATEC_T_STICK_PLUS:
case TWINTECH_UT40: case TWINTECH_UT40:
case ZAAPA_ZTMINDVBZP: case ZAAPA_ZTMINDVBZP:
TunerType tunerType = tunerClass.getTunerType(); return initRTL2832Tuner( tunerClass, device, descriptor );
if( tunerType == TunerType.RTL2832_VARIOUS )
{
tunerType = RTL2832TunerController.identifyTunerType( device );
}
mLog.debug( "identified tuner class [" +
tunerClass.toString() + "] with tuner type [" +
tunerType.toString() + "]" );
switch( tunerType )
{
case ELONICS_E4000:
try
{
E4KTunerController controller =
new E4KTunerController( device );
controller.init();
RTL2832Tuner rtlTuner =
new RTL2832Tuner( tunerClass, controller );
TunerConfiguration config =
getTunerConfiguration( rtlTuner );
if( config != null )
{
rtlTuner.apply( config );
}
mTuners.add( rtlTuner );
status = sLOADED;
name = rtlTuner.getName();
reason = null;
}
catch( SourceException se )
{
status = sNOT_LOADED;
reason = "Error constructing E4K tuner "
+ "controller - " + se.getLocalizedMessage();
}
break;
case RAFAELMICRO_R820T:
mLog.debug( "attempting to construct R820T "
+ "tuner controller" );
try
{
R820TTunerController controller =
new R820TTunerController( device );
mLog.debug( "initializing R820T tuner controller" );
controller.init();
RTL2832Tuner rtlTuner =
new RTL2832Tuner( tunerClass, controller );
TunerConfiguration config =
getTunerConfiguration( rtlTuner );
if( config != null )
{
mLog.debug( "applying tuner config to R820T tuner" );
rtlTuner.apply( config );
}
else
{
mLog.debug( "R820T tuner config was "
+ "null - not applied" );
}
mTuners.add( rtlTuner );
status = sLOADED;
name = rtlTuner.getName();
reason = null;
}
catch( SourceException se )
{
status = sNOT_LOADED;
reason = "Error constructing R820T tuner "
+ "controller - " + se.getLocalizedMessage();
mLog.error( "error constructing tuner", se );
}
break;
case FITIPOWER_FC0012:
case FITIPOWER_FC0013:
case RAFAELMICRO_R828D:
case UNKNOWN:
default:
status = sNOT_LOADED;
reason = "SDRTRunk doesn't currently support RTL2832 "
+ "Dongle with [" + tunerType.toString() +
"] tuner for tuner class[" + tunerClass.toString() + "]";
break;
}
break;
case ETTUS_USRP_B100:
mTuners.add( new B100Tuner( device ) );
status = sLOADED;
reason = null;
break;
case HACKRF_ONE:
// try
// {
// HackRFTunerController hackRFController =
// new HackRFTunerController( device );
//
// hackRFController.init();
//
// HackRFTuner hackRFTuner =
// new HackRFTuner( hackRFController );
//
// mTuners.add( hackRFTuner );
// name = hackRFTuner.getName();
// status = sLOADED;
// reason = null;
// }
// catch( SourceException se )
// {
// status = sNOT_LOADED;
// reason = "Error constructing HackRF tuner "
// + "controller - " + se.getLocalizedMessage();
// }
break;
case UNKNOWN: case UNKNOWN:
default: default:
break; break;
} }
/**
* Log the tuner loading status
*/
sb.append( status );
sb.append( String.format( "%04X",
device.getDevice().getUsbDeviceDescriptor().idVendor() ) );
sb.append( ":" );
sb.append( String.format( "%04X",
device.getDevice().getUsbDeviceDescriptor().idProduct() ) );
sb.append( " " );
sb.append( name );
if( reason != null )
{
sb.append( " - " );
sb.append( reason );
}
sb.append( "\n" );
} }
mLog.info( "Configuring USB Tuners" ); return new TunerInitStatus( null, "Unknown Device" );
mLog.info( sb.toString() );
} }
/** private TunerInitStatus initEttusB100Tuner( Device device,
* Get all USB tuner devices DeviceDescriptor descriptor )
*/
private ArrayList<USBTunerDevice> getUSBTunerDevices()
{ {
StringBuilder sb = new StringBuilder(); return new TunerInitStatus( null, "Ettus B100 tuner not currently "
+ "supported" );
List<UsbDevice> devices = getUSBDevices(); // case ETTUS_USRP_B100:
// mTuners.add( new B100Tuner( device ) );
sb.append( "discovered [" + devices.size() + // status = sLOADED;
"] attached USB devices\n" ); // reason = null;
// break;
ArrayList<USBTunerDevice> tuners = new ArrayList<USBTunerDevice>();
for (UsbDevice device : devices )
{
String status = "\t[NOT RECOGNIZED]\t";
TunerClass type = TunerClass.valueOf( device.getUsbDeviceDescriptor() );
if( type != TunerClass.UNKNOWN )
{
status = "\t[RECOGNIZED] \t";
tuners.add( new USBTunerDevice( device, type) );
}
sb.append( status );
sb.append( device.toString() );
if( type != TunerClass.UNKNOWN )
{
sb.append( " " );
sb.append( type.getVendorDescription() );
sb.append( " " );
sb.append( type.getDeviceDescription() );
}
sb.append( "\n" );
}
mLog.info( "USB Device Discovery" );
mLog.info( sb.toString() );
return tuners;
} }
/** private TunerInitStatus initFuncubeProTuner( Device device,
* Gets all USB devices from the root hub downward, recursively, or DeviceDescriptor descriptor )
* returns empty list if none are discovered {
*/ String reason = "NOT LOADED";
public static List<UsbDevice> getUSBDevices()
{
ArrayList<UsbDevice> devices = new ArrayList<UsbDevice>();
try MixerTunerDataLine dataline = getMixerTunerDataLine(
{ TunerClass.FUNCUBE_DONGLE_PRO.getTunerType() );
UsbServices services = UsbHostManager.getUsbServices();
devices = getUsbChildDevices( services.getRootUsbHub() );
}
catch( SecurityException e )
{
mLog.error( "security exception while getting USB devices", e );
}
catch( UsbException e )
{
mLog.error( "usb exception while getting USB devices", e );
}
return devices; if( dataline != null )
} {
FCD1TunerController controller =
new FCD1TunerController( device, descriptor );
/** try
* Get (recursively) all usb child devices below the usb hub
*/
public static ArrayList<UsbDevice> getUsbChildDevices( UsbHub hub )
{
ArrayList<UsbDevice> devices = new ArrayList<UsbDevice>();
for ( UsbDevice device : (List<UsbDevice>) hub.getAttachedUsbDevices() )
{
devices.add( device );
if ( device.isUsbHub() )
{ {
devices.addAll( getUsbChildDevices( (UsbHub)device ) ); controller.init();
}
}
return devices; FCDTuner tuner =
} new FCDTuner( dataline, controller );
TunerConfiguration config = getTunerConfiguration( tuner );
if( config != null )
{
tuner.apply( config );
}
return new TunerInitStatus( tuner, "LOADED" );
}
catch ( SourceException e )
{
mLog.error( "couldn't load funcube dongle pro tuner", e );
reason = "error during initialization - " + e.getLocalizedMessage();
}
}
else
{
reason = "couldn't find matching mixer dataline";
}
return new TunerInitStatus( null, "Funcube Dongle Pro tuner not "
+ "loaded - " + reason );
}
private TunerInitStatus initFuncubeProPlusTuner( Device device,
DeviceDescriptor descriptor )
{
String reason = "NOT LOADED";
MixerTunerDataLine dataline = getMixerTunerDataLine(
TunerClass.FUNCUBE_DONGLE_PRO_PLUS.getTunerType() );
if( dataline != null )
{
FCD2TunerController controller =
new FCD2TunerController( device, descriptor );
try
{
controller.init();
FCDTuner tuner =
new FCDTuner( dataline, controller );
TunerConfiguration config = getTunerConfiguration( tuner );
if( config != null )
{
tuner.apply( config );
}
return new TunerInitStatus( tuner, "LOADED" );
}
catch ( SourceException e )
{
mLog.error( "couldn't load funcube dongle pro plus tuner", e );
reason = "error during initialization - " +
e.getLocalizedMessage();
}
}
else
{
reason = "couldn't find matching mixer dataline";
}
return new TunerInitStatus( null, "Funcube Dongle Pro tuner not "
+ "loaded - " + reason );
}
private TunerInitStatus initHackRFTuner( Device device,
DeviceDescriptor descriptor )
{
try
{
HackRFTunerController hackRFController =
new HackRFTunerController( device, descriptor );
hackRFController.init();
HackRFTuner tuner = new HackRFTuner( hackRFController );
return new TunerInitStatus( tuner, "LOADED" );
}
catch( SourceException se )
{
mLog.error( "couldn't construct HackRF controller/tuner", se );
return new TunerInitStatus( null,
"error constructing HackRF tuner controller" );
}
}
private TunerInitStatus initRTL2832Tuner( TunerClass tunerClass,
Device device,
DeviceDescriptor deviceDescriptor )
{
String reason = "NOT LOADED";
TunerType tunerType = tunerClass.getTunerType();
if( tunerType == TunerType.RTL2832_VARIOUS )
{
try
{
tunerType = RTL2832TunerController.identifyTunerType( device );
}
catch( SourceException e )
{
mLog.error( "couldn't determine RTL2832 tuner type", e );
tunerType = TunerType.UNKNOWN;
}
}
switch( tunerType )
{
case ELONICS_E4000:
try
{
E4KTunerController controller =
new E4KTunerController( device, deviceDescriptor );
controller.init();
RTL2832Tuner rtlTuner =
new RTL2832Tuner( tunerClass, controller );
TunerConfiguration config =
getTunerConfiguration( rtlTuner );
if( config != null )
{
rtlTuner.apply( config );
}
return new TunerInitStatus( rtlTuner, "LOADED" );
}
catch( SourceException se )
{
return new TunerInitStatus( null, "Error constructing E4K tuner "
+ "controller - " + se.getLocalizedMessage() );
}
case RAFAELMICRO_R820T:
mLog.debug( "attempting to construct R820T "
+ "tuner controller" );
try
{
R820TTunerController controller =
new R820TTunerController( device, deviceDescriptor );
mLog.debug( "initializing R820T tuner controller" );
controller.init();
RTL2832Tuner rtlTuner =
new RTL2832Tuner( tunerClass, controller );
TunerConfiguration config =
getTunerConfiguration( rtlTuner );
if( config != null )
{
mLog.debug( "applying tuner config to R820T tuner" );
rtlTuner.apply( config );
}
else
{
mLog.debug( "R820T tuner config was "
+ "null - not applied" );
}
return new TunerInitStatus( rtlTuner, "LOADED" );
}
catch( SourceException se )
{
mLog.error( "error constructing tuner", se );
return new TunerInitStatus( null, "Error constructing R820T "
+ "tuner controller - " + se.getLocalizedMessage() );
}
case FITIPOWER_FC0012:
case FITIPOWER_FC0013:
case RAFAELMICRO_R828D:
case UNKNOWN:
default:
reason = "SDRTRunk doesn't currently support RTL2832 "
+ "Dongle with [" + tunerType.toString() +
"] tuner for tuner class[" + tunerClass.toString() + "]";
break;
}
return new TunerInitStatus( null, reason );
}
// /**
// * Get all USB tuner devices
// */
// private ArrayList<USBTunerDevice> getUSBTunerDevices()
// {
// StringBuilder sb = new StringBuilder();
//
// List<UsbDevice> devices = getUSBDevices();
//
// sb.append( "discovered [" + devices.size() +
// "] attached USB devices\n" );
//
// ArrayList<USBTunerDevice> tuners = new ArrayList<USBTunerDevice>();
//
// for (UsbDevice device : devices )
// {
// String status = "\t[NOT RECOGNIZED]\t";
//
// TunerClass type = TunerClass.valueOf( device.getUsbDeviceDescriptor() );
//
// if( type != TunerClass.UNKNOWN )
// {
// status = "\t[RECOGNIZED] \t";
// tuners.add( new USBTunerDevice( device, type) );
// }
//
// sb.append( status );
// sb.append( device.toString() );
//
// if( type != TunerClass.UNKNOWN )
// {
// sb.append( " " );
// sb.append( type.getVendorDescription() );
// sb.append( " " );
// sb.append( type.getDeviceDescription() );
// }
//
// sb.append( "\n" );
// }
//
// mLog.info( "USB Device Discovery" );
// mLog.info( sb.toString() );
//
// return tuners;
// }
//
// /**
// * Gets all USB devices from the root hub downward, recursively, or
// * returns empty list if none are discovered
// */
// public static List<UsbDevice> getUSBDevices()
// {
// ArrayList<UsbDevice> devices = new ArrayList<UsbDevice>();
//
// try
// {
// UsbServices services = UsbHostManager.getUsbServices();
// devices = getUsbChildDevices( services.getRootUsbHub() );
// }
// catch( SecurityException e )
// {
// mLog.error( "security exception while getting USB devices", e );
// }
// catch( UsbException e )
// {
// mLog.error( "usb exception while getting USB devices", e );
// }
//
// return devices;
// }
//
// /**
// * Get (recursively) all usb child devices below the usb hub
// */
// public static ArrayList<UsbDevice> getUsbChildDevices( UsbHub hub )
// {
// ArrayList<UsbDevice> devices = new ArrayList<UsbDevice>();
//
// for ( UsbDevice device : (List<UsbDevice>) hub.getAttachedUsbDevices() )
// {
// devices.add( device );
//
// if ( device.isUsbHub() )
// {
// devices.addAll( getUsbChildDevices( (UsbHub)device ) );
// }
// }
//
// return devices;
// }
/** /**
* Get a stored tuner configuration or create a default tuner configuration * Get a stored tuner configuration or create a default tuner configuration
@@ -585,4 +644,31 @@ public class TunerManager
return null; return null;
} }
public class TunerInitStatus
{
private Tuner mTuner;
private String mInfo;
public TunerInitStatus( Tuner tuner, String info )
{
mTuner = tuner;
mInfo = info;
}
public Tuner getTuner()
{
return mTuner;
}
public String getInfo()
{
return mInfo;
}
public boolean isLoaded()
{
return mTuner != null;
}
}
} }

View File

@@ -51,6 +51,11 @@ public class B100Tuner extends Tuner
mDevice = device; mDevice = device;
} }
public void dispose()
{
}
@Override @Override
public TunerClass getTunerClass() public TunerClass getTunerClass()
{ {

View File

@@ -50,6 +50,13 @@ public class FCDTuner extends MixerTuner
mController.addListener( (FrequencyChangeListener)this ); mController.addListener( (FrequencyChangeListener)this );
} }
public void dispose()
{
//TODO: release the mixer tuner data line as well
mController.dispose();
}
public FCDTunerController getController() public FCDTunerController getController()
{ {
return mController; return mController;
@@ -70,7 +77,7 @@ public class FCDTuner extends MixerTuner
@Override @Override
public String getUniqueID() public String getUniqueID()
{ {
return mController.getAddress(); return mController.getUSBAddress();
} }
@Override @Override

View File

@@ -17,18 +17,21 @@
******************************************************************************/ ******************************************************************************/
package source.tuner.fcd; package source.tuner.fcd;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.usb.UsbClaimException; import javax.usb.UsbClaimException;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbEndpoint;
import javax.usb.UsbException; import javax.usb.UsbException;
import javax.usb.UsbInterface;
import javax.usb.UsbInterfacePolicy;
import javax.usb.UsbPipe;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import source.SourceException; import source.SourceException;
import source.tuner.TunerClass; import source.tuner.TunerClass;
@@ -36,7 +39,6 @@ import source.tuner.TunerConfiguration;
import source.tuner.TunerController; import source.tuner.TunerController;
import source.tuner.TunerType; import source.tuner.TunerType;
import source.tuner.fcd.proV1.FCD1TunerController.Block; import source.tuner.fcd.proV1.FCD1TunerController.Block;
import source.tuner.usb.USBTunerDevice;
import controller.ResourceManager; import controller.ResourceManager;
public abstract class FCDTunerController extends TunerController public abstract class FCDTunerController extends TunerController
@@ -44,57 +46,105 @@ public abstract class FCDTunerController extends TunerController
private final static Logger mLog = private final static Logger mLog =
LoggerFactory.getLogger( FCDTunerController.class ); LoggerFactory.getLogger( FCDTunerController.class );
public final static int sINT_NULL_VALUE = -1; public final static byte FCD_INTERFACE = (byte)0x2;
public final static long sLONG_NULL_VALUE = -1l; public final static byte FCD_ENDPOINT_IN = (byte)0x82;
public final static double sDOUBLE_NULL_VALUE = -1.0D; public final static byte FCD_ENDPOINT_OUT = (byte)0x2;
public final static byte sFCD_INTERFACE = (byte)0x2; private Device mDevice;
public final static byte sFCD_ENDPOINT_IN = (byte)0x82; private DeviceDescriptor mDeviceDescriptor;
public final static byte sFCD_ENDPOINT_OUT = (byte)0x2; private DeviceHandle mDeviceHandle;
public final static boolean sFCD_FORCE_CLAIM_HID_INTERFACE = true;
private UsbDevice mFuncube;
private UsbConfiguration mUsbConfiguration;
private UsbInterface mFuncubeHID;
private UsbPipe mPipeIn;
private UsbPipe mPipeOut;
private FCDConfiguration mConfiguration = new FCDConfiguration(); private FCDConfiguration mConfiguration = new FCDConfiguration();
public FCDTunerController( USBTunerDevice device, /**
* Generic FCD tuner controller - contains functionality common across both
* funcube dongle tuners
*
* @param device
* @param descriptor
* @param minTunableFrequency
* @param maxTunableFrequency
*/
public FCDTunerController( Device device,
DeviceDescriptor descriptor,
int minTunableFrequency, int minTunableFrequency,
int maxTunableFrequency ) throws SourceException int maxTunableFrequency )
{ {
super( minTunableFrequency, maxTunableFrequency ); super( minTunableFrequency, maxTunableFrequency );
mFuncube = device.getDevice(); mDevice = device;
mUsbConfiguration = mFuncube.getActiveUsbConfiguration(); mDeviceDescriptor = descriptor;
mFuncubeHID = mUsbConfiguration.getUsbInterface( sFCD_INTERFACE );
} }
/**
* Initializes the controller by opening the USB device and claiming the
* HID interface.
*
* Invoke this method after constructing this class to setup the
* controller.
*
* @throws SourceException if cannot open and claim the USB device
*/
public void init() throws SourceException
{
mDeviceHandle = new DeviceHandle();
int result = LibUsb.open( mDevice, mDeviceHandle );
if( result != LibUsb.SUCCESS )
{
mDeviceHandle = null;
throw new SourceException( "libusb couldn't open funcube usb "
+ "device [" + LibUsb.errorName( result ) + "]" );
}
claimInterface();
}
/**
* Disposes of resources. Closes the USB device and interface.
*/
public void dispose()
{
if( mDeviceHandle != null )
{
try
{
LibUsb.close( mDeviceHandle );
}
catch( Exception e )
{
mLog.error( "error while closing device handle", e );
}
mDeviceHandle = null;
}
mDeviceDescriptor = null;
mDevice = null;
}
/**
* Sample rate of the tuner
*/
public abstract int getCurrentSampleRate() throws SourceException; public abstract int getCurrentSampleRate() throws SourceException;
/** /**
* Returns the tuner class. Since this is a generic container for both * Tuner class
* types of funcube, we let the controller self identify the class and type
*
* @return - tuner class
*/ */
public abstract TunerClass getTunerClass(); public abstract TunerClass getTunerClass();
/** /**
* Returns the tuner type. Since this is a generic container for both * Tuner type
* types of funcube, we let the controller self identify the class and type
*
* @return - tuner type
*/ */
public abstract TunerType getTunerType(); public abstract TunerType getTunerType();
/** /**
* FCD editor panel * Editor panel (GUI) component.
*/ */
public abstract JPanel getEditor( FCDTuner tuner, public abstract JPanel getEditor( FCDTuner tuner,
ResourceManager resourceManager ); ResourceManager resourceManager );
/** /**
* Applies the settings in the tuner configuration * Applies the settings in the tuner configuration
@@ -103,17 +153,81 @@ public abstract class FCDTunerController extends TunerController
throws SourceException; throws SourceException;
/** /**
* Returns the applied tuner configuration or null if one hasn't yet been * Returns the currently applied tuner configuration or null if one hasn't
* applied * yet been applied
*/ */
public abstract TunerConfiguration getTunerConfiguration(); public abstract TunerConfiguration getTunerConfiguration();
/** /**
* USB address * USB address (bus/port)
*/ */
public String getAddress() public String getUSBAddress()
{ {
return mFuncube.toString(); if( mDevice != null )
{
StringBuilder sb = new StringBuilder();
sb.append( "Bus:" );
int bus = LibUsb.getBusNumber( mDevice );
sb.append( bus );
sb.append( " Port:" );
int port = LibUsb.getPortNumber( mDevice );
sb.append( port );
return sb.toString();
}
return "UNKNOWN";
}
/**
* USB Vendor and Product ID
*/
public String getUSBID()
{
if( mDeviceDescriptor != null )
{
StringBuilder sb = new StringBuilder();
sb.append( String.format( "%04X",
(int)( mDeviceDescriptor.idVendor() & 0xFFFF ) ) );
sb.append( ":" );
sb.append( String.format( "%04X",
(int)( mDeviceDescriptor.idProduct() & 0xFFFF ) ) );
return sb.toString();
}
return "UNKNOWN";
}
/**
* USB Port Speed. Should be 2.0 for both types of funcube dongles
*/
public String getUSBSpeed()
{
if( mDevice != null )
{
int speed = LibUsb.getDeviceSpeed( mDevice );
switch( speed )
{
case 0:
return "1.1 LOW";
case 1:
return "1.1 FULL";
case 2:
return "2.0 HIGH";
case 3:
return "3.0 SUPER";
default:
}
}
return "UNKNOWN";
} }
/** /**
@@ -121,20 +235,17 @@ public abstract class FCDTunerController extends TunerController
*/ */
public void setFCDMode( Mode mode ) throws UsbException, UsbClaimException public void setFCDMode( Mode mode ) throws UsbException, UsbClaimException
{ {
byte[] response = null; ByteBuffer response = null;
switch( mode ) switch( mode )
{ {
case APPLICATION: case APPLICATION:
response = send( FCDCommand.BL_QUERY.getRequestTemplate(), response = send( FCDCommand.BL_QUERY );
FCDCommand.BL_QUERY.getResponseTemplate() );
break; break;
case BOOTLOADER: case BOOTLOADER:
response = send( FCDCommand.APP_RESET.getRequestTemplate(), response = send( FCDCommand.APP_RESET );
FCDCommand.APP_RESET.getResponseTemplate() );
break; break;
case ERROR: default:
case UNKNOWN:
break; break;
} }
@@ -171,7 +282,11 @@ public abstract class FCDTunerController extends TunerController
{ {
try try
{ {
return send( FCDCommand.APP_GET_FREQUENCY_HZ ); ByteBuffer buffer = send( FCDCommand.APP_GET_FREQUENCY_HZ );
buffer.order( ByteOrder.LITTLE_ENDIAN );
return (int)( buffer.getInt( 2 ) & 0xFFFFFFFF );
} }
catch( Exception e ) catch( Exception e )
{ {
@@ -189,185 +304,206 @@ public abstract class FCDTunerController extends TunerController
} }
/** /**
* Claims the FCD USB HID interface. If another application currently has * Claims the USB interface. Attempts to detach the active kernel driver if
* the interface claimed, the sFCD_FORCE_CLAIM_HID_INTERFACE setting * one is currently attached.
* will dictate if the interface is forcibly claimed from the other
* application
*/ */
private boolean claim() throws UsbException, UsbClaimException private void claimInterface() throws SourceException
{ {
boolean claimed = false; if( mDeviceHandle != null )
if( !mFuncubeHID.isClaimed() )
{ {
mFuncubeHID.claim( new UsbInterfacePolicy() int result = LibUsb.kernelDriverActive( mDeviceHandle, FCD_INTERFACE );
if( result == 1 )
{ {
@Override result = LibUsb.detachKernelDriver( mDeviceHandle,
public boolean forceClaim( UsbInterface arg0 ) FCD_INTERFACE );
{
return sFCD_FORCE_CLAIM_HID_INTERFACE;
}
} );
claimed = true; if( result != LibUsb.SUCCESS )
} {
else mLog.error( "failed attempt to detach kernel driver [" +
{ LibUsb.errorName( result ) + "]" );
mLog.info( "Attempted to claim the Funcube HID interface, but " }
+ "it's in use by another program" );
}
return claimed;
}
/**
* Releases the claimed USB (FCD) interface
*/
private void release()
{
mPipeIn = null;
mPipeOut = null;
try
{
mFuncubeHID.release();
}
catch ( Exception e )
{
mLog.error( "Exception thrown while releasing the funcube HID "
+ "interface", e );
}
}
/**
* Convenience wrapper for commands that don't take arguments
*/
public long send( FCDCommand command ) throws UsbException, UsbClaimException
{
return send( command, sLONG_NULL_VALUE );
}
/**
* Sends the command, optionally placing the argument value parsed into
* little endian bytes in the request array. Returns any integer value that
* part of the response, or sINT_NULL_VALUE (-1) if it fails.
*
* Note: we use a long return value to avoid any issues with the MSB of a
* 32-bit response value being misinterpreted as the integer sign bit.
*
* @param command
* @param commandArgument - command argument. Use -1 for no-argument commands
* @return - response long value, or -1 if fails
* @throws UsbException
* @throws UsbClaimException
*/
public long send( FCDCommand command, long commandArgument ) throws UsbException,
UsbClaimException
{
long retVal = sLONG_NULL_VALUE;
byte[] request = command.getRequestTemplate();
if( commandArgument != sLONG_NULL_VALUE )
{
//Parse the value argument into the request byte indices, according to command length
for( int x = 1; x < command.getArrayLength(); x++ )
{
//Little endian
request[ x ] = (byte)( 0xFF &
Long.rotateRight( commandArgument, ( x - 1 ) * 8 ) );
} }
}
byte[] response = send( request, command.getResponseTemplate() ); result = LibUsb.claimInterface( mDeviceHandle, FCD_INTERFACE );
if( response != null ) if( result != LibUsb.SUCCESS )
{
retVal = parseResponse( command, response );
}
return retVal;
}
/**
* Sends the request byte array to the device and returns the response array
* filled with the response bytes from the device, or returns null if
* something failed along the way
*/
private byte[] send( byte[] request, byte[] response )
throws UsbException, UsbClaimException
{
byte[] retVal = null;
if( mPipeIn != null && mPipeOut != null )
{
mPipeOut.syncSubmit( request );
mPipeIn.syncSubmit( response );
retVal = response;
}
return retVal;
}
/**
* Parses a multi-byte integer response value from a byte array that is
* 2 or more bytes long
*/
private long parseResponse( FCDCommand command, byte[] response )
{
long retVal = 0;
//Parse the value argument into the request byte indices, according to command length
for( int x = 2; x < command.getArrayLength(); x++ )
{
retVal += Long.rotateLeft( ( response[ x ] & 0xFF ), ( x - 2 ) * 8 );
}
return retVal;
}
protected void open() throws UsbException, UsbClaimException
{
if( claim() )
{
//Get the USB endpoints
UsbEndpoint endpointIn =
mFuncubeHID.getUsbEndpoint( sFCD_ENDPOINT_IN );
UsbEndpoint endpointOut =
mFuncubeHID.getUsbEndpoint( sFCD_ENDPOINT_OUT );
//Setup the pipes
if( endpointIn != null && endpointOut != null )
{ {
mPipeOut = endpointOut.getUsbPipe(); throw new SourceException( "couldn't claim usb interface [" +
mPipeOut.open(); LibUsb.errorName( result ) + "]" );
mPipeIn = endpointIn.getUsbPipe();
mPipeIn.open();
setFCDMode( Mode.APPLICATION );
}
else
{
mLog.error( "FCD Pro Tuner Controller - couldn't gain access " +
"to the USB in/out endpoints or pipes." );
} }
} }
else else
{ {
mLog.error( "FCD Pro Tuner Controller - couldn't claim the USB " + throw new SourceException( "couldn't claim usb hid interface - no "
"interface. Check to see if another program is using it." ); + "device handle" );
} }
} }
protected void close() /**
* Performs an interrupt write to the OUT endpoint.
* @param buffer - direct allocated buffer. Must be 64 bytes in length.
*
* @throws LibUsbException on error
*/
private void write( ByteBuffer buffer ) throws LibUsbException
{ {
release(); if( mDeviceHandle != null )
{
IntBuffer transferred = IntBuffer.allocate( 1 );
int result = LibUsb.interruptTransfer( mDeviceHandle,
FCD_ENDPOINT_OUT,
buffer,
transferred,
500l );
if( result != LibUsb.SUCCESS )
{
throw new LibUsbException( "error writing byte buffer",
result );
}
else if( transferred.get() != buffer.capacity() )
{
throw new LibUsbException( "transferred bytes [" +
transferred.get( 0 ) + "] is not what was expected [" +
buffer.capacity() + "]", result );
}
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
} }
/**
* Performs an interrupt write to the OUT endpoint for the FCD command.
* @param command - no-argument command to write
* @throws LibUsbException - on error
*/
private void write( FCDCommand command ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 64 );
buffer.put( 0, command.getCommand() );
buffer.put( 1, (byte)0x00 );
write( buffer );
}
/**
* Convenience logger for debugging read/write operations
*/
@SuppressWarnings( "unused" )
private void log( String label, ByteBuffer buffer )
{
StringBuilder sb = new StringBuilder();
sb.append( label );
sb.append( " " );
sb.append( buffer.get( 0 ) );
sb.append( " | " );
for( int x = 0; x < 64; x++ )
{
sb.append( String.format( "%02X", (int)( buffer.get( x ) & 0xFF ) ) );
sb.append( " " );
}
mLog.debug( sb.toString() );
}
/**
* Performs an interrupt write to the OUT endpoint for the FCD command.
* @param command - command to write
* @param argument - value to write with the command
* @throws LibUsbException - on error
*/
private void write( FCDCommand command, long argument ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 64 );
/* The FCD expects little-endian formatted values */
buffer.order( ByteOrder.LITTLE_ENDIAN );
buffer.put( 0, command.getCommand() );
buffer.putLong( 1, argument );
write( buffer );
}
/**
* Performs an interrupt read against the endpoint
* @return buffer read from FCD
* @throws LibUsbException on error
*/
private ByteBuffer read() throws LibUsbException
{
if( mDeviceHandle != null )
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 64 );
IntBuffer transferred = IntBuffer.allocate( 1 );
int result = LibUsb.interruptTransfer( mDeviceHandle,
FCD_ENDPOINT_IN,
buffer,
transferred,
500l );
if( result != LibUsb.SUCCESS )
{
throw new LibUsbException( "error reading byte buffer",
result );
}
else if( transferred.get( 0 ) != buffer.capacity() )
{
throw new LibUsbException( "received bytes [" +
transferred.get( 0 ) + "] didn't match expected "
+ "length [" + buffer.capacity() + "]", result );
}
return buffer;
}
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
/**
* Sends the FCD command and argument. Performs a read to complete the
* command.
*
* @param command - command to send
* @param argument - command argument to send
* @throws LibUsbException - on error
*/
protected void send( FCDCommand command, long argument ) throws LibUsbException
{
write( command, argument );
read();
}
/**
* Sends the no-argument FCD command. Performs a read to complete the
* command.
*
* @param command - command to send
* @throws LibUsbException - on error
*/
protected ByteBuffer send( FCDCommand command ) throws LibUsbException
{
write( command );
return read();
}
/**
* FCD configuration string parsing class
*/
public class FCDConfiguration public class FCDConfiguration
{ {
private String mConfig; private String mConfig;
@@ -385,11 +521,20 @@ public abstract class FCDTunerController extends TunerController
mMode = Mode.UNKNOWN; mMode = Mode.UNKNOWN;
} }
public void set( byte[] data ) /**
* Extracts the configuration string from the buffer
*/
public void set( ByteBuffer buffer )
{ {
if( FCDCommand.checkResponse( FCDCommand.BL_QUERY, data ) || if( buffer.capacity() == 64 )
FCDCommand.checkResponse( FCDCommand.APP_RESET, data ) )
{ {
byte[] data = new byte[ 64 ];
for( int x = 0; x < 64; x++ )
{
data[ x ] = buffer.get( x );
}
mConfig = new String( data ); mConfig = new String( data );
mMode = Mode.getMode( mConfig ); mMode = Mode.getMode( mConfig );
} }

View File

@@ -17,26 +17,27 @@
******************************************************************************/ ******************************************************************************/
package source.tuner.fcd; package source.tuner.fcd;
import javax.swing.BorderFactory;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JPanel; import javax.swing.JPanel;
import source.tuner.rtl.RTL2832TunerController.Descriptor;
import net.miginfocom.swing.MigLayout; import net.miginfocom.swing.MigLayout;
public class FCDTunerDetailsPanel extends JPanel public class FCDTunerDetailsPanel extends JPanel
{ {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private JLabel mAddress;
private JLabel mCellBlock;
private JLabel mFirmware;
public FCDTunerDetailsPanel( FCDTunerController controller ) public FCDTunerDetailsPanel( FCDTunerController controller )
{ {
setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][grow]" ) ); setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][][][grow]" ) );
add( new JLabel( "USB ID:" ) );
add( new JLabel( controller.getUSBID() ) );
add( new JLabel( "USB Address:" ) ); add( new JLabel( "USB Address:" ) );
add( new JLabel( controller.getAddress() ) ); add( new JLabel( controller.getUSBAddress() ) );
add( new JLabel( "USB Speed:" ) );
add( new JLabel( controller.getUSBSpeed() ) );
add( new JLabel( "Cellular Band:" ) ); add( new JLabel( "Cellular Band:" ) );
add( new JLabel( controller.getConfiguration().getBandBlocking() add( new JLabel( controller.getConfiguration().getBandBlocking()

View File

@@ -511,7 +511,7 @@ public class FCD1TunerConfigurationPanel extends JPanel
mResourceManager.getSettingsManager() mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration( .setSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO, TunerType.FUNCUBE_DONGLE_PRO,
mController.getAddress(), config ); mController.getUSBAddress(), config );
} }
catch ( SourceException e1 ) catch ( SourceException e1 )
{ {

View File

@@ -17,12 +17,17 @@
******************************************************************************/ ******************************************************************************/
package source.tuner.fcd.proV1; package source.tuner.fcd.proV1;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.usb.UsbClaimException; import javax.usb.UsbClaimException;
import javax.usb.UsbException; import javax.usb.UsbException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import source.SourceException; import source.SourceException;
import source.tuner.TunerClass; import source.tuner.TunerClass;
@@ -31,7 +36,6 @@ import source.tuner.TunerType;
import source.tuner.fcd.FCDCommand; import source.tuner.fcd.FCDCommand;
import source.tuner.fcd.FCDTuner; import source.tuner.fcd.FCDTuner;
import source.tuner.fcd.FCDTunerController; import source.tuner.fcd.FCDTunerController;
import source.tuner.usb.USBTunerDevice;
import controller.ResourceManager; import controller.ResourceManager;
public class FCD1TunerController extends FCDTunerController public class FCD1TunerController extends FCDTunerController
@@ -53,19 +57,22 @@ public class FCD1TunerController extends FCDTunerController
private FCD1TunerConfiguration mTunerConfiguration; private FCD1TunerConfiguration mTunerConfiguration;
private FCD1TunerEditorPanel mEditor; private FCD1TunerEditorPanel mEditor;
public FCD1TunerController( USBTunerDevice device ) public FCD1TunerController( Device device, DeviceDescriptor descriptor )
throws SourceException
{ {
super( device, super( device,
descriptor,
sMINIMUM_TUNABLE_FREQUENCY, sMINIMUM_TUNABLE_FREQUENCY,
sMAXIMUM_TUNABLE_FREQUENCY ); sMAXIMUM_TUNABLE_FREQUENCY );
}
public void init() throws SourceException
{
super.init();
mFrequencyController.setSampleRate( sSAMPLE_RATE ); mFrequencyController.setSampleRate( sSAMPLE_RATE );
try try
{ {
open();
setFCDMode( Mode.APPLICATION ); setFCDMode( Mode.APPLICATION );
getPhaseAndGainCorrection(); getPhaseAndGainCorrection();
getDCIQCorrection(); getDCIQCorrection();
@@ -73,7 +80,7 @@ public class FCD1TunerController extends FCDTunerController
getLNAEnhanceSetting(); getLNAEnhanceSetting();
getMixerGainSetting(); getMixerGainSetting();
send( FCDCommand.APP_SET_MIXER_GAIN, 1 ); send( FCDCommand.APP_SET_MIXER_GAIN, 1l );
} }
catch( Exception e ) catch( Exception e )
{ {
@@ -156,9 +163,11 @@ public class FCD1TunerController extends FCDTunerController
*/ */
private void getLNAGainSetting() throws UsbClaimException, UsbException private void getLNAGainSetting() throws UsbClaimException, UsbException
{ {
int gain = (int)send( FCDCommand.APP_GET_LNA_GAIN ); ByteBuffer buffer = send( FCDCommand.APP_GET_LNA_GAIN );
mLog.info( "FCD1: lna gain setting is:" + gain ); buffer.order( ByteOrder.LITTLE_ENDIAN );
int gain = buffer.getInt( 2 );
mLNAGain = LNAGain.valueOf( gain ); mLNAGain = LNAGain.valueOf( gain );
} }
@@ -286,7 +295,11 @@ public class FCD1TunerController extends FCDTunerController
private void getPhaseAndGainCorrection() throws UsbClaimException, private void getPhaseAndGainCorrection() throws UsbClaimException,
UsbException UsbException
{ {
long correction = send( FCDCommand.APP_GET_IQ_CORRECTION ); ByteBuffer buffer = send( FCDCommand.APP_GET_IQ_CORRECTION );
buffer.order( ByteOrder.LITTLE_ENDIAN );
int correction = buffer.getInt( 2 );
/** /**
* Gain: mask the upper 16 phase bits and right shift to get the * Gain: mask the upper 16 phase bits and right shift to get the
@@ -305,8 +318,6 @@ public class FCD1TunerController extends FCDTunerController
short phase = (short)( correction & 0x0000FFFF ); short phase = (short)( correction & 0x0000FFFF );
mPhaseCorrection = ( (double)phase / (double)Short.MAX_VALUE ); mPhaseCorrection = ( (double)phase / (double)Short.MAX_VALUE );
mLog.info( "FCD1: correction:" + correction + " gain:" + gain + " phase:" + phase );
} }
/** /**
@@ -413,7 +424,11 @@ public class FCD1TunerController extends FCDTunerController
private void getDCIQCorrection() throws UsbClaimException, private void getDCIQCorrection() throws UsbClaimException,
UsbException UsbException
{ {
long correction = send( FCDCommand.APP_GET_DC_CORRECTION ); ByteBuffer buffer = send( FCDCommand.APP_GET_DC_CORRECTION );
buffer.order( ByteOrder.LITTLE_ENDIAN );
int correction = buffer.getInt( 2 );
/** /**
* Quadrature: mask the upper 16 bits and divide by 32768 to get the * Quadrature: mask the upper 16 bits and divide by 32768 to get the
@@ -443,9 +458,11 @@ public class FCD1TunerController extends FCDTunerController
private void getLNAEnhanceSetting() throws UsbClaimException, UsbException private void getLNAEnhanceSetting() throws UsbClaimException, UsbException
{ {
int enhance = (int)send( FCDCommand.APP_GET_LNA_ENHANCE ); ByteBuffer buffer = send( FCDCommand.APP_GET_LNA_ENHANCE );
mLog.info( "FCD1: lna enhance setting is: " + enhance ); buffer.order( ByteOrder.LITTLE_ENDIAN );
int enhance = buffer.getInt( 2 );
mLNAEnhance = LNAEnhance.valueOf( enhance ); mLNAEnhance = LNAEnhance.valueOf( enhance );
} }
@@ -463,9 +480,11 @@ public class FCD1TunerController extends FCDTunerController
private void getMixerGainSetting() throws UsbClaimException, UsbException private void getMixerGainSetting() throws UsbClaimException, UsbException
{ {
int gain = (int)send( FCDCommand.APP_GET_MIXER_GAIN ); ByteBuffer buffer = send( FCDCommand.APP_GET_MIXER_GAIN );
mLog.info( "FCD1: mixer gain setting is:" + gain ); buffer.order( ByteOrder.LITTLE_ENDIAN );
int gain = buffer.getInt( 2 );
mMixerGain = MixerGain.valueOf( gain ); mMixerGain = MixerGain.valueOf( gain );
} }

View File

@@ -221,7 +221,7 @@ public class FCD2TunerConfigurationPanel extends JPanel
TunerConfigurationAssignment savedConfig = mResourceManager TunerConfigurationAssignment savedConfig = mResourceManager
.getSettingsManager().getSelectedTunerConfiguration( .getSettingsManager().getSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS, TunerType.FUNCUBE_DONGLE_PRO_PLUS,
mController.getAddress() ); mController.getUSBAddress() );
if( savedConfig != null ) if( savedConfig != null )
{ {
@@ -237,7 +237,7 @@ public class FCD2TunerConfigurationPanel extends JPanel
mResourceManager.getSettingsManager() mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration( .setSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS, TunerType.FUNCUBE_DONGLE_PRO_PLUS,
mController.getAddress(), mSelectedConfig ); mController.getUSBAddress(), mSelectedConfig );
} }
mComboConfigurations.setSelectedItem( mSelectedConfig ); mComboConfigurations.setSelectedItem( mSelectedConfig );
@@ -324,7 +324,7 @@ public class FCD2TunerConfigurationPanel extends JPanel
mResourceManager.getSettingsManager().setSelectedTunerConfiguration( mResourceManager.getSettingsManager().setSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS, TunerType.FUNCUBE_DONGLE_PRO_PLUS,
mController.getAddress(), config ); mController.getUSBAddress(), config );
} }
catch ( SourceException e1 ) catch ( SourceException e1 )
{ {

View File

@@ -17,12 +17,15 @@
******************************************************************************/ ******************************************************************************/
package source.tuner.fcd.proplusV2; package source.tuner.fcd.proplusV2;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.usb.UsbClaimException;
import javax.usb.UsbException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import source.SourceException; import source.SourceException;
import source.tuner.TunerClass; import source.tuner.TunerClass;
@@ -31,7 +34,6 @@ import source.tuner.TunerType;
import source.tuner.fcd.FCDCommand; import source.tuner.fcd.FCDCommand;
import source.tuner.fcd.FCDTuner; import source.tuner.fcd.FCDTuner;
import source.tuner.fcd.FCDTunerController; import source.tuner.fcd.FCDTunerController;
import source.tuner.usb.USBTunerDevice;
import controller.ResourceManager; import controller.ResourceManager;
public class FCD2TunerController extends FCDTunerController public class FCD2TunerController extends FCDTunerController
@@ -46,25 +48,27 @@ public class FCD2TunerController extends FCDTunerController
private FCD2TunerConfiguration mTunerConfiguration; private FCD2TunerConfiguration mTunerConfiguration;
private FCD2TunerEditorPanel mEditor; private FCD2TunerEditorPanel mEditor;
public FCD2TunerController( USBTunerDevice device ) public FCD2TunerController( Device device, DeviceDescriptor descriptor )
throws SourceException
{ {
super( device, super( device,
descriptor,
sMINIMUM_TUNABLE_FREQUENCY, sMINIMUM_TUNABLE_FREQUENCY,
sMAXIMUM_TUNABLE_FREQUENCY ); sMAXIMUM_TUNABLE_FREQUENCY );
}
public void init() throws SourceException
{
super.init();
mFrequencyController.setSampleRate( sSAMPLE_RATE ); mFrequencyController.setSampleRate( sSAMPLE_RATE );
try try
{ {
open();
setFCDMode( Mode.APPLICATION ); setFCDMode( Mode.APPLICATION );
} }
catch( Exception e ) catch( Exception e )
{ {
throw new SourceException( "FCDTunerController error " + throw new SourceException( "error setting Mode to APPLICATION", e );
"during construction", e );
} }
} }
@@ -109,7 +113,7 @@ public class FCD2TunerController extends FCDTunerController
{ {
if( plusConfig.getGainLNA() ) if( plusConfig.getGainLNA() )
{ {
send( FCDCommand.APP_SET_LNA_GAIN, 1 ); send( FCDCommand.APP_SET_LNA_GAIN, 1 );
} }
else else
@@ -117,20 +121,16 @@ public class FCD2TunerController extends FCDTunerController
send( FCDCommand.APP_SET_LNA_GAIN, 0 ); send( FCDCommand.APP_SET_LNA_GAIN, 0 );
} }
} }
catch ( UsbClaimException e ) catch ( Exception e )
{ {
throw new SourceException( "Exception while setting LNA Gain", e ); throw new SourceException( "error while setting LNA Gain", e );
}
catch ( UsbException e )
{
throw new SourceException( "Exception while setting LNA Gain", e );
} }
try try
{ {
if( plusConfig.getGainMixer() ) if( plusConfig.getGainMixer() )
{ {
send( FCDCommand.APP_SET_MIXER_GAIN, 1 ); send( FCDCommand.APP_SET_MIXER_GAIN, 1 );
} }
else else
@@ -138,13 +138,9 @@ public class FCD2TunerController extends FCDTunerController
send( FCDCommand.APP_SET_MIXER_GAIN, 0 ); send( FCDCommand.APP_SET_MIXER_GAIN, 0 );
} }
} }
catch ( UsbClaimException e ) catch ( Exception e )
{ {
throw new SourceException( "Exception while setting mixer gain", e ); throw new SourceException( "error while setting Mixer Gain", e );
}
catch ( UsbException e )
{
throw new SourceException( "Exception while setting mixer gain", e );
} }
mTunerConfiguration = plusConfig; mTunerConfiguration = plusConfig;
@@ -163,17 +159,15 @@ public class FCD2TunerController extends FCDTunerController
try try
{ {
dcCorrection = (int)send( FCDCommand.APP_GET_DC_CORRECTION ); ByteBuffer buffer = send( FCDCommand.APP_GET_DC_CORRECTION );
buffer.order( ByteOrder.LITTLE_ENDIAN );
return buffer.getInt( 2 );
} }
catch ( UsbClaimException e ) catch ( Exception e )
{ {
mLog.error( "FCTTunerController - couldn't claim funcube HID to" mLog.error( "error getting dc correction value", e );
+ " get dc correction value", e );
}
catch ( UsbException e )
{
mLog.error( "FCTTunerController - error getting dc correction "
+ "value", e );
} }
return dcCorrection; return dcCorrection;
@@ -183,17 +177,11 @@ public class FCD2TunerController extends FCDTunerController
{ {
try try
{ {
send( FCDCommand.APP_SET_DC_CORRECTION, value ); send( FCDCommand.APP_SET_DC_CORRECTION, value );
} }
catch ( UsbClaimException e ) catch ( Exception e )
{ {
mLog.error( "FCDTunerController - error claiming usb hid while " mLog.error( "error setting dc correction to [" + value + "]", e );
+ "trying to set dc correction to [" + value + "]", e );
}
catch ( UsbException e )
{
mLog.error( "FCDTunerController - error while "
+ "trying to set dc correction to [" + value + "]", e );
} }
} }
@@ -203,18 +191,15 @@ public class FCD2TunerController extends FCDTunerController
try try
{ {
iqCorrection = (int)send( FCDCommand.APP_GET_IQ_CORRECTION ); ByteBuffer buffer = send( FCDCommand.APP_GET_IQ_CORRECTION );
}
catch ( UsbClaimException e )
{
mLog.error( "FCTTunerController - couldn't claim funcube HID to"
+ " get iq correction value", e );
}
catch ( UsbException e )
{
mLog.error( "FCTTunerController - error getting iq correction "
+ "value", e );
buffer.order( ByteOrder.LITTLE_ENDIAN );
return buffer.getInt( 2 );
}
catch ( Exception e )
{
mLog.error( "error reading IQ correction value", e );
} }
return iqCorrection; return iqCorrection;
@@ -226,15 +211,9 @@ public class FCD2TunerController extends FCDTunerController
{ {
send( FCDCommand.APP_SET_IQ_CORRECTION, value ); send( FCDCommand.APP_SET_IQ_CORRECTION, value );
} }
catch ( UsbClaimException e ) catch ( Exception e )
{ {
mLog.error( "FCDTunerController - error claiming usb hid while " mLog.error( "error setting IQ correction to [" + value + "]", e );
+ "trying to set iq correction to [" + value + "]", e );
}
catch ( UsbException e )
{
mLog.error( "FCDTunerController - error while "
+ "trying to set iq correction to [" + value + "]", e );
} }
} }
@@ -272,98 +251,4 @@ public class FCD2TunerController extends FCDTunerController
return retVal; return retVal;
} }
} }
public enum TunerRFFilter
{
TRF_0_4,
TRF_4_8,
TRF_8_16,
TRF_16_32,
TRF_32_75,
TRF_75_125,
TRF_125_250,
TRF_145,
TRF_410_875,
TRF_435,
TRF_875_2000,
UNKNOWN;
public static TunerRFFilter get( int value )
{
TunerRFFilter retVal = UNKNOWN;
if( 0 <= value && value <= 10 )
{
retVal = values()[ value ];
}
return retVal;
}
}
public enum TunerIFFilter
{
TIF_200KHZ,
TIF_300KHZ,
TIF_600KHZ,
TIF_1536KHZ,
TIF_5MHZ,
TIF_6MHZ,
TIF_7MHZ,
TIF_8MHZ,
UNKNOWN;
public static TunerIFFilter get( int value )
{
TunerIFFilter retVal = UNKNOWN;
if( 0 <= value && value <= 7 )
{
retVal = values()[ value ];
}
return retVal;
}
}
public enum LNAGain
{
LNA_GAIN_MINUS_5_0( 0, "-5.0 dB" ),
LNA_GAIN_MINUS_2_5( 1, "-2.5 dB" ),
LNA_GAIN_PLUS_0_0( 4, "0.0 dB" ),
LNA_GAIN_PLUS_2_5( 5, "2.5 dB" ),
LNA_GAIN_PLUS_5_0( 6, "5.0 dB" ),
LNA_GAIN_PLUS_7_5( 7, "7.5 dB" ),
LNA_GAIN_PLUS_10_0( 8, "10.0 dB" ),
LNA_GAIN_PLUS_12_5( 9, "12.5 dB" ),
LNA_GAIN_PLUS_15_0( 10, "15.0 dB" ),
LNA_GAIN_PLUS_17_5( 11, "17.5 dB" ),
LNA_GAIN_PLUS_20_0( 12, "20.0 dB" ),
LNA_GAIN_PLUS_25_0( 13, "25.0 dB" ),
LNA_GAIN_PLUS_30_0( 14, "30.0 dB" );
private int mSetting;
private String mLabel;
private LNAGain( int setting, String label )
{
mSetting = setting;
mLabel = label;
}
public int getSetting()
{
return mSetting;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return getLabel();
}
}
} }

View File

@@ -71,6 +71,11 @@ public class HackRFTuner extends Tuner
} }
} }
public void dispose()
{
//TODO: dispose of something here
}
public HackRFTunerController getController() public HackRFTunerController getController()
{ {
return mController; return mController;

View File

@@ -31,6 +31,7 @@ public class HackRFTunerConfiguration extends TunerConfiguration
private HackRFSampleRate mSampleRate = HackRFSampleRate.RATE2_016MHZ; private HackRFSampleRate mSampleRate = HackRFSampleRate.RATE2_016MHZ;
private HackRFLNAGain mLNAGain = HackRFLNAGain.GAIN_0; private HackRFLNAGain mLNAGain = HackRFLNAGain.GAIN_0;
private HackRFVGAGain mVGAGain = HackRFVGAGain.GAIN_10; private HackRFVGAGain mVGAGain = HackRFVGAGain.GAIN_10;
private boolean mAmplifierEnabled = false;
private double mFrequencyCorrection = 0.0d; private double mFrequencyCorrection = 0.0d;
/** /**
@@ -52,6 +53,17 @@ public class HackRFTunerConfiguration extends TunerConfiguration
return TunerType.HACKRF; return TunerType.HACKRF;
} }
@XmlAttribute( name = "amplifier_enabled" )
public boolean getAmplifierEnabled()
{
return mAmplifierEnabled;
}
public void setAmplifierEnabled( boolean enabled )
{
mAmplifierEnabled = enabled;
}
@XmlAttribute( name = "lna_gain" ) @XmlAttribute( name = "lna_gain" )
public HackRFLNAGain getLNAGain() public HackRFLNAGain getLNAGain()
{ {

View File

@@ -35,6 +35,7 @@ import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.JSpinner; import javax.swing.JSpinner;
import javax.swing.JTextField; import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpinnerModel; import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel; import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants; import javax.swing.SwingConstants;
@@ -74,6 +75,7 @@ public class HackRFTunerConfigurationPanel extends JPanel
private JTextField mName; private JTextField mName;
private JSpinner mFrequencyCorrection; private JSpinner mFrequencyCorrection;
private JToggleButton mAmplifier;
private JComboBox<HackRFLNAGain> mComboLNAGain; private JComboBox<HackRFLNAGain> mComboLNAGain;
private JComboBox<HackRFVGAGain> mComboVGAGain; private JComboBox<HackRFVGAGain> mComboVGAGain;
@@ -284,9 +286,39 @@ public class HackRFTunerConfigurationPanel extends JPanel
* Gain Controls * Gain Controls
*/ */
JPanel gainPanel = new JPanel(); JPanel gainPanel = new JPanel();
gainPanel.setLayout( new MigLayout( "", "[grow,fill]", "[grow,fill]" ) ); gainPanel.setLayout( new MigLayout( "",
"[][right][grow,fill][right][grow,fill]", "[grow,fill]" ) );
gainPanel.setBorder( BorderFactory.createTitledBorder( "Gain" ) ); gainPanel.setBorder( BorderFactory.createTitledBorder( "Gain" ) );
/* Amplifier */
mAmplifier = new JToggleButton( "Amp" );
mAmplifier.setSelected( mSelectedConfig.getAmplifierEnabled() );
mAmplifier.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
mController.setAmplifierEnabled( mAmplifier.isSelected() );
mSelectedConfig.setAmplifierEnabled( mAmplifier.isSelected() );
save();
}
catch ( UsbException e )
{
mLog.error( "couldn't enable/disable amplifier", e );
mAmplifier.setEnabled( !mAmplifier.isSelected() );
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"Couldn't change amplifier setting",
"Error changing amplifier setting",
JOptionPane.ERROR_MESSAGE );
}
}
} );
gainPanel.add( mAmplifier );
/* LNA Gain Control */ /* LNA Gain Control */
mComboLNAGain = new JComboBox<HackRFLNAGain>( HackRFLNAGain.values() ); mComboLNAGain = new JComboBox<HackRFLNAGain>( HackRFLNAGain.values() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() ); mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
@@ -311,6 +343,7 @@ public class HackRFTunerConfigurationPanel extends JPanel
} }
mSelectedConfig.setLNAGain( lnaGain ); mSelectedConfig.setLNAGain( lnaGain );
save(); save();
} }
catch ( UsbException e ) catch ( UsbException e )
@@ -325,8 +358,8 @@ public class HackRFTunerConfigurationPanel extends JPanel
} }
} }
} ); } );
mComboLNAGain.setToolTipText( "<html>LNA Gain. Set master gain " mComboLNAGain.setToolTipText( "<html>LNA Gain. Adjust to set "
+ "to <b>MANUAL</b> to enable adjustment</html>" ); + "the IF gain</html>" );
gainPanel.add( new JLabel( "LNA" ) ); gainPanel.add( new JLabel( "LNA" ) );
gainPanel.add( mComboLNAGain ); gainPanel.add( mComboLNAGain );
@@ -367,12 +400,12 @@ public class HackRFTunerConfigurationPanel extends JPanel
} }
} }
} ); } );
mComboVGAGain.setToolTipText( "<html>VGA Gain. Set master gain " mComboVGAGain.setToolTipText( "<html>VGA Gain. Adjust to set the "
+ "to <b>MANUAL</b> to enable adjustment</html>" ); + "baseband gain</html>" );
gainPanel.add( new JLabel( "VGA" ) ); gainPanel.add( new JLabel( "VGA" ) );
gainPanel.add( mComboVGAGain, "wrap" ); gainPanel.add( mComboVGAGain, "wrap" );
add( gainPanel, "span" ); add( gainPanel, "span,growx" );
/** /**
* Create a new configuration * Create a new configuration

View File

@@ -1,5 +1,7 @@
package source.tuner.hackrf; package source.tuner.hackrf;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
@@ -10,46 +12,34 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.usb.UsbClaimException;
import javax.usb.UsbConfiguration;
import javax.usb.UsbControlIrp;
import javax.usb.UsbDevice;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbEndpoint;
import javax.usb.UsbEndpointDescriptor;
import javax.usb.UsbException; import javax.usb.UsbException;
import javax.usb.UsbInterface;
import javax.usb.UsbInterfacePolicy;
import javax.usb.UsbIrp;
import javax.usb.UsbNotActiveException;
import javax.usb.UsbNotOpenException;
import javax.usb.UsbPipe;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.apache.commons.io.EndianUtils; import org.apache.commons.io.EndianUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb; import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import org.usb4java.Transfer;
import org.usb4java.TransferCallback;
import sample.Listener; import sample.Listener;
import source.SourceException; import source.SourceException;
import source.tuner.TunerConfiguration; import source.tuner.TunerConfiguration;
import source.tuner.TunerController; import source.tuner.TunerController;
import source.tuner.rtl.ByteSampleAdapter; import source.tuner.rtl.ByteSampleAdapter;
import source.tuner.usb.USBTunerDevice;
public class HackRFTunerController extends TunerController public class HackRFTunerController extends TunerController
{ {
private final static Logger mLog = private final static Logger mLog =
LoggerFactory.getLogger( HackRFTunerController.class ); LoggerFactory.getLogger( HackRFTunerController.class );
public final static long TIMEOUT_US = 1000000l; //uSeconds
public static final byte USB_ENDPOINT = (byte)0x81; public static final byte USB_ENDPOINT = (byte)0x81;
public static final byte USB_INTERFACE = (byte)0x0; public static final byte USB_INTERFACE = (byte)0x0;
public static final boolean USB_FORCE_CLAIM_INTERFACE = true;
public static final byte REQUEST_TYPE_IN = public static final byte REQUEST_TYPE_IN =
(byte)( LibUsb.ENDPOINT_IN | (byte)( LibUsb.ENDPOINT_IN |
@@ -65,10 +55,10 @@ public class HackRFTunerController extends TunerController
public static final long MAX_FREQUENCY = 6000000000l; public static final long MAX_FREQUENCY = 6000000000l;
public static final long DEFAULT_FREQUENCY = 101100000; public static final long DEFAULT_FREQUENCY = 101100000;
public final static int USB_IRP_POOL_SIZE = 10; public final static int TRANSFER_BUFFER_POOL_SIZE = 16;
private LinkedTransferQueue<UsbIrp> mReceivedBuffers = private LinkedTransferQueue<byte[]> mFilledBuffers =
new LinkedTransferQueue<UsbIrp>(); new LinkedTransferQueue<byte[]>();
private CopyOnWriteArrayList<Listener<Float[]>> mSampleListeners = private CopyOnWriteArrayList<Listener<Float[]>> mSampleListeners =
new CopyOnWriteArrayList<Listener<Float[]>>(); new CopyOnWriteArrayList<Listener<Float[]>>();
@@ -76,63 +66,42 @@ public class HackRFTunerController extends TunerController
private ByteSampleAdapter mSampleAdapter = new ByteSampleAdapter(); private ByteSampleAdapter mSampleAdapter = new ByteSampleAdapter();
private BufferProcessor mBufferProcessor = new BufferProcessor(); private BufferProcessor mBufferProcessor = new BufferProcessor();
private UsbDevice mUSBDevice; private HackRFSampleRate mSampleRate = HackRFSampleRate.RATE2_016MHZ;
private UsbInterface mUSBInterface; public int mBufferSize = 262144;
private UsbPipe mUSBPipe; private boolean mAmplifierEnabled = false;
private HackRFSampleRate mSampleRate = HackRFSampleRate.RATE4_464MHZ; private Device mDevice;
public int mBufferSize = mSampleRate.getBufferSize(); private DeviceDescriptor mDeviceDescriptor;
private DeviceHandle mDeviceHandle;
public HackRFTunerController( USBTunerDevice tunerDevice ) public HackRFTunerController( Device device, DeviceDescriptor descriptor )
throws SourceException throws SourceException
{ {
super( MIN_FREQUENCY, MAX_FREQUENCY ); super( MIN_FREQUENCY, MAX_FREQUENCY );
mUSBDevice = tunerDevice.getDevice(); mDevice = device;
mDeviceDescriptor = descriptor;
} }
public void init() throws SourceException public void init() throws SourceException
{ {
mLog.info( "HackRF Tuner Controller init() starting" ); mDeviceHandle = new DeviceHandle();
UsbConfiguration config = mUSBDevice.getActiveUsbConfiguration(); LibUsb.open( mDevice, mDeviceHandle );
mUSBInterface = config.getUsbInterface( USB_INTERFACE );
try try
{ {
if( claim( mUSBInterface ) ) claimInterface();
{
/* Get the USB endpoint */
UsbEndpoint endpoint = mUSBInterface.getUsbEndpoint( USB_ENDPOINT );
UsbEndpointDescriptor d = endpoint.getUsbEndpointDescriptor(); setMode( Mode.RECEIVE );
System.out.println( "Endpoint max packet size:" + d.wMaxPacketSize() );
mUSBPipe = endpoint.getUsbPipe(); setFrequency( DEFAULT_FREQUENCY );
setMode( Mode.RECEIVE );
setFrequency( DEFAULT_FREQUENCY );
}
else
{
throw new SourceException( "HackRF Tuner Controller - couldn't "
+ "claim USB interface" );
}
} }
catch( UsbException e ) catch( Exception e )
{ {
throw new SourceException( "HackRF Tuner Controller - couldn't " throw new SourceException( "HackRF Tuner Controller - couldn't "
+ "claim USB interface or get endpoint or pipe", e ); + "claim USB interface or get endpoint or pipe", e );
} }
catch ( UsbDisconnectedException e )
{
throw new SourceException( "HackRF Tuner Controller - usb device "
+ "is disconnected", e );
}
mLog.info( "HackRF Tuner Controller init() complete" );
} }
/** /**
@@ -141,29 +110,39 @@ public class HackRFTunerController extends TunerController
* will dictate if the interface is forcibly claimed from the other * will dictate if the interface is forcibly claimed from the other
* application * application
*/ */
public static boolean claim( UsbInterface iface ) throws UsbException, private void claimInterface() throws SourceException
UsbClaimException
{ {
if( !iface.isClaimed() ) if( mDeviceHandle != null )
{ {
iface.claim( new UsbInterfacePolicy() int result = LibUsb.kernelDriverActive( mDeviceHandle, USB_INTERFACE );
{
@Override
public boolean forceClaim( UsbInterface arg0 )
{
return USB_FORCE_CLAIM_INTERFACE;
}
} );
return iface.isClaimed(); if( result == 1 )
{
result = LibUsb.detachKernelDriver( mDeviceHandle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
mLog.error( "failed attempt to detach kernel driver [" +
LibUsb.errorName( result ) + "]" );
throw new SourceException( "couldn't detach kernel driver "
+ "from device" );
}
}
result = LibUsb.claimInterface( mDeviceHandle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
throw new SourceException( "couldn't claim usb interface [" +
LibUsb.errorName( result ) + "]" );
}
} }
else else
{ {
mLog.error( "attempt to claim USB interface failed - in use by " throw new SourceException( "couldn't claim usb interface - no "
+ "another application" ); + "device handle" );
} }
return false;
} }
/** /**
@@ -181,19 +160,13 @@ public class HackRFTunerController extends TunerController
*/ */
public String getFirmwareVersion() throws UsbException public String getFirmwareVersion() throws UsbException
{ {
byte[] data = readArray( Request.VERSION_STRING_READ, 0, 0, 255 ); ByteBuffer buffer = readArray( Request.VERSION_STRING_READ, 0, 0, 255 );
StringBuilder sb = new StringBuilder(); byte[] data = new byte[ 255 ];
for( byte b: data ) buffer.get( data );
{
if( b != (byte)0 )
{
sb.append( (char)b );
}
}
return sb.toString(); return new String( data );
} }
/** /**
@@ -201,9 +174,9 @@ public class HackRFTunerController extends TunerController
*/ */
public Serial getSerial() throws UsbException public Serial getSerial() throws UsbException
{ {
byte[] data = readArray( Request.BOARD_PARTID_SERIALNO_READ, 0, 0, 24 ); ByteBuffer buffer = readArray( Request.BOARD_PARTID_SERIALNO_READ, 0, 0, 24 );
return new Serial( data ); return new Serial( buffer );
} }
/** /**
@@ -230,6 +203,13 @@ public class HackRFTunerController extends TunerController
public void setAmplifierEnabled( boolean enabled ) throws UsbException public void setAmplifierEnabled( boolean enabled ) throws UsbException
{ {
write( Request.AMP_ENABLE, ( enabled ? 1 : 0 ), 0 ); write( Request.AMP_ENABLE, ( enabled ? 1 : 0 ), 0 );
mAmplifierEnabled = enabled;
}
public boolean getAmplifier()
{
return mAmplifierEnabled;
} }
/** /**
@@ -269,17 +249,20 @@ public class HackRFTunerController extends TunerController
@Override @Override
public void setTunedFrequency( long frequency ) throws SourceException public void setTunedFrequency( long frequency ) throws SourceException
{ {
ByteBuffer buffer = ByteBuffer.allocateDirect( 8 );
buffer.order( ByteOrder.LITTLE_ENDIAN );
int mhz = (int)( frequency / 1E6 ); int mhz = (int)( frequency / 1E6 );
int hz = (int)( frequency - ( mhz * 1E6 ) ); int hz = (int)( frequency - ( mhz * 1E6 ) );
byte[] data = new byte[ 8 ]; buffer.putInt( mhz );
buffer.putInt( hz );
EndianUtils.writeSwappedInteger( data, 0, mhz ); buffer.rewind();
EndianUtils.writeSwappedInteger( data, 4, hz );
try try
{ {
write( Request.SET_FREQUENCY, 0, 0, data ); write( Request.SET_FREQUENCY, 0, 0, buffer );
} }
catch( UsbException e ) catch( UsbException e )
{ {
@@ -288,7 +271,6 @@ public class HackRFTunerController extends TunerController
throw new SourceException( "error setting frequency [" + throw new SourceException( "error setting frequency [" +
frequency + "]", e ); frequency + "]", e );
} }
} }
@Override @Override
@@ -302,15 +284,15 @@ public class HackRFTunerController extends TunerController
{ {
if( config instanceof HackRFTunerConfiguration ) if( config instanceof HackRFTunerConfiguration )
{ {
HackRFTunerConfiguration hackConfig = HackRFTunerConfiguration hackRFConfig =
(HackRFTunerConfiguration)config; (HackRFTunerConfiguration)config;
try try
{ {
setSampleRate( hackConfig.getSampleRate() ); setSampleRate( hackRFConfig.getSampleRate() );
setFrequencyCorrection( hackConfig.getFrequencyCorrection() ); setFrequencyCorrection( hackRFConfig.getFrequencyCorrection() );
setLNAGain( hackConfig.getLNAGain() ); setLNAGain( hackRFConfig.getLNAGain() );
setVGAGain( hackConfig.getVGAGain() ); setVGAGain( hackRFConfig.getVGAGain() );
setFrequency( getFrequency() ); setFrequency( getFrequency() );
} }
catch ( UsbException e ) catch ( UsbException e )
@@ -326,21 +308,35 @@ public class HackRFTunerController extends TunerController
} }
} }
public byte[] readArray( Request request, public ByteBuffer readArray( Request request,
int value, int value,
int index, int index,
int length ) throws UsbException int length ) throws UsbException
{ {
UsbControlIrp irp = mUSBDevice.createUsbControlIrp( REQUEST_TYPE_IN, if( mDeviceHandle != null )
request.getRequestNumber(), (short)value, (short)index ); {
ByteBuffer buffer = ByteBuffer.allocateDirect( length );
byte[] data = new byte[ length ]; int transferred = LibUsb.controlTransfer( mDeviceHandle,
REQUEST_TYPE_IN,
request.getRequestNumber(),
(short)value,
(short)index,
buffer,
TIMEOUT_US );
irp.setData( data ); if( transferred < 0 )
{
throw new LibUsbException( "read error", transferred );
}
mUSBDevice.syncSubmit( irp ); return buffer;
}
return data; else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
} }
public int read( Request request, int value, int index, int length ) public int read( Request request, int value, int index, int length )
@@ -349,10 +345,14 @@ public class HackRFTunerController extends TunerController
if( !( length == 1 || length == 2 || length == 4 ) ) if( !( length == 1 || length == 2 || length == 4 ) )
{ {
throw new IllegalArgumentException( "invalid length [" + length + throw new IllegalArgumentException( "invalid length [" + length +
"] must be: byte=1, short=2, int=3 to read a primitive" ); "] must be: byte=1, short=2, int=4 to read a primitive" );
} }
byte[] data = readArray( request, value, index, length ); ByteBuffer buffer = readArray( request, value, index, length );
byte[] data = new byte[ buffer.capacity() ];
buffer.get( data );
switch( data.length ) switch( data.length )
{ {
@@ -371,29 +371,50 @@ public class HackRFTunerController extends TunerController
public int readByte( Request request, int value, int index, boolean signed ) public int readByte( Request request, int value, int index, boolean signed )
throws UsbException throws UsbException
{ {
byte[] data = readArray( request, value, index, 1 ); ByteBuffer buffer = readArray( request, value, index, 1 );
if( signed ) if( signed )
{ {
return (int)( data[ 0 ] ); return (int)( buffer.get() );
} }
else else
{ {
return (int)( data[ 0 ] & 0xFF ); return (int)( buffer.get() & 0xFF );
} }
} }
public void write( Request request, public void write( Request request,
int value, int value,
int index, int index,
byte[] data ) throws UsbException ByteBuffer buffer ) throws UsbException
{ {
UsbControlIrp irp = mUSBDevice.createUsbControlIrp( REQUEST_TYPE_OUT, if( mDeviceHandle != null )
request.getRequestNumber(), (short)value, (short)index ); {
int transferred = LibUsb.controlTransfer( mDeviceHandle,
REQUEST_TYPE_OUT,
request.getRequestNumber(),
(short)value,
(short)index,
buffer,
TIMEOUT_US );
irp.setData( data ); if( transferred < 0 )
{
mUSBDevice.syncSubmit( irp ); throw new LibUsbException( "error writing byte buffer",
transferred );
}
else if( transferred != buffer.capacity() )
{
throw new LibUsbException( "transferred bytes [" +
transferred + "] is not what was expected [" +
buffer.capacity() + "]", transferred );
}
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
} }
/** /**
@@ -403,64 +424,22 @@ public class HackRFTunerController extends TunerController
int value, int value,
int index ) throws UsbException int index ) throws UsbException
{ {
write( request, value, index, new byte[ 0 ] ); write( request, value, index, ByteBuffer.allocateDirect( 0 ) );
} }
/** /**
* Sample Rate * Sample Rate
* *
* Note: this is direct translation of the libhackrf code, because I still * Note: the libhackrf set sample rate method is designed to allow fractional
* can't figure out how it works ... one day, maybe. * sample rates. However, since we're only using integral sample rates, we
* simply invoke the setSampleRateManual method directly.
*/ */
public void setSampleRate( HackRFSampleRate rate ) throws UsbException public void setSampleRate( HackRFSampleRate rate ) throws UsbException
{ {
// int MAX_N = 32;
//
// double freq = (double)rate.getRate() / 1E6d;
//
// double freq_frac = 1.0d + freq - (int)freq;
//
// long u64 = Double.doubleToLongBits( freq );
//
// int e = (int)( ( u64 >> 52 ) - 1023 );
//
// long m = (long)( 1l << 52 ) - 1l;
//
// u64 = Double.doubleToLongBits( freq_frac );
//
// u64 &= m;
//
// m &= ~( ( 1 << ( e + 4 ) ) - 1 );
//
// long a = 0;
//
// int x;
//
// for( x = 1; x < MAX_N; x++ )
// {
// a += u64;
//
// if( ( ( a & m ) == 0 ) || ( ( ~a & m ) == 0 ) )
// {
// break;
// }
// }
//
// if( x == MAX_N )
// {
// x = 1;
// }
//
// int freq_hz = (int)( freq * (double)x * 0.5d );
//
// setSampleRateManual( freq_hz, x );
setSampleRateManual( rate.getRate(), 1 ); setSampleRateManual( rate.getRate(), 1 );
mFrequencyController.setSampleRate( rate.getRate() ); mFrequencyController.setSampleRate( rate.getRate() );
mBufferSize = rate.getBufferSize();
setBasebandFilter( rate.getFilter() ); setBasebandFilter( rate.getFilter() );
mSampleRate = rate; mSampleRate = rate;
@@ -469,12 +448,14 @@ public class HackRFTunerController extends TunerController
public void setSampleRateManual( int frequency, int divider ) public void setSampleRateManual( int frequency, int divider )
throws UsbException throws UsbException
{ {
byte[] data = new byte[ 8 ]; ByteBuffer buffer = ByteBuffer.allocateDirect( 8 );
EndianUtils.writeSwappedInteger( data, 0, frequency ); buffer.order( ByteOrder.LITTLE_ENDIAN );
EndianUtils.writeSwappedInteger( data, 4, divider );
write( Request.SET_SAMPLE_RATE, 0, 0, data ); buffer.putInt( frequency );
buffer.putInt( divider );
write( Request.SET_SAMPLE_RATE, 0, 0, buffer );
} }
public int getSampleRate() public int getSampleRate()
@@ -522,29 +503,26 @@ public class HackRFTunerController extends TunerController
public enum HackRFSampleRate public enum HackRFSampleRate
{ {
RATE2_016MHZ( 2016000, 65536, "2.016 MHz", BasebandFilter.F2_50 ), RATE2_016MHZ( 2016000, "2.016 MHz", BasebandFilter.F3_50 ),
RATE3_024MHZ( 3024000, 98304, "3.024 MHz", BasebandFilter.F3_50 ), RATE3_024MHZ( 3024000, "3.024 MHz", BasebandFilter.F5_00 ),
RATE4_464MHZ( 4464000, 131072, "4.464 MHz", BasebandFilter.F5_00 ), RATE4_464MHZ( 4464000, "4.464 MHz", BasebandFilter.F6_00 ),
RATE5_472MHZ( 5472000, 196608, "5.472 MHz", BasebandFilter.F6_00 ), RATE5_472MHZ( 5472000, "5.472 MHz", BasebandFilter.F7_00 ),
RATE7_488MHZ( 7488000, 262144, "7.488 MHz", BasebandFilter.F8_00 ), RATE7_488MHZ( 7488000, "7.488 MHz", BasebandFilter.F9_00 ),
RATE10_032MHZ( 9984000, 131072, " 9.984 MHz", BasebandFilter.F10_00 ), RATE10_032MHZ( 9984000, " 9.984 MHz", BasebandFilter.F12_00 ),
RATE12_000MHZ( 12000000, 262144, "12.000 MHz", BasebandFilter.F12_00 ), RATE12_000MHZ( 12000000, "12.000 MHz", BasebandFilter.F14_00 ),
RATE13_488MHZ( 13488000, 262144, "13.488 MHz", BasebandFilter.F14_00 ), RATE13_488MHZ( 13488000, "13.488 MHz", BasebandFilter.F15_00 ),
RATE14_976MHZ( 14976000, 262144, "14.976 MHz", BasebandFilter.F15_00 ), RATE14_976MHZ( 14976000, "14.976 MHz", BasebandFilter.F20_00 ),
RATE19_968MHZ( 19968000, 262144, "19.968 MHz", BasebandFilter.F20_00 ); RATE19_968MHZ( 19968000, "19.968 MHz", BasebandFilter.F24_00 );
private int mRate; private int mRate;
private int mBufferSize;
private String mLabel; private String mLabel;
private BasebandFilter mFilter; private BasebandFilter mFilter;
private HackRFSampleRate( int rate, private HackRFSampleRate( int rate,
int bufferSize,
String label, String label,
BasebandFilter filter ) BasebandFilter filter )
{ {
mRate = rate; mRate = rate;
mBufferSize = bufferSize;
mLabel = label; mLabel = label;
mFilter = filter; mFilter = filter;
} }
@@ -554,11 +532,6 @@ public class HackRFTunerController extends TunerController
return mRate; return mRate;
} }
public int getBufferSize()
{
return mBufferSize;
}
public String getLabel() public String getLabel()
{ {
return mLabel; return mLabel;
@@ -577,6 +550,7 @@ public class HackRFTunerController extends TunerController
public enum BasebandFilter public enum BasebandFilter
{ {
FAUTO( 0, "AUTO" ),
F1_75( 1750000, "1.75 MHz" ), F1_75( 1750000, "1.75 MHz" ),
F2_50( 2500000, "2.50 MHz" ), F2_50( 2500000, "2.50 MHz" ),
F3_50( 3500000, "3.50 MHz" ), F3_50( 3500000, "3.50 MHz" ),
@@ -793,9 +767,11 @@ public class HackRFTunerController extends TunerController
{ {
private byte[] mData; private byte[] mData;
public Serial( byte[] data ) public Serial( ByteBuffer buffer )
{ {
mData = data; mData = new byte[ buffer.capacity() ];
buffer.get( mData );
} }
public String getPartID() public String getPartID()
@@ -841,8 +817,16 @@ public class HackRFTunerController extends TunerController
{ {
mSampleListeners.add( listener ); mSampleListeners.add( listener );
System.out.println( "HackRF - listener added - count:" + mSampleListeners.size() ); if( mBufferProcessor == null || !mBufferProcessor.isRunning() )
mBufferProcessor.start(); {
mBufferProcessor = new BufferProcessor();
Thread thread = new Thread( mBufferProcessor );
thread.setDaemon( true );
thread.setName( "Sample Processor" );
thread.start();
}
} }
/** /**
@@ -889,93 +873,72 @@ public class HackRFTunerController extends TunerController
} }
/** /**
* Buffer processing thread. Fetches samples from the RTL2832 Tuner and * Buffer processing thread. Fetches samples from the HackRF Tuner and
* dispatches them to all registered listeners * dispatches them to all registered listeners
*/ */
public class BufferProcessor implements UsbPipeListener public class BufferProcessor implements Runnable, TransferCallback
{ {
private ScheduledExecutorService mExecutor = private ScheduledExecutorService mExecutor =
Executors.newScheduledThreadPool( 2 ); Executors.newScheduledThreadPool( 1 );
private ScheduledFuture<?> mSampleDispatcherTask; private ScheduledFuture<?> mSampleDispatcherTask;
// private ScheduledFuture<?> mSampleRateCounterTask; private ArrayList<Transfer> mTransfers;
private AtomicBoolean mRunning = new AtomicBoolean(); private AtomicBoolean mRunning = new AtomicBoolean();
private AtomicBoolean mResetting = new AtomicBoolean();
private Boolean mTransitioning = false;
public void start() @Override
public void run()
{ {
synchronized( mTransitioning ) if( mRunning.compareAndSet( false, true ) )
{ {
if( mRunning.compareAndSet( false, true ) ) mLog.debug( "starting sample fetch thread" );
prepareTransfers();
for( Transfer transfer: mTransfers )
{ {
mLog.debug( "HackRF - starting sample fetch thread" ); int result = LibUsb.submitTransfer( transfer );
ArrayList<UsbIrp> irps = new ArrayList<UsbIrp>(); if( result != LibUsb.SUCCESS )
for( int x = 0; x < USB_IRP_POOL_SIZE; x++ )
{ {
UsbIrp irp = mUSBPipe.createUsbIrp(); mLog.error( "error submitting transfer [" +
irp.setData( new byte[ mBufferSize ] ); LibUsb.errorName( result ) + "]" );
irps.add( irp ); break;
} }
try
{
if( mUSBPipe.isActive() )
{
if( !mUSBPipe.isOpen() )
{
mUSBPipe.open();
mUSBPipe.addUsbPipeListener( this );
}
if( mUSBPipe.isOpen() )
{
mSampleDispatcherTask = mExecutor
.scheduleAtFixedRate( new BufferDispatcher(),
0, 20, TimeUnit.MILLISECONDS );
// mSampleRateMonitor =
// new SampleRateMonitor( mSampleRate.getRate() );
// mSampleRateCounterTask = mExecutor
// .scheduleAtFixedRate( mSampleRateMonitor,
// 10, 10, TimeUnit.SECONDS );
mUSBPipe.asyncSubmit( irps );
}
}
}
catch ( Exception e )
{
mLog.error( "Error in buffer processor thread", e );
}
} }
}
} mSampleDispatcherTask = mExecutor
.scheduleAtFixedRate( new BufferDispatcher(),
0, 20, TimeUnit.MILLISECONDS );
while( mRunning.get() )
{
ByteBuffer completed = ByteBuffer.allocateDirect( 4 );
int result = LibUsb.handleEventsTimeoutCompleted(
null, TIMEOUT_US, completed.asIntBuffer() );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error handling events for libusb" );
}
}
}
}
/** /**
* Stops the sample fetching thread * Stops the sample fetching thread
*/ */
public void stop() public void stop()
{ {
synchronized( mTransitioning ) if( mRunning.compareAndSet( true, false ) )
{ {
if( mRunning.compareAndSet( true, false ) ) mLog.debug( "stopping sample fetch thread" );
cancel();
if( mSampleDispatcherTask != null )
{ {
mLog.debug( "HackRF - stopping sample fetch thread" ); mSampleDispatcherTask.cancel( true );
mFilledBuffers.clear();
mUSBPipe.abortAllSubmissions();
if( mSampleDispatcherTask != null )
{
mSampleDispatcherTask.cancel( true );
// mSampleRateCounterTask.cancel( true );
// mRawSampleBuffer.clear();
// mSampleCounter.set( 0 );
}
} }
} }
} }
@@ -988,84 +951,149 @@ public class HackRFTunerController extends TunerController
return mRunning.get(); return mRunning.get();
} }
/**
* Receives filled data buffers and places them in the queue for the
* BufferDispatcher to process
*/
@Override @Override
public synchronized void dataEventOccurred( UsbPipeDataEvent event ) public void processTransfer( Transfer transfer )
{ {
mReceivedBuffers.add( event.getUsbIrp() ); if( transfer.status() == LibUsb.TRANSFER_COMPLETED )
}
@Override
public void errorEventOccurred( UsbPipeErrorEvent e )
{
/* When an error occurs, we'll get errors on all of the
* queued IRPS in succession. We use the mResetting to control
* the reset process and ignore all subsequent errors */
if( mResetting.compareAndSet( false, true ) )
{ {
mLog.error( "error during data transfer resetting USB pipe to " ByteBuffer buffer = transfer.buffer();
+ "HackRF", e );
stop(); byte[] data = new byte[ transfer.actualLength() ];
if( !mSampleListeners.isEmpty() ) buffer.get( data );
{
start();
}
mResetting.set( false ); buffer.rewind();
mFilledBuffers.add( data );
if( !isRunning() )
{
LibUsb.cancelTransfer( transfer );
}
} }
}
switch( transfer.status() )
{
case LibUsb.TRANSFER_COMPLETED:
/* resubmit the transfer */
int result = LibUsb.submitTransfer( transfer );
if( result != LibUsb.SUCCESS )
{
mLog.error( "couldn't resubmit buffer transfer to tuner" );
LibUsb.freeTransfer( transfer );
mTransfers.remove( transfer );
}
break;
case LibUsb.TRANSFER_CANCELLED:
/* free the transfer and remove it */
LibUsb.freeTransfer( transfer );
mTransfers.remove( transfer );
break;
default:
/* unexpected error */
mLog.error( "transfer error [" +
getTransferStatus( transfer.status() ) +
"] transferred actual: " + transfer.actualLength() );
}
}
private void cancel()
{
for( Transfer transfer: mTransfers )
{
LibUsb.cancelTransfer( transfer );
}
ByteBuffer completed = ByteBuffer.allocateDirect( 4 );
int result = LibUsb.handleEventsTimeoutCompleted(
null, TIMEOUT_US, completed.asIntBuffer() );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error handling usb events during cancel [" +
LibUsb.errorName( result ) + "]" );
}
}
/**
* Prepares (allocates) a set of transfer buffers for use in
* transferring data from the tuner via the bulk interface
*/
private void prepareTransfers() throws LibUsbException
{
mTransfers = new ArrayList<Transfer>();
for( int x = 0; x < TRANSFER_BUFFER_POOL_SIZE; x++ )
{
Transfer transfer = LibUsb.allocTransfer();
if( transfer == null )
{
throw new LibUsbException( "couldn't allocate transfer",
LibUsb.ERROR_NO_MEM );
}
final ByteBuffer buffer =
ByteBuffer.allocateDirect( mBufferSize );
LibUsb.fillBulkTransfer( transfer,
mDeviceHandle,
USB_ENDPOINT,
buffer,
BufferProcessor.this,
"Buffer #" + x,
TIMEOUT_US );
mTransfers.add( transfer );
}
}
} }
/** /**
* Fetches received UsbIrp buffers from the received queue, dispatches them * Fetches byte[] chunks from the raw sample buffer. Converts each byte
* and resubmits the processed buffer for more samples * array and broadcasts the array to all registered listeners
*/ */
public class BufferDispatcher implements Runnable public class BufferDispatcher implements Runnable
{ {
@Override @Override
public void run() public void run()
{ {
ArrayList<UsbIrp> buffers = new ArrayList<UsbIrp>(); ArrayList<byte[]> buffers = new ArrayList<byte[]>();
mReceivedBuffers.drainTo( buffers ); mFilledBuffers.drainTo( buffers );
for( UsbIrp buffer: buffers ) for( byte[] buffer: buffers )
{ {
Float[] samples = mSampleAdapter.convert( buffer.getData() ); //TODO: convert this to float primitive
Float[] samples = mSampleAdapter.convert( buffer );
broadcast( samples ); broadcast( samples );
if( mBufferProcessor != null && mBufferProcessor.isRunning() )
{
try
{
/* We adjust the buffer size according to sample rate.
* If this byte array matches the current buffer size
* then we reuse the byte array, otherwise create a
* new one. */
if( buffer.getData().length == mBufferSize )
{
mUSBPipe.asyncSubmit( buffer.getData() );
}
else
{
mUSBPipe.asyncSubmit( new byte[ mBufferSize ] );
}
}
catch ( UsbNotActiveException | UsbNotOpenException
| IllegalArgumentException | UsbDisconnectedException
| UsbException e )
{
mLog.error( "error submitting a byte array to the usb "
+ "pipe for samples", e );
}
}
} }
} }
} }
public static String getTransferStatus( int status )
{
switch( status )
{
case 0:
return "TRANSFER COMPLETED (0)";
case 1:
return "TRANSFER ERROR (1)";
case 2:
return "TRANSFER TIMED OUT (2)";
case 3:
return "TRANSFER CANCELLED (3)";
case 4:
return "TRANSFER STALL (4)";
case 5:
return "TRANSFER NO DEVICE (5)";
case 6:
return "TRANSFER OVERFLOW (6)";
default:
return "UNKNOWN TRANSFER STATUS (" + status + ")";
}
}
} }

View File

@@ -20,10 +20,10 @@ package source.tuner.rtl;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.usb.UsbException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.LibUsbException;
import sample.Listener; import sample.Listener;
import source.SourceException; import source.SourceException;
@@ -59,6 +59,11 @@ public class RTL2832Tuner extends Tuner
mController.addListener( (FrequencyChangeListener)this ); mController.addListener( (FrequencyChangeListener)this );
} }
public void dispose()
{
//TODO: dispose of something here
}
public RTL2832TunerController getController() public RTL2832TunerController getController()
{ {
return mController; return mController;
@@ -115,7 +120,7 @@ public class RTL2832Tuner extends Tuner
{ {
mController.setSampleRate( sampleRate ); mController.setSampleRate( sampleRate );
} }
catch( UsbException e ) catch( LibUsbException e )
{ {
throw new SourceException( "RTL2832 Tuner - error setting " throw new SourceException( "RTL2832 Tuner - error setting "
+ "sample rate", e ); + "sample rate", e );
@@ -139,7 +144,18 @@ public class RTL2832Tuner extends Tuner
throws RejectedExecutionException, throws RejectedExecutionException,
SourceException SourceException
{ {
return mController.getChannel( threadPoolManager, this, channel ); TunerChannelSource source = null;
try
{
source = mController.getChannel( threadPoolManager, this, channel );
}
catch( Exception e )
{
mLog.error( "couldn't provide source channel", e );
}
return source;
} }
/** /**
* Releases the tuned channel so that the tuner controller can tune to * Releases the tuned channel so that the tuner controller can tune to

File diff suppressed because it is too large Load Diff

View File

@@ -46,6 +46,7 @@ import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.LibUsbException;
import source.SourceException; import source.SourceException;
import source.tuner.TunerConfiguration; import source.tuner.TunerConfiguration;
@@ -258,7 +259,7 @@ public class E4KTunerConfigurationPanel extends JPanel
mSelectedConfig.setSampleRate( sampleRate ); mSelectedConfig.setSampleRate( sampleRate );
save(); save();
} }
catch ( SourceException | UsbException eSampleRate ) catch ( SourceException | LibUsbException eSampleRate )
{ {
JOptionPane.showMessageDialog( JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this, E4KTunerConfigurationPanel.this,

View File

@@ -17,37 +17,39 @@
******************************************************************************/ ******************************************************************************/
package source.tuner.rtl.e4k; package source.tuner.rtl.e4k;
import java.util.Arrays;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.usb.UsbException; import javax.usb.UsbException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import source.SourceException; import source.SourceException;
import source.tuner.TunerConfiguration; import source.tuner.TunerConfiguration;
import source.tuner.TunerType; import source.tuner.TunerType;
import source.tuner.rtl.RTL2832TunerController; import source.tuner.rtl.RTL2832TunerController;
import source.tuner.usb.USBTunerDevice; import source.tuner.rtl.RTL2832TunerController.Descriptor;
import controller.ResourceManager; import controller.ResourceManager;
public class E4KTunerController extends RTL2832TunerController public class E4KTunerController extends RTL2832TunerController
{ {
/** private final static Logger mLog =
* Note: E4K tuner max frequency range is 2200 MHz, but the LoggerFactory.getLogger( E4KTunerController.class );
* max value that can be assigned to a signed integer is
* 2147xxxxxx, so we constrain the E4K to the max integer value, for now public static final long MIN_FREQUENCY = 52000000;
* public static final long MAX_FREQUENCY = 2200000000l;
* TODO: change frequency to a long primitive type
*/
public static final long sMIN_FREQUENCY = 52000000;
public static final long sMIN_FREQUENCY_EXTENDED = 52000000;
public static final long sMAX_FREQUENCY = 2200000000l;
public static final long sMAX_FREQUENCY_EXTENDED = 2200000000l;
public static final long sMIN_VCO = 2600000000l; //2.6 GHz
public static final long sMAX_VCO = 3900000000l; //3.9 GHz
/* The local oscillator is defined by whole (integer) units of the oscillator /* The local oscillator is defined by whole (integer) units of the oscillator
* frequency and fractional units representing 1/65536th of the oscillator * frequency and fractional units representing 1/65536th of the oscillator
* frequency, meaning we can only tune the local oscillator in units of * frequency, meaning we can only tune the local oscillator in units of
* 439.453125 hertz. */ * 439.453125 hertz. */
public static final long sE4K_PLL_Y = 65536l; /* 16-bit fractional register */ public static final long E4K_PLL_Y = 65536l; /* 16-bit fractional register */
public static final byte MASTER1_RESET = (byte)0x01; public static final byte MASTER1_RESET = (byte)0x01;
public static final byte MASTER1_NORM_STBY = (byte)0x02; public static final byte MASTER1_NORM_STBY = (byte)0x02;
public static final byte MASTER1_POR_DET = (byte)0x04; public static final byte MASTER1_POR_DET = (byte)0x04;
@@ -108,9 +110,11 @@ public class E4KTunerController extends RTL2832TunerController
private E4KTunerEditorPanel mEditor; private E4KTunerEditorPanel mEditor;
public E4KTunerController( USBTunerDevice device ) throws SourceException public E4KTunerController( Device device,
DeviceDescriptor deviceDescriptor )
throws SourceException
{ {
super( device, sMIN_FREQUENCY, sMAX_FREQUENCY ); super( device, deviceDescriptor, MIN_FREQUENCY, MAX_FREQUENCY );
} }
@Override @Override
@@ -166,24 +170,75 @@ public class E4KTunerController extends RTL2832TunerController
public void init() throws SourceException public void init() throws SourceException
{ {
mDeviceHandle = new DeviceHandle();
int result = LibUsb.open( mDevice, mDeviceHandle );
if( result != LibUsb.SUCCESS )
{
mDeviceHandle = null;
throw new SourceException( "libusb couldn't open RTL2832 usb "
+ "device [" + LibUsb.errorName( result ) + "]" );
}
claimInterface( mDeviceHandle );
byte[] eeprom = null;
try
{
/* Read the contents of the 256-byte EEPROM */
eeprom = readEEPROM( mDeviceHandle, (short)0, 256 );
}
catch( Exception e )
{
mLog.error( "error while reading the EEPROM device descriptor", e );
}
try
{
mDescriptor = new Descriptor( eeprom );
if( eeprom == null )
{
mLog.error( "eeprom byte array was null - constructed "
+ "empty descriptor object" );
}
}
catch( Exception e )
{
mLog.error( "error while constructing device descriptor using "
+ "descriptor byte array " +
( eeprom == null ? "[null]" : Arrays.toString( eeprom )), e );
}
try try
{ {
/* Dummy write to test USB interface */ /* Dummy write to test USB interface */
writeRegister( mUSBDevice, Block.USB, writeRegister( mDeviceHandle, Block.USB,
Address.USB_SYSCTL.getAddress(), (short)0x09, 1 ); Address.USB_SYSCTL.getAddress(), (short)0x09, 1 );
initBaseband( mUSBDevice ); initBaseband( mDeviceHandle );
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
boolean i2CRepeaterControl = false; boolean i2CRepeaterControl = false;
initTuner( i2CRepeaterControl ); initTuner( i2CRepeaterControl );
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
try
{
setSampleRate( DEFAULT_SAMPLE_RATE );
}
catch( Exception e )
{
throw new SourceException( "RTL2832 Tuner Controller - couldn't "
+ "set default sample rate", e );
}
/* Initialize the super class */
super.init();
} }
catch( UsbException e ) catch( UsbException e )
{ {
@@ -208,14 +263,14 @@ public class E4KTunerController extends RTL2832TunerController
* for the selected bandwidth/sample rate * for the selected bandwidth/sample rate
*/ */
@Override @Override
public void setSampleRateFilters( int bandwidth ) throws UsbException public void setSampleRateFilters( int bandwidth ) throws SourceException
{ {
/* Determine repeater state so we can restore it when done */ /* Determine repeater state so we can restore it when done */
boolean i2CRepeaterEnabled = isI2CRepeaterEnabled(); boolean i2CRepeaterEnabled = isI2CRepeaterEnabled();
if( !i2CRepeaterEnabled ) if( !i2CRepeaterEnabled )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
boolean controlI2CRepeater = false; boolean controlI2CRepeater = false;
@@ -231,7 +286,7 @@ public class E4KTunerController extends RTL2832TunerController
if( !i2CRepeaterEnabled ) if( !i2CRepeaterEnabled )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -245,7 +300,7 @@ public class E4KTunerController extends RTL2832TunerController
if( !i2CRepeaterEnabled ) if( !i2CRepeaterEnabled )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
boolean controlI2CRepeater = false; boolean controlI2CRepeater = false;
@@ -263,12 +318,12 @@ public class E4KTunerController extends RTL2832TunerController
/* Return the repeater to its previous state */ /* Return the repeater to its previous state */
if( !i2CRepeaterEnabled ) if( !i2CRepeaterEnabled )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
return calculateActualFrequency( pll, z, x ); return calculateActualFrequency( pll, z, x );
} }
catch( UsbException e ) catch( LibUsbException e )
{ {
throw new SourceException( "E4K tuner controller - couldn't get " throw new SourceException( "E4K tuner controller - couldn't get "
+ "tuned frequency", e ); + "tuned frequency", e );
@@ -291,7 +346,7 @@ public class E4KTunerController extends RTL2832TunerController
int remainder = (int)( frequency - ( ( z & 0xFF ) * pll.getScaledOscillator() ) ); int remainder = (int)( frequency - ( ( z & 0xFF ) * pll.getScaledOscillator() ) );
/* X is a 16-bit representation of the remainder */ /* X is a 16-bit representation of the remainder */
int x = (int)( (double)remainder / (double)pll.getScaledOscillator() * sE4K_PLL_Y ); int x = (int)( (double)remainder / (double)pll.getScaledOscillator() * E4K_PLL_Y );
/* Calculate the exact (tunable) frequency and apply that to the tuner */ /* Calculate the exact (tunable) frequency and apply that to the tuner */
long actualFrequency = calculateActualFrequency( pll, z, x ); long actualFrequency = calculateActualFrequency( pll, z, x );
@@ -310,7 +365,7 @@ public class E4KTunerController extends RTL2832TunerController
/* Apply the actual frequency */ /* Apply the actual frequency */
try try
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
boolean controlI2CRepeater = false; boolean controlI2CRepeater = false;
@@ -341,10 +396,10 @@ public class E4KTunerController extends RTL2832TunerController
{ {
throw new SourceException( "E4K tuner controller - couldn't " throw new SourceException( "E4K tuner controller - couldn't "
+ "achieve PLL lock for frequency [" + + "achieve PLL lock for frequency [" +
actualFrequency + "]" ); actualFrequency + "] lock value [" + lock + "]" );
} }
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
catch( UsbException e ) catch( UsbException e )
{ {
@@ -358,7 +413,7 @@ public class E4KTunerController extends RTL2832TunerController
long whole = pll.getScaledOscillator() * ( z & 0xFF ); long whole = pll.getScaledOscillator() * ( z & 0xFF );
int fractional = (int)( pll.getScaledOscillator() * int fractional = (int)( pll.getScaledOscillator() *
( (double)x / (double)sE4K_PLL_Y ) ); ( (double)x / (double)E4K_PLL_Y ) );
return whole + fractional; return whole + fractional;
} }
@@ -367,7 +422,7 @@ public class E4KTunerController extends RTL2832TunerController
{ {
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
boolean i2CRepeaterControl = false; boolean i2CRepeaterControl = false;
@@ -473,7 +528,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -484,7 +539,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
/* Capture current gain settings to reapply at the end */ /* Capture current gain settings to reapply at the end */
@@ -548,7 +603,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -584,7 +639,7 @@ public class E4KTunerController extends RTL2832TunerController
{ {
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
if( gain == E4KLNAGain.AUTOMATIC ) if( gain == E4KLNAGain.AUTOMATIC )
@@ -610,7 +665,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -661,7 +716,7 @@ public class E4KTunerController extends RTL2832TunerController
{ {
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
boolean localI2CRepeaterControl = false; boolean localI2CRepeaterControl = false;
@@ -689,7 +744,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -810,7 +865,7 @@ public class E4KTunerController extends RTL2832TunerController
} }
public void setMixerFilter( MixerFilter filter, public void setMixerFilter( MixerFilter filter,
boolean controlI2CRepeater ) throws UsbException boolean controlI2CRepeater ) throws LibUsbException
{ {
writeMaskedE4KRegister( MixerFilter.getRegister(), writeMaskedE4KRegister( MixerFilter.getRegister(),
MixerFilter.getMask(), MixerFilter.getMask(),
@@ -828,7 +883,7 @@ public class E4KTunerController extends RTL2832TunerController
} }
public void setRCFilter( RCFilter filter, public void setRCFilter( RCFilter filter,
boolean controlI2CRepeater ) throws UsbException boolean controlI2CRepeater ) throws LibUsbException
{ {
writeMaskedE4KRegister( RCFilter.getRegister(), writeMaskedE4KRegister( RCFilter.getRegister(),
RCFilter.getMask(), RCFilter.getMask(),
@@ -844,7 +899,7 @@ public class E4KTunerController extends RTL2832TunerController
} }
public void setChannelFilter( ChannelFilter filter, public void setChannelFilter( ChannelFilter filter,
boolean controlI2CRepeater ) throws UsbException boolean controlI2CRepeater ) throws LibUsbException
{ {
writeMaskedE4KRegister( ChannelFilter.getRegister(), writeMaskedE4KRegister( ChannelFilter.getRegister(),
ChannelFilter.getMask(), ChannelFilter.getMask(),
@@ -885,7 +940,7 @@ public class E4KTunerController extends RTL2832TunerController
{ {
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
Band band = Band.fromFrequency( frequency ); Band band = Band.fromFrequency( frequency );
@@ -914,7 +969,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -946,7 +1001,7 @@ public class E4KTunerController extends RTL2832TunerController
{ {
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
boolean i2CRepeaterControl = false; boolean i2CRepeaterControl = false;
@@ -957,7 +1012,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
} }
@@ -969,7 +1024,7 @@ public class E4KTunerController extends RTL2832TunerController
{ {
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
} }
writeE4KRegister( Register.MAGIC_1, (byte)0x01, false ); writeE4KRegister( Register.MAGIC_1, (byte)0x01, false );
@@ -983,7 +1038,7 @@ public class E4KTunerController extends RTL2832TunerController
if( controlI2CRepeater ) if( controlI2CRepeater )
{ {
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
} }
@@ -999,7 +1054,7 @@ public class E4KTunerController extends RTL2832TunerController
private void writeMaskedE4KRegister( Register register, private void writeMaskedE4KRegister( Register register,
byte mask, byte mask,
byte value, byte value,
boolean controlI2CRepeater ) throws UsbException boolean controlI2CRepeater ) throws LibUsbException
{ {
int temp = readE4KRegister( register, controlI2CRepeater ); int temp = readE4KRegister( register, controlI2CRepeater );
@@ -1009,22 +1064,24 @@ public class E4KTunerController extends RTL2832TunerController
writeE4KRegister( register, writeE4KRegister( register,
(byte)( ( temp & ~mask ) | ( value & mask ) ), (byte)( ( temp & ~mask ) | ( value & mask ) ),
controlI2CRepeater ); controlI2CRepeater );
int temp2 = readE4KRegister( register, controlI2CRepeater );
} }
} }
private int readE4KRegister( Register register, private int readE4KRegister( Register register,
boolean controlI2CRepeater ) throws UsbException boolean controlI2CRepeater ) throws LibUsbException
{ {
return readI2CRegister( mUSBDevice, Register.I2C_REGISTER.getValue(), return readI2CRegister( mDeviceHandle, Register.I2C_REGISTER.getValue(),
register.getValue(), controlI2CRepeater ); register.getValue(), controlI2CRepeater );
} }
private void writeE4KRegister( Register register, private void writeE4KRegister( Register register,
byte value, byte value,
boolean controlI2CRepeater ) throws UsbException boolean controlI2CRepeater ) throws LibUsbException
{ {
writeI2CRegister( mUSBDevice, Register.I2C_REGISTER.getValue(), writeI2CRegister( mDeviceHandle, Register.I2C_REGISTER.getValue(),
register.getValue(), value, controlI2CRepeater ); register.getValue(), value, controlI2CRepeater );
} }

View File

@@ -46,6 +46,7 @@ import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.LibUsbException;
import source.SourceException; import source.SourceException;
import source.tuner.TunerConfiguration; import source.tuner.TunerConfiguration;
@@ -252,7 +253,7 @@ public class R820TTunerConfigurationPanel extends JPanel
mSelectedConfig.setSampleRate( sampleRate ); mSelectedConfig.setSampleRate( sampleRate );
save(); save();
} }
catch ( SourceException | UsbException eSampleRate ) catch ( SourceException | LibUsbException eSampleRate )
{ {
JOptionPane.showMessageDialog( JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this, R820TTunerConfigurationPanel.this,
@@ -308,7 +309,7 @@ public class R820TTunerConfigurationPanel extends JPanel
{ {
mController.setSampleRateFrequencyCorrection( value ); mController.setSampleRateFrequencyCorrection( value );
} }
catch ( SourceException | UsbException e1 ) catch ( SourceException | LibUsbException e1 )
{ {
JOptionPane.showMessageDialog( JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this, R820TTunerConfigurationPanel.this,

View File

@@ -22,17 +22,21 @@
******************************************************************************/ ******************************************************************************/
package source.tuner.rtl.r820t; package source.tuner.rtl.r820t;
import java.nio.ByteBuffer;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.usb.UsbException; import javax.usb.UsbException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.LibUsbException;
import source.SourceException; import source.SourceException;
import source.tuner.TunerConfiguration; import source.tuner.TunerConfiguration;
import source.tuner.TunerType; import source.tuner.TunerType;
import source.tuner.rtl.RTL2832TunerController; import source.tuner.rtl.RTL2832TunerController;
import source.tuner.usb.USBTunerDevice;
import controller.ResourceManager; import controller.ResourceManager;
public class R820TTunerController extends RTL2832TunerController public class R820TTunerController extends RTL2832TunerController
@@ -68,9 +72,11 @@ public class R820TTunerController extends RTL2832TunerController
private JPanel mEditor; private JPanel mEditor;
public R820TTunerController( USBTunerDevice device ) throws SourceException public R820TTunerController( Device device,
DeviceDescriptor deviceDescriptor )
throws SourceException
{ {
super( device, MIN_FREQUENCY, MAX_FREQUENCY ); super( device, deviceDescriptor, MIN_FREQUENCY, MAX_FREQUENCY );
} }
@Override @Override
@@ -80,7 +86,7 @@ public class R820TTunerController extends RTL2832TunerController
} }
@Override @Override
public void setSampleRateFilters( int sampleRate ) throws UsbException public void setSampleRateFilters( int sampleRate ) throws LibUsbException
{ {
//TODO: why is this being forced as an abstract method on sub classes? //TODO: why is this being forced as an abstract method on sub classes?
} }
@@ -155,7 +161,7 @@ public class R820TTunerController extends RTL2832TunerController
{ {
try try
{ {
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
boolean controlI2C = false; boolean controlI2C = false;
@@ -165,7 +171,7 @@ public class R820TTunerController extends RTL2832TunerController
setPLL( offsetFrequency, controlI2C ); setPLL( offsetFrequency, controlI2C );
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
} }
catch( UsbException e ) catch( UsbException e )
{ {
@@ -179,7 +185,7 @@ public class R820TTunerController extends RTL2832TunerController
* Overrides the same method from the RTL2832 tuner controller to apply * Overrides the same method from the RTL2832 tuner controller to apply
* settings specific to the R820T tuner. * settings specific to the R820T tuner.
*/ */
public void setSamplingMode( SampleMode mode ) throws UsbException public void setSamplingMode( SampleMode mode ) throws LibUsbException
{ {
switch( mode ) switch( mode )
{ {
@@ -188,14 +194,14 @@ public class R820TTunerController extends RTL2832TunerController
setIFFrequency( R820T_IF_FREQUENCY ); setIFFrequency( R820T_IF_FREQUENCY );
/* Enable spectrum inversion */ /* Enable spectrum inversion */
writeDemodRegister( mUSBDevice, writeDemodRegister( mDeviceHandle,
Page.ONE, Page.ONE,
(short)0x15, (short)0x15,
(short)0x01, (short)0x01,
1 ); 1 );
/* Set default i/q path */ /* Set default i/q path */
writeDemodRegister( mUSBDevice, writeDemodRegister( mDeviceHandle,
Page.ZERO, Page.ZERO,
(short)0x06, (short)0x06,
(short)0x80, (short)0x80,
@@ -239,18 +245,16 @@ public class R820TTunerController extends RTL2832TunerController
*/ */
public void init() throws SourceException public void init() throws SourceException
{ {
/* Initialize the super class to open and claim the usb interface*/
super.init();
try try
{ {
mLog.debug( "testing USB interface" );
/* Dummy write to test USB interface */
writeRegister( mUSBDevice, Block.USB,
Address.USB_SYSCTL.getAddress(), (short)0x09, 1 );
mLog.debug( "initializing RTL2832 tuner baseband" ); mLog.debug( "initializing RTL2832 tuner baseband" );
initBaseband( mUSBDevice ); initBaseband( mDeviceHandle );
mLog.debug( "enabling I2C repeater" ); mLog.debug( "enabling I2C repeater" );
enableI2CRepeater( mUSBDevice, true ); enableI2CRepeater( mDeviceHandle, true );
boolean i2CRepeaterControl = false; boolean i2CRepeaterControl = false;
@@ -258,11 +262,9 @@ public class R820TTunerController extends RTL2832TunerController
initTuner( i2CRepeaterControl ); initTuner( i2CRepeaterControl );
mLog.debug( "disabling I2C repeater" ); mLog.debug( "disabling I2C repeater" );
enableI2CRepeater( mUSBDevice, false ); enableI2CRepeater( mDeviceHandle, false );
mLog.debug( "initializing RTL2832 tuner controller super class" ); mLog.debug( "initializing RTL2832 tuner controller super class" );
/* Initialize the super class */
super.init();
} }
catch( UsbException e ) catch( UsbException e )
{ {
@@ -276,14 +278,14 @@ public class R820TTunerController extends RTL2832TunerController
public void initTuner( boolean controlI2C ) throws UsbException public void initTuner( boolean controlI2C ) throws UsbException
{ {
/* Disable zero IF mode */ /* Disable zero IF mode */
writeDemodRegister( mUSBDevice, writeDemodRegister( mDeviceHandle,
Page.ONE, Page.ONE,
(short)0xB1, (short)0xB1,
(short)0x1A, (short)0x1A,
1 ); 1 );
/* Only enable in-phase ADC input */ /* Only enable in-phase ADC input */
writeDemodRegister( mUSBDevice, writeDemodRegister( mDeviceHandle,
Page.ZERO, Page.ZERO,
(short)0x08, (short)0x08,
(short)0x4D, (short)0x4D,
@@ -293,7 +295,7 @@ public class R820TTunerController extends RTL2832TunerController
setIFFrequency( R820T_IF_FREQUENCY ); setIFFrequency( R820T_IF_FREQUENCY );
/* Enable spectrum inversion */ /* Enable spectrum inversion */
writeDemodRegister( mUSBDevice, writeDemodRegister( mDeviceHandle,
Page.ONE, Page.ONE,
(short)0x15, (short)0x15,
(short)0x01, (short)0x01,
@@ -570,7 +572,7 @@ public class R820TTunerController extends RTL2832TunerController
{ {
for( int x = 5; x < mShadowRegister.length; x++ ) for( int x = 5; x < mShadowRegister.length; x++ )
{ {
writeI2CRegister( mUSBDevice, writeI2CRegister( mDeviceHandle,
mI2CAddress, mI2CAddress,
(byte)x, (byte)x,
(byte)mShadowRegister[ x ], (byte)mShadowRegister[ x ],
@@ -583,11 +585,11 @@ public class R820TTunerController extends RTL2832TunerController
*/ */
private int getStatusRegister( int register, boolean controlI2C ) throws UsbException private int getStatusRegister( int register, boolean controlI2C ) throws UsbException
{ {
byte[] data = new byte[ 5 ]; ByteBuffer buffer = ByteBuffer.allocateDirect( 5 );
byte[] statusRegisters = read( mUSBDevice, Block.IIC, mI2CAddress, data ); read( mDeviceHandle, mI2CAddress, Block.I2C, buffer );
return bitReverse( statusRegisters[ register ] & 0xFF ); return bitReverse( buffer.get( register ) & 0xFF );
} }
/** /**
@@ -615,7 +617,7 @@ public class R820TTunerController extends RTL2832TunerController
( value & register.getMask() ) ); ( value & register.getMask() ) );
} }
writeI2CRegister( mUSBDevice, mI2CAddress, writeI2CRegister( mDeviceHandle, mI2CAddress,
(byte)register.getRegister(), value, controlI2C ); (byte)register.getRegister(), value, controlI2C );
mShadowRegister[ register.getRegister() ] = value; mShadowRegister[ register.getRegister() ] = value;
@@ -631,7 +633,7 @@ public class R820TTunerController extends RTL2832TunerController
public int readR820TRegister( Register register, boolean controlI2C ) public int readR820TRegister( Register register, boolean controlI2C )
throws UsbException throws UsbException
{ {
int value = readI2CRegister( mUSBDevice, int value = readI2CRegister( mDeviceHandle,
mI2CAddress, mI2CAddress,
(byte)register.getRegister(), (byte)register.getRegister(),
controlI2C ); controlI2C );