forked from glidernet/ogn-rf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtlsdr.h
349 lines (286 loc) · 12.8 KB
/
rtlsdr.h
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
/*
OGN - Open Glider Network - http://glidernet.org/
Copyright (c) 2015 The OGN Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 software. If not, see <http://www.gnu.org/licenses/>.
*/
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include "alloc.h"
#include "asciitime.h"
#include "thread.h"
#include "buffer.h"
// =================================================================================
#include <rtl-sdr.h>
class RTLSDR {
public:
MutEx Lock; // for multi-threading
uint32_t DeviceIndex; // RTL dongle index
rtlsdr_dev_t *Device; // RTL dongle handle
int Gains; // number of possible gain settings
int *Gain; // [0.1 dB] list of possible gain settings
uint64_t BytesRead; // Counts number of bytes read (1 sample = 2 bytes: I/Q)
int (*Callback)(uint8_t *Buffer, int Samples, double SampleTime, double SamplePeriod, void *Contex);
void *CallbackContext;
#ifndef __MACH__ // _POSIX_TIMERS
clockid_t RefClock; // CLOCK_REALTIME, CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW
#endif
double SampleTime; // [sec] time when a batch of samples starts
double StartTime; // [sec] time when acquisition started
double AverPeriod; // [sec] averaging period for TimeRef, TimeRef_DMS and SamplePeriod
double SamplePeriod; // [sec] time per sample
double PrevTime; // [sec]
double SampleTime_DMS; // [sec^2] mean square variation of SampleTime
public:
RTLSDR() {
DeviceIndex = 0;
Device = 0;
Gain = 0;
Callback = 0;
CallbackContext = 0;
AverPeriod = 100.0;
#ifndef __MACH__ // _POSIX_TIMERS
RefClock = CLOCK_REALTIME;
#endif
}
~RTLSDR() {
Close();
}
bool isOpen(void) const {
return Device != 0;
}
void Close(void) {
if (Device) { // printf("RTLSDR::Close() => %3.1f MB read, %3.1f samples/sec\n", BytesRead/(1024*1024.0), 1.0/SamplePeriod);
rtlsdr_cancel_async(Device);
rtlsdr_close(Device);
}
free(Gain);
Gain = 0;
Gains = 0;
// free(SampleTimePipe); free(SampleIdxPipe); PipeSize=0; SampleTimePipe=0; SampleIdxPipe=0;
Device = 0;
Callback = 0;
}
int getNumberOfDevices(void) {
return rtlsdr_get_device_count();
} // number of connected devices (USB RTL dongles)
int getDeviceUsbStrings(uint32_t DeviceIndex, char *Manufacturer, char *Product, char *Serial) {
return rtlsdr_get_device_usb_strings(DeviceIndex, Manufacturer, Product, Serial);
} // USB description strings
const char *getDeviceName(uint32_t DeviceIndex) {
return rtlsdr_get_device_name(DeviceIndex);
} // name of given device
const char *getDeviceName() {
return rtlsdr_get_device_name(DeviceIndex);
} // name of this device open by this object
int ReadEEPROM(uint8_t *Data, uint8_t Offset, uint16_t Size) {
return rtlsdr_read_eeprom(Device, Data, Offset, Size);
} // read the EEPROM
int WriteEEPROM(uint8_t *Data, uint8_t Offset, uint16_t Size) {
return rtlsdr_write_eeprom(Device, Data, Offset, Size);
} // write the EEPROM
int setOffsetTuning(int ON = 1) {
return rtlsdr_set_offset_tuning(Device, ON);
}
int getOffsetTuning(void) {
return rtlsdr_get_offset_tuning(Device);
}
int setCenterFreq(uint32_t Frequency) {
return rtlsdr_set_center_freq(Device, Frequency);
} // [Hz]
uint32_t getCenterFreq(void) {
return rtlsdr_get_center_freq(Device);
} // (fast call)
int setFreqCorrection(int PPM) {
return rtlsdr_set_freq_correction(Device, PPM);
} // [PPM] (Part-Per-Million)
int getFreqCorrection(void) {
return rtlsdr_get_freq_correction(Device);
} // (fast call)
int setTunerGain(int Gain) {
return rtlsdr_set_tuner_gain(Device, Gain);
} // [0.1 dB] set tuner gain when in manual mode
int getTunerGain(void) {
return rtlsdr_get_tuner_gain(Device);
}
int setTunerGainMode(int Manual = 1) {
return rtlsdr_set_tuner_gain_mode(Device, Manual);
} // set radio-tuner gain mode: manual or automatic
int setTunerGainManual(int Manual = 1) {
return setTunerGainMode(Manual);
} // set manual mode
int setTunerGainAuto(void) {
return setTunerGainManual(0);
} // set automatic mode
int setTestMode(int Test = 1) {
return rtlsdr_set_testmode(Device, Test);
} // Enable/Disable test mode - a counter is send, not real data
int ResetBuffer(void) {
return rtlsdr_reset_buffer(Device);
} // obligatory, the docs say, before you start reading
double getTime(void) const // read the system time at this very moment
#ifndef __MACH__ // _POSIX_TIMERS
{
struct timespec now;
clock_gettime(RefClock, &now);
return now.tv_sec + 1e-9 * now.tv_nsec;
}
#else // for OSX, there is no clock_gettime()
{
struct timeval now;
gettimeofday(&now, 0);
return now.tv_sec + 1e-6 * now.tv_usec;
}
#endif
int setSampleRate(uint32_t SampleRate) {
SamplePeriod = 1.0 / SampleRate;
SampleTime_DMS = 0.0001 * 0.0001;
return rtlsdr_set_sample_rate(Device, SampleRate);
} // [samples-per-second]
uint32_t getSampleRate(void) {
return rtlsdr_get_sample_rate(Device);
}
int getDeviceIndexBySerial(const char *Serial) {
return rtlsdr_get_index_by_serial(Serial);
}
int Open(uint32_t DeviceIndex = 0, uint32_t Frequency = 868000000, uint32_t SampleRate = 2048000) // open given device (by the index)
{
Close();
this->DeviceIndex = DeviceIndex;
if (rtlsdr_open(&Device, DeviceIndex) < 0) // open the RTLSDR device
{
printf("Cannot open device #%d\n", DeviceIndex);
Device = 0;
return -1;
}
if (setCenterFreq(Frequency) < 0) // set the desired frequency
{
printf("Cannot set the frequency %d for device #%d\n", Frequency, DeviceIndex);
}
if (setSampleRate(SampleRate) < 0) // set the desired sample rate
{
printf("Cannot set the sample rate %d for device #%d\n", SampleRate, DeviceIndex);
}
Gains = rtlsdr_get_tuner_gains(Device, 0); // get list of possible tuner gains
printf("RTLSDR::Open(%d,%d,%d) => %s, %8.3f MHz, %5.3f Msps\n",
DeviceIndex, Frequency, SampleRate, getDeviceName(), 1e-6 * getCenterFreq(), 1e-6 * getSampleRate());
if (Gains <= 0) Gains = 0;
else {
Malloc(Gain, Gains);
rtlsdr_get_tuner_gains(Device, Gain);
}
// PrintGains();
if (ResetBuffer() < 0) // reset the buffers (after the manual...)
{
printf("Cannot reset buffer for device #%d\n", DeviceIndex);
}
return 1;
}
void PrintGains(void) const {
printf("RTLSDR::Gain[%d] =", Gains);
for (int Idx = 0; Idx < Gains; Idx++)
printf(" %+5.1f", 0.1 * Gain[Idx]);
printf("\n");
}
double SampleTimeJitter(void) {
return sqrt(SampleTime_DMS);
}
static void StaticCallback(unsigned char *Buffer, uint32_t Len, void *Contex) // callback that receives the data
{
RTLSDR *This = (RTLSDR *) Contex;
return This->ClassCallback(Buffer, Len);
} // "This" points now to this class instance
void ClassCallback(unsigned char *Buffer, uint32_t Len) // callback but already in this class instance
{
Lock.Lock();
int Samples = Len / 2; // number of samples is half the buffer size
BytesRead += Len; // count number of bytes read
double ReadTime = getTime(); // read the time at this moment
/*
uint32_t PrevSampleIdx=SampleIdxPipe[PipeWrite]; // previous SampleIdx
PipeWrite++; if(PipeWrite>=PipeSize) PipeWrite=0; // advance pipe write pointer
double FirstSampleTime = SampleTimePipe[PipeRead];
uint32_t FirstSampleIdx = SampleIdxPipe[PipeRead];
if(PipeWrite==PipeRead) { PipeRead++; if(PipeRead>=PipeSize) PipeRead=0; }
SampleTimePipe[PipeWrite]=ReadTime; // ReadTime -> Pipe
SampleIdxPipe[PipeWrite]=PrevSampleIdx+Samples; // next SampleIdx -> Pipe
double SampleTimeDiff = ReadTime-FirstSampleTime;
uint32_t SampleIdxDiff = (PrevSampleIdx+Samples)-FirstSampleIdx;;
*/
double AcqTime = Samples * SamplePeriod; // time it took to acquire these samples
double AverWeight = AcqTime / AverPeriod; // ratio: acquisition period : averaging period
int Ret = 0;
if (Callback) {
Ret = (*(Callback))(Buffer, Samples, // buffer, number of samples
SampleTime - Samples*SamplePeriod, SamplePeriod, // SampleTime = time of the first sample, SamplePeriod = time period of one sample
CallbackContext);
}
if (Ret) CancelAsync(); // call the user callback, if it returns non-zero, then stop data acquisition
SampleTime += Samples * SamplePeriod; // increment predicted time for this batch
double TimeDiff = ReadTime - SampleTime; // difference: time read now versus predicted time
SampleTime += 0.125 * TimeDiff; // follow the ReadTime with weight 1/8 (a bit arbitrary...)
SampleTime_DMS += AverWeight * (TimeDiff * TimeDiff - SampleTime_DMS); // integrate the difference RMS
double PeriodDiff = (ReadTime - PrevTime) - AcqTime; // difference: measured time period to acquire this batch versus predicted time period
SamplePeriod += AverWeight * (PeriodDiff / Samples);
PrevTime = ReadTime;
// printf("%14.3f (%+7.3f:%+7.3f ms): RTLSDR::Callback( , %d, ) => %10.1f (%10.1f) samples/sec, %6.3f ms\r",
// ReadTime, 1e3*TimeDiff, 1e3*PeriodDiff, Len, 1.0/SamplePeriod, SampleIdxDiff/SampleTimeDiff, 1e3*SampleTimeJitter() );
/*
char Time[24]; AsciiTime_DDDDDHHMMSSFFF(Time, ReadTime);
printf("%s (%+7.3f:%+7.3f ms): RTLSDR::Callback( , %d, ) => %10.1f samples/sec, %6.3f ms\r",
Time, 1e3*TimeDiff, 1e3*PeriodDiff, Len, 1.0/SamplePeriod, 1e3*SampleTimeJitter() );
fflush(stdout);
*/
Lock.Unlock();
}
// read in async. mode, call Callback() for the data being received, block, wait and return when Callback() returns non-zero
int ReadAsync(int (*Callback)(uint8_t *Buffer, int Samples, double SampleTime, double SamplePeriod, void *Contex) = 0, void *Contex = 0,
int Buffers = 0, int BlockSize = 0) {
this->Callback = Callback;
StartTime = SampleTime = PrevTime = getTime();
this->CallbackContext = Contex;
// SampleTimePipe[0]=SampleTime; SampleIdxPipe[0]=0; PipeWrite=0; PipeRead=0;
return rtlsdr_read_async(Device, StaticCallback, this, Buffers, BlockSize);
}
int CancelAsync(void) {
return rtlsdr_cancel_async(Device);
}
// read directly given number of samples (remember to ResetBuffer() !)
int Read(uint8_t *Buffer, int Samples) {
Samples &= 0xFFFFFF00; // number of samples must be a multiply of 256
int BufferSize = 2 * Samples;
int ReadSize = 0;
if (rtlsdr_read_sync(Device, Buffer, BufferSize, &ReadSize) < 0) return -1;
return ReadSize / 2;
}
int Read(SampleBuffer<uint8_t> &Buffer, int Samples) {
if (Buffer.Allocate(2, Samples) <= 0) return 0;
int ReadSamples = Read(Buffer.Data, Samples);
double Time = getTime();
if (ReadSamples > 0) {
Buffer.Full = ReadSamples * 2;
Buffer.Rate = getSampleRate();
Buffer.Freq = getCenterFreq();
Buffer.Time = Time - (double) ReadSamples / Buffer.Rate;
}
return ReadSamples;
}
};
// =================================================================================