-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathlimesdr_io_impl.cpp
1232 lines (930 loc) · 32.7 KB
/
limesdr_io_impl.cpp
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) 2016-2017 Jiang Wei <jiangwei@jiangwei.org>
// Copyright (c) 2015-2016 Josh Blum
// Copyright 2013-2015 Ettus Research LLC
//
// 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/>.
//
#include "limesdr_impl.hpp"
#include <vector>
#include <map>
#include <algorithm>
#include <set>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace uhd;
using namespace uhd::usrp;
using namespace lime;
#define MIN_CGEN_RATE 6.4e6
#define MAX_CGEN_RATE 640e6
#define MIN_SAMP_RATE 1e5
#define MAX_SAMP_RATE 65e6
#define CGEN_DEADZONE_LO 450e6
#define CGEN_DEADZONE_HI 491.5e6
class LimeRxStream : public uhd::rx_streamer {
public:
LimeRxStream(lime::IConnection * c, const uhd::stream_args_t &args) :
_conn(c),
_elemSize(uhd::convert::get_bytes_per_item(args.cpu_format)),
_nchan(std::max<size_t>(1, args.channels.size())),
_activated(false),
_fc64(false)
{
StreamConfig config;
config.isTx = false;
config.performanceLatency = 0.5;
//default to channel 0, if none were specified
const std::vector<size_t> &channelIDs = args.channels.empty() ? std::vector<size_t>(1, 0) : args.channels;
for (size_t i = 0; i < channelIDs.size(); ++i)
{
config.channelID = (uint8_t)channelIDs[i];
if (args.cpu_format == "fc32") config.format = StreamConfig::STREAM_COMPLEX_FLOAT32;
else if (args.cpu_format == "sc16") config.format = StreamConfig::STREAM_12_BIT_IN_16;
else if (args.cpu_format == "fc64") {
config.format = StreamConfig::STREAM_COMPLEX_FLOAT32;
_fc64 = true;
}
else throw uhd::runtime_error("OpenUSRP::LimeRxStream(format=" + args.cpu_format + ") unsupported format");
//create the stream
size_t stream_id(~0);
const int status = _conn->SetupStream(stream_id, config);
if (status != 0)
throw uhd::runtime_error("OpenUSRP::LimeRxStream() failed: ");
streamID.push_back(stream_id);
}
}
~LimeRxStream(void) {
if (_activated) {
for (auto i : streamID)
_conn->ControlStream(i, false);
for (auto i : streamID)
_conn->CloseStream(i);
_activated = false;
}
}
size_t get_num_channels(void) const
{
return _nchan;
}
size_t get_max_num_samps(void) const
{
return _conn->GetStreamSize(streamID.front());
}
size_t recv(
const buffs_type &buffs,
const size_t nsamps_per_buff,
uhd::rx_metadata_t &md,
const double timeout = 1,
const bool one_packet = false
) {
size_t total = 0;
const auto exitTime = boost::chrono::high_resolution_clock::now() + boost::chrono::microseconds(long(timeout*1e6));
if (not _activated) {
while (boost::chrono::high_resolution_clock::now() < exitTime) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
}
md.error_code = uhd::rx_metadata_t::ERROR_CODE_TIMEOUT;
return 0;
}
size_t numElems = nsamps_per_buff;
if (one_packet)
numElems = std::min(numElems, _conn->GetStreamSize(streamID.front()));
StreamMetadata metadata;
if (md.has_time_spec) {
metadata.hasTimestamp = true;
metadata.timestamp = md.time_spec.to_ticks(_conn->GetHardwareTimestampRate());
}
md.reset();
int bufIndex = 0;
int status = 0;
for (auto i : streamID)
{
if (_fc64) {
float *buffer = new float[numElems * 2];
status = _conn->ReadStream(i, buffer, numElems, timeout * 1000, metadata);
double *ptr = (double*)buffs[bufIndex++];
for (size_t i = 0; i < numElems * 2; i++)
ptr[i] = (double)buffer[i];
delete[] buffer;
}
else {
status = _conn->ReadStream(i, buffs[bufIndex++], numElems, timeout * 1000, metadata);
}
if (status == 0) {
md.error_code = uhd::rx_metadata_t::ERROR_CODE_TIMEOUT;
return 0;
}
if (status < 0) {
md.error_code = uhd::rx_metadata_t::ERROR_CODE_BROKEN_CHAIN;
return 0;
}
}
if (metadata.hasTimestamp)
{
md.has_time_spec = true;
md.time_spec = uhd::time_spec_t::from_ticks(metadata.timestamp, _conn->GetHardwareTimestampRate());
}
if (metadata.packetDropped)
md.error_code = uhd::rx_metadata_t::ERROR_CODE_OVERFLOW;
if (metadata.endOfBurst)
md.end_of_burst = true;
return status;
}
void issue_stream_cmd(const uhd::stream_cmd_t &stream_cmd) {
switch (stream_cmd.stream_mode)
{
case uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS: {
if (not _activated) {
for (auto i : streamID) {
int status = _conn->ControlStream(i, true);
}
_activated = true;
}
}
break;
case uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS: {
if (_activated) {
for (auto i : streamID)
{
_conn->ControlStream(i, false);
}
_activated = false;
}
}
break;
case uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE:
//TODO//
break;
case uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_MORE:
//TODO//
break;
}
}
private:
lime::IConnection *_conn;
bool _fc64;
std::vector<size_t> streamID;
size_t _elemSize;
bool _activated;
const size_t _nchan;
};
class LimeTxStream : public uhd::tx_streamer
{
public:
LimeTxStream(lime::IConnection * c, const uhd::stream_args_t &args) :
_conn(c),
_nchan(std::max<size_t>(1, args.channels.size())),
_activated(false),
_fc64(false)
{
StreamConfig config;
config.isTx = true;
config.performanceLatency = 0.5;
//default to channel 0, if none were specified
const std::vector<size_t> &channelIDs = args.channels.empty() ? std::vector<size_t>(1, 0) : args.channels;
for (size_t i = 0; i < channelIDs.size(); ++i)
{
config.channelID = (uint8_t)channelIDs[i];
if (args.cpu_format == "fc32") config.format = StreamConfig::STREAM_COMPLEX_FLOAT32;
else if (args.cpu_format == "sc16") config.format = StreamConfig::STREAM_12_BIT_IN_16;
else if (args.cpu_format == "fc64") {
config.format = StreamConfig::STREAM_COMPLEX_FLOAT32;
_fc64 = true;
}
else throw uhd::runtime_error("OpenUSRP::LimeTxStream(format=" + args.cpu_format + ") unsupported format");
//create the stream
size_t stream_id(~0);
const int status = _conn->SetupStream(stream_id, config);
if (status != 0)
throw uhd::runtime_error("OpenUSRP::LimeTxStream() failed: ");
streamID.push_back(stream_id);
}
}
~LimeTxStream(void) {
if (_activated) {
for (auto i : streamID)
_conn->ControlStream(i, false);
for (auto i : streamID)
_conn->CloseStream(i);
_activated = false;
}
}
size_t get_num_channels(void) const
{
return _nchan;
}
size_t get_max_num_samps(void) const
{
return _conn->GetStreamSize(streamID.front());
}
size_t send(
const buffs_type &buffs,
const size_t _nsamps_per_buff,
const uhd::tx_metadata_t &md,
const double timeout = 0.1
) {
size_t numElems = _nsamps_per_buff;
size_t total = 0;
if (numElems == 0)
return 0;
if (not _activated) {
for (auto i : streamID)
{
int status = _conn->ControlStream(i, true);
}
_activated = true;
}
StreamMetadata metadata;
if (md.has_time_spec) {
metadata.hasTimestamp = true;
metadata.timestamp = md.time_spec.to_ticks(_conn->GetHardwareTimestampRate());
}
if (md.end_of_burst) {
metadata.endOfBurst = true;
}
int bufIndex = 0;
int status = 0;
for (auto i : streamID)
{
if (_fc64) {
float *buffer = new float[numElems * 2];
double *ptr = (double*)buffs[bufIndex++];
for (size_t i = 0; i < numElems * 2; i++)
buffer[i] = (float)ptr[i];
status = _conn->WriteStream(i, buffer, numElems, timeout * 1000, metadata);
delete[] buffer;
}
else {
status = _conn->WriteStream(i, buffs[bufIndex++], numElems, timeout * 1000, metadata);
}
}
return status;
}
bool recv_async_msg(uhd::async_metadata_t &md, double timeout = 0.1) {
auto start = boost::chrono::high_resolution_clock::now();
StreamMetadata metadata;
while (true) {
int channel = 0;
for (auto i : streamID) {
md.channel = channel;
int ret = _conn->ReadStreamStatus(i, timeout * 1000, metadata);
if (ret != 0) {
return false;
}
channel++;
}
if (metadata.endOfBurst || metadata.lateTimestamp || metadata.packetDropped)
break;
boost::chrono::duration<double> seconds = boost::chrono::high_resolution_clock::now() - start;
if (seconds.count()> (double)timeout)
return false;
boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
}
if (metadata.endOfBurst)
md.event_code = uhd::async_metadata_t::EVENT_CODE_BURST_ACK;
if (metadata.hasTimestamp) {
md.has_time_spec = true;
md.time_spec = uhd::time_spec_t::from_ticks(metadata.timestamp, _conn->GetHardwareTimestampRate());
}
if (metadata.packetDropped) {
md.event_code = uhd::async_metadata_t::EVENT_CODE_UNDERFLOW;
return true;
}
if (metadata.lateTimestamp) {
md.event_code = uhd::async_metadata_t::EVENT_CODE_TIME_ERROR;
return true;
}
return true;
}
private:
lime::IConnection *_conn;
std::vector<size_t> streamID;
bool _fc64;
bool _activated;
const size_t _nchan;
};
uhd::rx_streamer::sptr limesdr_impl::get_rx_stream(const uhd::stream_args_t &args)
{
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
if (not _rx_streamers[0].expired())
return _rx_streamers[0].lock();
while (not _channelsToCal.empty())
{
auto dir = _channelsToCal.begin()->first;
auto ch = _channelsToCal.begin()->second;
if (dir == RX_DIRECTION) getRFIC(ch)->CalibrateRx(_actualBw.at(dir).at(ch));
if (dir == TX_DIRECTION) getRFIC(ch)->CalibrateTx(_actualBw.at(dir).at(ch));
_channelsToCal.erase(_channelsToCal.begin());
}
uhd::rx_streamer::sptr stream(new LimeRxStream(_conn, args));
BOOST_FOREACH(const size_t ch, args.channels) _rx_streamers[ch] = stream;
if (args.channels.empty()) _rx_streamers[0] = stream;
return stream;
}
uhd::tx_streamer::sptr limesdr_impl::get_tx_stream(const uhd::stream_args_t &args)
{
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
if (not _tx_streamers[0].expired())
return _tx_streamers[0].lock();
while (not _channelsToCal.empty())
{
auto dir = _channelsToCal.begin()->first;
auto ch = _channelsToCal.begin()->second;
if (dir == RX_DIRECTION) getRFIC(ch)->CalibrateRx(_actualBw.at(dir).at(ch));
if (dir == TX_DIRECTION) getRFIC(ch)->CalibrateTx(_actualBw.at(dir).at(ch));
_channelsToCal.erase(_channelsToCal.begin());
}
uhd::tx_streamer::sptr stream(new LimeTxStream(_conn, args));
BOOST_FOREACH(const size_t ch, args.channels) _tx_streamers[ch] = stream;
if (args.channels.empty()) _tx_streamers[0] = stream;
return stream;
}
bool limesdr_impl::recv_async_msg(uhd::async_metadata_t &md, double timeout)
{
uhd::tx_streamer::sptr stream = _tx_streamers[0].lock();
if (not stream) return false;
return stream->recv_async_msg(md, timeout);
}
uhd::meta_range_t limesdr_impl::getSampleRange(const uhd::direction_t direction, const size_t channel) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
std::vector<double> rates;
const double clockRate = _rfics.front()->GetFrequencyCGEN();
const double dacFactor = clockRate / rfic->GetReferenceClk_TSP(LMS7002M::Tx);
const double adcFactor = clockRate / rfic->GetReferenceClk_TSP(LMS7002M::Rx);
const double dspRate = rfic->GetReferenceClk_TSP(lmsDir);
const bool fixedRx = _fixedRxSampRate.count(channel) != 0 and _fixedRxSampRate.at(channel);
const bool fixedTx = _fixedTxSampRate.count(channel) != 0 and _fixedTxSampRate.at(channel);
//clock rate is fixed, only half-band chain is configurable
if (not _autoTickRate)
{
for (int i = 32; i >= 2; i /= 2) rates.push_back(dspRate / i);
}
//special rates when looking for rx rates and tx is fixed
//return all rates where the tx sample rate is achievable
else if (direction == RX_DIRECTION and fixedTx)
{
const double txRate = this->getSampleRate(TX_DIRECTION, channel);
for (int iTx = 32; iTx >= 2; iTx /= 2)
{
const double clockRate = txRate*dacFactor*iTx;
if (clockRate > MAX_CGEN_RATE) continue;
if (clockRate > CGEN_DEADZONE_LO and clockRate < CGEN_DEADZONE_HI) continue;
for (int iRx = 32; iRx >= 2; iRx /= 2)
{
const double rxRate = clockRate / (adcFactor*iRx);
if (rxRate > MAX_SAMP_RATE) continue;
if (rxRate < MIN_SAMP_RATE) continue;
rates.push_back(rxRate);
}
}
}
//special rates when looking for tx rates and rx is fixed
//return all rates where the rx sample rate is achievable
else if (direction == TX_DIRECTION and fixedRx)
{
const double rxRate = this->getSampleRate(RX_DIRECTION, channel);
for (int iRx = 32; iRx >= 2; iRx /= 2)
{
const double clockRate = rxRate*adcFactor*iRx;
for (int iTx = 32; iTx >= 2; iTx /= 2)
{
const double txRate = clockRate / (dacFactor*iTx);
if (txRate > MAX_SAMP_RATE) continue;
if (txRate < MIN_SAMP_RATE) continue;
rates.push_back(txRate);
}
}
}
//otherwise, the clock is the only limiting factor
//just give a reasonable high and low
else
{
rates.push_back(MIN_SAMP_RATE);
rates.push_back(MAX_SAMP_RATE);
}
std::sort(rates.begin(), rates.end());
uhd::meta_range_t out;
for (size_t i = 0; i < rates.size(); i++)
{
out.push_back(uhd::range_t(rates[i]));
}
if (out.empty()) out.push_back(uhd::range_t(0.0));
return out;
}
double limesdr_impl::getSampleRate(const uhd::direction_t direction, const size_t channel) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
return rfic->GetSampleRate(lmsDir, rfic->GetActiveChannel());
}
static double calculateClockRate(
const int adcFactorRx,
const int dacFactorTx,
const double rateRx,
const double rateTx,
int &dspFactorRx,
int &dspFactorTx)
{
double bestClockRate = 0.0;
for (int decim = 2; decim <= 32; decim *= 2)
{
const double rateClock = rateRx*decim*adcFactorRx;
if (rateClock > MAX_CGEN_RATE) continue;
if (rateClock > CGEN_DEADZONE_LO && rateClock < CGEN_DEADZONE_HI) continue; //avoid range where CGEN does not lock
if (rateClock < bestClockRate) continue;
for (int interp = 2; interp <= 32; interp *= 2)
{
const double actualRateTx = rateClock / (interp*dacFactorTx);
//good if we got the same output rate with small margin of error
if (std::abs(actualRateTx - rateTx) < 10.0)
{
bestClockRate = rateClock;
dspFactorRx = decim;
dspFactorTx = interp;
}
}
}
//return the best possible match
if (bestClockRate != 0.0)
return bestClockRate;
std::cout << boost::format(
"OpenUSRP::setSampleRate(Rx %g MHz, Tx %g MHz) Failed -- no common clock rate.\n"
) % (rateRx / 1e6) % (rateTx / 1e6) << std::endl;
throw uhd::runtime_error("OpenUSRP::setSampleRate() -- no common clock rate");
}
void limesdr_impl::setSampleRate(const uhd::direction_t direction, const size_t channel, const double rate) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
LMS7002M_SelfCalState state(rfic);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
double clockRate = _rfics.front()->GetFrequencyCGEN();
const double dspFactor = clockRate / rfic->GetReferenceClk_TSP(lmsDir);
//select automatic clock rate
if (_autoTickRate)
{
double rxRate = rate, txRate = rate;
if (direction != RX_DIRECTION and _fixedRxSampRate[channel]) rxRate = this->getSampleRate(RX_DIRECTION, channel);
if (direction != TX_DIRECTION and _fixedTxSampRate[channel]) txRate = this->getSampleRate(TX_DIRECTION, channel);
clockRate = calculateClockRate(
clockRate / rfic->GetReferenceClk_TSP(LMS7002M::Rx),
clockRate / rfic->GetReferenceClk_TSP(LMS7002M::Tx),
rxRate, txRate, _decims[channel], _interps[channel]
);
}
const double dspRate = clockRate / dspFactor;
const double factor = dspRate / rate;
int intFactor = 1 << int((std::log(factor) / std::log(2.0)) + 0.5);
if (intFactor < 2) throw uhd::runtime_error(str(boost::format("OpenUSRP::setSampleRate(%g) -- rate too high") % (rate)));
if (intFactor > 32) throw uhd::runtime_error(str(boost::format("OpenUSRP::setSampleRate(%g) -- rate too low") % (rate)));
if (std::abs(factor - intFactor) > 0.01)
std::cout << boost::format(
"OpenUSRP::setSampleRate(): not a power of two factor.\n"
"TSP Rate = %g MHZ, Requested rate = %g MHz.\n"
) % (dspRate / 1e6) % (rate / 1e6) << std::endl;
if (direction == TX_DIRECTION) {
_fixedTxSampRate[channel] = true;
_interps[channel] = intFactor;
}
else {
_fixedRxSampRate[channel] = true;
_decims[channel] = intFactor;
}
int status = 0;
status = rfic->SetInterfaceFrequency(clockRate,
int(std::log(double(_interps[channel])) / std::log(2.0)) - 1,
int(std::log(double(_decims[channel])) / std::log(2.0)) - 1);
if (status != 0)
std::cout << "SetInterfaceFrequency Failed." << std::endl;
status = _conn->UpdateExternalDataRate(
rfic->GetActiveChannelIndex(),
rfic->GetSampleRate(LMS7002M::Tx, rfic->GetActiveChannel()),
rfic->GetSampleRate(LMS7002M::Rx, rfic->GetActiveChannel()));
if (status != 0)
std::cout << "UpdateExternalDataRate Failed." << std::endl;
}
double limesdr_impl::getFrequency(const uhd::direction_t direction, const size_t channel, const std::string &name) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
if (name == "RF")
{
return rfic->GetFrequencySX(lmsDir);
}
if (name == "BB")
{
int sign = 0;
int pos = 0, neg = 1;
if (direction == TX_DIRECTION) {
sign = (rfic->Get_SPI_Reg_bits(LMS7param(CMIX_SC_TXTSP)) == pos) ? 1 : -1;
}
else
{
if (rfic->Get_SPI_Reg_bits(LMS7_MASK, true) != 0) std::swap(pos, neg);
sign = (rfic->Get_SPI_Reg_bits(LMS7param(CMIX_SC_RXTSP)) == pos) ? 1 : -1;
}
return rfic->GetNCOFrequency(lmsDir, 0) * sign;
}
throw uhd::runtime_error("OpenUSRP::getFrequency(" + name + ") unknown name");
}
void limesdr_impl::setFrequency(const uhd::direction_t direction, const size_t channel, const std::string &name, const double frequency) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
if (name == "RF")
{
//clip the frequency into the allowed range
double targetRfFreq = frequency;
if (targetRfFreq < 30e6) targetRfFreq = 30e6;
if (targetRfFreq > 3.8e9) targetRfFreq = 3.8e9;
rfic->SetFrequencySX(lmsDir, targetRfFreq);
_channelsToCal.emplace(direction, channel);
return;
}
if (name == "BB")
{
int pos = 0, neg = 1;
if (direction == TX_DIRECTION) {
rfic->Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_TXTSP), (frequency == 0) ? 1 : 0);
rfic->Modify_SPI_Reg_bits(LMS7param(CMIX_SC_TXTSP), (frequency < 0) ? neg : pos);
}
else {
if (rfic->Get_SPI_Reg_bits(LMS7_MASK, true) != 0) std::swap(pos, neg);
rfic->Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), (frequency == 0) ? 1 : 0);
rfic->Modify_SPI_Reg_bits(LMS7param(CMIX_SC_RXTSP), (frequency < 0) ? neg : pos);
}
if (rfic->SetNCOFrequency(lmsDir, 0, std::abs(frequency)) != 0)
{
//rate was out of bounds, clip to the maximum frequency
const double dspRate = rfic->GetReferenceClk_TSP(lmsDir);
rfic->SetNCOFrequency(lmsDir, 0, dspRate / 2);
}
return;
}
throw uhd::runtime_error("OpenUSRP::setFrequency(" + name + ") unknown name");
}
uhd::meta_range_t limesdr_impl::getFrequencyRange(const uhd::direction_t direction, const size_t channel, const std::string &name) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
uhd::meta_range_t ranges;
if (name == "RF")
{
ranges.push_back(uhd::range_t(30e6, 3.8e9));
}
if (name == "BB")
{
const double dspRate = rfic->GetReferenceClk_TSP(lmsDir);
ranges.push_back(uhd::range_t(-dspRate / 2, dspRate / 2));
}
return ranges;
}
void limesdr_impl::old_issue_stream_cmd(const size_t chan, const uhd::stream_cmd_t &cmd) {
uhd::rx_streamer::sptr stream = _rx_streamers[chan].lock();
if (stream) stream->issue_stream_cmd(cmd);
}
void limesdr_impl::setAntenna(const uhd::direction_t direction, const size_t channel, const std::string &name) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
if (direction == RX_DIRECTION)
{
LMS7002M::PathRFE path = LMS7002M::PATH_RFE_NONE;
if (name == "TX/RX") path = (_rx_frontend_map[channel] == 0) ? LMS7002M::PATH_RFE_LNAL : LMS7002M::PATH_RFE_LNAH;
else if (name == "RX2") path = (_rx_frontend_map[channel] == 0) ? LMS7002M::PATH_RFE_LNAL : LMS7002M::PATH_RFE_LNAH;
else throw uhd::runtime_error("OpenUSRP::setAntenna(RX, " + name + ") - unknown antenna name");
rfic->SetPathRFE(path);
}
if (direction == TX_DIRECTION)
{
int band = 0;
if (name == "TX/RX") band = (_tx_frontend_map[channel] == 0) ? LMS7002M::PATH_RFE_LB1 : LMS7002M::PATH_RFE_LB2;
else throw uhd::runtime_error("OpenUSRP::setAntenna(TX, " + name + ") - unknown antenna name");
rfic->SetBandTRF(band);
}
_channelsToCal.emplace(direction, channel);
}
double limesdr_impl::getBandwidth(const uhd::direction_t direction, const size_t channel) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
try
{
return _actualBw.at(direction).at(channel);
}
catch (...)
{
return 1.0;
}
}
void limesdr_impl::setBandwidth(const uhd::direction_t direction, const size_t channel, const double bw) {
if (bw == 0.0) return; //special ignore value
if (bw<1000000.0 or bw >60000000.0) return;
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
//save dc offset mode
auto saveDcMode = this->getDCOffsetMode(direction, channel);
auto rfic = getRFIC(channel);
_actualBw[direction][channel] = bw;
if (direction == RX_DIRECTION)
{
if (rfic->TuneRxFilterWithCaching(bw) != 0)
{
std::cout << boost::format(
"OpenUSRP::setBandwidth(Rx, %d, %g MHz) Failed .\n"
) % (int(channel)) % (bw / 1e6) << std::endl;
}
}
if (direction == TX_DIRECTION)
{
if (rfic->TuneTxFilterWithCaching(bw) != 0)
{
std::cout << boost::format(
"OpenUSRP::setBandwidth(Tx, %d, %g MHz) Failed .\n"
) % (int(channel)) % (bw / 1e6) << std::endl;
}
}
//restore dc offset mode
this->setDCOffsetMode(direction, channel, saveDcMode);
_channelsToCal.emplace(direction, channel);
}
void limesdr_impl::setDCOffsetMode(const uhd::direction_t direction, const size_t channel, const bool automatic) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
if (direction == RX_DIRECTION) rfic->SetRxDCRemoval(automatic);
}
bool limesdr_impl::getDCOffsetMode(const uhd::direction_t direction, const size_t channel) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
if (direction == RX_DIRECTION) return rfic->GetRxDCRemoval();
return false;
}
void limesdr_impl::setDCOffset(const uhd::direction_t direction, const size_t channel, const std::complex<double> &offset) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
if (direction == TX_DIRECTION) rfic->SetTxDCOffset(offset.real(), offset.imag());
}
void limesdr_impl::setIQBalance(const uhd::direction_t direction, const size_t channel, const std::complex<double> &balance) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
const auto lmsDir = (direction == TX_DIRECTION) ? LMS7002M::Tx : LMS7002M::Rx;
double gain = std::abs(balance);
double gainI = 1.0; if (gain < 1.0) gainI = gain / 1.0;
double gainQ = 1.0; if (gain > 1.0) gainQ = 1.0 / gain;
rfic->SetIQBalance(lmsDir, std::arg(balance), gainI, gainQ);
}
LMS7002M * limesdr_impl::getRFIC(const size_t channel) const {
if (_rfics.size() <= channel / 2)
{
throw std::out_of_range("OpenUSRP::getRFIC(" + std::to_string(channel) + ") out of range");
}
auto rfic = _rfics.at(channel / 2);
rfic->SetActiveChannel(((channel % 2) == 0) ? LMS7002M::ChA : LMS7002M::ChB);
return rfic;
}
uhd::meta_range_t limesdr_impl::getBandwidthRange(const uhd::direction_t direction, const size_t channel) {
meta_range_t bws;
if (direction == RX_DIRECTION)
{
bws.push_back(uhd::range_t(1e6, 60e6, 1));
}
if (direction == TX_DIRECTION)
{
bws.push_back(uhd::range_t(0.8e6, 60e6, 1));
}
return bws;
}
double limesdr_impl::getGain(const uhd::direction_t direction, const size_t channel) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
if (rfic->Modify_SPI_Reg_bits(LMS7param(MAC), (channel % 2) + 1, true) != 0)
return 0;
if (direction==TX_DIRECTION)
{
int gain = rfic->Get_SPI_Reg_bits(LMS7param(LOSS_MAIN_TXPAD_TRF), true);
if (gain <= 10)
gain = 52 - gain;
else
gain = 62 - gain * 2;
int bak = rfic->Get_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), true); //backup
if (rfic->CalibrateTxGain(0, nullptr) != 0)
return 0;
int opt = rfic->Get_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), true);
gain += 20.0*log10((double)bak / (double)opt) + 0.5;
rfic->Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), bak, true); //restore
if (gain > 60)
gain = 60;
return gain/60.0*TX_GAIN_MAX;
}
else
{
const int max_gain_lna = 27;
const int max_gain_tia = 12;
int pga = rfic->Get_SPI_Reg_bits(LMS7param(G_PGA_RBB), true);
int ret = pga;
int tia = rfic->Get_SPI_Reg_bits(LMS7param(G_TIA_RFE), true);
if (tia == 3)
ret += max_gain_tia;
else if (tia == 2)
ret += max_gain_tia - 3;
int lna = rfic->Get_SPI_Reg_bits(LMS7param(G_LNA_RFE), true);
if (lna > 8)
ret += (max_gain_lna + lna - 15);
else if (lna > 1)
ret += (lna - 2) * 3;
return ret/70.0*RX_GAIN_MAX;
}
return 0;
}
void limesdr_impl::setGain(const uhd::direction_t direction, const size_t channel, const double value) {
boost::unique_lock<boost::recursive_mutex> lock(_accessMutex);
auto rfic = getRFIC(channel);
if (rfic->Modify_SPI_Reg_bits(LMS7param(MAC), (channel % 2) + 1, true) != 0)
return ;
double gain;
if (direction== TX_DIRECTION) //TX valid gain range 0-52
{
if (rfic->CalibrateTxGain(0, nullptr) != 0) //find optimal BB gain
return ;
gain = 60.0* value / TX_GAIN_MAX+0.49;