You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1390 lines
39 KiB

///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017-2021 Edouard Griffiths, F4EXB <f4exb06@gmail.com> //
// Copyright (C) 2019 Davide Gerhard <rainbow@irh.it> //
// Copyright (C) 2019 Robin Getz <robin.getz@analog.com> //
// Copyright (C) 2020 Felix Schneider <felix@fx-schneider.de> //
// Copyright (C) 2021 Christoph Berg <myon@debian.org> //
// //
// 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 as 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 V3 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 <iostream>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <regex>
#ifdef LIBIIO_V1
#include <iio/iio.h>
#else
#include <iio.h>
#endif
#include <boost/lexical_cast.hpp>
#include <QtGlobal>
#include "dsp/wfir.h"
#include "deviceplutosdr.h"
#include "deviceplutosdrbox.h"
#ifdef LIBIIO_V1
// libiio 1.x has no iio_device_identify_filename(): match the sysfs file name against
// the channel attributes first, then against the device and debug attribute names.
// type is set to 0 for a channel, 1 for a device and 2 for a debug attribute.
static const struct iio_attr *findAttrByFilename(const struct iio_device *dev, const char *filename, int& type)
{
unsigned int nbChannels = iio_device_get_channels_count(dev);
for (unsigned int i = 0; i < nbChannels; i++)
{
const struct iio_channel *chn = iio_device_get_channel(dev, i);
unsigned int nbAttrs = iio_channel_get_attrs_count(chn);
for (unsigned int j = 0; j < nbAttrs; j++)
{
const struct iio_attr *attr = iio_channel_get_attr(chn, j);
const char *attrFilename = iio_attr_get_filename(attr);
if (attrFilename && (strcmp(attrFilename, filename) == 0))
{
type = 0;
return attr;
}
}
}
const struct iio_attr *attr = iio_device_find_attr(dev, filename);
if (attr)
{
type = 1;
return attr;
}
attr = iio_device_find_debug_attr(dev, filename);
if (attr)
{
type = 2;
return attr;
}
return nullptr;
}
// Number of DMA blocks kept in flight by an iio_stream (libiio recommends 4)
static const size_t nbStreamBlocks = 4;
#endif
// In libiio 1.x channels are enabled in a mask that is applied when the stream is created
static void enableChannel(struct iio_channel *chn, struct iio_channels_mask *mask)
{
#ifdef LIBIIO_V1
iio_channel_enable(chn, mask);
#else
(void) mask;
iio_channel_enable(chn);
#endif
}
static void disableChannel(struct iio_channel *chn, struct iio_channels_mask *mask)
{
#ifdef LIBIIO_V1
iio_channel_disable(chn, mask);
#else
(void) mask;
iio_channel_disable(chn);
#endif
}
DevicePlutoSDRBox::DevicePlutoSDRBox(const std::string& uri) :
m_devSampleRate(0),
m_LOppmTenths(0),
m_lpfFIREnable(false),
m_lpfFIRBW(100.0f),
m_lpfFIRlog2Decim(0),
m_lpfFIRRxGain(0),
m_lpfFIRTxGain(0),
m_ctx(nullptr),
m_devPhy(nullptr),
m_devRx(nullptr),
m_devTx(nullptr),
m_rxBuf(nullptr),
m_txBuf(nullptr),
m_rxMask(nullptr),
m_rxStream(nullptr),
m_rxBlock(nullptr),
m_txMask(nullptr),
m_txStream(nullptr),
m_txBlock(nullptr),
m_xoInitial(0),
m_temp(0.0f),
m_rxSampleBytes(0),
m_txSampleBytes(0)
{
#ifdef LIBIIO_V1
m_ctx = iio_create_context(nullptr, uri.c_str());
if (iio_err(m_ctx)) {
m_ctx = nullptr;
}
#else
m_ctx = iio_create_context_from_uri(uri.c_str());
#endif
if (m_ctx)
{
m_devPhy = iio_context_find_device(m_ctx, "ad9361-phy");
m_devRx = iio_context_find_device(m_ctx, "cf-ad9361-lpc");
m_devTx = iio_context_find_device(m_ctx, "cf-ad9361-dds-core-lpc");
}
else
{
qCritical("DevicePlutoSDRBox::DevicePlutoSDRBox: cannot create context for uri: %s", uri.c_str());
}
#ifdef LIBIIO_V1
if (m_ctx && m_devRx) {
m_rxMask = iio_create_channels_mask(iio_device_get_channels_count(m_devRx));
}
if (m_ctx && m_devTx) {
m_txMask = iio_create_channels_mask(iio_device_get_channels_count(m_devTx));
}
m_valid = m_ctx && m_devPhy && m_devRx && m_devTx && m_rxMask && m_txMask;
#else
m_valid = m_ctx && m_devPhy && m_devRx && m_devTx;
#endif
if (m_valid)
{
std::regex channelIdReg("voltage([0-9]+)");
getXO();
int nbRxChannels = iio_device_get_channels_count(m_devRx);
for (int i = 0; i < nbRxChannels; i++)
{
iio_channel *chn = iio_device_get_channel(m_devRx, i);
std::string channelId(iio_channel_get_id(chn));
if (std::regex_match(channelId, channelIdReg))
{
int nbAttributes = iio_channel_get_attrs_count(chn);
m_rxChannelIds.append(QString(channelId.c_str()));
m_rxChannels.append(chn);
qDebug("DevicePlutoSDRBox::DevicePlutoSDRBox: Rx: %s #Attrs: %d", channelId.c_str(), nbAttributes);
}
}
int nbTxChannels = iio_device_get_channels_count(m_devTx);
for (int i = 0; i < nbTxChannels; i++)
{
iio_channel *chn = iio_device_get_channel(m_devTx, i);
std::string channelId(iio_channel_get_id(chn));
if (std::regex_match(channelId, channelIdReg))
{
int nbAttributes = iio_channel_get_attrs_count(chn);
m_txChannelIds.append(QString(channelId.c_str()));
m_txChannels.append(chn);
qDebug("DevicePlutoSDRBox::DevicePlutoSDRBox: Tx: %s #Attrs: %d", channelId.c_str(), nbAttributes);
}
}
}
}
DevicePlutoSDRBox::~DevicePlutoSDRBox()
{
deleteRxBuffer();
deleteTxBuffer();
closeRx();
closeTx();
#ifdef LIBIIO_V1
if (m_rxMask) { iio_channels_mask_destroy(m_rxMask); }
if (m_txMask) { iio_channels_mask_destroy(m_txMask); }
#endif
if (m_ctx) { iio_context_destroy(m_ctx); }
}
bool DevicePlutoSDRBox::probeURI(const std::string& uri)
{
bool retVal;
struct iio_context *ctx;
#ifdef LIBIIO_V1
ctx = iio_create_context(nullptr, uri.c_str());
if (iio_err(ctx)) {
ctx = nullptr;
}
#else
ctx = iio_create_context_from_uri(uri.c_str());
#endif
retVal = (ctx != 0);
if (ctx) {
iio_context_destroy(ctx);
}
return retVal;
}
void DevicePlutoSDRBox::set_params(DeviceType devType,
const std::vector<std::string>& params)
{
iio_device *dev;
switch (devType)
{
case DEVICE_PHY:
dev = m_devPhy;
break;
case DEVICE_RX:
dev = m_devRx;
break;
case DEVICE_TX:
dev = m_devTx;
break;
default:
dev = m_devPhy;
break;
}
for (std::vector<std::string>::const_iterator it = params.begin(); it != params.end(); ++it)
{
#ifndef LIBIIO_V1
struct iio_channel *chn = 0;
const char *attr = 0;
#endif
std::size_t pos;
int ret;
int type;
pos = it->find('=');
if (pos == std::string::npos)
{
std::cerr << "DevicePlutoSDRBox::set_params: Malformed line: " << *it << std::endl;
continue;
}
std::string key = it->substr(0, pos);
std::string val = it->substr(pos + 1, std::string::npos);
#ifdef LIBIIO_V1
const struct iio_attr *attr = findAttrByFilename(dev, key.c_str(), type);
if (!attr)
{
std::cerr << "DevicePlutoSDRBox::set_params: Parameter not recognized: " << key << std::endl;
continue;
}
ret = (int) iio_attr_write_string(attr, val.c_str());
#else
ret = iio_device_identify_filename(dev, key.c_str(), &chn, &attr);
if (ret)
{
std::cerr << "DevicePlutoSDRBox::set_params: Parameter not recognized: " << key << std::endl;
continue;
}
if (chn) {
ret = iio_channel_attr_write(chn, attr, val.c_str());
type = 0;
} else if (iio_device_find_attr(dev, attr)) {
ret = iio_device_attr_write(dev, attr, val.c_str());
type = 1;
} else {
ret = iio_device_debug_attr_write(dev, attr, val.c_str());
type = 2;
}
#endif
if (ret < 0)
{
std::string item;
char errstr[256];
switch (type)
{
case 0:
item = "channel";
break;
case 1:
item = "device";
break;
case 2:
item = "debug";
break;
default:
item = "unknown";
break;
}
iio_strerror(-ret, errstr, 255);
std::cerr << "DevicePlutoSDRBox::set_params: Unable to write " << item << " attribute " << key << "=" << val << ": " << errstr << " (" << ret << ") " << std::endl;
}
else
{
std::cerr << "DevicePlutoSDRBox::set_params: set attribute " << key << "=" << val << ": " << ret << std::endl;
}
}
}
bool DevicePlutoSDRBox::get_param(DeviceType devType, const std::string &param, std::string &value)
{
#ifndef LIBIIO_V1
struct iio_channel *chn = 0;
const char *attr = 0;
int ret;
#endif
char valuestr[256];
ssize_t nchars;
iio_device *dev;
switch (devType)
{
case DEVICE_PHY:
dev = m_devPhy;
break;
case DEVICE_RX:
dev = m_devRx;
break;
case DEVICE_TX:
dev = m_devTx;
break;
default:
dev = m_devPhy;
break;
}
#ifdef LIBIIO_V1
int type;
const struct iio_attr *attr = findAttrByFilename(dev, param.c_str(), type);
if (!attr)
{
std::cerr << "DevicePlutoSDRBox::get_param: Parameter not recognized: " << param << std::endl;
return false;
}
nchars = iio_attr_read_raw(attr, valuestr, sizeof(valuestr) - 1);
if (nchars >= 0) {
valuestr[nchars] = '\0';
}
#else
ret = iio_device_identify_filename(dev, param.c_str(), &chn, &attr);
if (ret)
{
std::cerr << "DevicePlutoSDRBox::get_param: Parameter not recognized: " << param << std::endl;
return false;
}
if (chn) {
nchars = iio_channel_attr_read(chn, attr, valuestr, 256);
} else if (iio_device_find_attr(dev, attr)) {
nchars = iio_device_attr_read(dev, attr, valuestr, 256);
} else {
nchars = iio_device_debug_attr_read(dev, attr, valuestr, 256);
}
#endif
if (nchars < 0)
{
std::cerr << "DevicePlutoSDRBox::get_param: Unable to read attribute " << param << ": " << nchars << std::endl;
return false;
}
else
{
value.assign(valuestr);
return true;
}
}
void DevicePlutoSDRBox::setFilter(const std::string &filterConfigStr)
{
int ret;
#ifdef LIBIIO_V1
const struct iio_attr *attr = iio_device_find_attr(m_devPhy, "filter_fir_config");
ret = attr ? (int) iio_attr_write_raw(attr, filterConfigStr.c_str(), filterConfigStr.size()) : -ENOENT;
#else
ret = iio_device_attr_write_raw(m_devPhy, "filter_fir_config", filterConfigStr.c_str(), filterConfigStr.size());
#endif
if (ret < 0)
{
std::cerr << "DevicePlutoSDRBox::set_filter: Unable to set: " << filterConfigStr << ": " << ret << std::endl;
}
}
bool DevicePlutoSDRBox::openRx()
{
if (!m_valid) { return false; }
if (m_rxChannels.size() > 0)
{
enableChannel(m_rxChannels.at(0), m_rxMask);
const struct iio_data_format *df = iio_channel_get_data_format(m_rxChannels.at(0));
qDebug("DevicePlutoSDRBox::openRx channel I: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale? "true" : "false",
df->scale,
df->repeat);
m_rxSampleBytes = df->length / 8;
}
else
{
qWarning("DevicePlutoSDRBox::openRx: open channel I failed");
return false;
}
if (m_rxChannels.size() > 1)
{
enableChannel(m_rxChannels.at(1), m_rxMask);
const struct iio_data_format* df = iio_channel_get_data_format(m_rxChannels.at(1));
qDebug("DevicePlutoSDRBox::openRx channel Q: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale ? "true" : "false",
df->scale,
df->repeat);
return true;
}
else
{
qWarning("DevicePlutoSDRBox::openRx: open channel Q failed");
return false;
}
}
bool DevicePlutoSDRBox::openSecondRx()
{
if (!m_valid) { return false; }
if (m_rxChannels.size() > 2)
{
enableChannel(m_rxChannels.at(2), m_rxMask);
const struct iio_data_format *df = iio_channel_get_data_format(m_rxChannels.at(2));
qDebug("DevicePlutoSDRBox::openSecondRx channel I: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale? "true" : "false",
df->scale,
df->repeat);
m_rxSampleBytes = df->length / 8;
}
else
{
qWarning("DevicePlutoSDRBox::openSecondRx: open channel I failed");
return false;
}
if (m_rxChannels.size() > 3)
{
enableChannel(m_rxChannels.at(3), m_rxMask);
const struct iio_data_format* df = iio_channel_get_data_format(m_rxChannels.at(3));
qDebug("DevicePlutoSDRBox::openSecondRx channel Q: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale ? "true" : "false",
df->scale,
df->repeat);
return true;
}
else
{
qWarning("DevicePlutoSDRBox::openSecondRx: open channel Q failed");
return false;
}
}
bool DevicePlutoSDRBox::openTx()
{
if (!m_valid) { return false; }
if (m_txChannels.size() > 0)
{
enableChannel(m_txChannels.at(0), m_txMask);
const struct iio_data_format *df = iio_channel_get_data_format(m_txChannels.at(0));
qDebug("DevicePlutoSDRBox::openTx: channel I: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale? "true" : "false",
df->scale,
df->repeat);
m_txSampleBytes = df->length / 8;
}
else
{
std::cerr << "DevicePlutoSDRBox::openTx: failed to open I channel" << std::endl;
return false;
}
if (m_txChannels.size() > 1)
{
enableChannel(m_txChannels.at(1), m_txMask);
const struct iio_data_format *df = iio_channel_get_data_format(m_txChannels.at(1));
qDebug("DevicePlutoSDRBox::openTx: channel Q: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale? "true" : "false",
df->scale,
df->repeat);
return true;
}
else
{
std::cerr << "DevicePlutoSDRBox::openTx: failed to open Q channel" << std::endl;
return false;
}
}
bool DevicePlutoSDRBox::openSecondTx()
{
if (!m_valid) { return false; }
if (m_txChannels.size() > 2)
{
enableChannel(m_txChannels.at(2), m_txMask);
const struct iio_data_format *df = iio_channel_get_data_format(m_txChannels.at(2));
qDebug("DevicePlutoSDRBox::openSecondTx: channel I: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale? "true" : "false",
df->scale,
df->repeat);
m_txSampleBytes = df->length / 8;
}
else
{
qWarning("DevicePlutoSDRBox::openSecondTx: failed to open I channel");
return false;
}
if (m_txChannels.size() > 3)
{
enableChannel(m_txChannels.at(3), m_txMask);
const struct iio_data_format *df = iio_channel_get_data_format(m_txChannels.at(3));
qDebug("DevicePlutoSDRBox::openSecondTx: channel Q: length: %u bits: %u shift: %u signed: %s be: %s with_scale: %s scale: %lf repeat: %u",
df->length,
df->bits,
df->shift,
df->is_signed ? "true" : "false",
df->is_be ? "true" : "false",
df->with_scale? "true" : "false",
df->scale,
df->repeat);
return true;
}
else
{
qWarning("DevicePlutoSDRBox::openSecondTx: failed to open Q channel");
return false;
}
}
void DevicePlutoSDRBox::closeRx()
{
if (!m_valid) { return; }
if (m_rxChannels.size() > 0) { disableChannel(m_rxChannels.at(0), m_rxMask); }
if (m_rxChannels.size() > 1) { disableChannel(m_rxChannels.at(1), m_rxMask); }
}
void DevicePlutoSDRBox::closeSecondRx()
{
if (!m_valid) { return; }
if (m_rxChannels.size() > 2) { disableChannel(m_rxChannels.at(2), m_rxMask); }
if (m_rxChannels.size() > 3) { disableChannel(m_rxChannels.at(3), m_rxMask); }
}
void DevicePlutoSDRBox::closeTx()
{
if (!m_valid) { return; }
if (m_txChannels.size() > 0) { disableChannel(m_txChannels.at(0), m_txMask); }
if (m_txChannels.size() > 1) { disableChannel(m_txChannels.at(1), m_txMask); }
}
void DevicePlutoSDRBox::closeSecondTx()
{
if (!m_valid) { return; }
if (m_txChannels.size() > 2) { disableChannel(m_txChannels.at(2), m_txMask); }
if (m_txChannels.size() > 3) { disableChannel(m_txChannels.at(3), m_txMask); }
}
// Other applications (e.g. SoapyPlutoSDR) may leave an LO powered down, and the Tx LO
// stays up in FDD mode even with no stream running, so set the LO state explicitly
void DevicePlutoSDRBox::setRxLOPowerdown(bool powerdown)
{
std::vector<std::string> params;
params.push_back(std::string("out_altvoltage0_RX_LO_powerdown=") + (powerdown ? "1" : "0"));
set_params(DEVICE_PHY, params);
}
void DevicePlutoSDRBox::setTxLOPowerdown(bool powerdown)
{
std::vector<std::string> params;
params.push_back(std::string("out_altvoltage1_TX_LO_powerdown=") + (powerdown ? "1" : "0"));
set_params(DEVICE_PHY, params);
}
struct iio_buffer *DevicePlutoSDRBox::createRxBuffer(unsigned int size, bool cyclic)
{
#ifdef LIBIIO_V1
(void) cyclic; // cyclic mode only exists for output buffers in libiio 1.x
m_rxBuf = nullptr;
m_rxBlock = nullptr;
if (m_valid)
{
struct iio_buffer *buf = iio_device_get_buffer(m_devRx, 0);
if (buf)
{
m_rxStream = iio_buffer_create_stream(buf, nbStreamBlocks, size, m_rxMask);
int err = iio_err(m_rxStream);
if (err)
{
qCritical("DevicePlutoSDRBox::createRxBuffer: cannot create stream: %s (%d)", strerror(-err), err);
m_rxStream = nullptr;
}
else
{
m_rxBuf = buf;
}
}
}
#else
if (m_devRx) {
m_rxBuf = iio_device_create_buffer(m_devRx, size, cyclic ? '\1' : '\0');
} else {
m_rxBuf = nullptr;
}
#endif
return m_rxBuf;
}
struct iio_buffer *DevicePlutoSDRBox::createTxBuffer(unsigned int size, bool cyclic)
{
#ifdef LIBIIO_V1
if (cyclic) { // iio_stream does not do cyclic transfers and SDRangel never asks for them
qWarning("DevicePlutoSDRBox::createTxBuffer: cyclic mode is not supported with libiio 1.x");
}
m_txBuf = nullptr;
m_txBlock = nullptr;
if (m_valid)
{
struct iio_buffer *buf = iio_device_get_buffer(m_devTx, 0);
if (buf)
{
m_txStream = iio_buffer_create_stream(buf, nbStreamBlocks, size, m_txMask);
int err = iio_err(m_txStream);
if (err)
{
qCritical("DevicePlutoSDRBox::createTxBuffer: cannot create stream: %s (%d)", strerror(-err), err);
m_txStream = nullptr;
}
else
{
// The first call only returns an empty block to fill: nothing is sent
// to the hardware until txBufferPush()
const struct iio_block *block = iio_stream_get_next_block(m_txStream);
err = iio_err(block);
if (err)
{
qCritical("DevicePlutoSDRBox::createTxBuffer: cannot get block: %s (%d)", strerror(-err), err);
iio_stream_destroy(m_txStream);
m_txStream = nullptr;
}
else
{
m_txBlock = block;
m_txBuf = buf;
}
}
}
}
#else
if (m_devTx) {
m_txBuf = iio_device_create_buffer(m_devTx, size, cyclic ? '\1' : '\0');
} else {
m_txBuf = nullptr;
}
#endif
return m_txBuf;
}
void DevicePlutoSDRBox::deleteRxBuffer()
{
#ifdef LIBIIO_V1
// The iio_buffer itself belongs to the device: only the stream is destroyed
if (m_rxStream)
{
iio_stream_destroy(m_rxStream);
m_rxStream = nullptr;
}
m_rxBlock = nullptr;
m_rxBuf = nullptr;
#else
if (m_rxBuf)
{
iio_buffer_destroy(m_rxBuf);
m_rxBuf = nullptr;
}
#endif
}
void DevicePlutoSDRBox::deleteTxBuffer()
{
#ifdef LIBIIO_V1
// The iio_buffer itself belongs to the device: only the stream is destroyed
if (m_txStream)
{
iio_stream_destroy(m_txStream);
m_txStream = nullptr;
}
m_txBlock = nullptr;
m_txBuf = nullptr;
#else
if (m_txBuf)
{
iio_buffer_destroy(m_txBuf);
m_txBuf = nullptr;
}
#endif
}
ssize_t DevicePlutoSDRBox::getRxSampleSize()
{
#ifdef LIBIIO_V1
if (m_devRx && m_rxMask) {
return iio_device_get_sample_size(m_devRx, m_rxMask);
} else {
#else
if (m_devRx) {
return iio_device_get_sample_size(m_devRx);
} else {
#endif
return 0;
}
}
ssize_t DevicePlutoSDRBox::getTxSampleSize()
{
#ifdef LIBIIO_V1
if (m_devTx && m_txMask) {
return iio_device_get_sample_size(m_devTx, m_txMask);
} else {
#else
if (m_devTx) {
return iio_device_get_sample_size(m_devTx);
} else {
#endif
return 0;
}
}
ssize_t DevicePlutoSDRBox::rxBufferRefill()
{
#ifdef LIBIIO_V1
if (!m_rxStream) {
return 0;
}
// Hands the previous block back to the hardware and waits for the next filled one
const struct iio_block *block = iio_stream_get_next_block(m_rxStream);
int err = iio_err(block);
if (err)
{
m_rxBlock = nullptr;
return err;
}
m_rxBlock = block;
return (char *) iio_block_end(block) - (char *) iio_block_start(block);
#else
if (m_rxBuf) {
return iio_buffer_refill(m_rxBuf);
} else {
return 0;
}
#endif
}
ssize_t DevicePlutoSDRBox::txBufferPush()
{
#ifdef LIBIIO_V1
if (!m_txBlock) {
return 0;
}
// Queues the filled block for sending and waits for a free one to fill next
ssize_t nbytes = (char *) iio_block_end(m_txBlock) - (char *) iio_block_start(m_txBlock);
const struct iio_block *block = iio_stream_get_next_block(m_txStream);
int err = iio_err(block);
if (err)
{
m_txBlock = nullptr;
return err;
}
m_txBlock = block;
return nbytes;
#else
if (m_txBuf) {
return iio_buffer_push(m_txBuf);
} else {
return 0;
}
#endif
}
std::ptrdiff_t DevicePlutoSDRBox::rxBufferStep()
{
#ifdef LIBIIO_V1
if (m_rxStream) {
return iio_device_get_sample_size(m_devRx, m_rxMask);
} else {
return 0;
}
#else
if (m_rxBuf) {
return iio_buffer_step(m_rxBuf);
} else {
return 0;
}
#endif
}
char* DevicePlutoSDRBox::rxBufferEnd()
{
#ifdef LIBIIO_V1
if (m_rxBlock) {
return (char *) iio_block_end(m_rxBlock);
} else {
return nullptr;
}
#else
if (m_rxBuf) {
return (char *) iio_buffer_end(m_rxBuf);
} else {
return nullptr;
}
#endif
}
char* DevicePlutoSDRBox::rxBufferFirst()
{
#ifdef LIBIIO_V1
if (m_rxBlock) {
return (char *) iio_block_first(m_rxBlock, m_rxChannels.at(0));
} else {
return nullptr;
}
#else
if (m_rxBuf) {
return (char *) iio_buffer_first(m_rxBuf, m_rxChannels.at(0));
} else {
return nullptr;
}
#endif
}
std::ptrdiff_t DevicePlutoSDRBox::txBufferStep()
{
#ifdef LIBIIO_V1
if (m_txStream) {
return iio_device_get_sample_size(m_devTx, m_txMask);
} else {
return 0;
}
#else
if (m_txBuf) {
return iio_buffer_step(m_txBuf);
} else {
return 0;
}
#endif
}
char* DevicePlutoSDRBox::txBufferEnd()
{
#ifdef LIBIIO_V1
if (m_txBlock) {
return (char *) iio_block_end(m_txBlock);
} else {
return nullptr;
}
#else
if (m_txBuf) {
return (char *) iio_buffer_end(m_txBuf);
} else {
return nullptr;
}
#endif
}
char* DevicePlutoSDRBox::txBufferFirst()
{
#ifdef LIBIIO_V1
if (m_txBlock) {
return (char *) iio_block_first(m_txBlock, m_txChannels.at(0));
} else {
return nullptr;
}
#else
if (m_txBuf) {
return (char *) iio_buffer_first(m_txBuf, m_txChannels.at(0));
} else {
return nullptr;
}
#endif
}
void DevicePlutoSDRBox::txChannelConvert(int16_t *dst, int16_t *src)
{
if (m_txChannels.size() > 0) {
iio_channel_convert_inverse(m_txChannels.at(0), &dst[0], &src[0]);
}
if (m_txChannels.size() > 1) {
iio_channel_convert_inverse(m_txChannels.at(1), &dst[1], &src[1]);
}
}
void DevicePlutoSDRBox::txChannelConvert(int chanIndex, int16_t *dst, int16_t *src)
{
if (m_txChannels.size() > 2*chanIndex) {
iio_channel_convert_inverse(m_txChannels.at(2*chanIndex), &dst[0], &src[0]);
}
if (m_txChannels.size() > 2*chanIndex+1) {
iio_channel_convert_inverse(m_txChannels.at(2*chanIndex+1), &dst[1], &src[1]);
}
}
bool DevicePlutoSDRBox::getRxSampleRates(SampleRates& sampleRates)
{
std::string srStr;
if (get_param(DEVICE_PHY, "rx_path_rates", srStr)) {
qDebug("DevicePlutoSDRBox::getRxSampleRates: %s", srStr.c_str());
return parseSampleRates(srStr, sampleRates);
} else {
return false;
}
}
bool DevicePlutoSDRBox::getTxSampleRates(SampleRates& sampleRates)
{
std::string srStr;
if (get_param(DEVICE_PHY, "tx_path_rates", srStr)) {
return parseSampleRates(srStr, sampleRates);
} else {
return false;
}
}
bool DevicePlutoSDRBox::parseSampleRates(const std::string& rateStr, SampleRates& sampleRates)
{
// Rx: "BBPLL:983040000 ADC:245760000 R2:122880000 R1:61440000 RF:30720000 RXSAMP:30720000"
// Tx: "BBPLL:983040000 DAC:122880000 T2:122880000 T1:61440000 TF:30720000 TXSAMP:30720000"
std::regex desc_regex("BBPLL:(.+) ..C:(.+) .2:(.+) .1:(.+) .F:(.+) .XSAMP:(.+)");
std::smatch desc_match;
std::regex_search(rateStr, desc_match, desc_regex);
std::string valueStr;
if (desc_match.size() == 7)
{
try
{
sampleRates.m_bbRateHz = boost::lexical_cast<uint32_t>(desc_match[1]);
sampleRates.m_addaConnvRate = boost::lexical_cast<uint32_t>(desc_match[2]);
sampleRates.m_hb3Rate = boost::lexical_cast<uint32_t>(desc_match[3]);
sampleRates.m_hb2Rate = boost::lexical_cast<uint32_t>(desc_match[4]);
sampleRates.m_hb1Rate = boost::lexical_cast<uint32_t>(desc_match[5]);
sampleRates.m_firRate = boost::lexical_cast<uint32_t>(desc_match[6]);
return true;
}
catch (const boost::bad_lexical_cast &e)
{
qWarning("DevicePlutoSDRBox::parseSampleRates: bad conversion to numeric");
return false;
}
}
else
{
return false;
}
}
void DevicePlutoSDRBox::setSampleRate(uint32_t sampleRate)
{
char buff[100];
std::vector<std::string> params;
snprintf(buff, sizeof(buff), "in_voltage_sampling_frequency=%u", sampleRate);
params.push_back(std::string(buff));
snprintf(buff, sizeof(buff), "out_voltage_sampling_frequency=%u", sampleRate);
params.push_back(std::string(buff));
set_params(DEVICE_PHY, params);
m_devSampleRate = sampleRate;
}
/**
* @param sampleRate baseband sample rate (S/s)
* @param log2IntDec FIR interpolation or decimation factor
* @param use Rx or Tx. Applies to the rest of the parameters
* @param bw FIR filter bandwidth at approximately -6 dB cutoff (Hz)
* @param gain FIR filter gain (dB)
*/
void DevicePlutoSDRBox::setFIR(uint32_t sampleRate, uint32_t log2IntDec, DeviceUse use, uint32_t bw, int gain)
{
SampleRates sampleRates;
std::ostringstream ostr;
uint32_t nbTaps;
double normalizedBW;
uint32_t intdec = 1<<(log2IntDec > 2 ? 2 : log2IntDec);
// update gain parameter
if (use == USE_RX) {
m_lpfFIRRxGain = gain;
} else {
m_lpfFIRTxGain = gain;
}
// set a dummy minimal filter first to get the sample rates right
setFIREnable(false); // disable first
formatFIRHeader(ostr, intdec);
formatFIRCoefficients(ostr, 16, 0.5);
setFilter(ostr.str());
ostr.str(""); // reset string stream
setFIREnable(true); // re-enable
setSampleRate(sampleRate); // set to new sample rate
if (!getRxSampleRates(sampleRates)) {
return;
}
setFIREnable(false); // disable again
uint32_t nbGroups = sampleRates.m_addaConnvRate / 16;
nbTaps = nbGroups*8 > 128 ? 128 : nbGroups*8;
nbTaps = intdec == 1 ? (nbTaps > 64 ? 64 : nbTaps) : nbTaps;
normalizedBW = ((float) bw) / sampleRates.m_hb1Rate;
normalizedBW = normalizedBW < DevicePlutoSDR::firBWLowLimitFactor ?
DevicePlutoSDR::firBWLowLimitFactor :
normalizedBW > DevicePlutoSDR::firBWHighLimitFactor ? DevicePlutoSDR::firBWHighLimitFactor : normalizedBW;
qDebug("DevicePlutoSDRBox::setFIR: intdec: %u gain: %d nbTaps: %u BWin: %u BW: %f (%f)",
intdec,
gain,
nbTaps,
bw,
normalizedBW*sampleRates.m_hb1Rate,
normalizedBW);
// set the right filter
formatFIRHeader(ostr, intdec);
formatFIRCoefficients(ostr, nbTaps, normalizedBW);
setFilter(ostr.str());
m_lpfFIRlog2Decim = log2IntDec;
m_lpfFIRBW = bw;
// enable and set sample rate will be done by the caller
}
void DevicePlutoSDRBox::setFIREnable(bool enable)
{
char buff[100];
std::vector<std::string> params;
snprintf(buff, sizeof(buff), "in_out_voltage_filter_fir_en=%d", enable ? 1 : 0);
params.push_back(std::string(buff));
set_params(DEVICE_PHY, params);
m_lpfFIREnable = enable;
}
void DevicePlutoSDRBox::setLOPPMTenths(int ppmTenths)
{
char buff[100];
std::vector<std::string> params;
int64_t newXO = m_xoInitial + ((m_xoInitial*ppmTenths) / 10000000L);
snprintf(buff, sizeof(buff), "xo_correction=%ld", (long int) newXO);
params.push_back(std::string(buff));
set_params(DEVICE_PHY, params);
m_LOppmTenths = ppmTenths;
}
void DevicePlutoSDRBox::formatFIRHeader(std::ostringstream& ostr,uint32_t intdec)
{
ostr << "RX 3 GAIN " << m_lpfFIRRxGain << " DEC " << intdec << std::endl;
ostr << "TX 3 GAIN " << m_lpfFIRTxGain << " INT " << intdec << std::endl;
}
void DevicePlutoSDRBox::formatFIRCoefficients(std::ostringstream& ostr, uint32_t nbTaps, double normalizedBW)
{
double *fcoeffs = new double[nbTaps];
WFIR::BasicFIR(fcoeffs, nbTaps, WFIR::LPF, normalizedBW, 0.0, normalizedBW < 0.2 ? WFIR::wtHAMMING : WFIR::wtBLACKMAN_HARRIS, 0.0);
for (unsigned int i = 0; i < nbTaps; i++) {
ostr << (int16_t) (fcoeffs[i] * 32768.0f) << ", " << (int16_t) (fcoeffs[i] * 32768.0f) << std::endl;
}
delete[] fcoeffs;
}
void DevicePlutoSDRBox::getXO()
{
std::string valueStr;
get_param(DEVICE_PHY, "xo_correction", valueStr);
try
{
m_xoInitial = boost::lexical_cast<quint64>(valueStr);
qDebug("DevicePlutoSDRBox::getXO: %ld", m_xoInitial);
}
catch (const boost::bad_lexical_cast &e)
{
qWarning("DevicePlutoSDRBox::getXO: cannot get initial XO correction");
}
}
bool DevicePlutoSDRBox::getRxGain(int& gaindB, unsigned int chan)
{
chan = chan % 2;
char buff[30];
snprintf(buff, sizeof(buff), "in_voltage%u_hardwaregain", chan);
std::string gainStr;
get_param(DEVICE_PHY, buff, gainStr);
std::regex gain_regex("(.+)\\.(.+) dB");
std::smatch gain_match;
std::regex_search(gainStr, gain_match, gain_regex);
if (gain_match.size() == 3)
{
try
{
gaindB = boost::lexical_cast<int>(gain_match[1]);
return true;
}
catch (const boost::bad_lexical_cast &e)
{
qWarning("DevicePlutoSDRBox::getRxGain: bad conversion to numeric");
return false;
}
}
else
{
return false;
}
}
bool DevicePlutoSDRBox::getRxRSSI(std::string& rssiStr, unsigned int chan)
{
chan = chan % 2;
char buff[20];
snprintf(buff, sizeof(buff), "in_voltage%u_rssi", chan);
return get_param(DEVICE_PHY, buff, rssiStr);
}
bool DevicePlutoSDRBox::getTxRSSI(std::string& rssiStr, unsigned int chan)
{
chan = chan % 2;
char buff[20];
snprintf(buff, sizeof(buff), "out_voltage%u_rssi", chan);
return get_param(DEVICE_PHY, buff, rssiStr);
}
void DevicePlutoSDRBox::getGainRange(qint64& minGain, qint64& stepGain, qint64& maxGain)
{
std::string rangeStr;
char buff[50];
snprintf(buff, sizeof(buff), "in_voltage0_hardwaregain_available");
if (get_param(DEVICE_PHY, buff, rangeStr) && (rangeStr.size() > 2))
{
// _available is always [min step max]
std::istringstream in(rangeStr.substr(1, rangeStr.size()-2));
in >> minGain;
in >> stepGain;
in >> maxGain;
}
else
{
minGain = DevicePlutoSDR::rxMinGain;
stepGain = 1;
maxGain = DevicePlutoSDR::rxMaxGain;
}
}
void DevicePlutoSDRBox::getRxLORange(uint64_t& minLimit, uint64_t& maxLimit)
{
// values are returned in Hz
qint64 stepLimit;
std::string rangeStr;
char buff[50];
snprintf(buff, sizeof(buff), "out_altvoltage0_RX_LO_frequency_available");
if (get_param(DEVICE_PHY, buff, rangeStr))
{
std::istringstream instream(rangeStr.substr(1, rangeStr.size() - 2));
instream >> minLimit >> stepLimit >> maxLimit;
}
else
{
minLimit = DevicePlutoSDR::rxLOLowLimitFreq;
maxLimit = DevicePlutoSDR::rxLOHighLimitFreq;
}
}
void DevicePlutoSDRBox::getTxLORange(uint64_t& minLimit, uint64_t& maxLimit)
{
// values are returned in Hz
qint64 stepLimit;
std::string rangeStr;
char buff[50];
snprintf(buff, sizeof(buff), "out_altvoltage1_TX_LO_frequency_available");
if (get_param(DEVICE_PHY, buff, rangeStr))
{
std::istringstream instream(rangeStr.substr(1, rangeStr.size() - 2));
instream >> minLimit >> stepLimit >> maxLimit;
}
else
{
minLimit = DevicePlutoSDR::txLOLowLimitFreq;
maxLimit = DevicePlutoSDR::txLOHighLimitFreq;
}
}
void DevicePlutoSDRBox::getbbLPRxRange(uint32_t& minLimit, uint32_t& maxLimit)
{
// values are returned in Hz of RF (complex channel) bandwidth
qint32 stepLimit;
std::string rangeStr;
char buff[50];
snprintf(buff, sizeof(buff), "in_voltage_rf_bandwidth_available");
if (get_param(DEVICE_PHY, buff, rangeStr))
{
std::istringstream instream(rangeStr.substr(1, rangeStr.size() - 2));
instream >> minLimit >> stepLimit >> maxLimit;
}
else
{
minLimit = DevicePlutoSDR::bbLPRxLowLimitFreq;
maxLimit = DevicePlutoSDR::bbLPRxHighLimitFreq;
}
}
void DevicePlutoSDRBox::getbbLPTxRange(uint32_t& minLimit, uint32_t& maxLimit)
{
// values are returned in Hz
qint32 stepLimit;
std::string rangeStr;
char buff[50];
snprintf(buff, sizeof(buff), "out_voltage_rf_bandwidth_available");
if (get_param(DEVICE_PHY, buff, rangeStr))
{
std::istringstream instream(rangeStr.substr(1, rangeStr.size() - 2));
instream >> minLimit >> stepLimit >> maxLimit;
}
else
{
minLimit = DevicePlutoSDR::bbLPTxLowLimitFreq;
maxLimit = DevicePlutoSDR::bbLPTxHighLimitFreq;
}
}
bool DevicePlutoSDRBox::fetchTemp()
{
std::string temp_mC_str;
if (get_param(DEVICE_PHY, "in_temp0_input", temp_mC_str))
{
try
{
uint32_t temp_mC = boost::lexical_cast<uint32_t>(temp_mC_str);
m_temp = temp_mC / 1000.0;
return true;
}
catch (const boost::bad_lexical_cast &e)
{
std::cerr << "PlutoSDRDevice::getTemp: bad conversion to numeric" << std::endl;
return false;
}
}
else
{
return false;
}
}
bool DevicePlutoSDRBox::getRateGovernors(std::string& rateGovernors)
{
return get_param(DEVICE_PHY, "trx_rate_governor", rateGovernors);
}