-
Notifications
You must be signed in to change notification settings - Fork 240
/
RTL2832TunerController.java
1625 lines (1421 loc) · 48.9 KB
/
RTL2832TunerController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* *****************************************************************************
* Copyright (C) 2014-2023 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.tuner.rtl;
import io.github.dsheirer.buffer.ByteNativeBufferFactory;
import io.github.dsheirer.buffer.INativeBufferFactory;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.ITunerErrorListener;
import io.github.dsheirer.source.tuner.TunerClass;
import io.github.dsheirer.source.tuner.TunerFactory;
import io.github.dsheirer.source.tuner.TunerType;
import io.github.dsheirer.source.tuner.configuration.TunerConfiguration;
import io.github.dsheirer.source.tuner.usb.USBTunerController;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
/**
* RTL-2832 tuner controller implementation.
*/
public class RTL2832TunerController extends USBTunerController
{
private static final Logger mLog = LoggerFactory.getLogger(RTL2832TunerController.class);
public static final int TWO_TO_22_POWER = 4194304;
public static final int USB_TRANSFER_BUFFER_SIZE = 65_536;
public static final byte CONTROL_ENDPOINT_IN = (byte) (LibUsb.ENDPOINT_IN | LibUsb.REQUEST_TYPE_VENDOR);
public static final byte CONTROL_ENDPOINT_OUT = (byte) (LibUsb.ENDPOINT_OUT | LibUsb.REQUEST_TYPE_VENDOR);
public static final long TIMEOUT_US = 1000000l; //uSeconds
public static final byte REQUEST_ZERO = (byte) 0;
public static final byte EEPROM_ADDRESS = (byte) 0xA0;
public static final byte[] FIR_FILTER_COEFFICIENTS = {(byte) 0xCA, (byte) 0xDC, (byte) 0xD7, (byte) 0xD8,
(byte) 0xE0, (byte) 0xF2, (byte) 0x0E, (byte) 0x35, (byte) 0x06, (byte) 0x50, (byte) 0x9C, (byte) 0x0D,
(byte) 0x71, (byte) 0x11, (byte) 0x14, (byte) 0x71, (byte) 0x74, (byte) 0x19, (byte) 0x41, (byte) 0xA5};
public static final SampleRate DEFAULT_SAMPLE_RATE = SampleRate.RATE_2_400MHZ;
private SampleRate mSampleRate = DEFAULT_SAMPLE_RATE;
private INativeBufferFactory mNativeBufferFactory = new ByteNativeBufferFactory();
private int mOscillatorFrequency = 28800000; //28.8 MHz
private Descriptor mDescriptor;
private EmbeddedTuner mEmbeddedTuner;
private long mTunedFrequency = 0;
private boolean mBiasTEnabled = false;
private ReentrantLock mLock = new ReentrantLock();
/**
* Abstract tuner controller device. Use the static gettype() method
* to determine the tuner type, and construct the corresponding child
* tuner controller class for that tuner type.
*/
public RTL2832TunerController(int bus, String portAddress, ITunerErrorListener tunerErrorListener)
{
super(bus, portAddress, tunerErrorListener);
}
/**
* Lock for controlling configuration access to this tuner controller and the embedded tuner to ensure that
* configuration changes involving multiple USB control messages can happen atomically. There are at least two
* threads that can touch this controller:
*
* A: channel processing that changes the center tuned frequency and frequency correction.
* b: user ui thread that can touch any of the frequency correction and gain controls.
*
* Generally, we'll lock on each of the primary configuration change points - getter and setter for:
* Frequency
* Frequency Correction
* Sample Rate
* Gain Controls
*
* @return lock for controlling access to tuner controller and em
*/
private ReentrantLock getLock()
{
return mLock;
}
@Override
protected INativeBufferFactory getNativeBufferFactory()
{
return mNativeBufferFactory;
}
@Override
protected int getTransferBufferSize()
{
return USB_TRANSFER_BUFFER_SIZE;
}
@Override
public int getBufferSampleCount()
{
return getTransferBufferSize() / 2;
}
/**
* The embedded tuner used with this RTL2832 USB tuner
*/
public EmbeddedTuner getEmbeddedTuner()
{
return mEmbeddedTuner;
}
public boolean hasEmbeddedTuner()
{
return mEmbeddedTuner != null;
}
/**
* Sets the tuned frequency in the embedded tuner
* @param frequency in Hertz
* @throws SourceException if there is an error
*/
@Override
public void setTunedFrequency(long frequency) throws SourceException
{
getEmbeddedTuner().setTunedFrequency(frequency);
mTunedFrequency = frequency;
}
@Override
public long getTunedFrequency() throws SourceException
{
return mTunedFrequency;
}
@Override
public void apply(TunerConfiguration tunerConfig) throws SourceException
{
//Invoke super for frequency, frequency correction and autoPPM
super.apply(tunerConfig);
if(tunerConfig instanceof RTL2832TunerConfiguration rtl)
{
setSampleRate(rtl.getSampleRate());
getEmbeddedTuner().apply(rtl);
}
}
/**
* Executes additional device startup actions after being commanded by the parent USB startup actions.
* @throws SourceException if there is an error/issue making this device is unusable
*/
@Override
protected void deviceStart() throws SourceException
{
//Perform dummy write to see if device needs reset
boolean resetRequired = false;
try
{
writeRegister(Block.USB, Address.USB_SYSCTL, 0x09, 1);
}
catch(LibUsbException lue)
{
if(lue.getErrorCode() < 0)
{
resetRequired = true;
}
else
{
mLog.error("Error performing test write to RTL2832 device - " + LibUsb.errorName(lue.getErrorCode()));
}
}
if(resetRequired)
{
int status = LibUsb.resetDevice(getDeviceHandle());
mLog.info("Resetting device - status: " + LibUsb.errorName(status));
try
{
writeRegister(Block.USB, Address.USB_SYSCTL, 0x09, 1);
}
catch(LibUsbException lue)
{
mLog.error("Couldnt' reset RTL2832 device - setting error");
throw new SourceException("unable to reset USB device - " + LibUsb.errorName(status));
}
}
byte[] eeprom = null;
try
{
/* Read the contents of the 256-byte EEPROM */
eeprom = readEEPROM((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);
}
initBaseband();
TunerType tunerType = identifyTunerType();
if(tunerType == TunerType.UNKNOWN)
{
throw new SourceException("Unrecognized RTL-2832 embedded tuner type: " + tunerType);
}
mEmbeddedTuner = TunerFactory.getRtlEmbeddedTuner(tunerType, new ControllerAdapter(this));
try
{
enableI2CRepeater(true);
getEmbeddedTuner().initTuner();
enableI2CRepeater(false);
}
catch(UsbException ue)
{
throw new SourceException("Unable to initialize " + tunerType, ue);
}
setMinimumFrequency(mEmbeddedTuner.getMinimumFrequencySupported());
setMaximumFrequency(mEmbeddedTuner.getMaximumFrequencySupported());
setMiddleUnusableHalfBandwidth(mEmbeddedTuner.getDcSpikeHalfBandwidth());
setUsableBandwidthPercentage(mEmbeddedTuner.getUsableBandwidthPercent());
try
{
setSampleRate(DEFAULT_SAMPLE_RATE);
}
catch(Exception e)
{
throw new SourceException("RTL2832 Tuner Controller - couldn't set default sample rate", e);
}
}
@Override
protected void deviceStop()
{
try
{
deinitBaseband();
}
catch(Exception e)
{
// mLog.error("Error on device stop", e);
//No-op
}
}
/**
* Descriptor contains all identifiers and labels parsed from the EEPROM.
*
* May return null if unable to get 256 byte eeprom descriptor from tuner or if the descriptor doesn't begin with
* byte values of 0x28 and 0x32 meaning it is a valid (and can be parsed) RTL2832 descriptor
*/
public Descriptor getDescriptor()
{
if(mDescriptor != null && mDescriptor.isValid())
{
return mDescriptor;
}
return null;
}
/**
* Sets the enabled state of the bias-t
* @param enabled true to turn-on the bias-t or false to turn-off the bias-t.
*/
public void setBiasT(boolean enabled)
{
setGPIOOutput((byte)0x01);
setGPIOBit((byte)0x01, enabled);
mBiasTEnabled = enabled;
}
/**
* Indicates if the bias-t is enabled.
* @return true if enabled.
*/
public boolean isBiasT()
{
return mBiasTEnabled;
}
/**
* Overrides updates for measured frequency error so that the updates can also be applied to the
* frequency error correction manager for automatic PPM updating.
* @param measuredFrequencyError in hertz averaged over a 5 second interval.
*/
@Override
public void setMeasuredFrequencyError(int measuredFrequencyError)
{
super.setMeasuredFrequencyError(measuredFrequencyError);
getFrequencyErrorCorrectionManager().updatePPM(getPPMFrequencyError());
}
private void setIFFrequency(int frequency) throws LibUsbException
{
long ifFrequency = ((long) TWO_TO_22_POWER * (long) frequency) / (long) mOscillatorFrequency * -1;
/* Write byte 2 (high) */
writeDemodRegister(Page.ONE, (short) 0x19, (short) (Long.rotateRight(ifFrequency, 16) & 0x3F), 1);
/* Write byte 1 (middle) */
writeDemodRegister(Page.ONE, (short) 0x1A, (short) (Long.rotateRight(ifFrequency, 8) & 0xFF), 1);
/* Write byte 0 (low) */
writeDemodRegister(Page.ONE, (short) 0x1B, (short) (ifFrequency & 0xFF), 1);
}
/**
* Provides a unique identifier to use in distinctly identifying this tuner from among other tuners of the same
* type, so that we can fetch a tuner configuration from the settings manager for this specific tuner.
*
* @return serial number of the device
*/
public String getUniqueID()
{
if(mDescriptor != null && mDescriptor.hasSerial())
{
if(hasEmbeddedTuner())
{
return TunerClass.RTL2832 + "/" + getTunerType().getLabel() + " " + mDescriptor.getSerial();
}
else
{
return TunerClass.RTL2832 + " " + mDescriptor.getSerial();
}
}
else
{
int serial = (0xFF & getDeviceDescriptor().iSerialNumber());
return TunerClass.RTL2832.toString() + " " + serial;
}
}
/**
* Sets the filters for the sample rate
* @param sampleRate to setup
* @throws SourceException if there is an error
*/
public void setSampleRateFilters(int sampleRate) throws SourceException
{
getEmbeddedTuner().setSampleRateFilters(sampleRate);
}
/**
* Identifies the embedded tuner type
*/
public TunerType getTunerType()
{
if(getEmbeddedTuner() != null)
{
return getEmbeddedTuner().getTunerType();
}
return TunerType.UNKNOWN;
}
/**
* Identifies the embedded tuner type
* @return tuner type
* @throws SourceException if there is an error
*/
private TunerType identifyTunerType() throws SourceException
{
TunerType tunerClass = TunerType.UNKNOWN;
try
{
enableI2CRepeater(true);
boolean controlI2CRepeater = false;
/* Test for each tuner type until we find the correct one */
if(isTuner(TunerTypeCheck.E4K, controlI2CRepeater))
{
tunerClass = TunerType.ELONICS_E4000;
}
else if(isTuner(TunerTypeCheck.R820T, controlI2CRepeater))
{
tunerClass = TunerType.RAFAELMICRO_R820T;
}
else if(isTuner(TunerTypeCheck.FC0013, controlI2CRepeater))
{
tunerClass = TunerType.FITIPOWER_FC0013;
}
else if(isTuner(TunerTypeCheck.R828D, controlI2CRepeater))
{
tunerClass = TunerType.RAFAELMICRO_R828D;
}
else if(isTuner(TunerTypeCheck.FC2580, controlI2CRepeater))
{
tunerClass = TunerType.FCI_FC2580;
}
else if(isTuner(TunerTypeCheck.FC0012, controlI2CRepeater))
{
tunerClass = TunerType.FITIPOWER_FC0012;
}
enableI2CRepeater(false);
}
catch(Exception e)
{
mLog.error("error while determining tuner type", e);
}
return tunerClass;
}
@Override
protected void prepareStreaming()
{
resetUSBBuffer();
}
/**
* Resets the USB buffer
* @throws LibUsbException if there is an error
*/
public void resetUSBBuffer() throws LibUsbException
{
writeRegister(Block.USB, Address.USB_EPA_CTL, 0x1002, 2);
writeRegister(Block.USB, Address.USB_EPA_CTL, 0x0000, 2);
}
/**
* Initializes the RF baseband system
* @throws LibUsbException if there is an error
*/
public void initBaseband() throws LibUsbException
{
/* Initialize USB */
writeRegister(Block.USB, Address.USB_SYSCTL, 0x09, 1);
writeRegister(Block.USB, Address.USB_EPA_MAXPKT, 0x0002, 2);
writeRegister(Block.USB, Address.USB_EPA_CTL, 0x1002, 2);
/* Power on demod */
writeRegister(Block.SYS, Address.DEMOD_CTL_1, 0x22, 1);
writeRegister(Block.SYS, Address.DEMOD_CTL, 0xE8, 1);
/* Reset demod */
writeDemodRegister(Page.ONE, (short) 0x01, 0x14, 1); //Bit 3 = soft reset
writeDemodRegister(Page.ONE, (short) 0x01, 0x10, 1);
/* Disable spectrum inversion and adjacent channel rejection */
writeDemodRegister(Page.ONE, (short) 0x15, 0x00, 1);
writeDemodRegister(Page.ONE, (short) 0x16, 0x0000, 2);
/* Clear DDC shift and IF frequency registers */
writeDemodRegister(Page.ONE, (short) 0x16, 0x00, 1);
writeDemodRegister(Page.ONE, (short) 0x17, 0x00, 1);
writeDemodRegister(Page.ONE, (short) 0x18, 0x00, 1);
writeDemodRegister(Page.ONE, (short) 0x19, 0x00, 1);
writeDemodRegister(Page.ONE, (short) 0x1A, 0x00, 1);
writeDemodRegister(Page.ONE, (short) 0x1B, 0x00, 1);
/* Set FIR coefficients */
for(int x = 0; x < FIR_FILTER_COEFFICIENTS.length; x++)
{
writeDemodRegister(Page.ONE, (short) (0x1C + x), FIR_FILTER_COEFFICIENTS[x], 1);
}
/* Enable SDR mode, disable DAGC (bit 5) */
writeDemodRegister(Page.ZERO, (short) 0x19, 0x05, 1);
/* Init FSM state-holding register */
writeDemodRegister(Page.ONE, (short) 0x93, 0xF0, 1);
writeDemodRegister(Page.ONE, (short) 0x94, 0x0F, 1);
/* Disable AGC (en_dagc, bit 0) (seems to have no effect) */
writeDemodRegister(Page.ONE, (short) 0x11, 0x00, 1);
/* Disable RF and IF AGC loop */
writeDemodRegister(Page.ONE, (short) 0x04, 0x00, 1);
/* Disable PID filter */
writeDemodRegister(Page.ZERO, (short) 0x61, 0x60, 1);
/* opt_adc_iq = 0, default ADC_I/ADC_Q datapath */
writeDemodRegister(Page.ZERO, (short) 0x06, 0x80, 1);
/* Enable Zero-if mode (en_bbin bit),
* DC cancellation (en_dc_est),
* IQ estimation/compensation (en_iq_comp, en_iq_est) */
writeDemodRegister(Page.ONE, (short) 0xB1, 0x1B, 1);
/* Disable 4.096 MHz clock output on pin TP_CK0 */
writeDemodRegister(Page.ZERO, (short) 0x0D, 0x83, 1);
}
/**
* Turns off the RF baseband system
* @throws IllegalArgumentException never
* @throws UsbDisconnectedException of the device is no longer accessible
*/
private void deinitBaseband() throws IllegalArgumentException, UsbDisconnectedException
{
writeRegister(Block.SYS, Address.DEMOD_CTL, 0x20, 1);
}
/**
* Sets the General Purpose Input/Output (GPIO) register bit
*
* @param bitMask - bit mask with one for targeted register bits and zero for the non-targeted register bits
* @param enabled - true to set the bit and false to clear the bit
* @throws UsbDisconnectedException - if the tuner device is disconnected
* @throws UsbException - if there is a USB error while communicating with the device
*/
private void setGPIOBit(byte bitMask, boolean enabled) throws LibUsbException
{
//Get current register value
int value = readRegister(Block.SYS, Address.GPO, 1);
//Update the masked bits
if(enabled)
{
value |= bitMask;
}
else
{
value &= ~bitMask;
}
//Write the change back to the device
writeRegister(Block.SYS, Address.GPO, value, 1);
}
/**
* Enables GPIO Output
*
* @param bitMask - mask containing one bit value in targeted bit field(s)
* @throws UsbDisconnectedException
* @throws UsbException
*/
private void setGPIOOutput(byte bitMask) throws LibUsbException
{
//Get current register value
int value = readRegister(Block.SYS, Address.GPD, 1);
//Mask the value and rewrite it
writeRegister(Block.SYS, Address.GPO, value & ~bitMask, 1);
//Get current register value
value = readRegister(Block.SYS, Address.GPOE, 1);
//Mask the value and rewrite it
writeRegister(Block.SYS, Address.GPOE, value | bitMask, 1);
}
/**
* Enables or disables the I2C repeater
* @param enabled to turn I2C on or off
* @throws LibUsbException if there is an error
*/
private void enableI2CRepeater(boolean enabled) throws LibUsbException
{
Page page = Page.ONE;
short address = 1;
int value = (enabled ? 0x18 : 0x10);
writeDemodRegister(page, address, value, 1);
}
/**
* Indicates if the I2C repeater is currently enabled or turned on.
*/
private boolean isI2CRepeaterEnabled()
{
return readDemodRegister(Page.ONE, (short) 0x1, 1) == 0x18;
}
/**
* Reads the I2C register
* @param i2CAddress address of the register
* @param i2CRegister register
* @param controlI2CRepeater set to true to have this method turn repeater on/off for this invocation or false if
* the repeater has already been enabled.
* @return register value
* @throws LibUsbException if there is an error
*/
private int readI2CRegister(byte i2CAddress, byte i2CRegister, boolean controlI2CRepeater) throws LibUsbException
{
short address = (short) (i2CAddress & 0xFF);
ByteBuffer buffer = ByteBuffer.allocateDirect(1);
buffer.put(i2CRegister);
buffer.rewind();
ByteBuffer data = ByteBuffer.allocateDirect(1);
if(controlI2CRepeater)
{
enableI2CRepeater(true);
write(address, Block.I2C, buffer);
read(address, Block.I2C, data);
enableI2CRepeater(false);
}
else
{
write(address, Block.I2C, buffer);
read(address, Block.I2C, data);
}
return (data.get() & 0xFF);
}
/**
* Writes to the I2C register
* @param i2CAddress of the register
* @param i2CRegister register
* @param value to write
* @param controlI2CRepeater set to true to have this method turn repeater on/off for this invocation or false if
* the repeater has already been enabled.
* @throws LibUsbException if there is an error
*/
private void writeI2CRegister(byte i2CAddress, byte i2CRegister, byte value, boolean controlI2CRepeater)
throws LibUsbException
{
short address = (short) (i2CAddress & 0xFF);
ByteBuffer buffer = ByteBuffer.allocateDirect(2);
buffer.put(i2CRegister);
buffer.put(value);
buffer.rewind();
if(controlI2CRepeater)
{
enableI2CRepeater(true);
write(address, Block.I2C, buffer);
enableI2CRepeater(false);
}
else
{
write(address, Block.I2C, buffer);
}
}
/**
* Writes to the demod register
* @param page of register
* @param address of resister
* @param value to write
* @param length of value in bytes
* @throws LibUsbException on error
*/
private void writeDemodRegister(Page page, short address, int value, int length) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect(length);
buffer.order(ByteOrder.BIG_ENDIAN);
if(length == 1)
{
buffer.put((byte) (value & 0xFF));
}
else if(length == 2)
{
buffer.putShort((short) (value & 0xFFFF));
}
else
{
throw new IllegalArgumentException("Cannot write value greater than 16 bits to the register - length [" +
length + "]");
}
short index = (short) (0x10 | page.getPage());
short newAddress = (short) (address << 8 | 0x20);
write(newAddress, index, buffer);
readDemodRegister(Page.TEN, (short) 1, length);
}
/**
* Reads the demod register
* @param page of register
* @param address of register
* @param length of value to read in bytes
* @return value read
* @throws LibUsbException on error
*/
private int readDemodRegister(Page page, short address, int length) throws LibUsbException
{
short index = page.getPage();
short newAddress = (short) ((address << 8) | 0x20);
ByteBuffer buffer = ByteBuffer.allocateDirect(length);
read(newAddress, index, buffer);
buffer.order(ByteOrder.LITTLE_ENDIAN);
if(length == 2)
{
return (buffer.getShort() & 0xFFFF);
}
else
{
return (buffer.get() & 0xFF);
}
}
/**
* Writes a value to the register
* @param block of register
* @param address of register
* @param value to write
* @param length of value in bytes
* @throws LibUsbException on error
*/
private void writeRegister(Block block, Address address, int value, int length) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect(length);
buffer.order(ByteOrder.BIG_ENDIAN);
if(length == 1)
{
buffer.put((byte) (value & 0xFF));
}
else if(length == 2)
{
buffer.putShort((short) value);
}
else
{
throw new IllegalArgumentException("Cannot write value greater than 16 bits to the register - length [" +
length + "]");
}
buffer.rewind();
write(address.getAddress(), block, buffer);
}
/**
* Reads a value from a register
* @param block of register
* @param address of register
* @param length of value to read
* @return value read
* @throws LibUsbException on error
*/
private int readRegister(Block block, Address address, int length) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect(2);
read(address.getAddress(), block, buffer);
buffer.order(ByteOrder.LITTLE_ENDIAN);
if(length == 2)
{
return (buffer.getShort() & 0xFFFF);
}
else
{
return (buffer.get() & 0xFF);
}
}
/**
* Writes a value
* @param address of register
* @param block of register
* @param buffer containing value to write
* @throws LibUsbException on error
*/
private void write(short address, Block block, ByteBuffer buffer) throws LibUsbException
{
write(address, block.getWriteIndex(), buffer);
}
/**
* Performs a control type write
* @param value to write
* @param index to write value to
* @param buffer contents to write
* @throws LibUsbException if there is an error
*/
private void write(short value, short index, ByteBuffer buffer) throws LibUsbException
{
if(hasDeviceHandle())
{
int transferred = LibUsb.controlTransfer(getDeviceHandle(), CONTROL_ENDPOINT_OUT, REQUEST_ZERO, value,
index, buffer, TIMEOUT_US);
if(transferred < 0)
{
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);
}
}
/**
* Performs a control type read
* @param address to read
* @param index to read
* @param buffer to store read content
*/
private void read(short address, short index, ByteBuffer buffer) throws LibUsbException
{
if(isRunning())
{
int transferred = LibUsb.controlTransfer(getDeviceHandle(), CONTROL_ENDPOINT_IN, REQUEST_ZERO, address,
index, buffer, TIMEOUT_US);
if(transferred < 0)
{
throw new LibUsbException("read error", transferred);
}
else if(transferred != buffer.capacity())
{
throw new LibUsbException("transferred bytes [" + transferred + "] is not what was expected [" +
buffer.capacity() + "]", transferred);
}
}
}
/**
* Reads byte array from index at the address.
*
* @return big-endian byte array (needs to be swapped to be usable)
*/
private void read(short address, Block block, ByteBuffer buffer) throws LibUsbException
{
read(address, block.getReadIndex(), buffer);
}
/**
* Tests if the specified tuner type is contained in the usb tuner device.
*
* @param type - tuner type to test for
* @param controlI2CRepeater - indicates if the method should control the I2C repeater independently
* @return - true if the device is the specified tuner type
*/
private boolean isTuner(TunerTypeCheck type, boolean controlI2CRepeater)
{
try
{
if(type == TunerTypeCheck.FC0012 || type == TunerTypeCheck.FC2580)
{
/* Initialize the GPIOs */
setGPIOOutput((byte) 0x20);
/* Reset tuner before probing */
setGPIOBit((byte) 0x20, true);
setGPIOBit((byte) 0x20, false);
}
int value = readI2CRegister(type.getI2CAddress(), type.getCheckAddress(), controlI2CRepeater);
if(type == TunerTypeCheck.FC2580)
{
return ((value & 0x7F) == (type.getCheckValue() & 0xFF));
}
else
{
return (value == (type.getCheckValue() & 0xFF));
}
}
catch(LibUsbException e)
{
//Do nothing ... it's not the specified tuner
}
return false;
}
public double getCurrentSampleRate()
{
return mSampleRate.getRate();
}
public int getSampleRateFromTuner() throws SourceException
{
int returnRate = DEFAULT_SAMPLE_RATE.getRate();
getLock().lock();
try
{
int high = readDemodRegister(Page.ONE, (short) 0x9F, 2);
int low = readDemodRegister(Page.ONE, (short) 0xA1, 2);
int ratio = Integer.rotateLeft(high, 16) | low;
int rate = (mOscillatorFrequency * TWO_TO_22_POWER / ratio);
SampleRate sampleRate = SampleRate.getClosest(rate);
/* If we're not currently set to this rate, set it as the current rate */
if(sampleRate.getRate() != rate)
{
setSampleRate(sampleRate);
returnRate = sampleRate.getRate();
}
}
catch(Exception e)
{
throw new SourceException("RTL2832 Tuner Controller - cannot get current sample rate", e);
}
finally
{
getLock().unlock();
}
return returnRate;
}
/**
* Sets the sampling rate of the RTL2832
* @param sampleRate to apply
* @throws SourceException
*/
public void setSampleRate(SampleRate sampleRate) throws SourceException
{
getLock().lock();
try
{
/* Write high-order 16-bits of sample rate ratio to demod register */
writeDemodRegister(Page.ONE, (short) 0x9F, sampleRate.getRatioHighBits(), 2);
/* Write low-order 16-bits of sample rate ratio to demod register.
* Note: none of the defined rates have a low order ratio value, so we
* simply write a zero to the register */
writeDemodRegister(Page.ONE, (short) 0xA1, 0, 2);
/* Set sample rate correction to 0 */
setSampleRateFrequencyCorrection(0);
/* Reset the demod for the changes to take effect */
writeDemodRegister(Page.ONE, (short) 0x01, 0x14, 1);
writeDemodRegister(Page.ONE, (short) 0x01, 0x10, 1);
/* Apply any tuner specific sample rate filter settings */
setSampleRateFilters(sampleRate.getRate());
mSampleRate = sampleRate;
mFrequencyController.setSampleRate(sampleRate.getRate());
//Updates native buffer factory so that sample buffers can be accurately timestamped
getNativeBufferFactory().setSamplesPerMillisecond(sampleRate.getRate() / 1000.0f);
}
finally
{
getLock().unlock();
}
}
/**
* Determines the size of USB transfer buffers according to the sample rate
*/
private int getUSBTransferBufferSize(double sampleRate)
{
return USB_TRANSFER_BUFFER_SIZE;
}
public void setSampleRateFrequencyCorrection(int ppm) throws SourceException
{
int offset = -ppm * TWO_TO_22_POWER / 1_000_000;
writeDemodRegister(Page.ONE, (short) 0x3F, (offset & 0xFF), 1);
writeDemodRegister(Page.ONE, (short) 0x3E, (Integer.rotateRight(offset, 8) & 0xFF), 1);
/* Test to retune controller to apply frequency correction */