From 337886ecc3efeecacf4a932943a9da65542cabda Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Fri, 2 Oct 2026 22:01:49 +0100 Subject: [PATCH] Add MIMO driver. Fix TX scaling bug that was costing 10dB of output power at max gain. Improve performance on Windows to reduce overruns at high sample rates. Add underrun stats. Display temperature. Improve error handling. Move setting device settings off GUI thread. For #1522 --- devices/usrp/CMakeLists.txt | 2 + devices/usrp/deviceusrp.cpp | 238 ++- devices/usrp/deviceusrp.h | 35 +- devices/usrp/deviceusrpparam.cpp | 66 +- devices/usrp/deviceusrpparam.h | 60 + devices/usrp/deviceusrpshared.cpp | 4 + devices/usrp/deviceusrpshared.h | 133 +- devices/usrp/deviceusrpstreamstats.cpp | 115 ++ devices/usrp/deviceusrpstreamstats.h | 64 + plugins/samplemimo/CMakeLists.txt | 6 + plugins/samplemimo/usrpmimo/CMakeLists.txt | 83 + plugins/samplemimo/usrpmimo/readme.md | 113 ++ plugins/samplemimo/usrpmimo/usrpmimo.cpp | 1387 +++++++++++++++++ plugins/samplemimo/usrpmimo/usrpmimo.h | 274 ++++ plugins/samplemimo/usrpmimo/usrpmimogui.cpp | 1022 ++++++++++++ plugins/samplemimo/usrpmimo/usrpmimogui.h | 131 ++ plugins/samplemimo/usrpmimo/usrpmimogui.ui | 952 +++++++++++ .../samplemimo/usrpmimo/usrpmimoplugin.cpp | 143 ++ plugins/samplemimo/usrpmimo/usrpmimoplugin.h | 54 + .../samplemimo/usrpmimo/usrpmimosettings.cpp | 396 +++++ .../samplemimo/usrpmimo/usrpmimosettings.h | 78 + .../usrpmimo/usrpmimowebapiadapter.cpp | 51 + .../usrpmimo/usrpmimowebapiadapter.h | 48 + .../samplemimo/usrpmimo/usrpmimoworker.cpp | 407 +++++ plugins/samplemimo/usrpmimo/usrpmimoworker.h | 66 + plugins/samplemimo/usrpmimo/usrpmithread.cpp | 282 ++++ plugins/samplemimo/usrpmimo/usrpmithread.h | 84 + plugins/samplemimo/usrpmimo/usrpmothread.cpp | 321 ++++ plugins/samplemimo/usrpmimo/usrpmothread.h | 97 ++ plugins/samplesink/usrpoutput/readme.md | 4 + plugins/samplesink/usrpoutput/usrpoutput.cpp | 904 +++++++---- plugins/samplesink/usrpoutput/usrpoutput.h | 15 +- .../samplesink/usrpoutput/usrpoutputgui.cpp | 55 +- plugins/samplesink/usrpoutput/usrpoutputgui.h | 3 + .../samplesink/usrpoutput/usrpoutputgui.ui | 19 + .../usrpoutput/usrpoutputsettings.cpp | 1 + .../usrpoutput/usrpoutputthread.cpp | 409 ++++- .../samplesink/usrpoutput/usrpoutputthread.h | 51 +- plugins/samplesource/usrpinput/readme.md | 4 + plugins/samplesource/usrpinput/usrpinput.cpp | 927 ++++++----- plugins/samplesource/usrpinput/usrpinput.h | 14 +- .../samplesource/usrpinput/usrpinputgui.cpp | 48 +- plugins/samplesource/usrpinput/usrpinputgui.h | 3 + .../samplesource/usrpinput/usrpinputgui.ui | 19 + .../usrpinput/usrpinputsettings.cpp | 1 + .../usrpinput/usrpinputthread.cpp | 413 ++++- .../samplesource/usrpinput/usrpinputthread.h | 56 +- .../doc/swagger/include/DeviceReports.yaml | 3 + .../doc/swagger/include/DeviceSettings.yaml | 3 + .../webapi/doc/swagger/include/USRP.yaml | 155 ++ sdrbase/webapi/webapirequestmapper.cpp | 7 + sdrbase/webapi/webapiutils.cpp | 2 + .../api/swagger/include/DeviceReports.yaml | 3 + .../api/swagger/include/DeviceSettings.yaml | 3 + .../sdrangel/api/swagger/include/USRP.yaml | 155 ++ .../code/qt5/client/SWGDeviceReport.cpp | 25 + .../code/qt5/client/SWGDeviceReport.h | 7 + .../code/qt5/client/SWGDeviceSettings.cpp | 25 + .../code/qt5/client/SWGDeviceSettings.h | 7 + .../code/qt5/client/SWGModelFactory.h | 12 + .../code/qt5/client/SWGUSRPMIMOReport.cpp | 292 ++++ .../code/qt5/client/SWGUSRPMIMOReport.h | 106 ++ .../code/qt5/client/SWGUSRPMIMOSettings.cpp | 858 ++++++++++ .../code/qt5/client/SWGUSRPMIMOSettings.h | 251 +++ 64 files changed, 10731 insertions(+), 841 deletions(-) create mode 100644 devices/usrp/deviceusrpstreamstats.cpp create mode 100644 devices/usrp/deviceusrpstreamstats.h create mode 100644 plugins/samplemimo/usrpmimo/CMakeLists.txt create mode 100644 plugins/samplemimo/usrpmimo/readme.md create mode 100644 plugins/samplemimo/usrpmimo/usrpmimo.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmimo.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmimogui.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmimogui.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmimogui.ui create mode 100644 plugins/samplemimo/usrpmimo/usrpmimoplugin.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmimoplugin.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmimosettings.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmimosettings.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmimoworker.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmimoworker.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmithread.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmithread.h create mode 100644 plugins/samplemimo/usrpmimo/usrpmothread.cpp create mode 100644 plugins/samplemimo/usrpmimo/usrpmothread.h create mode 100644 swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.cpp create mode 100644 swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.h create mode 100644 swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.cpp create mode 100644 swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.h diff --git a/devices/usrp/CMakeLists.txt b/devices/usrp/CMakeLists.txt index ec26fc273..53f4f2a97 100644 --- a/devices/usrp/CMakeLists.txt +++ b/devices/usrp/CMakeLists.txt @@ -5,12 +5,14 @@ set(usrpdevice_SOURCES deviceusrp.cpp deviceusrpparam.cpp deviceusrpshared.cpp + deviceusrpstreamstats.cpp ) set(usrpdevice_HEADERS deviceusrp.h deviceusrpparam.h deviceusrpshared.h + deviceusrpstreamstats.h ) include_directories( diff --git a/devices/usrp/deviceusrp.cpp b/devices/usrp/deviceusrp.cpp index 13c5ab58d..af54450de 100644 --- a/devices/usrp/deviceusrp.cpp +++ b/devices/usrp/deviceusrp.cpp @@ -22,9 +22,13 @@ #include #include #include +#include #include #include +#include + +#include "util/poweroftwo.h" #include "deviceusrpparam.h" #include "deviceusrp.h" @@ -54,7 +58,7 @@ void DeviceUSRP::enumOriginDevices(const QString& hardwareId, PluginInterface::O // Opening some devices can be a little slow, so use hardcoded number of channels, // for known devices - static const QMap channelMap{{"B200", 1}, {"B205", 1}, {"B210", 2}}; + static const QMap channelMap{{"B200", 1}, {"B205", 1}, {"B200mini", 1}, {"B205mini", 1}, {"B210", 2}}; if (channelMap.contains(product)) { originDevices.append(PluginInterface::OriginDevice( @@ -89,30 +93,234 @@ void DeviceUSRP::enumOriginDevices(const QString& hardwareId, PluginInterface::O } } -void DeviceUSRP::waitForLock(uhd::usrp::multi_usrp::sptr usrp, const QString& clockSource, int channel) +void DeviceUSRP::waitForLock(uhd::usrp::multi_usrp::sptr usrp, const QString& clockSource, int channel, bool rx) { int tries; const int maxTries = 100; - // Wait for Ref lock - std::vector sensor_names; - sensor_names = usrp->get_tx_sensor_names(channel); - if (clockSource == "external") + try { - if (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end()) + // Wait for Ref lock - ref_locked is a motherboard sensor + if (clockSource != "internal") + { + std::vector mboardSensorNames = usrp->get_mboard_sensor_names(0); + if (std::find(mboardSensorNames.begin(), mboardSensorNames.end(), "ref_locked") != mboardSensorNames.end()) + { + for (tries = 0; !usrp->get_mboard_sensor("ref_locked", 0).to_bool() && (tries < maxTries); tries++) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (tries == maxTries) + qCritical("DeviceUSRP::waitForLock: Failed to lock ref"); + } + } + + // Wait for LO lock + std::vector sensorNames = rx ? usrp->get_rx_sensor_names(channel) : usrp->get_tx_sensor_names(channel); + if (std::find(sensorNames.begin(), sensorNames.end(), "lo_locked") != sensorNames.end()) { - for (tries = 0; !usrp->get_mboard_sensor("ref_locked", 0).to_bool() && (tries < maxTries); tries++) + for (tries = 0; !(rx ? usrp->get_rx_sensor("lo_locked", channel) : usrp->get_tx_sensor("lo_locked", channel)).to_bool() && (tries < maxTries); tries++) std::this_thread::sleep_for(std::chrono::milliseconds(10)); if (tries == maxTries) - qCritical("USRPInput::acquireChannel: Failed to lock ref"); + qCritical("DeviceUSRP::waitForLock: Failed to lock %s LO", rx ? "Rx" : "Tx"); + } + } + catch (const std::exception& e) + { + qWarning() << "DeviceUSRP::waitForLock: exception: " << e.what(); + } +} + +bool DeviceUSRP::channelsShareLO(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channelA, int channelB) +{ + if (!usrp || (channelA < 0) || (channelB < 0)) { + return false; + } + if (channelA == channelB) { + return true; + } + + try + { + // Assume channels on the same daughterboard share an LO (E.g. B210/E310 "A:A A:B", N310 "A:0 A:1"), + // whereas channels on different daughterboards do not (E.g. X310 "A:0 B:0") + if (usrp->get_num_mboards() != 1) { + return false; + } + + uhd::usrp::subdev_spec_t spec = rx ? usrp->get_rx_subdev_spec(0) : usrp->get_tx_subdev_spec(0); + + if (((size_t) channelA >= spec.size()) || ((size_t) channelB >= spec.size())) { + return false; } + + return spec[channelA].db_name == spec[channelB].db_name; + } + catch (const std::exception& e) + { + qWarning() << "DeviceUSRP::channelsShareLO: exception: " << e.what(); + return false; + } +} + +bool DeviceUSRP::getTemperature(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channel, double& temperature) +{ + if (!usrp) { + return false; + } + + auto contains = [](const std::vector& names, const std::string& name) { + return std::find(names.begin(), names.end(), name) != names.end(); + }; + + try + { + // Motherboard sensor (E.g. E3xx, N3xx) + if (contains(usrp->get_mboard_sensor_names(0), "temp")) + { + temperature = usrp->get_mboard_sensor("temp", 0).to_real(); + return true; + } + + // Frontend sensor (E.g. B2xx, where it is the AD9361 temperature) + if ((channel >= 0) && contains(rx ? usrp->get_rx_sensor_names(channel) : usrp->get_tx_sensor_names(channel), "temp")) + { + temperature = (rx ? usrp->get_rx_sensor("temp", channel) : usrp->get_tx_sensor("temp", channel)).to_real(); + return true; + } + + // Frontend sensor in other direction (E.g. B2xx only has temperature sensor on Rx frontend) + if ((rx ? usrp->get_tx_num_channels() : usrp->get_rx_num_channels()) > 0) + { + if (contains(rx ? usrp->get_tx_sensor_names(0) : usrp->get_rx_sensor_names(0), "temp")) + { + temperature = (rx ? usrp->get_tx_sensor("temp", 0) : usrp->get_rx_sensor("temp", 0)).to_real(); + return true; + } + } + } + catch (const std::exception& e) + { + qDebug() << "DeviceUSRP::getTemperature: exception: " << e.what(); + } + + return false; +} + +// Read about 1ms of samples per recv() call, as reading a single packet (E.g. ~1000 samples) +// per call results in a high per call overhead at high sample rates (E.g. FIFO locking and signalling). +// Must be at least the maximum number of samples in a packet and a power of two (for the decimators, see #1161). +// Upper limit avoids too large a latency if the sample rate is reduced while running. +size_t DeviceUSRP::getRecvBufferSamples(size_t maxNumSamps, int sampleRate) +{ + const size_t maxSamples = 16384; + size_t minSamples = isPowerOfTwo(maxNumSamps) ? maxNumSamps : lowerPowerOfTwo(maxNumSamps); + size_t samples = sampleRate > 0 ? lowerPowerOfTwo((uint32_t) (sampleRate / 1000)) : minSamples; + + samples = std::min(samples, maxSamples); + samples = std::max(samples, minSamples); + + return samples; +} + +// Set priority of streaming thread higher than normal, so it isn't delayed by other threads (E.g. GUI or DSP), +// which can cause overflows / underflows, as UHD only buffers a few ms of samples by default +void DeviceUSRP::setStreamingThreadPriority() +{ + if (!uhd::set_thread_priority_safe()) { + qDebug("DeviceUSRP::setStreamingThreadPriority: Failed to set thread priority"); } - // Wait for LO lock - if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) +} + +// When UHD chooses the master clock rate automatically (B2xx), each time a channel's sample rate is set, +// it chooses one that's a multiple of the LCM of the sample rates of all channels (Rx and Tx), including +// those that haven't been changed yet. So when changing the sample rate of all channels, if no supported +// clock rate is a multiple of both the old and new rates (E.g. 8 and 9 MS/s), the clock rate is left unchanged, +// and the sample rate is coerced to what can be achieved with it (E.g. 8 MS/s). +// To avoid this, set the master clock rate for the new sample rate first, using the same rules as UHD. +bool DeviceUSRP::setMasterClockRateForSampleRate(uhd::usrp::multi_usrp::sptr usrp, double sampleRate, size_t nbChannels) +{ + const std::string autoTickRatePath = "/mboards/0/auto_tick_rate"; + uhd::property_tree::sptr properties = usrp->get_device()->get_tree(); + + if (!properties->exists(autoTickRatePath) || !properties->access(autoTickRatePath).get()) { + return false; // Master clock rate set manually + } + + uhd::meta_range_t clockRange = usrp->get_master_clock_rate_range(); + const double minClockRate = clockRange.start(); + const double maxClockRate = clockRange.stop() / std::max(nbChannels, (size_t) 1); + + if ((sampleRate <= 0.0) || (sampleRate > maxClockRate)) { + return false; // Let UHD report the error when the sample rate is set + } + + // Highest power of 2 multiple of the sample rate that doesn't exceed the max clock rate (See ad936x_manager::get_auto_tick_rate) + int multiplier = 1 << (int) std::log2(maxClockRate / sampleRate); + if ((multiplier == 2) && (sampleRate >= minClockRate)) { + multiplier = 1; + } + const double clockRate = sampleRate * multiplier; + + // Disable automatic selection while sample rates are set, even if the clock rate is already correct, + // as otherwise it could be changed when the first channel is set + properties->access(autoTickRatePath).set(false); + + if (std::abs(usrp->get_master_clock_rate() - clockRate) >= 1.0) { - for (tries = 0; !usrp->get_tx_sensor("lo_locked", channel).to_bool() && (tries < maxTries); tries++) - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - if (tries == maxTries) - qCritical("USRPInput::acquireChannel: Failed to lock LO"); + qDebug("DeviceUSRP::setMasterClockRateForSampleRate: setting master clock rate to %f for sample rate %f", clockRate, sampleRate); + usrp->set_master_clock_rate(clockRate); + } + + return true; +} + +void DeviceUSRP::enableAutoMasterClockRate(uhd::usrp::multi_usrp::sptr usrp) +{ + usrp->get_device()->get_tree()->access("/mboards/0/auto_tick_rate").set(true); +} + +void DeviceUSRP::setSampleRate(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channel, double sampleRate) +{ + auto set = [&]() { + if (rx) { + usrp->set_rx_rate(sampleRate, channel); + } else { + usrp->set_tx_rate(sampleRate, channel); + } + }; + + // Let UHD try first, as it may find a master clock rate that suits both this and other channels' rates + set(); + + double actualRate = rx ? usrp->get_rx_rate(channel) : usrp->get_tx_rate(channel); + + // Single channel streams, so 1 channel for clock rate limit, as UHD uses + if ((std::abs(actualRate - sampleRate) >= 1.0) && setMasterClockRateForSampleRate(usrp, sampleRate, 1)) + { + qDebug("DeviceUSRP::setSampleRate: %s channel %d: rate coerced to %f - setting master clock rate for %f", + rx ? "Rx" : "Tx", channel, actualRate, sampleRate); + + try + { + set(); + } + catch (...) + { + enableAutoMasterClockRate(usrp); + throw; + } + + enableAutoMasterClockRate(usrp); + } +} + +// When the master clock rate changes, UHD (B2xx) reprograms each channel's DSP for its previously set rate, +// which may be coerced to a different rate, but get_rx/tx_rate() still return the previous rate. +// So find the rate the DSP is actually using, which is the nearest rate achievable with the current clock rate. +double DeviceUSRP::getSampleRate(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channel) +{ + if (rx) { + return usrp->get_rx_rates(channel).clip(usrp->get_rx_rate(channel), true); + } else { + return usrp->get_tx_rates(channel).clip(usrp->get_tx_rate(channel), true); } } diff --git a/devices/usrp/deviceusrp.h b/devices/usrp/deviceusrp.h index ca21f3b60..b345e72e0 100644 --- a/devices/usrp/deviceusrp.h +++ b/devices/usrp/deviceusrp.h @@ -36,7 +36,40 @@ public: static void enumOriginDevices(const QString& hardwareId, PluginInterface::OriginDevices& originDevices); /** Wait for ref clock and LO to lock */ - static void waitForLock(uhd::usrp::multi_usrp::sptr usrp, const QString& clockSource, int channel); + static void waitForLock(uhd::usrp::multi_usrp::sptr usrp, const QString& clockSource, int channel, bool rx); + + /** Determine whether two Rx or two Tx channels share the same LO (and sample rate) */ + static bool channelsShareLO(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channelA, int channelB); + + /** Get board temperature in degrees C. Returns false if the device doesn't have a temperature sensor */ + static bool getTemperature(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channel, double& temperature); + + /** Get number of samples to read per recv() call, which is a power of two, as required by decimators */ + static size_t getRecvBufferSamples(size_t maxNumSamps, int sampleRate); + + /** Set priority of calling thread, so it can stream samples without overflowing / underflowing */ + static void setStreamingThreadPriority(); + + /** + * Call before setting all channels to the same sample rate, on devices where UHD chooses the master clock rate automatically (B2xx). + * Sets a master clock rate suitable for the new sample rate and disables automatic selection. + * Returns true if automatic selection should be re-enabled with enableAutoMasterClockRate() once the sample rates have been set. + */ + static bool setMasterClockRateForSampleRate(uhd::usrp::multi_usrp::sptr usrp, double sampleRate, size_t nbChannels); + static void enableAutoMasterClockRate(uhd::usrp::multi_usrp::sptr usrp); + + /** + * Set sample rate of a single channel. If it can't be achieved with a master clock rate UHD chooses automatically + * to also suit other channels' rates (E.g. a buddy's), the master clock rate is set for the requested rate, + * and other channels' rates are coerced, so need to be read back. + */ + static void setSampleRate(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channel, double sampleRate); + + /** Get actual sample rate of a channel, which may have been changed by the master clock rate being changed for another channel */ + static double getSampleRate(uhd::usrp::multi_usrp::sptr usrp, bool rx, int channel); + + /** Timeout for recv() and send(), in seconds */ + static constexpr double m_streamTimeout = 0.5; }; #endif /* DEVICES_USRP_DEVICEUSRP_H_ */ diff --git a/devices/usrp/deviceusrpparam.cpp b/devices/usrp/deviceusrpparam.cpp index 73a0e3caf..22f12376d 100644 --- a/devices/usrp/deviceusrpparam.cpp +++ b/devices/usrp/deviceusrpparam.cpp @@ -16,6 +16,8 @@ // along with this program. If not, see . // /////////////////////////////////////////////////////////////////////////////////// +#include + #include #include "deviceusrpparam.h" @@ -27,6 +29,13 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) { std::string device_args(qPrintable(deviceStr)); + // UHD's default receive buffering for USB devices (B2xx) is only a few ms at high sample rates, + // which isn't enough to absorb OS scheduling latency (particularly on Windows), resulting in overflows. + // So increase it (to ~2MB), unless specified by the user. + if (deviceStr.contains("type=b200") && !deviceStr.contains("num_recv_frames")) { + device_args += ",num_recv_frames=256"; + } + // For USB // The recv_frame_size must be a multiple of 8 bytes and not a multiple of 1024 bytes. // recv_frame_size max is 16360. @@ -39,11 +48,38 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) m_nbTxChannels = m_dev->get_tx_num_channels(); qDebug() << "DeviceUSRPParams::open: m_nbRxChannels: " << m_nbRxChannels << " m_nbTxChannels: " << m_nbTxChannels; - // Speed up program initialisation, by not getting all properties - // If we could find out number of channels without ::make ing the device - // that would be even better - if (!channelNumOnly) - { + // On B2xx, Rx streams share a transport, so recv() calls for different streams must be serialised + // (See DeviceUSRPRecvLock). Other devices have a transport per stream, so don't need this. + QString mboardName = QString::fromStdString(m_dev->get_mboard_name()); + m_recvLock.setEnabled(mboardName.startsWith("B2")); + qDebug() << "DeviceUSRPParams::open: mboard: " << mboardName; + } + catch (const std::exception& e) + { + qDebug() << "DeviceUSRPParams::open: exception: " << e.what(); + close(); + return false; + } + + // Speed up program initialisation, by not getting all properties + // If we could find out number of channels without ::make ing the device + // that would be even better + if (!channelNumOnly) + { + // Not all properties are supported by all devices / daughterboards, so + // query each group separately, so one failure doesn't prevent use of the device + auto tryQuery = [](const char *what, const std::function& query) { + try + { + query(); + } + catch (const std::exception& e) + { + qWarning() << "DeviceUSRPParams::open: failed to get" << what << ":" << e.what(); + } + }; + + tryQuery("frequency and bandwidth ranges", [this]() { if (m_nbRxChannels > 0) { m_lpfRangeRx = m_dev->get_rx_bandwidth_range(); @@ -54,7 +90,9 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) m_lpfRangeTx = m_dev->get_tx_bandwidth_range(); m_loRangeTx = m_dev->get_fe_tx_freq_range(); } + }); + tryQuery("sample rate ranges", [this, &deviceStr]() { // For some devices (B210), rx/tx_rates vary with master_clock_rate // which can be set automatically by UHD. For other devices, // master_clock_rate must be set manually (currently as a device arg) @@ -111,7 +149,9 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) properties->access("/mboards/0/auto_tick_rate").set(true); } } + }); + tryQuery("Rx gains and antennas", [this]() { if (m_nbRxChannels > 0) { m_gainRangeRx = m_dev->get_rx_gain_range(); @@ -128,6 +168,9 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) m_rxGainNames << QString::fromStdString(rxGainNames[i]); } } + }); + + tryQuery("Tx gains and antennas", [this]() { if (m_nbTxChannels > 0) { m_gainRangeTx = m_dev->get_tx_gain_range(); @@ -138,21 +181,18 @@ bool DeviceUSRPParams::open(const QString &deviceStr, bool channelNumOnly) m_txAntennas << QString::fromStdString(txAntennas[i]); } } + }); + tryQuery("clock sources", [this]() { std::vector clockSources = m_dev->get_clock_sources(0); m_clockSources.reserve(clockSources.size()); for(size_t i = 0, l = clockSources.size(); i < l; ++i) { m_clockSources << QString::fromStdString(clockSources[i]); } - } - - return true; - } - catch (const std::exception& e) - { - qDebug() << "DeviceUSRPParams::open: exception: " << e.what(); - return false; + }); } + + return true; } void DeviceUSRPParams::close() diff --git a/devices/usrp/deviceusrpparam.h b/devices/usrp/deviceusrpparam.h index 54fbc1be0..0808af169 100644 --- a/devices/usrp/deviceusrpparam.h +++ b/devices/usrp/deviceusrpparam.h @@ -20,6 +20,9 @@ #define DEVICES_USRP_DEVICEUSRPPARAM_H_ #include +#include +#include +#include #include #include @@ -27,6 +30,61 @@ #include "export.h" +/** + * Fair (first come, first served) lock, used to serialise calls to rx_streamer::recv() for + * different streams on the same device, on devices where that is required. + * + * On B2xx, all Rx streams share one transport, with packets being routed to each stream by UHD's + * recv_packet_demuxer_3000. This reads from the transport without holding its mutex, so if + * recv() is called concurrently for two streams, packets can be delivered out of order + * (Seen as 'D' in the console, and reported as an overflow, although no samples are lost). + * + * The lock needs to be fair, so one thread can't starve the other, as packets for a starved + * stream are queued by the demuxer, eventually exhausting the transport's receive frames. + */ +class DeviceUSRPRecvLock +{ +public: + DeviceUSRPRecvLock() : + m_enabled(false), + m_nextTicket(0), + m_servingTicket(0) + { + } + + void setEnabled(bool enabled) { m_enabled = enabled; } + + void lock() + { + if (m_enabled) + { + QMutexLocker locker(&m_mutex); + quint64 ticket = m_nextTicket++; + + while (ticket != m_servingTicket) { + m_waitCondition.wait(&m_mutex); + } + } + } + + void unlock() + { + if (m_enabled) + { + QMutexLocker locker(&m_mutex); + m_servingTicket++; + m_waitCondition.wakeAll(); + } + } + +private: + bool m_enabled; //!< Only set when device is opened, before any streams are created + QMutex m_mutex; + QWaitCondition m_waitCondition; + quint64 m_nextTicket; + quint64 m_servingTicket; +}; + /** * This structure refers to one physical device shared among parties (logical devices represented by * the DeviceAPI with single Rx or Tx stream type). @@ -51,6 +109,8 @@ struct DEVICES_API DeviceUSRPParams QStringList m_rxAntennas; //!< List of Rx antenna names QStringList m_rxGainNames; //!< List of Rx gain stages - Currently this seems limited to "PGA" QStringList m_clockSources; //!< List of clock sources E.g. "internal", "external", "gpsdo" + QRecursiveMutex m_mutex; //!< Serialises configuration of the device from the device engine threads of different buddies + DeviceUSRPRecvLock m_recvLock; //!< Serialises rx_streamer::recv() calls for streams of different buddies, where required DeviceUSRPParams() : m_dev(), diff --git a/devices/usrp/deviceusrpshared.cpp b/devices/usrp/deviceusrpshared.cpp index 5e47dec34..919ea9491 100644 --- a/devices/usrp/deviceusrpshared.cpp +++ b/devices/usrp/deviceusrpshared.cpp @@ -21,5 +21,9 @@ MESSAGE_CLASS_DEFINITION(DeviceUSRPShared::MsgReportBuddyChange, Message) MESSAGE_CLASS_DEFINITION(DeviceUSRPShared::MsgReportClockSourceChange, Message) +MESSAGE_CLASS_DEFINITION(DeviceUSRPShared::MsgReportDeviceSettings, Message) +MESSAGE_CLASS_DEFINITION(DeviceUSRPShared::MsgReadDeviceSampleRate, Message) +MESSAGE_CLASS_DEFINITION(DeviceUSRPShared::MsgReportDeviceInfo, Message) +MESSAGE_CLASS_DEFINITION(DeviceUSRPShared::MsgResizeSampleFifo, Message) const unsigned int DeviceUSRPShared::m_sampleFifoMinRate = 48000; diff --git a/devices/usrp/deviceusrpshared.h b/devices/usrp/deviceusrpshared.h index e880e63a0..d5e211a7e 100644 --- a/devices/usrp/deviceusrpshared.h +++ b/devices/usrp/deviceusrpshared.h @@ -41,20 +41,23 @@ public: int getLOOffset() const { return m_loOffset; } int getMasterClockRate() const { return m_masterClockRate; } bool getRxElseTx() const { return m_rxElseTx; } + int getChannel() const { return m_channel; } static MsgReportBuddyChange* create( int devSampleRate, uint64_t centerFrequency, int loOffset, int masterClockRate, - bool rxElseTx) + bool rxElseTx, + int channel = -1) { return new MsgReportBuddyChange( devSampleRate, centerFrequency, loOffset, masterClockRate, - rxElseTx); + rxElseTx, + channel); } private: @@ -63,19 +66,22 @@ public: int m_loOffset; //!< LO offset int m_masterClockRate; //!< FPGA/RFIC sample rate bool m_rxElseTx; //!< tells which side initiated the message + int m_channel; //!< channel of the buddy that initiated the message (-1 if unknown) MsgReportBuddyChange( int devSampleRate, uint64_t centerFrequency, int loOffset, int masterClockRate, - bool rxElseTx) : + bool rxElseTx, + int channel) : Message(), m_devSampleRate(devSampleRate), m_centerFrequency(centerFrequency), m_loOffset(loOffset), m_masterClockRate(masterClockRate), - m_rxElseTx(rxElseTx) + m_rxElseTx(rxElseTx), + m_channel(channel) { } }; @@ -101,6 +107,125 @@ public: }; + /** + * Actual device settings, read back in the device engine thread after settings have been applied + * (or after a buddy has changed a shared setting such as the master clock rate) + */ + class DEVICES_API MsgReportDeviceSettings : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getSampleRateValid() const { return m_sampleRateValid; } + double getSampleRate() const { return m_sampleRate; } + double getMasterClockRate() const { return m_masterClockRate; } + bool getClockSourceValid() const { return m_clockSourceValid; } + const QString& getClockSource() const { return m_clockSource; } + bool getForwardToBuddies() const { return m_forwardToBuddies; } + + static MsgReportDeviceSettings* create( + bool sampleRateValid, + double sampleRate, + double masterClockRate, + bool clockSourceValid, + const QString& clockSource, + bool forwardToBuddies) + { + return new MsgReportDeviceSettings( + sampleRateValid, + sampleRate, + masterClockRate, + clockSourceValid, + clockSource, + forwardToBuddies); + } + + private: + bool m_sampleRateValid; //!< m_sampleRate and m_masterClockRate are valid + double m_sampleRate; //!< Actual device/host sample rate + double m_masterClockRate; //!< Actual FPGA/RFIC sample rate + bool m_clockSourceValid; //!< m_clockSource is valid + QString m_clockSource; //!< Actual clock source + bool m_forwardToBuddies; //!< Result of our own settings change, so buddies need to be informed + + MsgReportDeviceSettings( + bool sampleRateValid, + double sampleRate, + double masterClockRate, + bool clockSourceValid, + const QString& clockSource, + bool forwardToBuddies) : + Message(), + m_sampleRateValid(sampleRateValid), + m_sampleRate(sampleRate), + m_masterClockRate(masterClockRate), + m_clockSourceValid(clockSourceValid), + m_clockSource(clockSource), + m_forwardToBuddies(forwardToBuddies) + { } + }; + + /** Request for the device engine thread to read back the actual sample rate (E.g. after a buddy has changed the master clock rate) */ + class DEVICES_API MsgReadDeviceSampleRate : public Message { + MESSAGE_CLASS_DECLARATION + + public: + static MsgReadDeviceSampleRate* create() { + return new MsgReadDeviceSampleRate(); + } + + private: + MsgReadDeviceSampleRate() : + Message() + { } + }; + + /** + * Request for the device engine thread to resize the Tx sample FIFO. + * This needs to be done in the device engine thread, as that's where samples are written to the FIFO, + * with the Tx streaming thread paused, as that's where they are read. + */ + class DEVICES_API MsgResizeSampleFifo : public Message { + MESSAGE_CLASS_DECLARATION + + public: + unsigned int getSize() const { return m_size; } + + static MsgResizeSampleFifo* create(unsigned int size) { + return new MsgResizeSampleFifo(size); + } + + private: + unsigned int m_size; + + MsgResizeSampleFifo(unsigned int size) : + Message(), + m_size(size) + { } + }; + + /** Device information (E.g. temperature), sent to the GUIs of all buddies */ + class DEVICES_API MsgReportDeviceInfo : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getTemperatureValid() const { return m_temperatureValid; } + float getTemperature() const { return m_temperature; } + + static MsgReportDeviceInfo* create(bool temperatureValid, float temperature) { + return new MsgReportDeviceInfo(temperatureValid, temperature); + } + + private: + bool m_temperatureValid; //!< False if device doesn't have a temperature sensor + float m_temperature; //!< Board temperature in degrees C + + MsgReportDeviceInfo(bool temperatureValid, float temperature) : + Message(), + m_temperatureValid(temperatureValid), + m_temperature(temperature) + { } + }; + class DEVICES_API ThreadInterface { public: diff --git a/devices/usrp/deviceusrpstreamstats.cpp b/devices/usrp/deviceusrpstreamstats.cpp new file mode 100644 index 000000000..42d1f672e --- /dev/null +++ b/devices/usrp/deviceusrpstreamstats.cpp @@ -0,0 +1,115 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "deviceusrpstreamstats.h" + +DeviceUSRPStreamStats::DeviceUSRPStreamStats() : + m_running(false), + m_started(false), + m_lastCount(0), + m_offset(0), + m_runTimeMs(0) +{ +} + +void DeviceUSRPStreamStats::update(bool running, quint32 count) +{ + if (running && !m_running) + { + // Stream started - reset statistics + m_started = true; + m_lastCount = 0; + m_offset = 0; + m_runTimer.start(); + m_runTimeMs = 0; + m_lastEventTime = QDateTime(); + m_history.clear(); + } + else if (!running && m_running) + { + // Stream stopped - keep statistics from last run + m_runTimeMs = m_runTimer.elapsed(); + } + + m_running = running; + + if (!running) { + return; + } + + if (count < m_lastCount) + { + // Streaming thread was restarted, which resets its count + m_offset += m_lastCount; + + if (count > 0) { // Events since restart + m_lastEventTime = QDateTime::currentDateTime(); + } + } + else if (count > m_lastCount) + { + m_lastEventTime = QDateTime::currentDateTime(); + } + + m_lastCount = count; + + // Keep history for last minute, so we can count recent events + qint64 now = m_runTimer.elapsed(); + m_history.push_back({now, getCount()}); + + while ((m_history.size() > 1) && (now - m_history.front().first > m_historyMs)) { + m_history.pop_front(); + } +} + +QString DeviceUSRPStreamStats::getToolTip(const QString& description, const QString& eventName) const +{ + QStringList lines; + + lines.append(description); + + if (!m_started) { + return lines.join("\n"); + } + + quint64 count = getCount(); + qint64 runTimeMs = m_running ? m_runTimer.elapsed() : m_runTimeMs; + + lines.append(""); + lines.append(QString("%1%2: %3").arg(eventName).arg(m_running ? "" : " (last run)").arg(count)); + + if (runTimeMs >= 1000) + { + double perMinute = count / (runTimeMs / 60000.0); + lines.append(QString("Average: %1 per minute").arg(QString::number(perMinute, 'f', 1))); + } + + if (m_running && !m_history.empty()) { + lines.append(QString("Last minute: %1").arg(count - m_history.front().second)); + } + + if (m_lastEventTime.isValid()) + { + qint64 secsAgo = m_lastEventTime.secsTo(QDateTime::currentDateTime()); + lines.append(QString("Last: %1 (%2 s ago)").arg(m_lastEventTime.toString("hh:mm:ss")).arg(secsAgo)); + } + + return lines.join("\n"); +} diff --git a/devices/usrp/deviceusrpstreamstats.h b/devices/usrp/deviceusrpstreamstats.h new file mode 100644 index 000000000..19aa00a74 --- /dev/null +++ b/devices/usrp/deviceusrpstreamstats.h @@ -0,0 +1,64 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef DEVICES_USRP_DEVICEUSRPSTREAMSTATS_H_ +#define DEVICES_USRP_DEVICEUSRPSTREAMSTATS_H_ + +#include +#include + +#include +#include +#include + +#include "export.h" + +/** + * Statistics for stream events (E.g. overruns, underruns, timeouts or dropped packets), + * calculated from the event counts that are periodically reported by the streaming threads. + * + * The streaming threads reset their counts whenever they are restarted, which can happen + * while the stream is running (E.g. when paused while a buddy creates its stream), + * so counts are accumulated, and only reset when the stream is started. + */ +class DEVICES_API DeviceUSRPStreamStats +{ +public: + DeviceUSRPStreamStats(); + + //! Update with latest report. count is the event count reported by the streaming thread. + void update(bool running, quint32 count); + //! Total number of events since the stream was started + quint64 getCount() const { return m_offset + m_lastCount; } + //! Get tooltip, with statistics appended to description. eventName is plural (E.g. "Overruns") + QString getToolTip(const QString& description, const QString& eventName) const; + +private: + bool m_running; + bool m_started; //!< Stream has been started at least once + quint32 m_lastCount; //!< Last count reported by streaming thread + quint64 m_offset; //!< Accumulated count from before the streaming thread's count was reset + QElapsedTimer m_runTimer; //!< Time since stream was started + qint64 m_runTimeMs; //!< Run time when stopped + QDateTime m_lastEventTime; + std::deque> m_history; //!< (run time ms, total count) for last minute + + static const qint64 m_historyMs = 60000; +}; + +#endif // DEVICES_USRP_DEVICEUSRPSTREAMSTATS_H_ diff --git a/plugins/samplemimo/CMakeLists.txt b/plugins/samplemimo/CMakeLists.txt index b9cd58c7b..595503c26 100644 --- a/plugins/samplemimo/CMakeLists.txt +++ b/plugins/samplemimo/CMakeLists.txt @@ -24,6 +24,12 @@ else() message(STATUS "Not building plutosdrmimo (ENABLE_IIO=${ENABLE_IIO} LIBIIO_FOUND=${LIBIIO_FOUND})") endif() +if(ENABLE_USRP AND UHD_FOUND) + add_subdirectory(usrpmimo) +else() + message(STATUS "Not building usrpmimo (ENABLE_USRP=${ENABLE_USRP} UHD_FOUND=${UHD_FOUND})") +endif() + find_package (Hamlib) if(hamlib_FOUND) add_subdirectory(audiocatsiso) diff --git a/plugins/samplemimo/usrpmimo/CMakeLists.txt b/plugins/samplemimo/usrpmimo/CMakeLists.txt new file mode 100644 index 000000000..3455ffa84 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/CMakeLists.txt @@ -0,0 +1,83 @@ +project(usrpmimo) + +set(usrpmimo_SOURCES + usrpmimo.cpp + usrpmimoplugin.cpp + usrpmimosettings.cpp + usrpmimowebapiadapter.cpp + usrpmimoworker.cpp + usrpmithread.cpp + usrpmothread.cpp +) + +set(usrpmimo_HEADERS + usrpmimo.h + usrpmimoplugin.h + usrpmimosettings.h + usrpmimowebapiadapter.h + usrpmimoworker.h + usrpmithread.h + usrpmothread.h +) + +include_directories( + ${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client + ${CMAKE_SOURCE_DIR}/devices + ${UHD_INCLUDE_DIR} + ${Boost_INCLUDE_DIRS} +) + +if(NOT SERVER_MODE) + set(usrpmimo_SOURCES + ${usrpmimo_SOURCES} + usrpmimogui.cpp + usrpmimogui.ui + ) + set(usrpmimo_HEADERS + ${usrpmimo_HEADERS} + usrpmimogui.h + ) + + set(TARGET_NAME ${PLUGINS_PREFIX}mimousrp) + set(TARGET_LIB "Qt::Widgets") + set(TARGET_LIB_GUI "sdrgui") + set(INSTALL_FOLDER ${INSTALL_PLUGINS_DIR}) +else() + set(TARGET_NAME ${PLUGINSSRV_PREFIX}mimousrpsrv) + set(TARGET_LIB "") + set(TARGET_LIB_GUI "") + set(INSTALL_FOLDER ${INSTALL_PLUGINSSRV_DIR}) +endif() + +if(NOT Qt6_FOUND) + add_library(${TARGET_NAME} ${usrpmimo_SOURCES}) +else() + qt_add_plugin(${TARGET_NAME} CLASS_NAME USRPMIMOPlugin) + target_sources(${TARGET_NAME} PRIVATE ${usrpmimo_SOURCES}) +endif() + +if(NOT BUILD_SHARED_LIBS) + set_property(GLOBAL APPEND PROPERTY STATIC_PLUGINS_PROPERTY ${TARGET_NAME}) +endif() + +if(UHD_EXTERNAL) + add_dependencies(${TARGET_NAME} uhd) +endif() + +target_link_libraries(${TARGET_NAME} PRIVATE + Qt::Core + ${TARGET_LIB} + sdrbase + ${TARGET_LIB_GUI} + swagger + ${UHD_LIBRARIES} + usrpdevice +) + +install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER}) + +# Install debug symbols +if (WIN32) + install(FILES $/${TARGET_NAME}stripped.pdb CONFIGURATIONS Release DESTINATION ${INSTALL_FOLDER} RENAME ${TARGET_NAME}.pdb ) + install(FILES $ CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} ) +endif() diff --git a/plugins/samplemimo/usrpmimo/readme.md b/plugins/samplemimo/usrpmimo/readme.md new file mode 100644 index 000000000..bb137f8ef --- /dev/null +++ b/plugins/samplemimo/usrpmimo/readme.md @@ -0,0 +1,113 @@ +

USRP MIMO plugin

+ +

Introduction

+ +This MIMO plugin sends and receives multiple streams of I/Q samples to and from a [USRP device](https://www.ettus.com/product-category/usrp-bus-series/) that has more than one Rx or Tx channel, such as the B210, X310 or N320. + +Up to two Rx and two Tx channels are supported. On devices with more channels (E.g. N310), the first two channels are used. + +The Rx channels are received using a single UHD stream and the Tx channels are transmitted using a single UHD stream, +so that samples for each channel are time aligned, which is required for applications such as direction finding and beamforming. + +The Rx and Tx sides can be started and stopped independently. + +The center frequency is common to both channels on each side (Rx and Tx), as is required for coherent operation. +On devices where the two channels share an LO (E.g. B210), this is also a hardware requirement. +The sample rate is common to Rx and Tx. + +Settings are applied to the device in a separate thread, so that settings that take a long time to apply +(E.g. sample rate, clock source and bandwidth) do not block the GUI. + +

Interface

+ +The top and bottom bars of the device window are described [here](../../../sdrgui/device/readme.md) + +![USRP MIMO plugin GUI](../../../doc/img/USRPMIMO_plugin.png) + +

1: Stream selection

+ +Selects which side (Rx or Tx) and which channel (0 or 1) the settings below apply to. +Settings common to both channels of a side (E.g. center frequency, LO offset, bandwidth, decimation or interpolation) +are shown for the selected side. Settings that are per channel (gain, gain mode and antenna) are shown for the selected channel. + +

2: Spectrum source

+ +Selects which side (Rx or Tx) and which channel is displayed in the main spectrum. + +

3: Rx and Tx start/stop

+ +Starts or stops the Rx or Tx side. The button color indicates the state: + + - Grey: device is not running + - Blue: device is idle + - Green: device is running + - Red: device is in error + +

4: Baseband sample rate

+ +This is the baseband sample rate of the selected side, after software decimation or interpolation. + +

5: Center frequency

+ +This is the center frequency in kHz of the selected side. It is common to both channels. + +

6: LO offset

+ +The LO of the selected side is offset from the center frequency by this amount (in kHz), and the digital NCOs in the device are used to +compensate. This can be used to move the DC spike and LO leakage away from the center of the band. It should be less than half of the sample rate. + +

7: Clock source

+ +Selects the reference clock source for the device (E.g. internal, external or gpsdo). If the selected clock is not detected, the device +falls back to the internal clock, and this is shown here. + +

8: DC offset and IQ imbalance correction

+ +Enables automatic DC offset and IQ imbalance correction in the device, for both Rx channels. These are not available for Tx. + +

9: Analog low pass filter bandwidth

+ +Sets the bandwidth of the analog low pass filter, in kHz, for both channels of the selected side. + +

10: Transverter mode

+ +Opens the transverter dialog for the selected side. See the [transverter dialog](../../../sdrgui/gui/transverterdialog.md) documentation for details. + +

11: Sample rate

+ +This is the device to host (SR) or baseband (BB) sample rate in samples per second. The button on the left switches between the two modes. +The device to host sample rate is common to the Rx and Tx sides. + +

12: Master clock rate

+ +This is the sample rate between the FPGA and RFIC, as calculated by UHD from the requested sample rate. It is common to Rx and Tx. + +

13: Software decimation or interpolation factor

+ +This is the software decimation (Rx) or interpolation (Tx) factor applied to the samples of the selected side, to obtain the baseband sample rate. + +

14: Gain

+ +The gain lock button, when engaged, applies gain settings to both channels of the selected side. + +The gain mode (Rx only) selects between automatic gain control and manual gain. The slider sets the gain in dB, when manual gain is selected. + +

15: Antenna

+ +Selects the antenna for the selected channel. + +

16: Board temperature

+ +This is the temperature of the board in degrees C, for devices that have a temperature sensor (E.g. the AD9361 on the B210). + +

17: Stream status indicators

+ +These show the status of the stream for the selected side: + + - Stream: turns green when the stream is running + - **O**/**U**: turns red if the Rx stream experiences overruns or the Tx stream experiences underruns + - **T**/**D**: turns red if the Rx stream experiences timeouts or the Tx stream drops packets + +The indicators are reset when the side is restarted. + +Hovering over an indicator shows statistics for the current (or last) run: the total number of events, the average number per minute, the number in the last minute and the time of the last event. diff --git a/plugins/samplemimo/usrpmimo/usrpmimo.cpp b/plugins/samplemimo/usrpmimo/usrpmimo.cpp new file mode 100644 index 000000000..aac1a25c8 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimo.cpp @@ -0,0 +1,1387 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include +#include +#include +#include +#include + +#include "SWGDeviceSettings.h" +#include "SWGDeviceState.h" +#include "SWGDeviceReport.h" +#include "SWGUSRPMIMOSettings.h" +#include "SWGUSRPMIMOReport.h" + +#include "device/deviceapi.h" +#include "dsp/dspcommands.h" +#include "dsp/samplemofifo.h" +#include "util/poweroftwo.h" +#include "usrp/deviceusrp.h" +#include "usrp/deviceusrpparam.h" +#include "usrp/deviceusrpshared.h" + +#include "usrpmithread.h" +#include "usrpmothread.h" +#include "usrpmimoworker.h" +#include "usrpmimo.h" + +MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgConfigureUSRPMIMO, Message) +MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgStartStop, Message) +MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgGetStreamInfo, Message) +MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgReportStreamInfo, Message) +MESSAGE_CLASS_DEFINITION(USRPMIMO::MsgGetDeviceInfo, Message) + +USRPMIMO::USRPMIMO(DeviceAPI *deviceAPI) : + m_deviceAPI(deviceAPI), + m_settings(), + m_sourceThread(nullptr), + m_sinkThread(nullptr), + m_deviceDescription("USRPMIMO"), + m_runningRx(false), + m_runningTx(false), + m_deviceParams(nullptr), + m_nbRx(0), + m_nbTx(0), + m_workerThread(nullptr), + m_worker(nullptr) +{ + openDevice(); + + m_mimoType = MIMOHalfSynchronous; + m_sampleMIFifo.init(m_nbRx, 1<<20); + m_sampleMOFifo.init(m_nbTx, 4096 * 64); + m_deviceAPI->setNbSourceStreams(m_nbRx); + m_deviceAPI->setNbSinkStreams(m_nbTx); + + m_networkManager = new QNetworkAccessManager(); + QObject::connect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &USRPMIMO::networkManagerFinished + ); + + if (m_deviceParams) + { + // Settings are applied to the device in a separate thread, so they don't block the GUI + m_workerThread = new QThread(); + m_workerThread->setObjectName("USRPMIMOWorker"); + m_worker = new USRPMIMOWorker(m_deviceParams, m_nbRx, m_nbTx, getInputMessageQueue()); + m_worker->moveToThread(m_workerThread); + m_workerThread->start(); + } +} + +USRPMIMO::~USRPMIMO() +{ + QObject::disconnect( + m_networkManager, + &QNetworkAccessManager::finished, + this, + &USRPMIMO::networkManagerFinished + ); + delete m_networkManager; + + if (m_workerThread) + { + m_workerThread->quit(); + m_workerThread->wait(); + delete m_worker; + delete m_workerThread; + } + + closeDevice(); +} + +void USRPMIMO::destroy() +{ + delete this; +} + +bool USRPMIMO::openDevice() +{ + QString deviceStr; + + // If a non-discoverable device, serial will be of the form USRP-N + if (m_deviceAPI->getSamplingDeviceSerial().startsWith("USRP")) + { + deviceStr = m_deviceAPI->getHardwareUserArguments(); + } + else + { + deviceStr = m_deviceAPI->getSamplingDeviceSerial(); + + if (m_deviceAPI->getHardwareUserArguments().size() != 0) { + deviceStr = deviceStr + ',' + m_deviceAPI->getHardwareUserArguments(); + } + } + + m_deviceParams = new DeviceUSRPParams(); + + if (!m_deviceParams->open(deviceStr, false)) + { + qCritical("USRPMIMO::openDevice: failed to open device"); + delete m_deviceParams; + m_deviceParams = nullptr; + // Nominal number of streams, so GUI can be displayed + m_nbRx = 2; + m_nbTx = 2; + return false; + } + + m_nbRx = std::min(2, (int) m_deviceParams->m_nbRxChannels); + m_nbTx = std::min(2, (int) m_deviceParams->m_nbTxChannels); + qDebug("USRPMIMO::openDevice: using %d Rx and %d Tx channels", m_nbRx, m_nbTx); + + return true; +} + +void USRPMIMO::closeDevice() +{ + // Stop Tx first, so stopRx doesn't pause and resume the Tx thread, which may be called from the GUI thread, + // while the device engine thread might be resizing the Tx FIFO + if (m_runningTx) { + stopTx(); + } + + if (m_runningRx) { + stopRx(); + } + + if (m_deviceParams) + { + m_deviceParams->close(); + delete m_deviceParams; + m_deviceParams = nullptr; + } +} + +void USRPMIMO::init() +{ + applySettings(m_settings, QList(), true); +} + +// Called from the device engine thread +bool USRPMIMO::startRx() +{ + QMutexLocker mutexLocker(&m_mutex); + + if (m_runningRx) { + return true; + } + + uhd::usrp::multi_usrp::sptr device = m_deviceParams ? m_deviceParams->getDevice() : nullptr; + + if (!device || (m_nbRx == 0)) + { + qCritical("USRPMIMO::startRx: device was not opened or has no Rx channels"); + return false; + } + + qDebug("USRPMIMO::startRx"); + size_t bufSamples = 0; + + USRPMIMOSettings settings; + + // Pause Tx streaming while the device is reconfigured + bool txWasRunning = m_sinkThread && m_sinkThread->isRunning(); + if (txWasRunning) { + m_sinkThread->stopWork(); + } + + { + // Prevent settings being applied to the device while we set up the stream + QMutexLocker deviceLocker(&m_deviceParams->m_mutex); + + { + // Take a copy of the settings, as they can be changed in the GUI thread while the stream is being created. + // Take it with the device mutex held, so it includes any settings already applied by the worker. + // Settings changed after this will be applied by the worker once we release the device mutex. + QMutexLocker settingsLocker(&m_settingsMutex); + settings = m_settings; + } + + try + { + // Apply Rx settings before creating stream + // However, don't set LPF to <10MHz at this stage, otherwise there is massive TX LO leakage + USRPMIMOWorker::applyDeviceSettings(m_deviceParams, m_nbRx, m_nbTx, settings, QList(), + true, false, true, false, false, getInputMessageQueue()); + + uhd::stream_args_t streamArgs("sc16", "sc16"); + + for (int channel = 0; channel < m_nbRx; channel++) + { + device->set_rx_bandwidth(56000000, channel); + streamArgs.channels.push_back(channel); + } + + m_rxStream = device->get_rx_stream(streamArgs); + + // Read multiple packets per recv() call at high sample rates, to reduce overhead + bufSamples = DeviceUSRP::getRecvBufferSamples(m_rxStream->get_max_num_samps(), settings.m_devSampleRate); + + // Wait for reference and LO to lock, then we can set desired bandwidth + // Use actual clock source, in case requested clock wasn't detected + QString clockSource = QString::fromStdString(device->get_clock_source(0)); + + for (int channel = 0; channel < m_nbRx; channel++) + { + DeviceUSRP::waitForLock(device, clockSource, channel, true); + device->set_rx_bandwidth(settings.m_rxLpfBW, channel); + } + } + catch (std::exception& e) + { + qCritical() << "USRPMIMO::startRx: exception: " << e.what(); + } + } + + if (txWasRunning) { + m_sinkThread->startWork(); + } + + if (!m_rxStream) { + return false; + } + + m_sampleMIFifo.reset(); + USRPMIThread *thread = new USRPMIThread(device, m_rxStream, bufSamples, m_nbRx, &m_sampleMIFifo); + thread->setLog2Decimation(settings.m_log2SoftDecim); + thread->startWork(); + + { + // Settings changed while the stream was being created weren't sent to the thread, as it didn't exist, + // so use current settings. Lock settings first, so no more changes can be made until it's published. + QMutexLocker settingsLocker(&m_settingsMutex); + QMutexLocker threadLocker(&m_threadMutex); + thread->setLog2Decimation(m_settings.m_log2SoftDecim); + m_sourceThread = thread; + } + + m_runningRx = true; + + return true; +} + +// Called from the device engine thread +bool USRPMIMO::startTx() +{ + QMutexLocker mutexLocker(&m_mutex); + + if (m_runningTx) { + return true; + } + + uhd::usrp::multi_usrp::sptr device = m_deviceParams ? m_deviceParams->getDevice() : nullptr; + + if (!device || (m_nbTx == 0)) + { + qCritical("USRPMIMO::startTx: device was not opened or has no Tx channels"); + return false; + } + + qDebug("USRPMIMO::startTx"); + size_t bufSamples = 0; + + USRPMIMOSettings settings; + + // Pause Rx streaming while the device is reconfigured. Rx channels will be realigned on restart + bool rxWasRunning = m_sourceThread && m_sourceThread->isRunning(); + if (rxWasRunning) { + m_sourceThread->stopWork(); + } + + { + // Prevent settings being applied to the device while we set up the stream + QMutexLocker deviceLocker(&m_deviceParams->m_mutex); + + { + // Take a copy of the settings, as they can be changed in the GUI thread while the stream is being created. + // Take it with the device mutex held, so it includes any settings already applied by the worker. + // Settings changed after this will be applied by the worker once we release the device mutex. + QMutexLocker settingsLocker(&m_settingsMutex); + settings = m_settings; + } + + try + { + // Apply Tx settings before creating stream + // However, don't set LPF to <10MHz at this stage, otherwise there is massive TX LO leakage + USRPMIMOWorker::applyDeviceSettings(m_deviceParams, m_nbRx, m_nbTx, settings, QList(), + true, false, false, true, false, getInputMessageQueue()); + + uhd::stream_args_t streamArgs("sc16", "sc16"); + + for (int channel = 0; channel < m_nbTx; channel++) + { + device->set_tx_bandwidth(56000000, channel); + streamArgs.channels.push_back(channel); + } + + m_txStream = device->get_tx_stream(streamArgs); + + // Match our transmit buffer size to what UHD uses + bufSamples = m_txStream->get_max_num_samps(); + + // Wait for reference and LO to lock, then we can set desired bandwidth + // Use actual clock source, in case requested clock wasn't detected + QString clockSource = QString::fromStdString(device->get_clock_source(0)); + + for (int channel = 0; channel < m_nbTx; channel++) + { + DeviceUSRP::waitForLock(device, clockSource, channel, false); + device->set_tx_bandwidth(settings.m_txLpfBW, channel); + } + } + catch (std::exception& e) + { + qCritical() << "USRPMIMO::startTx: exception: " << e.what(); + } + } + + if (rxWasRunning) { + m_sourceThread->startWork(); + } + + if (!m_txStream) { + return false; + } + + // Size FIFO for sample rate. This is safe here, as Tx isn't running, so FIFO isn't being written to + m_sampleMOFifo.resize(getSampleMOFifoSize(settings)); + USRPMOThread *thread = new USRPMOThread(device, m_txStream, bufSamples, m_nbTx, &m_sampleMOFifo); + thread->setLog2Interpolation(settings.m_log2SoftInterp); + thread->startWork(); + + { + // Settings changed while the stream was being created weren't sent to the thread, as it didn't exist, + // so use current settings. Lock settings first, so no more changes can be made until it's published. + QMutexLocker settingsLocker(&m_settingsMutex); + QMutexLocker threadLocker(&m_threadMutex); + thread->setLog2Interpolation(m_settings.m_log2SoftInterp); + unsigned int fifoSize = getSampleMOFifoSize(m_settings); + + if (fifoSize != getSampleMOFifoSize(settings)) { + // Resize in device engine thread once we return + thread->getInputMessageQueue()->push(DeviceUSRPShared::MsgResizeSampleFifo::create(fifoSize)); + } + + m_sinkThread = thread; + } + + m_runningTx = true; + + return true; +} + +// Usually called from the device engine thread, but can be called from the GUI thread from the destructor +void USRPMIMO::stopRx() +{ + QMutexLocker mutexLocker(&m_mutex); + + if (!m_runningRx) { + return; + } + + qDebug("USRPMIMO::stopRx"); + m_runningRx = false; + + USRPMIThread *thread; + { + QMutexLocker threadLocker(&m_threadMutex); + thread = m_sourceThread; + m_sourceThread = nullptr; + } + + if (thread) + { + thread->stopWork(); + delete thread; + } + + // Pause Tx streaming while the Rx stream is destroyed, as that reconfigures the device + bool txWasRunning = m_sinkThread && m_sinkThread->isRunning(); + if (txWasRunning) { + m_sinkThread->stopWork(); + } + + m_rxStream = nullptr; + + if (txWasRunning) { + m_sinkThread->startWork(); + } +} + +// Usually called from the device engine thread, but can be called from the GUI thread from the destructor +void USRPMIMO::stopTx() +{ + QMutexLocker mutexLocker(&m_mutex); + + if (!m_runningTx) { + return; + } + + qDebug("USRPMIMO::stopTx"); + m_runningTx = false; + + USRPMOThread *thread; + { + QMutexLocker threadLocker(&m_threadMutex); + thread = m_sinkThread; + m_sinkThread = nullptr; + } + + if (thread) + { + // Wait for any FIFO resize being performed in the device engine thread to complete and prevent any more + thread->detach(); + thread->stopWork(); + // Release stream, so it's destroyed before the device, even if the thread is deleted later + thread->releaseStream(); + + QThread *ownerThread = thread->thread(); + if (!ownerThread || (ownerThread == QThread::currentThread()) || ownerThread->isFinished()) { + delete thread; + } else { + // Called from another thread while the device engine thread is still running, which may have + // a pending call to handleInputMessages, so delete it in the device engine thread + thread->deleteLater(); + } + } + + // Pause Rx streaming while the Tx stream is destroyed, as that reconfigures the device + bool rxWasRunning = m_sourceThread && m_sourceThread->isRunning(); + if (rxWasRunning) { + m_sourceThread->stopWork(); + } + + m_txStream = nullptr; + + if (rxWasRunning) { + m_sourceThread->startWork(); + } +} + +QByteArray USRPMIMO::serialize() const +{ + return m_settings.serialize(); +} + +bool USRPMIMO::deserialize(const QByteArray& data) +{ + bool success = true; + + { + QMutexLocker settingsLocker(&m_settingsMutex); + + if (!m_settings.deserialize(data)) + { + m_settings.resetToDefaults(); + success = false; + } + } + + MsgConfigureUSRPMIMO* message = MsgConfigureUSRPMIMO::create(m_settings, QList(), true); + m_inputMessageQueue.push(message); + + if (m_guiMessageQueue) + { + MsgConfigureUSRPMIMO* messageToGUI = MsgConfigureUSRPMIMO::create(m_settings, QList(), true); + m_guiMessageQueue->push(messageToGUI); + } + + return success; +} + +const QString& USRPMIMO::getDeviceDescription() const +{ + return m_deviceDescription; +} + +int USRPMIMO::getSourceSampleRate(int index) const +{ + (void) index; + return m_settings.m_devSampleRate / (1<{"rxCenterFrequency"}, false); + m_inputMessageQueue.push(message); + + if (m_guiMessageQueue) + { + MsgConfigureUSRPMIMO* messageToGUI = MsgConfigureUSRPMIMO::create(settings, QList{"rxCenterFrequency"}, false); + m_guiMessageQueue->push(messageToGUI); + } +} + +quint64 USRPMIMO::getSinkCenterFrequency(int index) const +{ + (void) index; + return m_settings.m_txCenterFrequency; +} + +void USRPMIMO::setSinkCenterFrequency(qint64 centerFrequency, int index) +{ + (void) index; + USRPMIMOSettings settings = m_settings; + settings.m_txCenterFrequency = centerFrequency; + + MsgConfigureUSRPMIMO* message = MsgConfigureUSRPMIMO::create(settings, QList{"txCenterFrequency"}, false); + m_inputMessageQueue.push(message); + + if (m_guiMessageQueue) + { + MsgConfigureUSRPMIMO* messageToGUI = MsgConfigureUSRPMIMO::create(settings, QList{"txCenterFrequency"}, false); + m_guiMessageQueue->push(messageToGUI); + } +} + +void USRPMIMO::getRxLORange(float& minF, float& maxF) const +{ + minF = m_deviceParams ? m_deviceParams->m_loRangeRx.start() : 0.0f; + maxF = m_deviceParams ? m_deviceParams->m_loRangeRx.stop() : 0.0f; +} + +void USRPMIMO::getTxLORange(float& minF, float& maxF) const +{ + minF = m_deviceParams ? m_deviceParams->m_loRangeTx.start() : 0.0f; + maxF = m_deviceParams ? m_deviceParams->m_loRangeTx.stop() : 0.0f; +} + +// Sample rate is common to Rx and Tx, so return intersection of ranges +void USRPMIMO::getSRRange(float& minF, float& maxF) const +{ + minF = 0.0f; + maxF = 0.0f; + + if (m_deviceParams) + { + if ((m_nbRx > 0) && (m_nbTx > 0)) + { + minF = std::max(m_deviceParams->m_srRangeRx.start(), m_deviceParams->m_srRangeTx.start()); + maxF = std::min(m_deviceParams->m_srRangeRx.stop(), m_deviceParams->m_srRangeTx.stop()); + } + else if (m_nbRx > 0) + { + minF = m_deviceParams->m_srRangeRx.start(); + maxF = m_deviceParams->m_srRangeRx.stop(); + } + else if (m_nbTx > 0) + { + minF = m_deviceParams->m_srRangeTx.start(); + maxF = m_deviceParams->m_srRangeTx.stop(); + } + } +} + +void USRPMIMO::getRxLPRange(float& minF, float& maxF) const +{ + minF = m_deviceParams ? m_deviceParams->m_lpfRangeRx.start() : 0.0f; + maxF = m_deviceParams ? m_deviceParams->m_lpfRangeRx.stop() : 0.0f; +} + +void USRPMIMO::getTxLPRange(float& minF, float& maxF) const +{ + minF = m_deviceParams ? m_deviceParams->m_lpfRangeTx.start() : 0.0f; + maxF = m_deviceParams ? m_deviceParams->m_lpfRangeTx.stop() : 0.0f; +} + +void USRPMIMO::getRxGainRange(float& minF, float& maxF) const +{ + minF = m_deviceParams ? m_deviceParams->m_gainRangeRx.start() : 0.0f; + maxF = m_deviceParams ? m_deviceParams->m_gainRangeRx.stop() : 0.0f; +} + +void USRPMIMO::getTxGainRange(float& minF, float& maxF) const +{ + minF = m_deviceParams ? m_deviceParams->m_gainRangeTx.start() : 0.0f; + maxF = m_deviceParams ? m_deviceParams->m_gainRangeTx.stop() : 0.0f; +} + +QStringList USRPMIMO::getRxAntennas() const +{ + return m_deviceParams ? m_deviceParams->m_rxAntennas : QStringList(); +} + +QStringList USRPMIMO::getTxAntennas() const +{ + return m_deviceParams ? m_deviceParams->m_txAntennas : QStringList(); +} + +QStringList USRPMIMO::getClockSources() const +{ + return m_deviceParams ? m_deviceParams->m_clockSources : QStringList(); +} + +bool USRPMIMO::handleMessage(const Message& message) +{ + if (MsgConfigureUSRPMIMO::match(message)) + { + MsgConfigureUSRPMIMO& conf = (MsgConfigureUSRPMIMO&) message; + qDebug() << "USRPMIMO::handleMessage: MsgConfigureUSRPMIMO"; + + if (!applySettings(conf.getSettings(), conf.getSettingsKeys(), conf.getForce())) { + qDebug("USRPMIMO::handleMessage: config error"); + } + + return true; + } + else if (DeviceUSRPShared::MsgReportDeviceSettings::match(message)) + { + // Settings actually set on the device, as read back in the worker or device engine thread + DeviceUSRPShared::MsgReportDeviceSettings& report = (DeviceUSRPShared::MsgReportDeviceSettings&) message; + QMutexLocker settingsLocker(&m_settingsMutex); + QList settingsKeys; + + if (report.getClockSourceValid() && (report.getClockSource() != m_settings.m_clockSource)) + { + m_settings.m_clockSource = report.getClockSource(); + settingsKeys.append("clockSource"); + } + + if (report.getSampleRateValid()) + { + int devSampleRate = (int) std::round(report.getSampleRate()); + int masterClockRate = (int) std::round(report.getMasterClockRate()); + qDebug() << "USRPMIMO::handleMessage: MsgReportDeviceSettings: devSampleRate:" << devSampleRate << "masterClockRate:" << masterClockRate; + + if ((devSampleRate != m_settings.m_devSampleRate) || (masterClockRate != m_settings.m_masterClockRate)) + { + bool sampleRateChanged = devSampleRate != m_settings.m_devSampleRate; + m_settings.m_devSampleRate = devSampleRate; + m_settings.m_masterClockRate = masterClockRate; + + if (sampleRateChanged) { + resizeSampleMOFifo(); + } + + settingsKeys.append("devSampleRate"); + settingsKeys.append("masterClockRate"); + forwardChangeRxDSP(); + forwardChangeTxDSP(); + } + } + + if (!settingsKeys.isEmpty() && m_guiMessageQueue) { + m_guiMessageQueue->push(MsgConfigureUSRPMIMO::create(m_settings, settingsKeys, false)); + } + + return true; + } + else if (MsgStartStop::match(message)) + { + MsgStartStop& cmd = (MsgStartStop&) message; + qDebug() << "USRPMIMO::handleMessage: " + << " " << (cmd.getRxElseTx() ? "Rx" : "Tx") + << " MsgStartStop: " << (cmd.getStartStop() ? "start" : "stop"); + + bool startStopRxElseTx = cmd.getRxElseTx(); + + if (cmd.getStartStop()) + { + if (m_deviceAPI->initDeviceEngine(startStopRxElseTx ? 0 : 1)) { + m_deviceAPI->startDeviceEngine(startStopRxElseTx ? 0 : 1); + } + } + else + { + m_deviceAPI->stopDeviceEngine(startStopRxElseTx ? 0 : 1); + } + + if (m_settings.m_useReverseAPI) { + webapiReverseSendStartStop(startStopRxElseTx, cmd.getStartStop()); + } + + return true; + } + else if (MsgGetStreamInfo::match(message)) + { + if (m_guiMessageQueue) + { + QMutexLocker threadLocker(&m_threadMutex); + bool active; + quint32 overUnderRuns; + quint32 timeoutsDropped; + + if (m_sourceThread) + { + m_sourceThread->getStreamStatus(active, overUnderRuns, timeoutsDropped); + m_guiMessageQueue->push(MsgReportStreamInfo::create(true, true, active, overUnderRuns, timeoutsDropped)); + } + else + { + m_guiMessageQueue->push(MsgReportStreamInfo::create(true, false, false, 0, 0)); + } + + if (m_sinkThread) + { + m_sinkThread->getStreamStatus(active, overUnderRuns, timeoutsDropped); + m_guiMessageQueue->push(MsgReportStreamInfo::create(false, true, active, overUnderRuns, timeoutsDropped)); + } + else + { + m_guiMessageQueue->push(MsgReportStreamInfo::create(false, false, false, 0, 0)); + } + } + + return true; + } + else if (MsgGetDeviceInfo::match(message)) + { + // Reading a sensor is quick, so do it here, but don't block the GUI thread + // if settings are being applied to the device in another thread + if (m_deviceParams && m_deviceParams->getDevice() && m_deviceParams->m_mutex.tryLock()) + { + double temperature = 0.0; + bool temperatureValid = DeviceUSRP::getTemperature(m_deviceParams->getDevice(), m_nbRx > 0, 0, temperature); + m_deviceParams->m_mutex.unlock(); + + if (m_guiMessageQueue) { + m_guiMessageQueue->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); + } + } + + return true; + } + else + { + return false; + } +} + +bool USRPMIMO::applySettings(const USRPMIMOSettings& settings, const QList& settingsKeys, bool force) +{ + QMutexLocker settingsLocker(&m_settingsMutex); + qDebug() << "USRPMIMO::applySettings: force:" << force << settings.getDebugString(settingsKeys, force); + bool changeRxDSP = false; + bool changeTxDSP = false; + + if (settingsKeys.contains("devSampleRate") || force) + { + changeRxDSP = true; + changeTxDSP = true; + } + + if (settingsKeys.contains("rxCenterFrequency") + || settingsKeys.contains("rxTransverterMode") + || settingsKeys.contains("rxTransverterDeltaFrequency") + || settingsKeys.contains("log2SoftDecim") + || force) + { + changeRxDSP = true; + } + + if (settingsKeys.contains("txCenterFrequency") + || settingsKeys.contains("txTransverterMode") + || settingsKeys.contains("txTransverterDeltaFrequency") + || settingsKeys.contains("log2SoftInterp") + || force) + { + changeTxDSP = true; + } + + { + QMutexLocker threadLocker(&m_threadMutex); + + if (m_sourceThread && (settingsKeys.contains("log2SoftDecim") || force)) { + m_sourceThread->setLog2Decimation(settings.m_log2SoftDecim); + } + + if (m_sinkThread && (settingsKeys.contains("log2SoftInterp") || force)) { + m_sinkThread->setLog2Interpolation(settings.m_log2SoftInterp); + } + } + + // Applying settings to the device can take a long time (E.g. sample rate, clock source and bandwidth), + // so they are applied in the worker thread, rather than blocking the GUI thread. + // Values actually set are reported back via DeviceUSRPShared::MsgReportDeviceSettings. + if (m_worker) { + m_worker->getInputMessageQueue()->push(MsgConfigureUSRPMIMO::create(settings, settingsKeys, force)); + } + + if (settings.m_useReverseAPI) + { + bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) || + settingsKeys.contains("reverseAPIAddress") || + settingsKeys.contains("reverseAPIPort") || + settingsKeys.contains("reverseAPIDeviceIndex"); + webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); + } + + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } + + if (settingsKeys.contains("devSampleRate") || settingsKeys.contains("log2SoftInterp") || force) { + resizeSampleMOFifo(); + } + + // If the device coerces the sample rate, this will be sent again with the actual rate, once reported + if (changeRxDSP) { + forwardChangeRxDSP(); + } + if (changeTxDSP) { + forwardChangeTxDSP(); + } + + return true; +} + +unsigned int USRPMIMO::getSampleMOFifoSize(const USRPMIMOSettings& settings) +{ + unsigned int fifoRate = std::max( + (unsigned int) settings.m_devSampleRate / (1<getInputMessageQueue()->push(DeviceUSRPShared::MsgResizeSampleFifo::create(getSampleMOFifoSize(m_settings))); + } +} + +void USRPMIMO::forwardChangeRxDSP() +{ + int sampleRate = m_settings.m_devSampleRate / (1<getDeviceEngineInputMessageQueue()->push(notif); + } +} + +void USRPMIMO::forwardChangeTxDSP() +{ + int sampleRate = m_settings.m_devSampleRate / (1<getDeviceEngineInputMessageQueue()->push(notif); + } +} + +int USRPMIMO::webapiSettingsGet( + SWGSDRangel::SWGDeviceSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setUsrpMimoSettings(new SWGSDRangel::SWGUSRPMIMOSettings()); + response.getUsrpMimoSettings()->init(); + webapiFormatDeviceSettings(response, m_settings); + return 200; +} + +int USRPMIMO::webapiSettingsPutPatch( + bool force, + const QStringList& deviceSettingsKeys, + SWGSDRangel::SWGDeviceSettings& response, // query + response + QString& errorMessage) +{ + (void) errorMessage; + USRPMIMOSettings settings = m_settings; + webapiUpdateDeviceSettings(settings, deviceSettingsKeys, response); + + MsgConfigureUSRPMIMO *msg = MsgConfigureUSRPMIMO::create(settings, deviceSettingsKeys, force); + m_inputMessageQueue.push(msg); + + if (m_guiMessageQueue) // forward to GUI if any + { + MsgConfigureUSRPMIMO *msgToGUI = MsgConfigureUSRPMIMO::create(settings, deviceSettingsKeys, force); + m_guiMessageQueue->push(msgToGUI); + } + + webapiFormatDeviceSettings(response, settings); + return 200; +} + +void USRPMIMO::webapiUpdateDeviceSettings( + USRPMIMOSettings& settings, + const QStringList& deviceSettingsKeys, + SWGSDRangel::SWGDeviceSettings& response) +{ + if (deviceSettingsKeys.contains("title")) { + settings.m_title = *response.getUsrpMimoSettings()->getTitle(); + } + if (deviceSettingsKeys.contains("devSampleRate")) { + settings.m_devSampleRate = response.getUsrpMimoSettings()->getDevSampleRate(); + } + if (deviceSettingsKeys.contains("clockSource")) { + settings.m_clockSource = *response.getUsrpMimoSettings()->getClockSource(); + } + if (deviceSettingsKeys.contains("gpioDir")) { + settings.m_gpioDir = response.getUsrpMimoSettings()->getGpioDir() & 0xFF; + } + if (deviceSettingsKeys.contains("gpioPins")) { + settings.m_gpioPins = response.getUsrpMimoSettings()->getGpioPins() & 0xFF; + } + if (deviceSettingsKeys.contains("rxCenterFrequency")) { + settings.m_rxCenterFrequency = response.getUsrpMimoSettings()->getRxCenterFrequency(); + } + if (deviceSettingsKeys.contains("rxLOOffset")) { + settings.m_rxLOOffset = response.getUsrpMimoSettings()->getRxLoOffset(); + } + if (deviceSettingsKeys.contains("log2SoftDecim")) { + settings.m_log2SoftDecim = qBound(0, response.getUsrpMimoSettings()->getLog2SoftDecim(), 6); + } + if (deviceSettingsKeys.contains("rxLpfBW")) { + settings.m_rxLpfBW = response.getUsrpMimoSettings()->getRxLpfBw(); + } + if (deviceSettingsKeys.contains("dcBlock")) { + settings.m_dcBlock = response.getUsrpMimoSettings()->getDcBlock() != 0; + } + if (deviceSettingsKeys.contains("iqCorrection")) { + settings.m_iqCorrection = response.getUsrpMimoSettings()->getIqCorrection() != 0; + } + if (deviceSettingsKeys.contains("rxTransverterMode")) { + settings.m_rxTransverterMode = response.getUsrpMimoSettings()->getRxTransverterMode() != 0; + } + if (deviceSettingsKeys.contains("rxTransverterDeltaFrequency")) { + settings.m_rxTransverterDeltaFrequency = response.getUsrpMimoSettings()->getRxTransverterDeltaFrequency(); + } + if (deviceSettingsKeys.contains("rx0GainMode")) { + settings.m_rx0GainMode = response.getUsrpMimoSettings()->getRx0GainMode() == 0 ? USRPMIMOSettings::GAIN_AUTO : USRPMIMOSettings::GAIN_MANUAL; + } + if (deviceSettingsKeys.contains("rx0Gain")) { + settings.m_rx0Gain = response.getUsrpMimoSettings()->getRx0Gain(); + } + if (deviceSettingsKeys.contains("rx0AntennaPath")) { + settings.m_rx0AntennaPath = *response.getUsrpMimoSettings()->getRx0AntennaPath(); + } + if (deviceSettingsKeys.contains("rx1GainMode")) { + settings.m_rx1GainMode = response.getUsrpMimoSettings()->getRx1GainMode() == 0 ? USRPMIMOSettings::GAIN_AUTO : USRPMIMOSettings::GAIN_MANUAL; + } + if (deviceSettingsKeys.contains("rx1Gain")) { + settings.m_rx1Gain = response.getUsrpMimoSettings()->getRx1Gain(); + } + if (deviceSettingsKeys.contains("rx1AntennaPath")) { + settings.m_rx1AntennaPath = *response.getUsrpMimoSettings()->getRx1AntennaPath(); + } + if (deviceSettingsKeys.contains("txCenterFrequency")) { + settings.m_txCenterFrequency = response.getUsrpMimoSettings()->getTxCenterFrequency(); + } + if (deviceSettingsKeys.contains("txLOOffset")) { + settings.m_txLOOffset = response.getUsrpMimoSettings()->getTxLoOffset(); + } + if (deviceSettingsKeys.contains("log2SoftInterp")) { + settings.m_log2SoftInterp = qBound(0, response.getUsrpMimoSettings()->getLog2SoftInterp(), 6); + } + if (deviceSettingsKeys.contains("txLpfBW")) { + settings.m_txLpfBW = response.getUsrpMimoSettings()->getTxLpfBw(); + } + if (deviceSettingsKeys.contains("txTransverterMode")) { + settings.m_txTransverterMode = response.getUsrpMimoSettings()->getTxTransverterMode() != 0; + } + if (deviceSettingsKeys.contains("txTransverterDeltaFrequency")) { + settings.m_txTransverterDeltaFrequency = response.getUsrpMimoSettings()->getTxTransverterDeltaFrequency(); + } + if (deviceSettingsKeys.contains("tx0Gain")) { + settings.m_tx0Gain = response.getUsrpMimoSettings()->getTx0Gain(); + } + if (deviceSettingsKeys.contains("tx0AntennaPath")) { + settings.m_tx0AntennaPath = *response.getUsrpMimoSettings()->getTx0AntennaPath(); + } + if (deviceSettingsKeys.contains("tx1Gain")) { + settings.m_tx1Gain = response.getUsrpMimoSettings()->getTx1Gain(); + } + if (deviceSettingsKeys.contains("tx1AntennaPath")) { + settings.m_tx1AntennaPath = *response.getUsrpMimoSettings()->getTx1AntennaPath(); + } + if (deviceSettingsKeys.contains("useReverseAPI")) { + settings.m_useReverseAPI = response.getUsrpMimoSettings()->getUseReverseApi() != 0; + } + if (deviceSettingsKeys.contains("reverseAPIAddress")) { + settings.m_reverseAPIAddress = *response.getUsrpMimoSettings()->getReverseApiAddress(); + } + if (deviceSettingsKeys.contains("reverseAPIPort")) { + settings.m_reverseAPIPort = response.getUsrpMimoSettings()->getReverseApiPort(); + } + if (deviceSettingsKeys.contains("reverseAPIDeviceIndex")) { + settings.m_reverseAPIDeviceIndex = response.getUsrpMimoSettings()->getReverseApiDeviceIndex(); + } +} + +void USRPMIMO::webapiFormatDeviceSettings(SWGSDRangel::SWGDeviceSettings& response, const USRPMIMOSettings& settings) +{ + if (response.getUsrpMimoSettings()->getTitle()) { + *response.getUsrpMimoSettings()->getTitle() = settings.m_title; + } else { + response.getUsrpMimoSettings()->setTitle(new QString(settings.m_title)); + } + response.getUsrpMimoSettings()->setDevSampleRate(settings.m_devSampleRate); + if (response.getUsrpMimoSettings()->getClockSource()) { + *response.getUsrpMimoSettings()->getClockSource() = settings.m_clockSource; + } else { + response.getUsrpMimoSettings()->setClockSource(new QString(settings.m_clockSource)); + } + response.getUsrpMimoSettings()->setGpioDir(settings.m_gpioDir); + response.getUsrpMimoSettings()->setGpioPins(settings.m_gpioPins); + response.getUsrpMimoSettings()->setRxCenterFrequency(settings.m_rxCenterFrequency); + response.getUsrpMimoSettings()->setRxLoOffset(settings.m_rxLOOffset); + response.getUsrpMimoSettings()->setLog2SoftDecim(settings.m_log2SoftDecim); + response.getUsrpMimoSettings()->setRxLpfBw((qint32) settings.m_rxLpfBW); + response.getUsrpMimoSettings()->setDcBlock(settings.m_dcBlock ? 1 : 0); + response.getUsrpMimoSettings()->setIqCorrection(settings.m_iqCorrection ? 1 : 0); + response.getUsrpMimoSettings()->setRxTransverterMode(settings.m_rxTransverterMode ? 1 : 0); + response.getUsrpMimoSettings()->setRxTransverterDeltaFrequency(settings.m_rxTransverterDeltaFrequency); + response.getUsrpMimoSettings()->setRx0GainMode((int) settings.m_rx0GainMode); + response.getUsrpMimoSettings()->setRx0Gain(settings.m_rx0Gain); + if (response.getUsrpMimoSettings()->getRx0AntennaPath()) { + *response.getUsrpMimoSettings()->getRx0AntennaPath() = settings.m_rx0AntennaPath; + } else { + response.getUsrpMimoSettings()->setRx0AntennaPath(new QString(settings.m_rx0AntennaPath)); + } + response.getUsrpMimoSettings()->setRx1GainMode((int) settings.m_rx1GainMode); + response.getUsrpMimoSettings()->setRx1Gain(settings.m_rx1Gain); + if (response.getUsrpMimoSettings()->getRx1AntennaPath()) { + *response.getUsrpMimoSettings()->getRx1AntennaPath() = settings.m_rx1AntennaPath; + } else { + response.getUsrpMimoSettings()->setRx1AntennaPath(new QString(settings.m_rx1AntennaPath)); + } + response.getUsrpMimoSettings()->setTxCenterFrequency(settings.m_txCenterFrequency); + response.getUsrpMimoSettings()->setTxLoOffset(settings.m_txLOOffset); + response.getUsrpMimoSettings()->setLog2SoftInterp(settings.m_log2SoftInterp); + response.getUsrpMimoSettings()->setTxLpfBw((qint32) settings.m_txLpfBW); + response.getUsrpMimoSettings()->setTxTransverterMode(settings.m_txTransverterMode ? 1 : 0); + response.getUsrpMimoSettings()->setTxTransverterDeltaFrequency(settings.m_txTransverterDeltaFrequency); + response.getUsrpMimoSettings()->setTx0Gain(settings.m_tx0Gain); + if (response.getUsrpMimoSettings()->getTx0AntennaPath()) { + *response.getUsrpMimoSettings()->getTx0AntennaPath() = settings.m_tx0AntennaPath; + } else { + response.getUsrpMimoSettings()->setTx0AntennaPath(new QString(settings.m_tx0AntennaPath)); + } + response.getUsrpMimoSettings()->setTx1Gain(settings.m_tx1Gain); + if (response.getUsrpMimoSettings()->getTx1AntennaPath()) { + *response.getUsrpMimoSettings()->getTx1AntennaPath() = settings.m_tx1AntennaPath; + } else { + response.getUsrpMimoSettings()->setTx1AntennaPath(new QString(settings.m_tx1AntennaPath)); + } + response.getUsrpMimoSettings()->setUseReverseApi(settings.m_useReverseAPI ? 1 : 0); + if (response.getUsrpMimoSettings()->getReverseApiAddress()) { + *response.getUsrpMimoSettings()->getReverseApiAddress() = settings.m_reverseAPIAddress; + } else { + response.getUsrpMimoSettings()->setReverseApiAddress(new QString(settings.m_reverseAPIAddress)); + } + response.getUsrpMimoSettings()->setReverseApiPort(settings.m_reverseAPIPort); + response.getUsrpMimoSettings()->setReverseApiDeviceIndex(settings.m_reverseAPIDeviceIndex); +} + +int USRPMIMO::webapiRunGet( + int subsystemIndex, + SWGSDRangel::SWGDeviceState& response, + QString& errorMessage) +{ + if ((subsystemIndex == 0) || (subsystemIndex == 1)) + { + m_deviceAPI->getDeviceEngineStateStr(*response.getState(), subsystemIndex); + return 200; + } + else + { + errorMessage = QString("Subsystem invalid: must be 0 (Rx) or 1 (Tx)"); + return 404; + } +} + +int USRPMIMO::webapiRun( + bool run, + int subsystemIndex, + SWGSDRangel::SWGDeviceState& response, + QString& errorMessage) +{ + if ((subsystemIndex == 0) || (subsystemIndex == 1)) + { + m_deviceAPI->getDeviceEngineStateStr(*response.getState(), subsystemIndex); + MsgStartStop *message = MsgStartStop::create(run, subsystemIndex == 0); + m_inputMessageQueue.push(message); + + if (m_guiMessageQueue) // forward to GUI if any + { + MsgStartStop *msgToGUI = MsgStartStop::create(run, subsystemIndex == 0); + m_guiMessageQueue->push(msgToGUI); + } + + return 200; + } + else + { + errorMessage = QString("Subsystem invalid: must be 0 (Rx) or 1 (Tx)"); + return 404; + } +} + +int USRPMIMO::webapiReportGet(SWGSDRangel::SWGDeviceReport& response, QString& errorMessage) +{ + (void) errorMessage; + response.setUsrpMimoReport(new SWGSDRangel::SWGUSRPMIMOReport()); + response.getUsrpMimoReport()->init(); + webapiFormatDeviceReport(response); + return 200; +} + +void USRPMIMO::webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response) +{ + SWGSDRangel::SWGUSRPMIMOReport *report = response.getUsrpMimoReport(); + bool active = false; + quint32 overUnderRuns = 0; + quint32 timeoutsDropped = 0; + + report->setSuccess(m_deviceParams ? 1 : 0); + + { + QMutexLocker threadLocker(&m_threadMutex); + + if (m_sourceThread) { + m_sourceThread->getStreamStatus(active, overUnderRuns, timeoutsDropped); + } + + report->setRxStreamActive(active ? 1 : 0); + report->setRxOverrunCount(overUnderRuns); + report->setRxTimeoutCount(timeoutsDropped); + + active = false; + overUnderRuns = 0; + timeoutsDropped = 0; + + if (m_sinkThread) { + m_sinkThread->getStreamStatus(active, overUnderRuns, timeoutsDropped); + } + + report->setTxStreamActive(active ? 1 : 0); + report->setTxUnderrunCount(overUnderRuns); + report->setTxDroppedPacketsCount(timeoutsDropped); + } + + report->setMasterClockRate(m_settings.m_masterClockRate); + + // Don't block if settings are being applied to the device in another thread + if (m_deviceParams && m_deviceParams->getDevice() && m_deviceParams->m_mutex.tryLock()) + { + double temperature; + + if (DeviceUSRP::getTemperature(m_deviceParams->getDevice(), m_nbRx > 0, 0, temperature)) { + report->setTemperature(temperature); + } + + m_deviceParams->m_mutex.unlock(); + } +} + +void USRPMIMO::webapiReverseSendSettings(const QList& deviceSettingsKeys, const USRPMIMOSettings& settings, bool force) +{ + SWGSDRangel::SWGDeviceSettings *swgDeviceSettings = new SWGSDRangel::SWGDeviceSettings(); + swgDeviceSettings->setDirection(2); // MIMO + swgDeviceSettings->setOriginatorIndex(m_deviceAPI->getDeviceSetIndex()); + swgDeviceSettings->setDeviceHwType(new QString("USRP")); + swgDeviceSettings->setUsrpMimoSettings(new SWGSDRangel::SWGUSRPMIMOSettings()); + SWGSDRangel::SWGUSRPMIMOSettings *swgUSRPMIMOSettings = swgDeviceSettings->getUsrpMimoSettings(); + + // transfer data that has been modified. When force is on transfer all data except reverse API data + + if (deviceSettingsKeys.contains("title") || force) { + swgUSRPMIMOSettings->setTitle(new QString(settings.m_title)); + } + if (deviceSettingsKeys.contains("devSampleRate") || force) { + swgUSRPMIMOSettings->setDevSampleRate(settings.m_devSampleRate); + } + if (deviceSettingsKeys.contains("clockSource") || force) { + swgUSRPMIMOSettings->setClockSource(new QString(settings.m_clockSource)); + } + if (deviceSettingsKeys.contains("gpioDir") || force) { + swgUSRPMIMOSettings->setGpioDir(settings.m_gpioDir); + } + if (deviceSettingsKeys.contains("gpioPins") || force) { + swgUSRPMIMOSettings->setGpioPins(settings.m_gpioPins); + } + if (deviceSettingsKeys.contains("rxCenterFrequency") || force) { + swgUSRPMIMOSettings->setRxCenterFrequency(settings.m_rxCenterFrequency); + } + if (deviceSettingsKeys.contains("rxLOOffset") || force) { + swgUSRPMIMOSettings->setRxLoOffset(settings.m_rxLOOffset); + } + if (deviceSettingsKeys.contains("log2SoftDecim") || force) { + swgUSRPMIMOSettings->setLog2SoftDecim(settings.m_log2SoftDecim); + } + if (deviceSettingsKeys.contains("rxLpfBW") || force) { + swgUSRPMIMOSettings->setRxLpfBw((qint32) settings.m_rxLpfBW); + } + if (deviceSettingsKeys.contains("dcBlock") || force) { + swgUSRPMIMOSettings->setDcBlock(settings.m_dcBlock ? 1 : 0); + } + if (deviceSettingsKeys.contains("iqCorrection") || force) { + swgUSRPMIMOSettings->setIqCorrection(settings.m_iqCorrection ? 1 : 0); + } + if (deviceSettingsKeys.contains("rxTransverterMode") || force) { + swgUSRPMIMOSettings->setRxTransverterMode(settings.m_rxTransverterMode ? 1 : 0); + } + if (deviceSettingsKeys.contains("rxTransverterDeltaFrequency") || force) { + swgUSRPMIMOSettings->setRxTransverterDeltaFrequency(settings.m_rxTransverterDeltaFrequency); + } + if (deviceSettingsKeys.contains("rx0GainMode") || force) { + swgUSRPMIMOSettings->setRx0GainMode((int) settings.m_rx0GainMode); + } + if (deviceSettingsKeys.contains("rx0Gain") || force) { + swgUSRPMIMOSettings->setRx0Gain(settings.m_rx0Gain); + } + if (deviceSettingsKeys.contains("rx0AntennaPath") || force) { + swgUSRPMIMOSettings->setRx0AntennaPath(new QString(settings.m_rx0AntennaPath)); + } + if (deviceSettingsKeys.contains("rx1GainMode") || force) { + swgUSRPMIMOSettings->setRx1GainMode((int) settings.m_rx1GainMode); + } + if (deviceSettingsKeys.contains("rx1Gain") || force) { + swgUSRPMIMOSettings->setRx1Gain(settings.m_rx1Gain); + } + if (deviceSettingsKeys.contains("rx1AntennaPath") || force) { + swgUSRPMIMOSettings->setRx1AntennaPath(new QString(settings.m_rx1AntennaPath)); + } + if (deviceSettingsKeys.contains("txCenterFrequency") || force) { + swgUSRPMIMOSettings->setTxCenterFrequency(settings.m_txCenterFrequency); + } + if (deviceSettingsKeys.contains("txLOOffset") || force) { + swgUSRPMIMOSettings->setTxLoOffset(settings.m_txLOOffset); + } + if (deviceSettingsKeys.contains("log2SoftInterp") || force) { + swgUSRPMIMOSettings->setLog2SoftInterp(settings.m_log2SoftInterp); + } + if (deviceSettingsKeys.contains("txLpfBW") || force) { + swgUSRPMIMOSettings->setTxLpfBw((qint32) settings.m_txLpfBW); + } + if (deviceSettingsKeys.contains("txTransverterMode") || force) { + swgUSRPMIMOSettings->setTxTransverterMode(settings.m_txTransverterMode ? 1 : 0); + } + if (deviceSettingsKeys.contains("txTransverterDeltaFrequency") || force) { + swgUSRPMIMOSettings->setTxTransverterDeltaFrequency(settings.m_txTransverterDeltaFrequency); + } + if (deviceSettingsKeys.contains("tx0Gain") || force) { + swgUSRPMIMOSettings->setTx0Gain(settings.m_tx0Gain); + } + if (deviceSettingsKeys.contains("tx0AntennaPath") || force) { + swgUSRPMIMOSettings->setTx0AntennaPath(new QString(settings.m_tx0AntennaPath)); + } + if (deviceSettingsKeys.contains("tx1Gain") || force) { + swgUSRPMIMOSettings->setTx1Gain(settings.m_tx1Gain); + } + if (deviceSettingsKeys.contains("tx1AntennaPath") || force) { + swgUSRPMIMOSettings->setTx1AntennaPath(new QString(settings.m_tx1AntennaPath)); + } + + QString deviceSettingsURL = QString("http://%1:%2/sdrangel/deviceset/%3/device/settings") + .arg(settings.m_reverseAPIAddress) + .arg(settings.m_reverseAPIPort) + .arg(settings.m_reverseAPIDeviceIndex); + m_networkRequest.setUrl(QUrl(deviceSettingsURL)); + m_networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + + QBuffer *buffer = new QBuffer(); + buffer->open((QBuffer::ReadWrite)); + buffer->write(swgDeviceSettings->asJson().toUtf8()); + buffer->seek(0); + + // Always use PATCH to avoid passing reverse API settings + QNetworkReply *reply = m_networkManager->sendCustomRequest(m_networkRequest, "PATCH", buffer); + buffer->setParent(reply); + + delete swgDeviceSettings; +} + +void USRPMIMO::webapiReverseSendStartStop(bool rxElseTx, bool start) +{ + SWGSDRangel::SWGDeviceSettings *swgDeviceSettings = new SWGSDRangel::SWGDeviceSettings(); + swgDeviceSettings->setDirection(2); // MIMO + swgDeviceSettings->setOriginatorIndex(m_deviceAPI->getDeviceSetIndex()); + swgDeviceSettings->setDeviceHwType(new QString("USRP")); + + // MIMO devices are started and stopped per subsystem (0 for Rx, 1 for Tx), as /device/run only supports Rx or Tx devices + QString deviceSettingsURL = QString("http://%1:%2/sdrangel/deviceset/%3/subdevice/%4/run") + .arg(m_settings.m_reverseAPIAddress) + .arg(m_settings.m_reverseAPIPort) + .arg(m_settings.m_reverseAPIDeviceIndex) + .arg(rxElseTx ? 0 : 1); + m_networkRequest.setUrl(QUrl(deviceSettingsURL)); + m_networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + + QBuffer *buffer = new QBuffer(); + buffer->open((QBuffer::ReadWrite)); + buffer->write(swgDeviceSettings->asJson().toUtf8()); + buffer->seek(0); + QNetworkReply *reply; + + if (start) { + reply = m_networkManager->sendCustomRequest(m_networkRequest, "POST", buffer); + } else { + reply = m_networkManager->sendCustomRequest(m_networkRequest, "DELETE", buffer); + } + + buffer->setParent(reply); + delete swgDeviceSettings; +} + +void USRPMIMO::networkManagerFinished(QNetworkReply *reply) +{ + QNetworkReply::NetworkError replyError = reply->error(); + + if (replyError) + { + qWarning() << "USRPMIMO::networkManagerFinished:" + << " error(" << (int) replyError + << "): " << replyError + << ": " << reply->errorString(); + } + else + { + QString answer = reply->readAll(); + answer.chop(1); // remove last \n + qDebug("USRPMIMO::networkManagerFinished: reply:\n%s", answer.toStdString().c_str()); + } + + reply->deleteLater(); +} diff --git a/plugins/samplemimo/usrpmimo/usrpmimo.h b/plugins/samplemimo/usrpmimo/usrpmimo.h new file mode 100644 index 000000000..4c39ad107 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimo.h @@ -0,0 +1,274 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMO_H_ +#define PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMO_H_ + +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "dsp/devicesamplemimo.h" +#include "usrpmimosettings.h" + +class QNetworkAccessManager; +class QNetworkReply; +class QThread; +class DeviceAPI; +class USRPMIThread; +class USRPMOThread; +class USRPMIMOWorker; +struct DeviceUSRPParams; + +class USRPMIMO : public DeviceSampleMIMO { + Q_OBJECT + +public: + class MsgConfigureUSRPMIMO : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const USRPMIMOSettings& getSettings() const { return m_settings; } + const QList& getSettingsKeys() const { return m_settingsKeys; } + bool getForce() const { return m_force; } + + static MsgConfigureUSRPMIMO* create(const USRPMIMOSettings& settings, const QList& settingsKeys, bool force) { + return new MsgConfigureUSRPMIMO(settings, settingsKeys, force); + } + + private: + USRPMIMOSettings m_settings; + QList m_settingsKeys; + bool m_force; + + MsgConfigureUSRPMIMO(const USRPMIMOSettings& settings, const QList& settingsKeys, bool force) : + Message(), + m_settings(settings), + m_settingsKeys(settingsKeys), + m_force(force) + { } + }; + + class MsgStartStop : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getStartStop() const { return m_startStop; } + bool getRxElseTx() const { return m_rxElseTx; } + + static MsgStartStop* create(bool startStop, bool rxElseTx) { + return new MsgStartStop(startStop, rxElseTx); + } + + protected: + bool m_startStop; + bool m_rxElseTx; + + MsgStartStop(bool startStop, bool rxElseTx) : + Message(), + m_startStop(startStop), + m_rxElseTx(rxElseTx) + { } + }; + + class MsgGetStreamInfo : public Message { + MESSAGE_CLASS_DECLARATION + + public: + static MsgGetStreamInfo* create() { + return new MsgGetStreamInfo(); + } + + private: + MsgGetStreamInfo() : + Message() + { } + }; + + class MsgReportStreamInfo : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getRxElseTx() const { return m_rxElseTx; } + bool getSuccess() const { return m_success; } + bool getActive() const { return m_active; } + quint32 getOverUnderRuns() const { return m_overUnderRuns; } + quint32 getTimeoutsDropped() const { return m_timeoutsDropped; } + + static MsgReportStreamInfo* create(bool rxElseTx, bool success, bool active, quint32 overUnderRuns, quint32 timeoutsDropped) { + return new MsgReportStreamInfo(rxElseTx, success, active, overUnderRuns, timeoutsDropped); + } + + private: + bool m_rxElseTx; + bool m_success; + bool m_active; + quint32 m_overUnderRuns; //!< Rx overruns or Tx underruns + quint32 m_timeoutsDropped; //!< Rx timeouts or Tx dropped packets + + MsgReportStreamInfo(bool rxElseTx, bool success, bool active, quint32 overUnderRuns, quint32 timeoutsDropped) : + Message(), + m_rxElseTx(rxElseTx), + m_success(success), + m_active(active), + m_overUnderRuns(overUnderRuns), + m_timeoutsDropped(timeoutsDropped) + { } + }; + + class MsgGetDeviceInfo : public Message { + MESSAGE_CLASS_DECLARATION + + public: + static MsgGetDeviceInfo* create() { + return new MsgGetDeviceInfo(); + } + + private: + MsgGetDeviceInfo() : + Message() + { } + }; + + USRPMIMO(DeviceAPI *deviceAPI); + virtual ~USRPMIMO(); + virtual void destroy(); + + virtual void init(); + virtual bool startRx(); + virtual void stopRx(); + virtual bool startTx(); + virtual void stopTx(); + + virtual QByteArray serialize() const; + virtual bool deserialize(const QByteArray& data); + + virtual void setMessageQueueToGUI(MessageQueue *queue) { m_guiMessageQueue = queue; } + virtual const QString& getDeviceDescription() const; + + virtual int getSourceSampleRate(int index) const; + virtual void setSourceSampleRate(int sampleRate, int index) { (void) sampleRate; (void) index; } + virtual quint64 getSourceCenterFrequency(int index) const; + virtual void setSourceCenterFrequency(qint64 centerFrequency, int index); + + virtual int getSinkSampleRate(int index) const; + virtual void setSinkSampleRate(int sampleRate, int index) { (void) sampleRate; (void) index; } + virtual quint64 getSinkCenterFrequency(int index) const; + virtual void setSinkCenterFrequency(qint64 centerFrequency, int index); + + virtual quint64 getMIMOCenterFrequency() const { return getSourceCenterFrequency(0); } + virtual unsigned int getMIMOSampleRate() const { return getSourceSampleRate(0); } + + virtual bool handleMessage(const Message& message); + + virtual int webapiSettingsGet( + SWGSDRangel::SWGDeviceSettings& response, + QString& errorMessage); + + virtual int webapiSettingsPutPatch( + bool force, + const QStringList& deviceSettingsKeys, + SWGSDRangel::SWGDeviceSettings& response, // query + response + QString& errorMessage); + + virtual int webapiReportGet( + SWGSDRangel::SWGDeviceReport& response, + QString& errorMessage); + + virtual int webapiRunGet( + int subsystemIndex, + SWGSDRangel::SWGDeviceState& response, + QString& errorMessage); + + virtual int webapiRun( + bool run, + int subsystemIndex, + SWGSDRangel::SWGDeviceState& response, + QString& errorMessage); + + static void webapiFormatDeviceSettings( + SWGSDRangel::SWGDeviceSettings& response, + const USRPMIMOSettings& settings); + + static void webapiUpdateDeviceSettings( + USRPMIMOSettings& settings, + const QStringList& deviceSettingsKeys, + SWGSDRangel::SWGDeviceSettings& response); + + int getNbRxChannels() const { return m_nbRx; } + int getNbTxChannels() const { return m_nbTx; } + void getRxLORange(float& minF, float& maxF) const; + void getTxLORange(float& minF, float& maxF) const; + void getSRRange(float& minF, float& maxF) const; + void getRxLPRange(float& minF, float& maxF) const; + void getTxLPRange(float& minF, float& maxF) const; + void getRxGainRange(float& minF, float& maxF) const; + void getTxGainRange(float& minF, float& maxF) const; + QStringList getRxAntennas() const; + QStringList getTxAntennas() const; + QStringList getClockSources() const; + + bool getRxRunning() const { return m_runningRx; } + bool getTxRunning() const { return m_runningTx; } + +private: + DeviceAPI *m_deviceAPI; + QMutex m_mutex; //!< Serialises start and stop + QMutex m_threadMutex; //!< Protects thread pointers, for access from other threads + QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread in start + USRPMIMOSettings m_settings; + USRPMIThread* m_sourceThread; + USRPMOThread* m_sinkThread; + QString m_deviceDescription; + bool m_runningRx; + bool m_runningTx; + QNetworkAccessManager *m_networkManager; + QNetworkRequest m_networkRequest; + + DeviceUSRPParams *m_deviceParams; + int m_nbRx; //!< Number of Rx channels used + int m_nbTx; //!< Number of Tx channels used + uhd::rx_streamer::sptr m_rxStream; + uhd::tx_streamer::sptr m_txStream; + QThread *m_workerThread; + USRPMIMOWorker *m_worker; + + bool openDevice(); + void closeDevice(); + + bool applySettings(const USRPMIMOSettings& settings, const QList& settingsKeys, bool force); + static unsigned int getSampleMOFifoSize(const USRPMIMOSettings& settings); + void resizeSampleMOFifo(); + void forwardChangeRxDSP(); + void forwardChangeTxDSP(); + void webapiReverseSendSettings(const QList& deviceSettingsKeys, const USRPMIMOSettings& settings, bool force); + void webapiReverseSendStartStop(bool rxElseTx, bool start); + void webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response); + +private slots: + void networkManagerFinished(QNetworkReply *reply); +}; + +#endif // PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMO_H_ diff --git a/plugins/samplemimo/usrpmimo/usrpmimogui.cpp b/plugins/samplemimo/usrpmimo/usrpmimogui.cpp new file mode 100644 index 000000000..3554d0bbc --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimogui.cpp @@ -0,0 +1,1022 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include +#include + +#include "device/deviceapi.h" +#include "device/deviceuiset.h" +#include "gui/messagedialog.h" +#include "gui/colormapper.h" +#include "gui/glspectrum.h" +#include "gui/basicdevicesettingsdialog.h" +#include "gui/dialogpositioner.h" +#include "mainspectrum/mainspectrumgui.h" +#include "dsp/dspcommands.h" +#include "usrp/deviceusrpshared.h" + +#include "usrpmimo.h" +#include "ui_usrpmimogui.h" +#include "usrpmimogui.h" + +USRPMIMOGUI::USRPMIMOGUI(DeviceUISet *deviceUISet, QWidget* parent) : + DeviceGUI(parent), + ui(new Ui::USRPMIMOGUI), + m_settings(), + m_rxElseTx(true), + m_streamIndex(0), + m_spectrumRxElseTx(true), + m_spectrumStreamIndex(0), + m_gainLock(false), + m_doApplySettings(true), + m_forceSettings(true), + m_sampleMIMO(nullptr), + m_rxBasebandSampleRate(3000000), + m_txBasebandSampleRate(3000000), + m_rxDeviceCenterFrequency(435000*1000), + m_txDeviceCenterFrequency(435000*1000), + m_lastRxEngineState(DeviceAPI::StNotStarted), + m_lastTxEngineState(DeviceAPI::StNotStarted), + m_sampleRateMode(true), + m_statusCounter(0), + m_deviceStatusCounter(10) // Get device info on first status update +{ + qDebug("USRPMIMOGUI::USRPMIMOGUI"); + m_deviceUISet = deviceUISet; + setAttribute(Qt::WA_DeleteOnClose, true); + ui->setupUi(getContents()); + sizeToContents(); + getContents()->setStyleSheet("#USRPMIMOGUI { background-color: rgb(64, 64, 64); }"); + m_helpURL = "plugins/samplemimo/usrpmimo/readme.md"; + m_sampleMIMO = (USRPMIMO*) m_deviceUISet->m_deviceAPI->getSampleMIMO(); + + for (int i = 0; i < 2; i++) { + m_streamStatus[i] = StreamStatus{false, false, 0, 0}; + } + + // Limit stream selection to number of channels the device has + updateStreamIndexItems(ui->streamIndex, m_rxElseTx); + updateStreamIndexItems(ui->spectrumIndex, m_spectrumRxElseTx); + + ui->centerFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); + ui->sampleRate->setColorMapper(ColorMapper(ColorMapper::GrayGreenYellow)); + ui->bandwidth->setColorMapper(ColorMapper(ColorMapper::GrayYellow)); + ui->loOffset->setColorMapper(ColorMapper(ColorMapper::GrayYellow)); + + ui->clockSource->addItems(m_sampleMIMO->getClockSources()); + + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); + + connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware())); + connect(&m_statusTimer, SIGNAL(timeout()), this, SLOT(updateStatus())); + m_statusTimer.start(500); + + connect(&m_inputMessageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleInputMessages()), Qt::QueuedConnection); + m_sampleMIMO->setMessageQueueToGUI(&m_inputMessageQueue); + + connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(openDeviceSettingsDialog(const QPoint &))); + + sendSettings(); + makeUIConnections(); + m_resizer.enableChildMouseTracking(); +} + +USRPMIMOGUI::~USRPMIMOGUI() +{ + m_statusTimer.stop(); + m_updateTimer.stop(); + delete ui; +} + +void USRPMIMOGUI::destroy() +{ + delete this; +} + +void USRPMIMOGUI::resetToDefaults() +{ + m_settings.resetToDefaults(); + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); + m_forceSettings = true; + sendSettings(); +} + +QByteArray USRPMIMOGUI::serialize() const +{ + return m_settings.serialize(); +} + +bool USRPMIMOGUI::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); + m_forceSettings = true; + sendSettings(); + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +// Should be called with settings blocked +void USRPMIMOGUI::displaySettings() +{ + float minF, maxF; + + setTitle(m_settings.m_title); + getDeviceUISet()->m_mainSpectrumGUI->setTitle(m_settings.m_title); + + updateFrequencyLimits(); + + if (m_rxElseTx) + { + ui->transverter->setDeltaFrequency(m_settings.m_rxTransverterDeltaFrequency); + ui->transverter->setDeltaFrequencyActive(m_settings.m_rxTransverterMode); + ui->centerFrequency->setValue(m_settings.m_rxCenterFrequency / 1000); + ui->loOffset->setValue(m_settings.m_rxLOOffset / 1000); + m_sampleMIMO->getRxLPRange(minF, maxF); + ui->bandwidth->setValueRange(5, (minF / 1000) + 1, maxF / 1000); + ui->bandwidth->setValue(m_settings.m_rxLpfBW / 1000); + ui->dcOffset->setEnabled(true); + ui->dcOffset->setChecked(m_settings.m_dcBlock); + ui->iqImbalance->setEnabled(true); + ui->iqImbalance->setChecked(m_settings.m_iqCorrection); + ui->decim->setCurrentIndex(m_settings.m_log2SoftDecim); + ui->label_decim->setText(QString("Dec")); + ui->decim->setToolTip(QString("Software decimation factor")); + } + else + { + ui->transverter->setDeltaFrequency(m_settings.m_txTransverterDeltaFrequency); + ui->transverter->setDeltaFrequencyActive(m_settings.m_txTransverterMode); + ui->centerFrequency->setValue(m_settings.m_txCenterFrequency / 1000); + ui->loOffset->setValue(m_settings.m_txLOOffset / 1000); + m_sampleMIMO->getTxLPRange(minF, maxF); + ui->bandwidth->setValueRange(5, (minF / 1000) + 1, maxF / 1000); + ui->bandwidth->setValue(m_settings.m_txLpfBW / 1000); + ui->dcOffset->setEnabled(false); + ui->iqImbalance->setEnabled(false); + ui->decim->setCurrentIndex(m_settings.m_log2SoftInterp); + ui->label_decim->setText(QString("Int")); + ui->decim->setToolTip(QString("Software interpolation factor")); + } + + ui->clockSource->setCurrentIndex(ui->clockSource->findText(m_settings.m_clockSource)); + + displaySampleRate(); + displayMasterClockRate(); + displayGain(); + displayAntennas(); + displayStreamStatus(); +} + +void USRPMIMOGUI::displaySampleRate() +{ + float minF, maxF; + m_sampleMIMO->getSRRange(minF, maxF); + quint32 log2Factor = m_rxElseTx ? m_settings.m_log2SoftDecim : m_settings.m_log2SoftInterp; + + ui->sampleRate->blockSignals(true); + + if (m_sampleRateMode) + { + ui->sampleRateMode->setStyleSheet("QToolButton { background:rgb(60,60,60); }"); + ui->sampleRateMode->setText("SR"); + ui->sampleRate->setValueRange(8, (uint32_t) minF, (uint32_t) maxF); + ui->sampleRate->setValue(m_settings.m_devSampleRate); + ui->sampleRate->setToolTip("Device to host sample rate (S/s)"); + ui->deviceRateText->setToolTip("Baseband sample rate (S/s)"); + uint32_t basebandSampleRate = m_settings.m_devSampleRate / (1<deviceRateText->setText(tr("%1k").arg(QString::number(basebandSampleRate / 1000.0f, 'g', 5))); + } + else + { + ui->sampleRateMode->setStyleSheet("QToolButton { background:rgb(50,50,50); }"); + ui->sampleRateMode->setText("BB"); + ui->sampleRate->setValueRange(8, (uint32_t) minF / (1<sampleRate->setValue(m_settings.m_devSampleRate / (1<sampleRate->setToolTip("Baseband sample rate (S/s)"); + ui->deviceRateText->setToolTip("Device to host sample rate (S/s)"); + ui->deviceRateText->setText(tr("%1k").arg(QString::number(m_settings.m_devSampleRate / 1000.0f, 'g', 5))); + } + + ui->sampleRate->blockSignals(false); + + // LO offset shouldn't be greater than half the sample rate + int32_t maxLOOffset = m_settings.m_devSampleRate / 2 / 1000; + ui->loOffset->setValueRange(false, 5, -maxLOOffset, maxLOOffset); +} + +void USRPMIMOGUI::displayMasterClockRate() +{ + int cr = m_settings.m_masterClockRate; + + if (cr < 0) { + ui->masterClockRateLabel->setText("-"); + } else if (cr < 100000000) { + ui->masterClockRateLabel->setText(tr("%1k").arg(QString::number(cr / 1000.0f, 'g', 5))); + } else { + ui->masterClockRateLabel->setText(tr("%1M").arg(QString::number(cr / 1000000.0f, 'g', 5))); + } +} + +void USRPMIMOGUI::displayGain() +{ + float minF, maxF; + int gain; + + if (m_rxElseTx) + { + m_sampleMIMO->getRxGainRange(minF, maxF); + USRPMIMOSettings::GainMode gainMode = m_streamIndex == 0 ? m_settings.m_rx0GainMode : m_settings.m_rx1GainMode; + gain = m_streamIndex == 0 ? m_settings.m_rx0Gain : m_settings.m_rx1Gain; + ui->gainMode->setEnabled(true); + ui->gainMode->setCurrentIndex((int) gainMode); + ui->gain->setEnabled(gainMode == USRPMIMOSettings::GAIN_MANUAL); + } + else + { + m_sampleMIMO->getTxGainRange(minF, maxF); + gain = m_streamIndex == 0 ? m_settings.m_tx0Gain : m_settings.m_tx1Gain; + ui->gainMode->setCurrentIndex((int) USRPMIMOSettings::GAIN_MANUAL); + ui->gainMode->setEnabled(false); + ui->gain->setEnabled(true); + } + + ui->gain->setRange((int) minF, (int) maxF); + ui->gain->setValue(gain); + ui->gainText->setText(tr("%1 dB").arg(gain)); +} + +void USRPMIMOGUI::displayAntennas() +{ + QStringList antennas; + QString antenna; + + if (m_rxElseTx) + { + antennas = m_sampleMIMO->getRxAntennas(); + antenna = m_streamIndex == 0 ? m_settings.m_rx0AntennaPath : m_settings.m_rx1AntennaPath; + } + else + { + antennas = m_sampleMIMO->getTxAntennas(); + antenna = m_streamIndex == 0 ? m_settings.m_tx0AntennaPath : m_settings.m_tx1AntennaPath; + } + + ui->antenna->blockSignals(true); + ui->antenna->clear(); + ui->antenna->addItems(antennas); + ui->antenna->setCurrentIndex(ui->antenna->findText(antenna)); + ui->antenna->blockSignals(false); +} + +void USRPMIMOGUI::displayStreamStatus() +{ + int side = m_rxElseTx ? 0 : 1; + const StreamStatus& status = m_streamStatus[side]; + + if (status.m_success) + { + if (status.m_active) { + ui->streamStatusLabel->setStyleSheet("QLabel { background-color : green; }"); + } else { + ui->streamStatusLabel->setStyleSheet("QLabel { background-color : blue; }"); + } + + if (m_overUnderRunStats[side].getCount() > 0) { + ui->overrunLabel->setStyleSheet("QLabel { background-color : red; }"); + } else { + ui->overrunLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); + } + + if (m_timeoutDroppedStats[side].getCount() > 0) { + ui->timeoutLabel->setStyleSheet("QLabel { background-color : red; }"); + } else { + ui->timeoutLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); + } + } + else + { + ui->streamStatusLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); + ui->overrunLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); + ui->timeoutLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); + } + + ui->overrunLabel->setText(m_rxElseTx ? "O" : "U"); + ui->timeoutLabel->setText(m_rxElseTx ? "T" : "D"); + + if (m_rxElseTx) + { + ui->overrunLabel->setToolTip(m_overUnderRunStats[side].getToolTip("Red if Rx overruns occurred. Cleared when restarting Rx", "Overruns")); + ui->timeoutLabel->setToolTip(m_timeoutDroppedStats[side].getToolTip("Red if Rx timeouts occurred. Cleared when restarting Rx", "Timeouts")); + } + else + { + ui->overrunLabel->setToolTip(m_overUnderRunStats[side].getToolTip("Red if Tx underruns occurred. Cleared when restarting Tx", "Underruns")); + ui->timeoutLabel->setToolTip(m_timeoutDroppedStats[side].getToolTip("Red if Tx packets were dropped. Cleared when restarting Tx", "Dropped packets")); + } +} + +bool USRPMIMOGUI::handleMessage(const Message& message) +{ + if (DSPMIMOSignalNotification::match(message)) + { + const DSPMIMOSignalNotification& notif = (const DSPMIMOSignalNotification&) message; + int istream = notif.getIndex(); + bool sourceOrSink = notif.getSourceOrSink(); + + if (sourceOrSink) + { + m_rxBasebandSampleRate = notif.getSampleRate(); + m_rxDeviceCenterFrequency = notif.getCenterFrequency(); + } + else + { + m_txBasebandSampleRate = notif.getSampleRate(); + m_txDeviceCenterFrequency = notif.getCenterFrequency(); + } + + qDebug("USRPMIMOGUI::handleMessage: DSPMIMOSignalNotification: %s stream: %d SampleRate:%d, CenterFrequency:%llu", + sourceOrSink ? "source" : "sink", + istream, + notif.getSampleRate(), + notif.getCenterFrequency()); + + updateSampleRateAndFrequency(); + + return true; + } + else if (USRPMIMO::MsgConfigureUSRPMIMO::match(message)) + { + const USRPMIMO::MsgConfigureUSRPMIMO& notif = (const USRPMIMO::MsgConfigureUSRPMIMO&) message; + + if (notif.getForce()) { + m_settings = notif.getSettings(); + } else { + // Don't overwrite edits that haven't been sent yet + USRPMIMOSettings pending = m_settings; + m_settings.applySettings(notif.getSettingsKeys(), notif.getSettings()); + m_settings.applySettings(m_settingsKeys, pending); + } + + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); + + return true; + } + else if (USRPMIMO::MsgStartStop::match(message)) + { + const USRPMIMO::MsgStartStop& notif = (const USRPMIMO::MsgStartStop&) message; + blockApplySettings(true); + (notif.getRxElseTx() ? ui->startStopRx : ui->startStopTx)->setChecked(notif.getStartStop()); + blockApplySettings(false); + + return true; + } + else if (USRPMIMO::MsgReportStreamInfo::match(message)) + { + const USRPMIMO::MsgReportStreamInfo& report = (const USRPMIMO::MsgReportStreamInfo&) message; + int side = report.getRxElseTx() ? 0 : 1; + m_streamStatus[side] = StreamStatus{ + report.getSuccess(), + report.getActive(), + report.getOverUnderRuns(), + report.getTimeoutsDropped() + }; + // Accumulate statistics, as the counts reported can be reset while running (E.g. when paused while the other side is started) + m_overUnderRunStats[side].update(report.getSuccess(), report.getOverUnderRuns()); + m_timeoutDroppedStats[side].update(report.getSuccess(), report.getTimeoutsDropped()); + displayStreamStatus(); + + return true; + } + else if (DeviceUSRPShared::MsgReportDeviceInfo::match(message)) + { + const DeviceUSRPShared::MsgReportDeviceInfo& report = (const DeviceUSRPShared::MsgReportDeviceInfo&) message; + + if (report.getTemperatureValid()) { + ui->temperatureText->setText(tr("%1C").arg(QString::number(report.getTemperature(), 'f', 0))); + } + // Hide if device doesn't have a temperature sensor + ui->temperatureText->setVisible(report.getTemperatureValid()); + + return true; + } + + return false; +} + +void USRPMIMOGUI::handleInputMessages() +{ + Message* message; + + while ((message = m_inputMessageQueue.pop())) + { + if (!handleMessage(*message)) { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + delete message; + } +} + +void USRPMIMOGUI::sendSettings() +{ + if (!m_updateTimer.isActive()) { + m_updateTimer.start(100); + } +} + +void USRPMIMOGUI::updateHardware() +{ + if (m_doApplySettings) + { + USRPMIMO::MsgConfigureUSRPMIMO* message = USRPMIMO::MsgConfigureUSRPMIMO::create(m_settings, m_settingsKeys, m_forceSettings); + m_sampleMIMO->getInputMessageQueue()->push(message); + m_forceSettings = false; + m_settingsKeys.clear(); + m_updateTimer.stop(); + } +} + +void USRPMIMOGUI::updateSampleRateAndFrequency() +{ + if (m_spectrumRxElseTx) + { + m_deviceUISet->getSpectrum()->setSampleRate(m_rxBasebandSampleRate); + m_deviceUISet->getSpectrum()->setCenterFrequency(m_rxDeviceCenterFrequency); + } + else + { + m_deviceUISet->getSpectrum()->setSampleRate(m_txBasebandSampleRate); + m_deviceUISet->getSpectrum()->setCenterFrequency(m_txDeviceCenterFrequency); + } +} + +// Set stream index combo box items to number of channels for Rx or Tx side +void USRPMIMOGUI::updateStreamIndexItems(QComboBox *comboBox, bool rxElseTx) +{ + int count = std::max(1, rxElseTx ? m_sampleMIMO->getNbRxChannels() : m_sampleMIMO->getNbTxChannels()); + int index = std::max(0, comboBox->currentIndex()); + + comboBox->blockSignals(true); + comboBox->clear(); + + for (int i = 0; i < count; i++) { + comboBox->addItem(QString::number(i)); + } + + comboBox->setCurrentIndex(std::min(index, count - 1)); + comboBox->blockSignals(false); +} + +void USRPMIMOGUI::on_streamSide_currentIndexChanged(int index) +{ + m_rxElseTx = index == 0; + updateStreamIndexItems(ui->streamIndex, m_rxElseTx); + m_streamIndex = ui->streamIndex->currentIndex(); + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); +} + +void USRPMIMOGUI::on_streamIndex_currentIndexChanged(int index) +{ + m_streamIndex = index < 0 ? 0 : index > 1 ? 1 : index; + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); +} + +void USRPMIMOGUI::on_spectrumSide_currentIndexChanged(int index) +{ + m_spectrumRxElseTx = (index == 0); + updateStreamIndexItems(ui->spectrumIndex, m_spectrumRxElseTx); + m_spectrumStreamIndex = ui->spectrumIndex->currentIndex(); + m_deviceUISet->m_spectrum->setDisplayedStream(m_spectrumRxElseTx, m_spectrumStreamIndex); + m_deviceUISet->m_deviceAPI->setSpectrumSinkInput(m_spectrumRxElseTx, m_spectrumStreamIndex); + m_deviceUISet->setSpectrumScalingFactor(m_spectrumRxElseTx ? SDR_RX_SCALEF : SDR_TX_SCALEF); + updateSampleRateAndFrequency(); +} + +void USRPMIMOGUI::on_spectrumIndex_currentIndexChanged(int index) +{ + m_spectrumStreamIndex = index < 0 ? 0 : index > 1 ? 1 : index; + m_deviceUISet->m_spectrum->setDisplayedStream(m_spectrumRxElseTx, m_spectrumStreamIndex); + m_deviceUISet->m_deviceAPI->setSpectrumSinkInput(m_spectrumRxElseTx, m_spectrumStreamIndex); + updateSampleRateAndFrequency(); +} + +void USRPMIMOGUI::on_startStopRx_toggled(bool checked) +{ + if (m_doApplySettings) + { + USRPMIMO::MsgStartStop *message = USRPMIMO::MsgStartStop::create(checked, true); + m_sampleMIMO->getInputMessageQueue()->push(message); + } +} + +void USRPMIMOGUI::on_startStopTx_toggled(bool checked) +{ + if (m_doApplySettings) + { + USRPMIMO::MsgStartStop *message = USRPMIMO::MsgStartStop::create(checked, false); + m_sampleMIMO->getInputMessageQueue()->push(message); + } +} + +void USRPMIMOGUI::on_centerFrequency_changed(quint64 value) +{ + if (!m_doApplySettings) { + return; + } + + setCenterFrequencySetting(value); + sendSettings(); +} + +void USRPMIMOGUI::on_loOffset_changed(qint64 value) +{ + if (!m_doApplySettings) { + return; + } + + if (m_rxElseTx) + { + m_settings.m_rxLOOffset = value * 1000; + m_settingsKeys.append("rxLOOffset"); + } + else + { + m_settings.m_txLOOffset = value * 1000; + m_settingsKeys.append("txLOOffset"); + } + + sendSettings(); +} + +void USRPMIMOGUI::on_clockSource_currentIndexChanged(int index) +{ + if (!m_doApplySettings || (index < 0)) { + return; + } + + m_settings.m_clockSource = ui->clockSource->currentText(); + m_settingsKeys.append("clockSource"); + sendSettings(); +} + +void USRPMIMOGUI::on_dcOffset_toggled(bool checked) +{ + if (!m_doApplySettings) { + return; + } + + m_settings.m_dcBlock = checked; + m_settingsKeys.append("dcBlock"); + sendSettings(); +} + +void USRPMIMOGUI::on_iqImbalance_toggled(bool checked) +{ + if (!m_doApplySettings) { + return; + } + + m_settings.m_iqCorrection = checked; + m_settingsKeys.append("iqCorrection"); + sendSettings(); +} + +void USRPMIMOGUI::on_bandwidth_changed(quint64 value) +{ + if (!m_doApplySettings) { + return; + } + + if (m_rxElseTx) + { + m_settings.m_rxLpfBW = value * 1000; + m_settingsKeys.append("rxLpfBW"); + } + else + { + m_settings.m_txLpfBW = value * 1000; + m_settingsKeys.append("txLpfBW"); + } + + sendSettings(); +} + +void USRPMIMOGUI::on_transverter_clicked() +{ + if (!m_doApplySettings) { + return; + } + + if (m_rxElseTx) + { + m_settings.m_rxTransverterMode = ui->transverter->getDeltaFrequencyAcive(); + m_settings.m_rxTransverterDeltaFrequency = ui->transverter->getDeltaFrequency(); + m_settingsKeys.append("rxTransverterMode"); + m_settingsKeys.append("rxTransverterDeltaFrequency"); + qDebug("USRPMIMOGUI::on_transverter_clicked: Rx: %lld Hz %s", m_settings.m_rxTransverterDeltaFrequency, m_settings.m_rxTransverterMode ? "on" : "off"); + } + else + { + m_settings.m_txTransverterMode = ui->transverter->getDeltaFrequencyAcive(); + m_settings.m_txTransverterDeltaFrequency = ui->transverter->getDeltaFrequency(); + m_settingsKeys.append("txTransverterMode"); + m_settingsKeys.append("txTransverterDeltaFrequency"); + qDebug("USRPMIMOGUI::on_transverter_clicked: Tx: %lld Hz %s", m_settings.m_txTransverterDeltaFrequency, m_settings.m_txTransverterMode ? "on" : "off"); + } + + updateFrequencyLimits(); + setCenterFrequencySetting(ui->centerFrequency->getValueNew()); + sendSettings(); +} + +void USRPMIMOGUI::on_sampleRateMode_toggled(bool checked) +{ + m_sampleRateMode = checked; + displaySampleRate(); +} + +void USRPMIMOGUI::on_sampleRate_changed(quint64 value) +{ + if (!m_doApplySettings) { + return; + } + + if (m_sampleRateMode) { + m_settings.m_devSampleRate = value; + } else { + m_settings.m_devSampleRate = value * (1 << (m_rxElseTx ? m_settings.m_log2SoftDecim : m_settings.m_log2SoftInterp)); + } + + displaySampleRate(); + m_settingsKeys.append("devSampleRate"); + sendSettings(); +} + +void USRPMIMOGUI::on_decim_currentIndexChanged(int index) +{ + if (!m_doApplySettings || (index < 0) || (index > 6)) { + return; + } + + if (m_rxElseTx) + { + m_settings.m_log2SoftDecim = index; + m_settingsKeys.append("log2SoftDecim"); + } + else + { + m_settings.m_log2SoftInterp = index; + m_settingsKeys.append("log2SoftInterp"); + } + + displaySampleRate(); + + if (m_sampleRateMode) { + m_settings.m_devSampleRate = ui->sampleRate->getValueNew(); + } else { + m_settings.m_devSampleRate = ui->sampleRate->getValueNew() * (1 << index); + } + + m_settingsKeys.append("devSampleRate"); + sendSettings(); +} + +void USRPMIMOGUI::on_gainLock_toggled(bool checked) +{ + if (!m_gainLock && checked) + { + m_settings.m_rx1Gain = m_settings.m_rx0Gain; + m_settings.m_rx1GainMode = m_settings.m_rx0GainMode; + m_settings.m_tx1Gain = m_settings.m_tx0Gain; + m_settingsKeys.append("rx1Gain"); + m_settingsKeys.append("rx1GainMode"); + m_settingsKeys.append("tx1Gain"); + sendSettings(); + } + + m_gainLock = checked; +} + +void USRPMIMOGUI::on_gainMode_currentIndexChanged(int index) +{ + if (!m_doApplySettings || !m_rxElseTx || (index < 0)) { // not for Tx + return; + } + + USRPMIMOSettings::GainMode gainMode = index == 0 ? USRPMIMOSettings::GAIN_AUTO : USRPMIMOSettings::GAIN_MANUAL; + + if ((m_streamIndex == 0) || m_gainLock) + { + m_settings.m_rx0GainMode = gainMode; + m_settingsKeys.append("rx0GainMode"); + } + if ((m_streamIndex == 1) || m_gainLock) + { + m_settings.m_rx1GainMode = gainMode; + m_settingsKeys.append("rx1GainMode"); + } + + ui->gain->setEnabled(gainMode == USRPMIMOSettings::GAIN_MANUAL); + sendSettings(); +} + +void USRPMIMOGUI::on_gain_valueChanged(int value) +{ + ui->gainText->setText(tr("%1 dB").arg(value)); + + if (!m_doApplySettings) { + return; + } + + setGain(value); + sendSettings(); +} + +void USRPMIMOGUI::setGain(int gain) +{ + if (m_rxElseTx) + { + if ((m_streamIndex == 0) || m_gainLock) + { + m_settings.m_rx0Gain = gain; + m_settingsKeys.append("rx0Gain"); + } + if ((m_streamIndex == 1) || m_gainLock) + { + m_settings.m_rx1Gain = gain; + m_settingsKeys.append("rx1Gain"); + } + } + else + { + if ((m_streamIndex == 0) || m_gainLock) + { + m_settings.m_tx0Gain = gain; + m_settingsKeys.append("tx0Gain"); + } + if ((m_streamIndex == 1) || m_gainLock) + { + m_settings.m_tx1Gain = gain; + m_settingsKeys.append("tx1Gain"); + } + } +} + +void USRPMIMOGUI::on_antenna_currentIndexChanged(int index) +{ + if (!m_doApplySettings || (index < 0)) { + return; + } + + QString antenna = ui->antenna->currentText(); + + if (m_rxElseTx) + { + if (m_streamIndex == 0) + { + m_settings.m_rx0AntennaPath = antenna; + m_settingsKeys.append("rx0AntennaPath"); + } + else + { + m_settings.m_rx1AntennaPath = antenna; + m_settingsKeys.append("rx1AntennaPath"); + } + } + else + { + if (m_streamIndex == 0) + { + m_settings.m_tx0AntennaPath = antenna; + m_settingsKeys.append("tx0AntennaPath"); + } + else + { + m_settings.m_tx1AntennaPath = antenna; + m_settingsKeys.append("tx1AntennaPath"); + } + } + + sendSettings(); +} + +void USRPMIMOGUI::updateFrequencyLimits() +{ + // values in kHz + float minF, maxF; + qint64 deltaFrequency; + + if (m_rxElseTx) + { + deltaFrequency = m_settings.m_rxTransverterMode ? m_settings.m_rxTransverterDeltaFrequency/1000 : 0; + m_sampleMIMO->getRxLORange(minF, maxF); + } + else + { + deltaFrequency = m_settings.m_txTransverterMode ? m_settings.m_txTransverterDeltaFrequency/1000 : 0; + m_sampleMIMO->getTxLORange(minF, maxF); + } + + qint64 minLimit = minF/1000 + deltaFrequency; + qint64 maxLimit = maxF/1000 + deltaFrequency; + + if (m_settings.m_rxTransverterMode || m_settings.m_txTransverterMode) + { + minLimit = minLimit < 0 ? 0 : minLimit > 999999999 ? 999999999 : minLimit; + maxLimit = maxLimit < 0 ? 0 : maxLimit > 999999999 ? 999999999 : maxLimit; + ui->centerFrequency->setValueRange(9, minLimit, maxLimit); + } + else + { + minLimit = minLimit < 0 ? 0 : minLimit > 9999999 ? 9999999 : minLimit; + maxLimit = maxLimit < 0 ? 0 : maxLimit > 9999999 ? 9999999 : maxLimit; + ui->centerFrequency->setValueRange(7, minLimit, maxLimit); + } +} + +void USRPMIMOGUI::setCenterFrequencySetting(uint64_t kHzValue) +{ + int64_t centerFrequency = kHzValue*1000; + + if (m_rxElseTx) + { + m_settings.m_rxCenterFrequency = centerFrequency < 0 ? 0 : (uint64_t) centerFrequency; + m_settingsKeys.append("rxCenterFrequency"); + } + else + { + m_settings.m_txCenterFrequency = centerFrequency < 0 ? 0 : (uint64_t) centerFrequency; + m_settingsKeys.append("txCenterFrequency"); + } +} + +void USRPMIMOGUI::updateStatus() +{ + int stateRx = m_deviceUISet->m_deviceAPI->state(0); + int stateTx = m_deviceUISet->m_deviceAPI->state(1); + + if (m_lastRxEngineState != stateRx) + { + switch(stateRx) + { + case DeviceAPI::StNotStarted: + ui->startStopRx->setStyleSheet("QToolButton { background:rgb(79,79,79); }"); + break; + case DeviceAPI::StIdle: + ui->startStopRx->setStyleSheet("QToolButton { background-color : blue; }"); + break; + case DeviceAPI::StRunning: + ui->startStopRx->setStyleSheet("QToolButton { background-color : green; }"); + break; + case DeviceAPI::StError: + ui->startStopRx->setStyleSheet("QToolButton { background-color : red; }"); + MessageDialog::information(this, tr("Message"), m_deviceUISet->m_deviceAPI->errorMessage(0)); + break; + default: + break; + } + + m_lastRxEngineState = stateRx; + } + + if (m_lastTxEngineState != stateTx) + { + switch(stateTx) + { + case DeviceAPI::StNotStarted: + ui->startStopTx->setStyleSheet("QToolButton { background:rgb(79,79,79); }"); + break; + case DeviceAPI::StIdle: + ui->startStopTx->setStyleSheet("QToolButton { background-color : blue; }"); + break; + case DeviceAPI::StRunning: + ui->startStopTx->setStyleSheet("QToolButton { background-color : green; }"); + break; + case DeviceAPI::StError: + ui->startStopTx->setStyleSheet("QToolButton { background-color : red; }"); + MessageDialog::information(this, tr("Message"), m_deviceUISet->m_deviceAPI->errorMessage(1)); + break; + default: + break; + } + + m_lastTxEngineState = stateTx; + } + + if (m_statusCounter < 1) + { + m_statusCounter++; + } + else + { + m_sampleMIMO->getInputMessageQueue()->push(USRPMIMO::MsgGetStreamInfo::create()); + m_statusCounter = 0; + } + + if (m_deviceStatusCounter < 10) + { + m_deviceStatusCounter++; + } + else + { + m_sampleMIMO->getInputMessageQueue()->push(USRPMIMO::MsgGetDeviceInfo::create()); + m_deviceStatusCounter = 0; + } +} + +void USRPMIMOGUI::openDeviceSettingsDialog(const QPoint& p) +{ + if (m_contextMenuType == ContextMenuDeviceSettings) + { + BasicDeviceSettingsDialog dialog(this); + dialog.setUseReverseAPI(m_settings.m_useReverseAPI); + dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress); + dialog.setReverseAPIPort(m_settings.m_reverseAPIPort); + dialog.setReverseAPIDeviceIndex(m_settings.m_reverseAPIDeviceIndex); + dialog.setTitle(m_settings.m_title); + dialog.setDefaultTitle(getDefaultTitle()); + + dialog.move(p); + new DialogPositioner(&dialog, false); + dialog.exec(); + + if (dialog.result() == QDialog::Accepted) + { + m_settings.m_title = dialog.getTitle(); + setTitle(m_settings.m_title); + getDeviceUISet()->m_mainSpectrumGUI->setTitle(m_settings.m_title); + m_settings.m_useReverseAPI = dialog.useReverseAPI(); + m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); + m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); + m_settings.m_reverseAPIDeviceIndex = dialog.getReverseAPIDeviceIndex(); + m_settingsKeys.append("title"); + m_settingsKeys.append("useReverseAPI"); + m_settingsKeys.append("reverseAPIAddress"); + m_settingsKeys.append("reverseAPIPort"); + m_settingsKeys.append("reverseAPIDeviceIndex"); + + sendSettings(); + } + } + + resetContextMenuType(); +} + +void USRPMIMOGUI::makeUIConnections() +{ + QObject::connect(ui->streamSide, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_streamSide_currentIndexChanged); + QObject::connect(ui->streamIndex, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_streamIndex_currentIndexChanged); + QObject::connect(ui->spectrumSide, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_spectrumSide_currentIndexChanged); + QObject::connect(ui->spectrumIndex, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_spectrumIndex_currentIndexChanged); + QObject::connect(ui->startStopRx, &ButtonSwitch::toggled, this, &USRPMIMOGUI::on_startStopRx_toggled); + QObject::connect(ui->startStopTx, &ButtonSwitch::toggled, this, &USRPMIMOGUI::on_startStopTx_toggled); + QObject::connect(ui->centerFrequency, &ValueDial::changed, this, &USRPMIMOGUI::on_centerFrequency_changed); + QObject::connect(ui->loOffset, &ValueDialZ::changed, this, &USRPMIMOGUI::on_loOffset_changed); + QObject::connect(ui->clockSource, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_clockSource_currentIndexChanged); + QObject::connect(ui->dcOffset, &ButtonSwitch::toggled, this, &USRPMIMOGUI::on_dcOffset_toggled); + QObject::connect(ui->iqImbalance, &ButtonSwitch::toggled, this, &USRPMIMOGUI::on_iqImbalance_toggled); + QObject::connect(ui->bandwidth, &ValueDial::changed, this, &USRPMIMOGUI::on_bandwidth_changed); + QObject::connect(ui->transverter, &TransverterButton::clicked, this, &USRPMIMOGUI::on_transverter_clicked); + QObject::connect(ui->sampleRateMode, &QToolButton::toggled, this, &USRPMIMOGUI::on_sampleRateMode_toggled); + QObject::connect(ui->sampleRate, &ValueDial::changed, this, &USRPMIMOGUI::on_sampleRate_changed); + QObject::connect(ui->decim, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_decim_currentIndexChanged); + QObject::connect(ui->gainLock, &QToolButton::toggled, this, &USRPMIMOGUI::on_gainLock_toggled); + QObject::connect(ui->gainMode, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_gainMode_currentIndexChanged); + QObject::connect(ui->gain, &QSlider::valueChanged, this, &USRPMIMOGUI::on_gain_valueChanged); + QObject::connect(ui->antenna, QOverload::of(&QComboBox::currentIndexChanged), this, &USRPMIMOGUI::on_antenna_currentIndexChanged); +} diff --git a/plugins/samplemimo/usrpmimo/usrpmimogui.h b/plugins/samplemimo/usrpmimo/usrpmimogui.h new file mode 100644 index 000000000..4fbb5e6ea --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimogui.h @@ -0,0 +1,131 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef _USRPMIMO_USRPMIMOGUI_H_ +#define _USRPMIMO_USRPMIMOGUI_H_ + +#include +#include + +#include "util/messagequeue.h" +#include "usrp/deviceusrpstreamstats.h" +#include "device/devicegui.h" + +#include "usrpmimosettings.h" + +class QComboBox; +class DeviceUISet; +class USRPMIMO; + +namespace Ui { + class USRPMIMOGUI; +} + +class USRPMIMOGUI : public DeviceGUI { + Q_OBJECT + +public: + explicit USRPMIMOGUI(DeviceUISet *deviceUISet, QWidget* parent = nullptr); + virtual ~USRPMIMOGUI(); + virtual void destroy(); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + virtual MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + +private: + struct StreamStatus { + bool m_success; + bool m_active; + quint32 m_overUnderRuns; + quint32 m_timeoutsDropped; + }; + + Ui::USRPMIMOGUI* ui; + + USRPMIMOSettings m_settings; + QList m_settingsKeys; + bool m_rxElseTx; //!< Which side is being dealt with + int m_streamIndex; //!< Current stream index being dealt with + bool m_spectrumRxElseTx; + int m_spectrumStreamIndex; //!< Index of the stream displayed on main spectrum + bool m_gainLock; //!< Lock Rx or Tx channel gains (set channel gains to gain of channel 0 when engaged) + QTimer m_updateTimer; + QTimer m_statusTimer; + bool m_doApplySettings; + bool m_forceSettings; + USRPMIMO* m_sampleMIMO; + int m_rxBasebandSampleRate; + int m_txBasebandSampleRate; + quint64 m_rxDeviceCenterFrequency; //!< Center frequency in Rx device + quint64 m_txDeviceCenterFrequency; //!< Center frequency in Tx device + int m_lastRxEngineState; + int m_lastTxEngineState; + MessageQueue m_inputMessageQueue; + bool m_sampleRateMode; + int m_statusCounter; + int m_deviceStatusCounter; + StreamStatus m_streamStatus[2]; //!< Rx and Tx + DeviceUSRPStreamStats m_overUnderRunStats[2]; //!< Rx overruns and Tx underruns + DeviceUSRPStreamStats m_timeoutDroppedStats[2]; //!< Rx timeouts and Tx dropped packets + + void blockApplySettings(bool block) { m_doApplySettings = !block; } + void displaySettings(); + void displaySampleRate(); + void displayMasterClockRate(); + void displayGain(); + void displayAntennas(); + void displayStreamStatus(); + void updateStreamIndexItems(QComboBox *comboBox, bool rxElseTx); + void sendSettings(); + void updateSampleRateAndFrequency(); + void updateFrequencyLimits(); + void setCenterFrequencySetting(uint64_t kHzValue); + void setGain(int gain); + bool handleMessage(const Message& message); + void makeUIConnections(); + +private slots: + void handleInputMessages(); + void updateHardware(); + void updateStatus(); + void on_streamSide_currentIndexChanged(int index); + void on_streamIndex_currentIndexChanged(int index); + void on_spectrumSide_currentIndexChanged(int index); + void on_spectrumIndex_currentIndexChanged(int index); + void on_startStopRx_toggled(bool checked); + void on_startStopTx_toggled(bool checked); + void on_centerFrequency_changed(quint64 value); + void on_loOffset_changed(qint64 value); + void on_clockSource_currentIndexChanged(int index); + void on_dcOffset_toggled(bool checked); + void on_iqImbalance_toggled(bool checked); + void on_bandwidth_changed(quint64 value); + void on_transverter_clicked(); + void on_sampleRateMode_toggled(bool checked); + void on_sampleRate_changed(quint64 value); + void on_decim_currentIndexChanged(int index); + void on_gainLock_toggled(bool checked); + void on_gainMode_currentIndexChanged(int index); + void on_gain_valueChanged(int value); + void on_antenna_currentIndexChanged(int index); + void openDeviceSettingsDialog(const QPoint& p); +}; + +#endif // _USRPMIMO_USRPMIMOGUI_H_ diff --git a/plugins/samplemimo/usrpmimo/usrpmimogui.ui b/plugins/samplemimo/usrpmimo/usrpmimogui.ui new file mode 100644 index 000000000..019c15509 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimogui.ui @@ -0,0 +1,952 @@ + + + USRPMIMOGUI + + + + 0 + 0 + 370 + 240 + + + + + 0 + 0 + + + + + 370 + 240 + + + + + 390 + 252 + + + + + Liberation Sans + 9 + + + + USRP MIMO + + + + 3 + + + 2 + + + 2 + + + 2 + + + 2 + + + + + 6 + + + + + + 16777215 + 22 + + + + + + + :/antenna.png + + + + + + + + 45 + 16777215 + + + + Select Rx or Tx settings + + + + Rx + + + + + Tx + + + + + + + + + 35 + 16777215 + + + + Select stream index to which settings apply + + + + 0 + + + + + 1 + + + + + + + + + 16777215 + 22 + + + + + + + :/dsb.png + + + + + + + + 45 + 0 + + + + + 45 + 16777215 + + + + Select Rx or Tx spectrum + + + + Rx + + + + + Tx + + + + + + + + + 35 + 16777215 + + + + Select which stream index to display spectrum + + + + 0 + + + + + 1 + + + + + + + + Qt::Vertical + + + + + + + Rx + + + + + + + start/stop acquisition (Rx) + + + + + + + :/play.png + :/stop.png:/play.png + + + + + + + Tx + + + + + + + start/stop generation (Tx) + + + + + + + :/play.png + :/stop.png:/play.png + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 4 + + + + + + + + + + + + + 50 + 0 + + + + I/Q sample rate kS/s + + + 00000k + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Liberation Mono + 16 + + + + PointingHandCursor + + + Qt::StrongFocus + + + Tuner center frequency in kHz + + + + + + + kHz + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + + + + LO + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Liberation Mono + 12 + false + + + + PointingHandCursor + + + LO offset (kHz). The LO is offset from the center frequency by this amount and a digital NCO is used to compensate + + + + + + + kHz + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Clk + + + + + + + + 70 + 0 + + + + Clock source (common to Rx and Tx) + + + + + + + + + + + Automatic IQ imbalance correction (Rx) + + + IQ + + + + + + + Automatic DC offset removal (Rx) + + + DC + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Auto + + + + + + + kHz + + + + + + + + 0 + 0 + + + + BW + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Liberation Mono + 12 + + + + PointingHandCursor + + + RF bandwidth + + + + + + + + 24 + 24 + + + + Transverter frequency translation dialog + + + X + + + + + + + + + Qt::Horizontal + + + + + + + 2 + + + 2 + + + + + + 24 + 0 + + + + + 24 + 16777215 + + + + Toggle between device to host (SR) and base band (BB) sample rate input + + + SR + + + true + + + true + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Liberation Mono + 12 + + + + PointingHandCursor + + + Device sample rate + + + + + + + S/s + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 54 + 0 + + + + Master clock rate (sample rate between FPGA and RFIC) (S/s) + + + - + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Dec + + + + + + + + 50 + 16777215 + + + + Decimation factor + + + 0 + + + + 1 + + + + + 2 + + + + + 4 + + + + + 8 + + + + + 16 + + + + + 32 + + + + + 64 + + + + + + + + + + 3 + + + + + Gain value + + + 1 + + + Qt::Horizontal + + + + + + + Automatic or manual gain control + + + + Auto + + + + + Manual + + + + + + + + Gain + + + + + + + + 45 + 0 + + + + 000 dB + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Lock both channels gain + + + + + + + :/unlocked.png + :/locked.png:/unlocked.png + + + true + + + + + + + + + + + + + + :/antenna.png + + + + + + + + 80 + 0 + + + + Antenna + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 24 + 0 + + + + Board temperature (degrees C) + + + - + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + 24 + 24 + + + + + 24 + 24 + + + + Green when stream is active (Rx or Tx as selected) + + + + + + :/stream.png + + + + + + + + 12 + 0 + + + + Red if Rx overruns or Tx underruns occurred. Cleared when restarting + + + background:rgb(79,79,79); + + + O + + + Qt::AlignCenter + + + + + + + + 12 + 0 + + + + Red if Rx timeouts or Tx dropped packets occurred. Cleared when restarting + + + background:rgb(79,79,79); + + + T + + + Qt::AlignCenter + + + + + + + + + + ValueDialZ + QWidget +
gui/valuedialz.h
+ 1 +
+ + ValueDial + QWidget +
gui/valuedial.h
+ 1 +
+ + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
+ + TransverterButton + QPushButton +
gui/transverterbutton.h
+
+
+ + + + +
diff --git a/plugins/samplemimo/usrpmimo/usrpmimoplugin.cpp b/plugins/samplemimo/usrpmimo/usrpmimoplugin.cpp new file mode 100644 index 000000000..a45b9b3f6 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimoplugin.cpp @@ -0,0 +1,143 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include "plugin/pluginapi.h" +#include "usrp/deviceusrp.h" + +#ifndef SERVER_MODE +#include "usrpmimogui.h" +#endif +#include "usrpmimo.h" +#include "usrpmimoplugin.h" +#include "usrpmimowebapiadapter.h" + +const PluginDescriptor USRPMIMOPlugin::m_pluginDescriptor = { + QStringLiteral("USRP"), + QStringLiteral("USRP MIMO"), + QStringLiteral("7.28.0"), + QStringLiteral("(c) Jon Beniston, M7RCE"), + QStringLiteral("https://github.com/f4exb/sdrangel"), + true, + QStringLiteral("https://github.com/f4exb/sdrangel") +}; + +static constexpr const char* const m_hardwareID = "USRP"; +static constexpr const char* const m_deviceTypeID = USRPMIMO_DEVICE_TYPE_ID; + +USRPMIMOPlugin::USRPMIMOPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& USRPMIMOPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void USRPMIMOPlugin::initPlugin(PluginAPI* pluginAPI) +{ + pluginAPI->registerSampleMIMO(m_deviceTypeID, this); +} + +void USRPMIMOPlugin::enumOriginDevices(QStringList& listedHwIds, OriginDevices& originDevices) +{ + if (listedHwIds.contains(m_hardwareID)) { // check if it was done + return; + } + + DeviceUSRP::enumOriginDevices(m_hardwareID, originDevices); + listedHwIds.append(m_hardwareID); +} + +PluginInterface::SamplingDevices USRPMIMOPlugin::enumSampleMIMO(const OriginDevices& originDevices) +{ + SamplingDevices result; + + for (OriginDevices::const_iterator it = originDevices.begin(); it != originDevices.end(); ++it) + { + // Only offer MIMO for devices with more than one Rx or Tx channel + if ((it->hardwareId == m_hardwareID) && ((it->nbRxStreams > 1) || (it->nbTxStreams > 1))) + { + QString displayedName = it->displayableName; + displayedName.replace(QString(":$1]"), QString("]")); + result.append(SamplingDevice( + displayedName, + m_hardwareID, + m_deviceTypeID, + it->serial, + it->sequence, + PluginInterface::SamplingDevice::PhysicalDevice, + PluginInterface::SamplingDevice::StreamMIMO, + 1, + 0 + )); + } + } + + return result; +} + +#ifdef SERVER_MODE +DeviceGUI* USRPMIMOPlugin::createSampleMIMOPluginInstanceGUI( + const QString& sourceId, + QWidget **widget, + DeviceUISet *deviceUISet) +{ + (void) sourceId; + (void) widget; + (void) deviceUISet; + return nullptr; +} +#else +DeviceGUI* USRPMIMOPlugin::createSampleMIMOPluginInstanceGUI( + const QString& sourceId, + QWidget **widget, + DeviceUISet *deviceUISet) +{ + if (sourceId == m_deviceTypeID) + { + USRPMIMOGUI* gui = new USRPMIMOGUI(deviceUISet); + *widget = gui; + return gui; + } + else + { + return nullptr; + } +} +#endif + +DeviceSampleMIMO *USRPMIMOPlugin::createSampleMIMOPluginInstance(const QString& mimoId, DeviceAPI *deviceAPI) +{ + if (mimoId == m_deviceTypeID) + { + USRPMIMO* mimo = new USRPMIMO(deviceAPI); + return mimo; + } + else + { + return nullptr; + } +} + +DeviceWebAPIAdapter *USRPMIMOPlugin::createDeviceWebAPIAdapter() const +{ + return new USRPMIMOWebAPIAdapter(); +} diff --git a/plugins/samplemimo/usrpmimo/usrpmimoplugin.h b/plugins/samplemimo/usrpmimo/usrpmimoplugin.h new file mode 100644 index 000000000..0003542d7 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimoplugin.h @@ -0,0 +1,54 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef _USRPMIMO_USRPMIMOPLUGIN_H +#define _USRPMIMO_USRPMIMOPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class PluginAPI; + +#define USRPMIMO_DEVICE_TYPE_ID "sdrangel.samplemimo.usrpmimo" + +class USRPMIMOPlugin : public QObject, public PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID USRPMIMO_DEVICE_TYPE_ID) + +public: + explicit USRPMIMOPlugin(QObject* parent = nullptr); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + virtual void enumOriginDevices(QStringList& listedHwIds, OriginDevices& originDevices); + virtual SamplingDevices enumSampleMIMO(const OriginDevices& originDevices); + + virtual DeviceGUI* createSampleMIMOPluginInstanceGUI( + const QString& sourceId, + QWidget **widget, + DeviceUISet *deviceUISet); + virtual DeviceSampleMIMO* createSampleMIMOPluginInstance(const QString& sourceId, DeviceAPI *deviceAPI); + virtual DeviceWebAPIAdapter* createDeviceWebAPIAdapter() const; + +private: + static const PluginDescriptor m_pluginDescriptor; +}; + +#endif // _USRPMIMO_USRPMIMOPLUGIN_H diff --git a/plugins/samplemimo/usrpmimo/usrpmimosettings.cpp b/plugins/samplemimo/usrpmimo/usrpmimosettings.cpp new file mode 100644 index 000000000..ac41541d1 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimosettings.cpp @@ -0,0 +1,396 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#include "util/simpleserializer.h" +#include "usrpmimosettings.h" + +USRPMIMOSettings::USRPMIMOSettings() +{ + resetToDefaults(); +} + +void USRPMIMOSettings::resetToDefaults() +{ + m_title = "USRP"; + m_masterClockRate = -1; + m_devSampleRate = 3000000; + m_clockSource = "internal"; + m_gpioDir = 0; + m_gpioPins = 0; + m_rxCenterFrequency = 435000*1000; + m_rxLOOffset = 0; + m_log2SoftDecim = 0; + m_rxLpfBW = 10e6f; + m_dcBlock = false; + m_iqCorrection = false; + m_rxTransverterMode = false; + m_rxTransverterDeltaFrequency = 0; + m_rx0GainMode = GAIN_AUTO; + m_rx0Gain = 50; + m_rx0AntennaPath = "RX2"; + m_rx1GainMode = GAIN_AUTO; + m_rx1Gain = 50; + m_rx1AntennaPath = "RX2"; + m_txCenterFrequency = 435000*1000; + m_txLOOffset = 0; + m_log2SoftInterp = 0; + m_txLpfBW = 10e6f; + m_txTransverterMode = false; + m_txTransverterDeltaFrequency = 0; + m_tx0Gain = 50; + m_tx0AntennaPath = "TX/RX"; + m_tx1Gain = 50; + m_tx1AntennaPath = "TX/RX"; + m_useReverseAPI = false; + m_reverseAPIAddress = "127.0.0.1"; + m_reverseAPIPort = 8888; + m_reverseAPIDeviceIndex = 0; +} + +QByteArray USRPMIMOSettings::serialize() const +{ + SimpleSerializer s(1); + + s.writeString(1, m_title); + s.writeS32(2, m_devSampleRate); + s.writeString(3, m_clockSource); + s.writeU32(4, m_gpioDir); + s.writeU32(5, m_gpioPins); + s.writeU64(6, m_rxCenterFrequency); + s.writeS32(7, m_rxLOOffset); + s.writeU32(8, m_log2SoftDecim); + s.writeFloat(9, m_rxLpfBW); + s.writeBool(10, m_dcBlock); + s.writeBool(11, m_iqCorrection); + s.writeBool(12, m_rxTransverterMode); + s.writeS64(13, m_rxTransverterDeltaFrequency); + s.writeS32(14, (int) m_rx0GainMode); + s.writeU32(15, m_rx0Gain); + s.writeString(16, m_rx0AntennaPath); + s.writeS32(17, (int) m_rx1GainMode); + s.writeU32(18, m_rx1Gain); + s.writeString(19, m_rx1AntennaPath); + s.writeU64(20, m_txCenterFrequency); + s.writeS32(21, m_txLOOffset); + s.writeU32(22, m_log2SoftInterp); + s.writeFloat(23, m_txLpfBW); + s.writeBool(24, m_txTransverterMode); + s.writeS64(25, m_txTransverterDeltaFrequency); + s.writeU32(26, m_tx0Gain); + s.writeString(27, m_tx0AntennaPath); + s.writeU32(28, m_tx1Gain); + s.writeString(29, m_tx1AntennaPath); + s.writeBool(30, m_useReverseAPI); + s.writeString(31, m_reverseAPIAddress); + s.writeU32(32, m_reverseAPIPort); + s.writeU32(33, m_reverseAPIDeviceIndex); + + return s.final(); +} + +bool USRPMIMOSettings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if (!d.isValid()) + { + resetToDefaults(); + return false; + } + + if (d.getVersion() == 1) + { + int intval; + uint32_t uintval; + + d.readString(1, &m_title, "USRP"); + d.readS32(2, &m_devSampleRate, 3000000); + d.readString(3, &m_clockSource, "internal"); + d.readU32(4, &uintval, 0); + m_gpioDir = uintval & 0xFF; + d.readU32(5, &uintval, 0); + m_gpioPins = uintval & 0xFF; + d.readU64(6, &m_rxCenterFrequency, 435000*1000); + d.readS32(7, &m_rxLOOffset, 0); + d.readU32(8, &m_log2SoftDecim, 0); + m_log2SoftDecim = m_log2SoftDecim > 6 ? 6 : m_log2SoftDecim; + d.readFloat(9, &m_rxLpfBW, 10e6f); + d.readBool(10, &m_dcBlock, false); + d.readBool(11, &m_iqCorrection, false); + d.readBool(12, &m_rxTransverterMode, false); + d.readS64(13, &m_rxTransverterDeltaFrequency, 0); + d.readS32(14, &intval, (int) GAIN_AUTO); + m_rx0GainMode = intval == 0 ? GAIN_AUTO : GAIN_MANUAL; + d.readU32(15, &m_rx0Gain, 50); + d.readString(16, &m_rx0AntennaPath, "RX2"); + d.readS32(17, &intval, (int) GAIN_AUTO); + m_rx1GainMode = intval == 0 ? GAIN_AUTO : GAIN_MANUAL; + d.readU32(18, &m_rx1Gain, 50); + d.readString(19, &m_rx1AntennaPath, "RX2"); + d.readU64(20, &m_txCenterFrequency, 435000*1000); + d.readS32(21, &m_txLOOffset, 0); + d.readU32(22, &m_log2SoftInterp, 0); + m_log2SoftInterp = m_log2SoftInterp > 6 ? 6 : m_log2SoftInterp; + d.readFloat(23, &m_txLpfBW, 10e6f); + d.readBool(24, &m_txTransverterMode, false); + d.readS64(25, &m_txTransverterDeltaFrequency, 0); + d.readU32(26, &m_tx0Gain, 50); + d.readString(27, &m_tx0AntennaPath, "TX/RX"); + d.readU32(28, &m_tx1Gain, 50); + d.readString(29, &m_tx1AntennaPath, "TX/RX"); + d.readBool(30, &m_useReverseAPI, false); + d.readString(31, &m_reverseAPIAddress, "127.0.0.1"); + d.readU32(32, &uintval, 0); + + if ((uintval > 1023) && (uintval < 65535)) { + m_reverseAPIPort = uintval; + } else { + m_reverseAPIPort = 8888; + } + + d.readU32(33, &uintval, 0); + m_reverseAPIDeviceIndex = uintval > 99 ? 99 : uintval; + + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +void USRPMIMOSettings::applySettings(const QStringList& settingsKeys, const USRPMIMOSettings& settings) +{ + if (settingsKeys.contains("masterClockRate")) { + m_masterClockRate = settings.m_masterClockRate; + } + if (settingsKeys.contains("title")) { + m_title = settings.m_title; + } + if (settingsKeys.contains("devSampleRate")) { + m_devSampleRate = settings.m_devSampleRate; + } + if (settingsKeys.contains("clockSource")) { + m_clockSource = settings.m_clockSource; + } + if (settingsKeys.contains("gpioDir")) { + m_gpioDir = settings.m_gpioDir; + } + if (settingsKeys.contains("gpioPins")) { + m_gpioPins = settings.m_gpioPins; + } + if (settingsKeys.contains("rxCenterFrequency")) { + m_rxCenterFrequency = settings.m_rxCenterFrequency; + } + if (settingsKeys.contains("rxLOOffset")) { + m_rxLOOffset = settings.m_rxLOOffset; + } + if (settingsKeys.contains("log2SoftDecim")) { + m_log2SoftDecim = settings.m_log2SoftDecim; + } + if (settingsKeys.contains("rxLpfBW")) { + m_rxLpfBW = settings.m_rxLpfBW; + } + if (settingsKeys.contains("dcBlock")) { + m_dcBlock = settings.m_dcBlock; + } + if (settingsKeys.contains("iqCorrection")) { + m_iqCorrection = settings.m_iqCorrection; + } + if (settingsKeys.contains("rxTransverterMode")) { + m_rxTransverterMode = settings.m_rxTransverterMode; + } + if (settingsKeys.contains("rxTransverterDeltaFrequency")) { + m_rxTransverterDeltaFrequency = settings.m_rxTransverterDeltaFrequency; + } + if (settingsKeys.contains("rx0GainMode")) { + m_rx0GainMode = settings.m_rx0GainMode; + } + if (settingsKeys.contains("rx0Gain")) { + m_rx0Gain = settings.m_rx0Gain; + } + if (settingsKeys.contains("rx0AntennaPath")) { + m_rx0AntennaPath = settings.m_rx0AntennaPath; + } + if (settingsKeys.contains("rx1GainMode")) { + m_rx1GainMode = settings.m_rx1GainMode; + } + if (settingsKeys.contains("rx1Gain")) { + m_rx1Gain = settings.m_rx1Gain; + } + if (settingsKeys.contains("rx1AntennaPath")) { + m_rx1AntennaPath = settings.m_rx1AntennaPath; + } + if (settingsKeys.contains("txCenterFrequency")) { + m_txCenterFrequency = settings.m_txCenterFrequency; + } + if (settingsKeys.contains("txLOOffset")) { + m_txLOOffset = settings.m_txLOOffset; + } + if (settingsKeys.contains("log2SoftInterp")) { + m_log2SoftInterp = settings.m_log2SoftInterp; + } + if (settingsKeys.contains("txLpfBW")) { + m_txLpfBW = settings.m_txLpfBW; + } + if (settingsKeys.contains("txTransverterMode")) { + m_txTransverterMode = settings.m_txTransverterMode; + } + if (settingsKeys.contains("txTransverterDeltaFrequency")) { + m_txTransverterDeltaFrequency = settings.m_txTransverterDeltaFrequency; + } + if (settingsKeys.contains("tx0Gain")) { + m_tx0Gain = settings.m_tx0Gain; + } + if (settingsKeys.contains("tx0AntennaPath")) { + m_tx0AntennaPath = settings.m_tx0AntennaPath; + } + if (settingsKeys.contains("tx1Gain")) { + m_tx1Gain = settings.m_tx1Gain; + } + if (settingsKeys.contains("tx1AntennaPath")) { + m_tx1AntennaPath = settings.m_tx1AntennaPath; + } + if (settingsKeys.contains("useReverseAPI")) { + m_useReverseAPI = settings.m_useReverseAPI; + } + if (settingsKeys.contains("reverseAPIAddress")) { + m_reverseAPIAddress = settings.m_reverseAPIAddress; + } + if (settingsKeys.contains("reverseAPIPort")) { + m_reverseAPIPort = settings.m_reverseAPIPort; + } + if (settingsKeys.contains("reverseAPIDeviceIndex")) { + m_reverseAPIDeviceIndex = settings.m_reverseAPIDeviceIndex; + } +} + +QString USRPMIMOSettings::getDebugString(const QStringList& settingsKeys, bool force) const +{ + std::ostringstream ostr; + + if (settingsKeys.contains("masterClockRate") || force) { + ostr << " m_masterClockRate: " << m_masterClockRate; + } + if (settingsKeys.contains("title") || force) { + ostr << " m_title: " << m_title.toStdString(); + } + if (settingsKeys.contains("devSampleRate") || force) { + ostr << " m_devSampleRate: " << m_devSampleRate; + } + if (settingsKeys.contains("clockSource") || force) { + ostr << " m_clockSource: " << m_clockSource.toStdString(); + } + if (settingsKeys.contains("gpioDir") || force) { + ostr << " m_gpioDir: " << (int) m_gpioDir; + } + if (settingsKeys.contains("gpioPins") || force) { + ostr << " m_gpioPins: " << (int) m_gpioPins; + } + if (settingsKeys.contains("rxCenterFrequency") || force) { + ostr << " m_rxCenterFrequency: " << m_rxCenterFrequency; + } + if (settingsKeys.contains("rxLOOffset") || force) { + ostr << " m_rxLOOffset: " << m_rxLOOffset; + } + if (settingsKeys.contains("log2SoftDecim") || force) { + ostr << " m_log2SoftDecim: " << m_log2SoftDecim; + } + if (settingsKeys.contains("rxLpfBW") || force) { + ostr << " m_rxLpfBW: " << m_rxLpfBW; + } + if (settingsKeys.contains("dcBlock") || force) { + ostr << " m_dcBlock: " << m_dcBlock; + } + if (settingsKeys.contains("iqCorrection") || force) { + ostr << " m_iqCorrection: " << m_iqCorrection; + } + if (settingsKeys.contains("rxTransverterMode") || force) { + ostr << " m_rxTransverterMode: " << m_rxTransverterMode; + } + if (settingsKeys.contains("rxTransverterDeltaFrequency") || force) { + ostr << " m_rxTransverterDeltaFrequency: " << m_rxTransverterDeltaFrequency; + } + if (settingsKeys.contains("rx0GainMode") || force) { + ostr << " m_rx0GainMode: " << m_rx0GainMode; + } + if (settingsKeys.contains("rx0Gain") || force) { + ostr << " m_rx0Gain: " << m_rx0Gain; + } + if (settingsKeys.contains("rx0AntennaPath") || force) { + ostr << " m_rx0AntennaPath: " << m_rx0AntennaPath.toStdString(); + } + if (settingsKeys.contains("rx1GainMode") || force) { + ostr << " m_rx1GainMode: " << m_rx1GainMode; + } + if (settingsKeys.contains("rx1Gain") || force) { + ostr << " m_rx1Gain: " << m_rx1Gain; + } + if (settingsKeys.contains("rx1AntennaPath") || force) { + ostr << " m_rx1AntennaPath: " << m_rx1AntennaPath.toStdString(); + } + if (settingsKeys.contains("txCenterFrequency") || force) { + ostr << " m_txCenterFrequency: " << m_txCenterFrequency; + } + if (settingsKeys.contains("txLOOffset") || force) { + ostr << " m_txLOOffset: " << m_txLOOffset; + } + if (settingsKeys.contains("log2SoftInterp") || force) { + ostr << " m_log2SoftInterp: " << m_log2SoftInterp; + } + if (settingsKeys.contains("txLpfBW") || force) { + ostr << " m_txLpfBW: " << m_txLpfBW; + } + if (settingsKeys.contains("txTransverterMode") || force) { + ostr << " m_txTransverterMode: " << m_txTransverterMode; + } + if (settingsKeys.contains("txTransverterDeltaFrequency") || force) { + ostr << " m_txTransverterDeltaFrequency: " << m_txTransverterDeltaFrequency; + } + if (settingsKeys.contains("tx0Gain") || force) { + ostr << " m_tx0Gain: " << m_tx0Gain; + } + if (settingsKeys.contains("tx0AntennaPath") || force) { + ostr << " m_tx0AntennaPath: " << m_tx0AntennaPath.toStdString(); + } + if (settingsKeys.contains("tx1Gain") || force) { + ostr << " m_tx1Gain: " << m_tx1Gain; + } + if (settingsKeys.contains("tx1AntennaPath") || force) { + ostr << " m_tx1AntennaPath: " << m_tx1AntennaPath.toStdString(); + } + if (settingsKeys.contains("useReverseAPI") || force) { + ostr << " m_useReverseAPI: " << m_useReverseAPI; + } + if (settingsKeys.contains("reverseAPIAddress") || force) { + ostr << " m_reverseAPIAddress: " << m_reverseAPIAddress.toStdString(); + } + if (settingsKeys.contains("reverseAPIPort") || force) { + ostr << " m_reverseAPIPort: " << m_reverseAPIPort; + } + if (settingsKeys.contains("reverseAPIDeviceIndex") || force) { + ostr << " m_reverseAPIDeviceIndex: " << m_reverseAPIDeviceIndex; + } + + return QString(ostr.str().c_str()); +} diff --git a/plugins/samplemimo/usrpmimo/usrpmimosettings.h b/plugins/samplemimo/usrpmimo/usrpmimosettings.h new file mode 100644 index 000000000..ce7c7199d --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimosettings.h @@ -0,0 +1,78 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOSETTINGS_H_ +#define PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOSETTINGS_H_ + +#include + +#include +#include + +struct USRPMIMOSettings +{ + typedef enum { + GAIN_AUTO, + GAIN_MANUAL + } GainMode; + + QString m_title; + int m_masterClockRate; //!< Read-only, reported by device (-1 if unknown) + int m_devSampleRate; + QString m_clockSource; + uint8_t m_gpioDir; + uint8_t m_gpioPins; + quint64 m_rxCenterFrequency; + int m_rxLOOffset; + quint32 m_log2SoftDecim; + float m_rxLpfBW; + bool m_dcBlock; + bool m_iqCorrection; + bool m_rxTransverterMode; + qint64 m_rxTransverterDeltaFrequency; + GainMode m_rx0GainMode; + quint32 m_rx0Gain; + QString m_rx0AntennaPath; + GainMode m_rx1GainMode; + quint32 m_rx1Gain; + QString m_rx1AntennaPath; + quint64 m_txCenterFrequency; + int m_txLOOffset; + quint32 m_log2SoftInterp; + float m_txLpfBW; + bool m_txTransverterMode; + qint64 m_txTransverterDeltaFrequency; + quint32 m_tx0Gain; + QString m_tx0AntennaPath; + quint32 m_tx1Gain; + QString m_tx1AntennaPath; + + bool m_useReverseAPI; + QString m_reverseAPIAddress; + uint16_t m_reverseAPIPort; + uint16_t m_reverseAPIDeviceIndex; + + USRPMIMOSettings(); + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + void applySettings(const QStringList& settingsKeys, const USRPMIMOSettings& settings); + QString getDebugString(const QStringList& settingsKeys, bool force=false) const; +}; + +#endif /* PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOSETTINGS_H_ */ diff --git a/plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.cpp b/plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.cpp new file mode 100644 index 000000000..c5e108798 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.cpp @@ -0,0 +1,51 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "SWGDeviceSettings.h" +#include "SWGUSRPMIMOSettings.h" +#include "usrpmimo.h" +#include "usrpmimowebapiadapter.h" + +USRPMIMOWebAPIAdapter::USRPMIMOWebAPIAdapter() +{} + +USRPMIMOWebAPIAdapter::~USRPMIMOWebAPIAdapter() +{} + +int USRPMIMOWebAPIAdapter::webapiSettingsGet( + SWGSDRangel::SWGDeviceSettings& response, + QString& errorMessage) +{ + (void) errorMessage; + response.setUsrpMimoSettings(new SWGSDRangel::SWGUSRPMIMOSettings()); + response.getUsrpMimoSettings()->init(); + USRPMIMO::webapiFormatDeviceSettings(response, m_settings); + return 200; +} + +int USRPMIMOWebAPIAdapter::webapiSettingsPutPatch( + bool force, + const QStringList& deviceSettingsKeys, + SWGSDRangel::SWGDeviceSettings& response, // query + response + QString& errorMessage) +{ + (void) force; // no action + (void) errorMessage; + USRPMIMO::webapiUpdateDeviceSettings(m_settings, deviceSettingsKeys, response); + return 200; +} diff --git a/plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.h b/plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.h new file mode 100644 index 000000000..d6fae1b68 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimowebapiadapter.h @@ -0,0 +1,48 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOWEBAPIADAPTER_H_ +#define PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOWEBAPIADAPTER_H_ + +#include "device/devicewebapiadapter.h" +#include "usrpmimosettings.h" + +class USRPMIMOWebAPIAdapter : public DeviceWebAPIAdapter +{ +public: + USRPMIMOWebAPIAdapter(); + virtual ~USRPMIMOWebAPIAdapter(); + + virtual QByteArray serialize() { return m_settings.serialize(); } + virtual bool deserialize(const QByteArray& data) { return m_settings.deserialize(data); } + + virtual int webapiSettingsGet( + SWGSDRangel::SWGDeviceSettings& response, + QString& errorMessage); + + virtual int webapiSettingsPutPatch( + bool force, + const QStringList& deviceSettingsKeys, + SWGSDRangel::SWGDeviceSettings& response, // query + response + QString& errorMessage); + +private: + USRPMIMOSettings m_settings; +}; + +#endif // PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOWEBAPIADAPTER_H_ diff --git a/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp b/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp new file mode 100644 index 000000000..39962b6d4 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimoworker.cpp @@ -0,0 +1,407 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include + +#include +#include + +#include "usrp/deviceusrp.h" +#include "usrp/deviceusrpparam.h" +#include "usrp/deviceusrpshared.h" + +#include "usrpmimo.h" +#include "usrpmimoworker.h" + +USRPMIMOWorker::USRPMIMOWorker(DeviceUSRPParams *deviceParams, int nbRx, int nbTx, MessageQueue *reportQueue) : + m_deviceParams(deviceParams), + m_nbRx(nbRx), + m_nbTx(nbTx), + m_reportQueue(reportQueue) +{ + // Executes in the thread this object has been moved to + connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &USRPMIMOWorker::handleInputMessages); +} + +void USRPMIMOWorker::handleInputMessages() +{ + Message* message; + + // Merge consecutive configuration messages, so we only apply the latest settings. + // This avoids a backlog of slow device calls (E.g. when a slider is dragged) + bool pendingConfig = false; + USRPMIMOSettings settings; + QList settingsKeys; + bool force = false; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (USRPMIMO::MsgConfigureUSRPMIMO::match(*message)) + { + const USRPMIMO::MsgConfigureUSRPMIMO& conf = (const USRPMIMO::MsgConfigureUSRPMIMO&) *message; + + if (conf.getForce() || !pendingConfig) + { + settings = conf.getSettings(); + settingsKeys = conf.getSettingsKeys(); + force = force || conf.getForce(); + } + else + { + settings.applySettings(conf.getSettingsKeys(), conf.getSettings()); + for (const auto& key : conf.getSettingsKeys()) + { + if (!settingsKeys.contains(key)) { + settingsKeys.append(key); + } + } + } + pendingConfig = true; + } + else + { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + + delete message; + } + + if (pendingConfig) { + applyDeviceSettings(m_deviceParams, m_nbRx, m_nbTx, settings, settingsKeys, force, true, true, true, true, m_reportQueue); + } +} + +// Apply settings to the device and send what was actually set to reportQueue. +// applyCommon - apply settings common to Rx and Tx (clock source and GPIO) +// applyRx/applyTx - apply Rx/Tx settings +// applyBandwidth - apply LPF bandwidths. These shouldn't be set to a narrow bandwidth before the stream is created. +void USRPMIMOWorker::applyDeviceSettings( + DeviceUSRPParams *deviceParams, + int nbRx, + int nbTx, + const USRPMIMOSettings& settings, + const QList& settingsKeys, + bool force, + bool applyCommon, + bool applyRx, + bool applyTx, + bool applyBandwidth, + MessageQueue *reportQueue) +{ + uhd::usrp::multi_usrp::sptr device = deviceParams ? deviceParams->getDevice() : nullptr; + + if (!device) { + return; + } + + QMutexLocker mutexLocker(&deviceParams->m_mutex); + + bool reapplyRx = false; + bool reapplyTx = false; + bool checkRates = false; + bool checkClockSource = false; + + const quint32 rxGain[2] = {settings.m_rx0Gain, settings.m_rx1Gain}; + const USRPMIMOSettings::GainMode rxGainMode[2] = {settings.m_rx0GainMode, settings.m_rx1GainMode}; + const QString rxAntenna[2] = {settings.m_rx0AntennaPath, settings.m_rx1AntennaPath}; + const quint32 txGain[2] = {settings.m_tx0Gain, settings.m_tx1Gain}; + const QString txAntenna[2] = {settings.m_tx0AntennaPath, settings.m_tx1AntennaPath}; + + // Apply each setting separately, so a failure (E.g. an antenna name not supported by the + // daughterboard) doesn't prevent other settings from being applied + auto apply = [](const char *what, const std::function& func) { + try { + func(); + } catch (std::exception &e) { + qWarning() << "USRPMIMOWorker::applyDeviceSettings: failed to set" << what << ":" << e.what(); + } + }; + + auto setRxGain = [&](int channel) { + if (rxGainMode[channel] == USRPMIMOSettings::GAIN_AUTO) + { + try { + device->set_rx_agc(true, channel); + } catch (uhd::not_implemented_error &e) { + qDebug() << "USRPMIMOWorker::applyDeviceSettings: AGC not implemented on this radio. Please set to manual."; + } + } + else + { + try { + device->set_rx_agc(false, channel); + } catch (uhd::not_implemented_error &e) { + // Ignore + } + device->set_rx_gain(rxGain[channel], channel); + } + }; + + // Common settings + + if (applyCommon && (settingsKeys.contains("clockSource") || force)) + { + try + { + device->set_clock_source(settings.m_clockSource.toStdString(), 0); + qDebug() << "USRPMIMOWorker::applyDeviceSettings: clock set to " << settings.m_clockSource; + } + catch (std::exception &e) + { + // An exception will be thrown if the clock is not detected + qCritical() << "USRPMIMOWorker::applyDeviceSettings: could not set clock " << settings.m_clockSource; + // So, default back to internal + apply("clock source to internal", [&]() { device->set_clock_source("internal", 0); }); + } + // Report actual clock source, in case requested clock couldn't be set + checkClockSource = true; + reapplyRx = true; + reapplyTx = true; + } + + const std::string gpioBank = "FP0"; // Front Panel GPIO + + if (applyCommon && (settingsKeys.contains("gpioDir") || settingsKeys.contains("gpioPins") || force)) + { + apply("GPIO", [&]() { + std::vector banks = device->get_gpio_banks(0); + + if (std::find(banks.begin(), banks.end(), gpioBank) != banks.end()) + { + device->set_gpio_attr(gpioBank, "CTRL", ~settings.m_gpioDir, 0xff); // 0 for GPIO, 1 for ATR + device->set_gpio_attr(gpioBank, "DDR", settings.m_gpioDir, 0xff); // 0 for input, 1 for output + device->set_gpio_attr(gpioBank, "OUT", settings.m_gpioPins, 0xff); + qDebug() << "USRPMIMOWorker::applyDeviceSettings: set GPIO dir to" << settings.m_gpioDir << "pins to" << settings.m_gpioPins; + } + }); + } + + // All channels use the same sample rate, so set a master clock rate suitable for it first, + // otherwise UHD may not be able to change it automatically (See DeviceUSRP::setMasterClockRateForSampleRate) + bool reenableAutoMasterClockRate = false; + + if ((settingsKeys.contains("devSampleRate") || force) && ((applyRx && (nbRx > 0)) || (applyTx && (nbTx > 0)))) + { + apply("master clock rate", [&]() { + reenableAutoMasterClockRate = DeviceUSRP::setMasterClockRateForSampleRate(device, settings.m_devSampleRate, std::max(nbRx, nbTx)); + }); + } + + // Rx settings + + if (applyRx && (nbRx > 0)) + { + if (settingsKeys.contains("devSampleRate") || force) + { + apply("Rx sample rate", [&]() { + for (int channel = 0; channel < nbRx; channel++) { + device->set_rx_rate(settings.m_devSampleRate, channel); + } + qDebug("USRPMIMOWorker::applyDeviceSettings: Rx sample rate set to %d", settings.m_devSampleRate); + }); + checkRates = true; + reapplyRx = true; + } + + if (settingsKeys.contains("rxCenterFrequency") + || settingsKeys.contains("rxLOOffset") + || settingsKeys.contains("rxTransverterMode") + || settingsKeys.contains("rxTransverterDeltaFrequency") + || force) + { + apply("Rx frequency", [&]() { + qint64 deviceCenterFrequency = settings.m_rxCenterFrequency; + deviceCenterFrequency -= settings.m_rxTransverterMode ? settings.m_rxTransverterDeltaFrequency : 0; + deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; + uhd::tune_request_t tuneRequest = settings.m_rxLOOffset != 0 + ? uhd::tune_request_t(deviceCenterFrequency, settings.m_rxLOOffset) + : uhd::tune_request_t(deviceCenterFrequency); + + for (int channel = 0; channel < nbRx; channel++) { + device->set_rx_freq(tuneRequest, channel); + } + qDebug("USRPMIMOWorker::applyDeviceSettings: Rx frequency set to %lld with LO offset %d", deviceCenterFrequency, settings.m_rxLOOffset); + }); + } + + if (settingsKeys.contains("dcBlock") || force) + { + apply("Rx DC offset correction", [&]() { + for (int channel = 0; channel < nbRx; channel++) { + device->set_rx_dc_offset(settings.m_dcBlock, channel); + } + }); + } + + if (settingsKeys.contains("iqCorrection") || force) + { + apply("Rx IQ correction", [&]() { + for (int channel = 0; channel < nbRx; channel++) { + device->set_rx_iq_balance(settings.m_iqCorrection, channel); + } + }); + } + + for (int channel = 0; channel < nbRx; channel++) + { + QString prefix = QString("rx%1").arg(channel); + + if (settingsKeys.contains(prefix + "GainMode") || settingsKeys.contains(prefix + "Gain") || force) { + apply("Rx gain", [&]() { setRxGain(channel); }); + } + + if (settingsKeys.contains(prefix + "AntennaPath") || force) { + apply("Rx antenna", [&]() { device->set_rx_antenna(rxAntenna[channel].toStdString(), channel); }); + } + } + + if (applyBandwidth && (settingsKeys.contains("rxLpfBW") || force)) + { + apply("Rx LPF bandwidth", [&]() { + for (int channel = 0; channel < nbRx; channel++) { + device->set_rx_bandwidth(settings.m_rxLpfBW, channel); + } + qDebug("USRPMIMOWorker::applyDeviceSettings: Rx LPF BW set to %f", settings.m_rxLpfBW); + }); + } + } + + // Tx settings + + if (applyTx && (nbTx > 0)) + { + if (settingsKeys.contains("devSampleRate") || force) + { + apply("Tx sample rate", [&]() { + for (int channel = 0; channel < nbTx; channel++) { + device->set_tx_rate(settings.m_devSampleRate, channel); + } + qDebug("USRPMIMOWorker::applyDeviceSettings: Tx sample rate set to %d", settings.m_devSampleRate); + }); + checkRates = true; + reapplyTx = true; + } + + if (settingsKeys.contains("txCenterFrequency") + || settingsKeys.contains("txLOOffset") + || settingsKeys.contains("txTransverterMode") + || settingsKeys.contains("txTransverterDeltaFrequency") + || force) + { + apply("Tx frequency", [&]() { + qint64 deviceCenterFrequency = settings.m_txCenterFrequency; + deviceCenterFrequency -= settings.m_txTransverterMode ? settings.m_txTransverterDeltaFrequency : 0; + deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; + uhd::tune_request_t tuneRequest = settings.m_txLOOffset != 0 + ? uhd::tune_request_t(deviceCenterFrequency, settings.m_txLOOffset) + : uhd::tune_request_t(deviceCenterFrequency); + + for (int channel = 0; channel < nbTx; channel++) { + device->set_tx_freq(tuneRequest, channel); + } + qDebug("USRPMIMOWorker::applyDeviceSettings: Tx frequency set to %lld with LO offset %d", deviceCenterFrequency, settings.m_txLOOffset); + }); + } + + for (int channel = 0; channel < nbTx; channel++) + { + QString prefix = QString("tx%1").arg(channel); + + if (settingsKeys.contains(prefix + "Gain") || force) { + apply("Tx gain", [&]() { device->set_tx_gain(txGain[channel], channel); }); + } + + if (settingsKeys.contains(prefix + "AntennaPath") || force) { + apply("Tx antenna", [&]() { device->set_tx_antenna(txAntenna[channel].toStdString(), channel); }); + } + } + + if (applyBandwidth && (settingsKeys.contains("txLpfBW") || force)) + { + apply("Tx LPF bandwidth", [&]() { + for (int channel = 0; channel < nbTx; channel++) { + device->set_tx_bandwidth(settings.m_txLpfBW, channel); + } + qDebug("USRPMIMOWorker::applyDeviceSettings: Tx LPF BW set to %f", settings.m_txLpfBW); + }); + } + } + + if (reenableAutoMasterClockRate) { + apply("automatic master clock rate", [&]() { DeviceUSRP::enableAutoMasterClockRate(device); }); + } + + // Need to re-set bandwidth and AGC after changing sample rate or clock source + + if (applyBandwidth && applyRx && reapplyRx) + { + for (int channel = 0; channel < nbRx; channel++) + { + apply("Rx LPF bandwidth", [&]() { device->set_rx_bandwidth(settings.m_rxLpfBW, channel); }); + apply("Rx gain", [&]() { setRxGain(channel); }); + } + } + + if (applyBandwidth && applyTx && reapplyTx) + { + for (int channel = 0; channel < nbTx; channel++) { + apply("Tx LPF bandwidth", [&]() { device->set_tx_bandwidth(settings.m_txLpfBW, channel); }); + } + } + + // Report what was actually set, so USRPMIMO can update its settings and the GUI + double sampleRate = 0.0; + double masterClockRate = 0.0; + QString clockSource; + + if (checkRates) + { + try + { + sampleRate = DeviceUSRP::getSampleRate(device, nbRx > 0, 0); + masterClockRate = device->get_master_clock_rate(); + qDebug("USRPMIMOWorker::applyDeviceSettings: actual sample rate %f master_clock_rate %f", sampleRate, masterClockRate); + } + catch (std::exception &e) + { + qDebug() << "USRPMIMOWorker::applyDeviceSettings: could not get sample rate: " << e.what(); + checkRates = false; + } + } + + if (checkClockSource) + { + try + { + clockSource = QString::fromStdString(device->get_clock_source(0)); + qDebug() << "USRPMIMOWorker::applyDeviceSettings: clock source is " << clockSource; + } + catch (std::exception &e) + { + qDebug() << "USRPMIMOWorker::applyDeviceSettings: could not get clock source: " << e.what(); + checkClockSource = false; + } + } + + if ((checkRates || checkClockSource) && reportQueue) { + reportQueue->push(DeviceUSRPShared::MsgReportDeviceSettings::create(checkRates, sampleRate, masterClockRate, checkClockSource, clockSource, false)); + } +} diff --git a/plugins/samplemimo/usrpmimo/usrpmimoworker.h b/plugins/samplemimo/usrpmimo/usrpmimoworker.h new file mode 100644 index 000000000..8b7989c3c --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmimoworker.h @@ -0,0 +1,66 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOWORKER_H_ +#define PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOWORKER_H_ + +#include + +#include "util/messagequeue.h" +#include "usrpmimosettings.h" + +struct DeviceUSRPParams; + +/** + * Applies settings to the device in its own thread, as some settings (E.g. sample rate, + * clock source and bandwidth) can take a long time to set, which would otherwise block the GUI. + * Values actually set are reported via DeviceUSRPShared::MsgReportDeviceSettings. + */ +class USRPMIMOWorker : public QObject +{ + Q_OBJECT + +public: + USRPMIMOWorker(DeviceUSRPParams *deviceParams, int nbRx, int nbTx, MessageQueue *reportQueue); + MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + + static void applyDeviceSettings( + DeviceUSRPParams *deviceParams, + int nbRx, + int nbTx, + const USRPMIMOSettings& settings, + const QList& settingsKeys, + bool force, + bool applyCommon, + bool applyRx, + bool applyTx, + bool applyBandwidth, + MessageQueue *reportQueue); + +private: + DeviceUSRPParams *m_deviceParams; + int m_nbRx; + int m_nbTx; + MessageQueue *m_reportQueue; //!< Where to send MsgReportDeviceSettings (USRPMIMO's input queue) + MessageQueue m_inputMessageQueue; //!< Settings to apply to the device + +private slots: + void handleInputMessages(); +}; + +#endif // PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMIMOWORKER_H_ diff --git a/plugins/samplemimo/usrpmimo/usrpmithread.cpp b/plugins/samplemimo/usrpmimo/usrpmithread.cpp new file mode 100644 index 000000000..34d9523a3 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmithread.cpp @@ -0,0 +1,282 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#include +#include + +#include "dsp/samplemififo.h" +#include "usrp/deviceusrp.h" + +#include "usrpmithread.h" + +USRPMIThread::USRPMIThread(uhd::usrp::multi_usrp::sptr device, uhd::rx_streamer::sptr stream, size_t bufSamples, + int nbChannels, SampleMIFifo *sampleFifo, QObject* parent) : + QThread(parent), + m_running(false), + m_started(false), + m_runStarted(false), + m_packets(0), + m_overflows(0), + m_timeouts(0), + m_device(device), + m_stream(stream), + m_bufSamples(bufSamples), + m_nbChannels(std::min(nbChannels, m_maxChannels)), + m_sampleFifo(sampleFifo), + m_log2Decim(0) +{ + setObjectName("USRPMI"); + + for (int channel = 0; channel < m_nbChannels; channel++) + { + // *2 as samples are I+Q + m_buf.push_back(std::vector(2 * m_bufSamples, 0)); + m_convertBuffer[channel].resize(m_bufSamples, Sample{0, 0}); + } + + for (int channel = 0; channel < m_nbChannels; channel++) { + m_bufPtrs.push_back(m_buf[channel].data()); + } +} + +USRPMIThread::~USRPMIThread() +{ + stopWork(); +} + +void USRPMIThread::issueStreamCmd(bool start) +{ + uhd::stream_cmd_t streamCmd(start ? uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS : uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS); + streamCmd.num_samps = 0; + + if (start && (m_nbChannels > 1)) + { + // Channels in a multi-channel stream need to be started at the same time, so they are aligned + streamCmd.stream_now = false; + streamCmd.time_spec = m_device->get_time_now() + uhd::time_spec_t(0.05); + } + else + { + streamCmd.stream_now = true; + } + + m_stream->issue_stream_cmd(streamCmd); + qDebug() << "USRPMIThread::issueStreamCmd:" << (start ? "start" : "stop"); +} + +void USRPMIThread::startWork() +{ + if (m_started) { + return; + } + + m_packets = 0; + m_overflows = 0; + m_timeouts = 0; + + try + { + issueStreamCmd(true); + } + catch (std::exception& e) + { + qWarning() << "USRPMIThread::startWork: exception: " << e.what(); + } + + // Wait for run() to start. Use a separate flag to m_running, as run() may exit immediately on error + m_runStarted = false; + m_started = true; + m_startWaitMutex.lock(); + start(); + + while (!m_runStarted) { + m_startWaiter.wait(&m_startWaitMutex, 100); + } + + m_startWaitMutex.unlock(); +} + +void USRPMIThread::stopWork() +{ + if (!m_started) { + return; + } + + m_started = false; + m_running = false; + wait(); + + try + { + issueStreamCmd(false); + flush(); + } + catch (std::exception& e) + { + qWarning() << "USRPMIThread::stopWork: exception: " << e.what(); + } +} + +// Clear out any data left in the stream, otherwise we'll get an +// exception 'recv buffer smaller than vrt packet offset' when restarting +void USRPMIThread::flush() +{ + uhd::rx_metadata_t md; + const int maxFlushes = 1000; // In case device has been disconnected + + md.end_of_burst = false; + md.error_code = uhd::rx_metadata_t::ERROR_CODE_NONE; + + for (int i = 0; (i < maxFlushes) && !md.end_of_burst && (md.error_code != uhd::rx_metadata_t::ERROR_CODE_TIMEOUT); i++) + { + try + { + md.reset(); + m_stream->recv(m_bufPtrs, m_bufSamples, md); + } + catch (std::exception& e) + { + qDebug() << "USRPMIThread::flush: exception: " << e.what(); + break; + } + } +} + +void USRPMIThread::run() +{ + uhd::rx_metadata_t md; + // First samples won't arrive until the timed start + double timeout = 1.0; + + // Higher priority, so streaming isn't delayed by other threads + DeviceUSRP::setStreamingThreadPriority(); + + m_running = true; + m_runStarted = true; + m_startWaiter.wakeAll(); + + try + { + while (m_running) + { + md.reset(); + const size_t samplesReceived = m_stream->recv(m_bufPtrs, m_bufSamples, md, timeout); + timeout = DeviceUSRP::m_streamTimeout; + + m_packets++; + + if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) + { + qDebug("USRPMIThread::run: timeout - restarting"); + m_timeouts++; + issueStreamCmd(false); + issueStreamCmd(true); + timeout = 1.0; + } + else if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) + { + m_overflows++; + } + else if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_ALIGNMENT) + { + // Channels lose alignment when the device is reconfigured while streaming + // (E.g. sample rate or clock source change, which resets the AD9361 on B2xx). + // UHD can't recover from this itself, so restart with a timed start to realign them + qDebug("USRPMIThread::run: multi-channel alignment failed - restarting"); + issueStreamCmd(false); + flush(); + issueStreamCmd(true); + timeout = 1.0; + continue; + } + else if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) + { + qDebug() << "USRPMIThread::run: error: " << QString::fromStdString(md.strerror()); + } + + if (samplesReceived > 0) + { + std::vector vbegin; + int length = 0; + // Read once, as it can be changed from another thread, and the same value must be used for all channels + const unsigned int log2Decim = m_log2Decim; + + for (int channel = 0; channel < m_nbChannels; channel++) + { + int channelLength = channelCallback(m_buf[channel].data(), 2 * samplesReceived, channel, log2Decim); + length = channel == 0 ? channelLength : std::min(length, channelLength); + vbegin.push_back(m_convertBuffer[channel].begin()); + } + + m_sampleFifo->writeSync(vbegin, length); + } + } + } + catch (std::exception& e) + { + qWarning() << "USRPMIThread::run: exception: " << e.what(); + } + + m_running = false; +} + +// Decimate according to specified log2 (ex: log2=4 => decim=16). len is number of I and Q values +int USRPMIThread::channelCallback(const qint16* buf, qint32 len, int channel, unsigned int log2Decim) +{ + SampleVector::iterator it = m_convertBuffer[channel].begin(); + + switch (log2Decim) + { + case 0: + m_decimators[channel].decimate1(&it, buf, len); + break; + case 1: + m_decimators[channel].decimate2_cen(&it, buf, len); + break; + case 2: + m_decimators[channel].decimate4_cen(&it, buf, len); + break; + case 3: + m_decimators[channel].decimate8_cen(&it, buf, len); + break; + case 4: + m_decimators[channel].decimate16_cen(&it, buf, len); + break; + case 5: + m_decimators[channel].decimate32_cen(&it, buf, len); + break; + case 6: + m_decimators[channel].decimate64_cen(&it, buf, len); + break; + default: + break; + } + + return it - m_convertBuffer[channel].begin(); +} + +void USRPMIThread::getStreamStatus(bool& active, quint32& overflows, quint32& timeouts) +{ + active = m_packets > 0; + overflows = m_overflows; + timeouts = m_timeouts; +} diff --git a/plugins/samplemimo/usrpmimo/usrpmithread.h b/plugins/samplemimo/usrpmimo/usrpmithread.h new file mode 100644 index 000000000..492706d7d --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmithread.h @@ -0,0 +1,84 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMITHREAD_H_ +#define PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMITHREAD_H_ + +#include +#include + +#include +#include +#include + +#include + +#include "dsp/decimators.h" + +class SampleMIFifo; + +/** + * Receives samples from all Rx channels of the device, using a single multi-channel + * stream, so samples from each channel are time aligned. + */ +class USRPMIThread : public QThread { + Q_OBJECT + +public: + static constexpr int m_maxChannels = 2; + + USRPMIThread(uhd::usrp::multi_usrp::sptr device, uhd::rx_streamer::sptr stream, size_t bufSamples, + int nbChannels, SampleMIFifo *sampleFifo, QObject* parent = nullptr); + ~USRPMIThread(); + + void startWork(); + void stopWork(); + bool isRunning() const { return m_started; } + void setLog2Decimation(unsigned int log2Decim) { m_log2Decim = log2Decim; } + void getStreamStatus(bool& active, quint32& overflows, quint32& timeouts); + +private: + QMutex m_startWaitMutex; + QWaitCondition m_startWaiter; + std::atomic m_running; //!< Set while run() loop should continue + std::atomic m_started; //!< Set from startWork() to stopWork() + std::atomic m_runStarted; //!< Set when run() has started + + std::atomic m_packets; + std::atomic m_overflows; + std::atomic m_timeouts; + + uhd::usrp::multi_usrp::sptr m_device; + uhd::rx_streamer::sptr m_stream; + size_t m_bufSamples; + int m_nbChannels; + std::vector> m_buf; //!< Per channel buffers of interleaved I/Q + std::vector m_bufPtrs; + SampleVector m_convertBuffer[m_maxChannels]; + SampleMIFifo *m_sampleFifo; + std::atomic m_log2Decim; + + Decimators m_decimators[m_maxChannels]; + + void run(); + void issueStreamCmd(bool start); + void flush(); + int channelCallback(const qint16* buf, qint32 len, int channel, unsigned int log2Decim); +}; + +#endif // PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMITHREAD_H_ diff --git a/plugins/samplemimo/usrpmimo/usrpmothread.cpp b/plugins/samplemimo/usrpmimo/usrpmothread.cpp new file mode 100644 index 000000000..f8b759d51 --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmothread.cpp @@ -0,0 +1,321 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +#include + +#include + +#include "dsp/samplemofifo.h" +#include "usrp/deviceusrpshared.h" +#include "usrp/deviceusrp.h" + +#include "usrpmothread.h" + +USRPMOThread::USRPMOThread(uhd::usrp::multi_usrp::sptr device, uhd::tx_streamer::sptr stream, size_t bufSamples, + int nbChannels, SampleMOFifo *sampleFifo, QObject* parent) : + QThread(parent), + m_running(false), + m_packets(0), + m_underflows(0), + m_droppedPackets(0), + m_device(device), + m_stream(stream), + m_bufSamples(bufSamples), + m_nbChannels(std::min(nbChannels, m_maxChannels)), + m_sampleFifo(sampleFifo), + m_log2Interp(0), + m_detached(false) +{ + setObjectName("USRPMO"); + + for (int channel = 0; channel < m_nbChannels; channel++) { + // *2 as samples are I+Q + m_buf.push_back(std::vector(2 * m_bufSamples, 0)); + } + + for (int channel = 0; channel < m_nbChannels; channel++) { + m_bufPtrs.push_back(m_buf[channel].data()); + } + + // Executes in the thread this object was created in (the device engine thread), not in run() + connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &USRPMOThread::handleInputMessages); +} + +USRPMOThread::~USRPMOThread() +{ + stopWork(); +} + +void USRPMOThread::startWork() +{ + if (m_running || !m_stream) { + return; + } + + m_packets = 0; + m_underflows = 0; + m_droppedPackets = 0; + + m_startWaitMutex.lock(); + start(); + + while (!m_running) { + m_startWaiter.wait(&m_startWaitMutex, 100); + } + + m_startWaitMutex.unlock(); +} + +void USRPMOThread::stopWork() +{ + if (!m_running) { + return; + } + + m_running = false; + wait(); + + try + { + // Get message indicating underflow, so it doesn't appear if we restart + uhd::async_metadata_t md; + m_stream->recv_async_msg(md); + } + catch (std::exception& e) + { + qDebug() << "USRPMOThread::stopWork: exception: " << e.what(); + } +} + +// Release references to stream and device, so they're destroyed when the device is closed, +// even if this object is deleted later. Thread must be stopped. +void USRPMOThread::releaseStream() +{ + m_stream = nullptr; + m_device = nullptr; +} + +// Stop handling requests, waiting for any request being handled to complete. +// Used when stopping from a thread other than the device engine thread (E.g. when USRPMIMO is being destroyed) +void USRPMOThread::detach() +{ + QMutexLocker mutexLocker(&m_configMutex); + m_detached = true; +} + +void USRPMOThread::handleInputMessages() +{ + QMutexLocker mutexLocker(&m_configMutex); + Message* message; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (!m_detached) + { + if (DeviceUSRPShared::MsgResizeSampleFifo::match(*message)) { + resizeSampleFifo(((const DeviceUSRPShared::MsgResizeSampleFifo&) *message).getSize()); + } else { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + } + + delete message; + } +} + +// Resize the sample FIFO. This executes in the device engine thread, which writes to the FIFO, +// so the only other thread that accesses it is the streaming thread, which is paused while it is resized. +void USRPMOThread::resizeSampleFifo(unsigned int size) +{ + bool wasRunning = m_running; + + if (wasRunning) { + stopWork(); + } + + m_sampleFifo->resize(size); + qDebug("USRPMOThread::resizeSampleFifo: %u", size); + + if (wasRunning) { + startWork(); + } +} + +void USRPMOThread::run() +{ + uhd::tx_metadata_t md; + md.end_of_burst = false; + + // Higher priority, so streaming isn't delayed by other threads + DeviceUSRP::setStreamingThreadPriority(); + + if (m_nbChannels > 1) + { + // Channels in a multi-channel stream need to be started at the same time, so they are aligned + try + { + md.start_of_burst = true; + md.has_time_spec = true; + md.time_spec = m_device->get_time_now() + uhd::time_spec_t(0.05); + } + catch (std::exception& e) + { + qWarning() << "USRPMOThread::run: could not get time: " << e.what(); + md.start_of_burst = false; + md.has_time_spec = false; + } + } + else + { + md.start_of_burst = false; + md.has_time_spec = false; + } + + m_running = true; + m_startWaiter.wakeAll(); + + while (m_running) + { + unsigned int writtenSamples = callback(); + + try + { + // First packet may not be sent until its time, so allow for that in timeout + const size_t sentSamples = m_stream->send(m_bufPtrs, writtenSamples, md, md.has_time_spec ? 1.0 : DeviceUSRP::m_streamTimeout); + m_packets++; + + if (sentSamples != writtenSamples) { + qDebug("USRPMOThread::run: sent %zu/%u samples", sentSamples, writtenSamples); + } + } + catch (std::exception& e) + { + qDebug() << "USRPMOThread::run: exception: " << e.what(); + } + + md.start_of_burst = false; + md.has_time_spec = false; + } + + // End the burst, so the stream can be restarted cleanly + try + { + md.end_of_burst = true; + m_stream->send(m_bufPtrs, 0, md); + } + catch (std::exception& e) + { + qDebug() << "USRPMOThread::run: exception sending end of burst: " << e.what(); + } + + m_running = false; +} + +// Read and interpolate samples for all channels. +// Returns number of samples written to each channel buffer, which may be less than the buffer size, +// when the buffer size is not divisible by the interpolation factor. +unsigned int USRPMOThread::callback() +{ + // Read once, as it can be changed from another thread, and the same value must be used for the whole buffer + const unsigned int log2Interp = m_log2Interp; + const unsigned int interpolationFactor = 1U << log2Interp; + unsigned int iPart1Begin, iPart1End, iPart2Begin, iPart2End; + + m_sampleFifo->readSync(m_bufSamples / interpolationFactor, iPart1Begin, iPart1End, iPart2Begin, iPart2End); + + if (iPart1Begin != iPart1End) { + callbackPart(iPart1Begin, iPart1End - iPart1Begin, 0, log2Interp); + } + + if (iPart2Begin != iPart2End) { + callbackPart(iPart2Begin, iPart2End - iPart2Begin, (iPart1End - iPart1Begin) * interpolationFactor, log2Interp); + } + + return ((iPart1End - iPart1Begin) + (iPart2End - iPart2Begin)) * interpolationFactor; +} + +// Interpolate nSamples from FIFO starting at iBegin, into each channel buffer, starting at sample offset +void USRPMOThread::callbackPart(unsigned int iBegin, unsigned int nSamples, unsigned int offset, unsigned int log2Interp) +{ + const int len = 2 * nSamples * (1 << log2Interp); // Number of I and Q values output + + for (int channel = 0; channel < m_nbChannels; channel++) + { + SampleVector::iterator begin = m_sampleFifo->getData(channel).begin() + iBegin; + qint16 *buf = &m_buf[channel][2 * offset]; + + switch (log2Interp) + { + case 0: + m_interpolators[channel].interpolate1(&begin, buf, len); + break; + case 1: + m_interpolators[channel].interpolate2_cen(&begin, buf, len); + break; + case 2: + m_interpolators[channel].interpolate4_cen(&begin, buf, len); + break; + case 3: + m_interpolators[channel].interpolate8_cen(&begin, buf, len); + break; + case 4: + m_interpolators[channel].interpolate16_cen(&begin, buf, len); + break; + case 5: + m_interpolators[channel].interpolate32_cen(&begin, buf, len); + break; + case 6: + m_interpolators[channel].interpolate64_cen(&begin, buf, len); + break; + default: + break; + } + } +} + +// Called from GUI thread +void USRPMOThread::getStreamStatus(bool& active, quint32& underflows, quint32& droppedPackets) +{ + uhd::async_metadata_t md; + + // Don't wait for messages (default timeout is 0.1s), and drain all pending messages + try + { + while (m_stream && m_stream->recv_async_msg(md, 0.0)) + { + if ((md.event_code & uhd::async_metadata_t::EVENT_CODE_UNDERFLOW) + || (md.event_code & uhd::async_metadata_t::EVENT_CODE_UNDERFLOW_IN_PACKET)) { + m_underflows++; + } + if ((md.event_code & uhd::async_metadata_t::EVENT_CODE_SEQ_ERROR) + || (md.event_code & uhd::async_metadata_t::EVENT_CODE_SEQ_ERROR_IN_BURST)) { + m_droppedPackets++; + } + } + } + catch (std::exception& e) + { + qDebug() << "USRPMOThread::getStreamStatus: exception: " << e.what(); + } + + active = m_packets > 0; + underflows = m_underflows; + droppedPackets = m_droppedPackets; +} diff --git a/plugins/samplemimo/usrpmimo/usrpmothread.h b/plugins/samplemimo/usrpmimo/usrpmothread.h new file mode 100644 index 000000000..86e6cfecf --- /dev/null +++ b/plugins/samplemimo/usrpmimo/usrpmothread.h @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// 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 . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMOTHREAD_H_ +#define PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMOTHREAD_H_ + +#include +#include + +#include +#include +#include + +#include + +#include "dsp/interpolators.h" +#include "util/messagequeue.h" + +class SampleMOFifo; + +/** + * Sends samples to all Tx channels of the device, using a single multi-channel + * stream, so samples for each channel are time aligned. + * + * As this object is created in USRPMIMO::startTx(), which is called from the device engine thread, + * its slots execute in the device engine thread, which is where samples are written to the FIFO. + * This allows the FIFO to be resized safely (See MsgResizeSampleFifo). + */ +class USRPMOThread : public QThread { + Q_OBJECT + +public: + static constexpr int m_maxChannels = 2; + + USRPMOThread(uhd::usrp::multi_usrp::sptr device, uhd::tx_streamer::sptr stream, size_t bufSamples, + int nbChannels, SampleMOFifo *sampleFifo, QObject* parent = nullptr); + ~USRPMOThread(); + + void startWork(); + void stopWork(); + bool isRunning() const { return m_running; } + void setLog2Interpolation(unsigned int log2Interp) { m_log2Interp = log2Interp; } + void getStreamStatus(bool& active, quint32& underflows, quint32& droppedPackets); + MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + void detach(); + void releaseStream(); + +private: + QMutex m_startWaitMutex; + QWaitCondition m_startWaiter; + std::atomic m_running; + + std::atomic m_packets; + quint32 m_underflows; + quint32 m_droppedPackets; + + uhd::usrp::multi_usrp::sptr m_device; + uhd::tx_streamer::sptr m_stream; + size_t m_bufSamples; + int m_nbChannels; + std::vector> m_buf; //!< Per channel buffers of interleaved I/Q + std::vector m_bufPtrs; + SampleMOFifo *m_sampleFifo; + std::atomic m_log2Interp; + + //!< UHD's sc16 format is 16-bit, converted by UHD to device wire format (E.g. 12-bit for B2xx) + Interpolators m_interpolators[m_maxChannels]; + + MessageQueue m_inputMessageQueue; //!< Requests to execute in device engine thread + QMutex m_configMutex; //!< Held while handling requests, so detach() can wait for them to complete + bool m_detached; //!< When set, no longer handle requests + + void run(); + unsigned int callback(); + void callbackPart(unsigned int iBegin, unsigned int nSamples, unsigned int offset, unsigned int log2Interp); + void resizeSampleFifo(unsigned int size); + +private slots: + void handleInputMessages(); +}; + +#endif // PLUGINS_SAMPLEMIMO_USRPMIMO_USRPMOTHREAD_H_ diff --git a/plugins/samplesink/usrpoutput/readme.md b/plugins/samplesink/usrpoutput/readme.md index 2fc29d960..4ff00ba50 100644 --- a/plugins/samplesink/usrpoutput/readme.md +++ b/plugins/samplesink/usrpoutput/readme.md @@ -117,6 +117,8 @@ This adjusts the Tx local oscillator (LO) frequency from the centre frequency by This label turns green when data has been transmitted to the device. +The board temperature in degrees C is displayed to the left of this indicator, for devices that have a temperature sensor (E.g. the AD9361 on the B2xx). +

13: Stream warning indicators

- **U**: turns red if stream experiences underruns @@ -124,6 +126,8 @@ This label turns green when data has been transmitted to the device. The stream warning indicators are reset when the acquisition is started. +Hovering over an indicator shows statistics for the current (or last) run: the total number of events, the average number per minute, the number in the last minute and the time of the last event. +

GPIOs

The USRP device settings supports 8-bit `gpioDir` and `gpioPins` settings. These can be set via the Web API or Simple PTT feature. diff --git a/plugins/samplesink/usrpoutput/usrpoutput.cpp b/plugins/samplesink/usrpoutput/usrpoutput.cpp index a6a6c1072..826b9efd8 100644 --- a/plugins/samplesink/usrpoutput/usrpoutput.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutput.cpp @@ -17,12 +17,14 @@ /////////////////////////////////////////////////////////////////////////////////// #include +#include #include #include #include #include #include +#include #include @@ -58,11 +60,23 @@ USRPOutput::USRPOutput(DeviceAPI *deviceAPI) : m_deviceAPI->setNbSinkStreams(1); m_sampleSourceFifo.resize(SampleSourceFifo::getSizePolicy(m_settings.m_devSampleRate)); m_streamId = nullptr; + // Hold the shared device mutex (if there are buddies) across suspend...resume, so it can't interleave + // with buddies doing the same in their device engine threads + DeviceUSRPParams *buddyDeviceParams = getBuddyDeviceParams(); + + if (buddyDeviceParams) { + buddyDeviceParams->m_mutex.lock(); + } + suspendRxBuddies(); suspendTxBuddies(); openDevice(); resumeTxBuddies(); resumeRxBuddies(); + + if (buddyDeviceParams) { + buddyDeviceParams->m_mutex.unlock(); + } m_networkManager = new QNetworkAccessManager(); QObject::connect( m_networkManager, @@ -86,11 +100,32 @@ USRPOutput::~USRPOutput() stop(); } + DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams; + bool hasBuddies = (m_deviceAPI->getSourceBuddies().size() > 0) || (m_deviceAPI->getSinkBuddies().size() > 0); + + if (deviceParams) + { + // Prevent buddies using our shared data after we've been deleted, but before buddy lists are cleared. + // Buddies read this in their device engine threads with the device mutex held. + QMutexLocker deviceLocker(&deviceParams->m_mutex); + m_deviceAPI->setBuddySharedPtr(nullptr); + } + + // Hold device mutex across suspend...resume, so it can't interleave with buddies doing the same. + // If there are no buddies, the device params are deleted in closeDevice, but then there's nothing to protect. + if (hasBuddies && deviceParams) { + deviceParams->m_mutex.lock(); + } + suspendRxBuddies(); suspendTxBuddies(); closeDevice(); resumeTxBuddies(); resumeRxBuddies(); + + if (hasBuddies && deviceParams) { + deviceParams->m_mutex.unlock(); + } } void USRPOutput::destroy() @@ -102,17 +137,27 @@ bool USRPOutput::openDevice() { bool ret = true; + // Set shared pointer first, so it is valid for buddies, even if we return early on error + m_deviceAPI->setBuddySharedPtr(&m_deviceShared); // propagate common parameters to API + int requestedChannel = m_deviceAPI->getDeviceItemIndex(); // look for Tx buddies and get reference to common parameters // if there is a channel left take the first available if (m_deviceAPI->getSinkBuddies().size() > 0) // look sink sibling first { - qDebug("USRPOutput::openDevice: look in Ix buddies"); + qDebug("USRPOutput::openDevice: look in Tx buddies"); DeviceAPI *sinkBuddy = m_deviceAPI->getSinkBuddies()[0]; //m_deviceShared = *((DeviceUSRPShared *) sinkBuddy->getBuddySharedPtr()); // copy shared data DeviceUSRPShared *deviceUSRPShared = (DeviceUSRPShared*) sinkBuddy->getBuddySharedPtr(); + + if (deviceUSRPShared == nullptr) + { + qCritical("USRPOutput::openDevice: the sink buddy shared pointer is null"); + return false; + } + m_deviceShared.m_deviceParams = deviceUSRPShared->m_deviceParams; DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams; // get device parameters @@ -144,7 +189,7 @@ bool USRPOutput::openDevice() DeviceAPI *buddy = m_deviceAPI->getSinkBuddies()[i]; DeviceUSRPShared *buddyShared = (DeviceUSRPShared *) buddy->getBuddySharedPtr(); - if (buddyShared->m_channel == requestedChannel) + if (buddyShared && (buddyShared->m_channel == requestedChannel)) { qCritical("USRPOutput::openDevice: cannot open busy channel %u", requestedChannel); return false; @@ -162,6 +207,13 @@ bool USRPOutput::openDevice() DeviceAPI *sourceBuddy = m_deviceAPI->getSourceBuddies()[0]; //m_deviceShared = *((DeviceUSRPShared *) sourceBuddy->getBuddySharedPtr()); // copy parameters DeviceUSRPShared *deviceUSRPShared = (DeviceUSRPShared*) sourceBuddy->getBuddySharedPtr(); + + if (deviceUSRPShared == nullptr) + { + qCritical("USRPOutput::openDevice: the source buddy shared pointer is null"); + return false; + } + m_deviceShared.m_deviceParams = deviceUSRPShared->m_deviceParams; if (m_deviceShared.m_deviceParams == 0) @@ -206,11 +258,33 @@ bool USRPOutput::openDevice() m_deviceShared.m_channel = requestedChannel; // acknowledge the requested channel } - m_deviceAPI->setBuddySharedPtr(&m_deviceShared); // propagate common parameters to API - return ret; } +// Get device parameters shared with buddies, or nullptr if there are no buddies. Called from GUI thread. +DeviceUSRPParams *USRPOutput::getBuddyDeviceParams() const +{ + for (const auto& buddy : m_deviceAPI->getSourceBuddies()) + { + DeviceUSRPShared *buddyShared = (DeviceUSRPShared *) buddy->getBuddySharedPtr(); + + if (buddyShared && buddyShared->m_deviceParams) { + return buddyShared->m_deviceParams; + } + } + + for (const auto& buddy : m_deviceAPI->getSinkBuddies()) + { + DeviceUSRPShared *buddyShared = (DeviceUSRPShared *) buddy->getBuddySharedPtr(); + + if (buddyShared && buddyShared->m_deviceParams) { + return buddyShared->m_deviceParams; + } + } + + return nullptr; +} + void USRPOutput::suspendRxBuddies() { const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); @@ -222,6 +296,13 @@ void USRPOutput::suspendRxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSource)->getBuddySharedPtr(); + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + if (buddySharedPtr->m_thread && buddySharedPtr->m_thread->isRunning()) { buddySharedPtr->m_thread->stopWork(); @@ -245,6 +326,13 @@ void USRPOutput::suspendTxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSink)->getBuddySharedPtr(); + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + if (buddySharedPtr->m_thread && buddySharedPtr->m_thread->isRunning()) { buddySharedPtr->m_thread->stopWork(); @@ -268,7 +356,14 @@ void USRPOutput::resumeRxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSource)->getBuddySharedPtr(); - if (buddySharedPtr->m_threadWasRunning) { + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + + if (buddySharedPtr->m_threadWasRunning && buddySharedPtr->m_thread) { buddySharedPtr->m_thread->startWork(); } } @@ -285,7 +380,14 @@ void USRPOutput::resumeTxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSink)->getBuddySharedPtr(); - if (buddySharedPtr->m_threadWasRunning) { + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + + if (buddySharedPtr->m_threadWasRunning && buddySharedPtr->m_thread) { buddySharedPtr->m_thread->startWork(); } } @@ -293,38 +395,50 @@ void USRPOutput::resumeTxBuddies() void USRPOutput::closeDevice() { - if (m_deviceShared.m_deviceParams->getDevice() == nullptr) { // was never open + if (m_running) { stop(); } + + m_deviceShared.m_channel = -1; // effectively release the channel for the possible buddies + + if (m_deviceShared.m_deviceParams == nullptr) { // was never created return; } - if (m_running) stop(); - // No buddies so effectively close the device + // (params are deleted even if the device failed to open, to avoid a leak) if ((m_deviceAPI->getSourceBuddies().size() == 0) && (m_deviceAPI->getSinkBuddies().size() == 0)) { m_deviceShared.m_deviceParams->close(); delete m_deviceShared.m_deviceParams; - m_deviceShared.m_deviceParams = 0; + m_deviceShared.m_deviceParams = nullptr; } - - m_deviceShared.m_channel = -1; // effectively release the channel for the possible buddies } -bool USRPOutput::acquireChannel() +bool USRPOutput::acquireChannel(const USRPOutputSettings& settings) { + bool success = true; + + // Hold buddies and device mutexes across suspend...resume, so buddies doing the same at the same time + // can't interleave (which could leave a buddy suspended), and buddy lists can't be changed while we use them + QMutexLocker buddiesLocker(&DeviceAPI::getBuddiesMutex()); + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + suspendRxBuddies(); suspendTxBuddies(); if (m_streamId == nullptr) { + // Prevent buddies from configuring the device while we set up the stream + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + try { uhd::usrp::multi_usrp::sptr usrp = m_deviceShared.m_deviceParams->getDevice(); // Apply settings before creating stream // However, don't set LPF to <10MHz at this stage, otherwise there is massive TX LO leakage - applySettings(m_settings, QList(), true, true); + // Actual settings are reported back to handleMessage, which forwards them to buddies and GUI + USRPOutputThread::applyDeviceSettings(m_deviceShared.m_deviceParams, m_deviceShared.m_channel, settings, QList(), true, true, false, getInputMessageQueue()); usrp->set_tx_bandwidth(56000000, m_deviceShared.m_channel); // set up the stream @@ -341,28 +455,37 @@ bool USRPOutput::acquireChannel() // Match our transmit buffer size to what UHD uses m_bufSamples = m_streamId->get_max_num_samps(); - // Wait for reference and LO to lock - DeviceUSRP::waitForLock(usrp, m_settings.m_clockSource, m_deviceShared.m_channel); + // Wait for reference and LO to lock. Use actual clock source, in case requested clock wasn't detected + DeviceUSRP::waitForLock(usrp, QString::fromStdString(usrp->get_clock_source(0)), m_deviceShared.m_channel, false); // Now we can set desired bandwidth - usrp->set_tx_bandwidth(m_settings.m_lpfBW, m_deviceShared.m_channel); + usrp->set_tx_bandwidth(settings.m_lpfBW, m_deviceShared.m_channel); } catch (std::exception& e) { - qDebug() << "USRPOutput::acquireChannel: exception: " << e.what(); + qCritical() << "USRPOutput::acquireChannel: exception: " << e.what(); } + + // Can't run without a stream + success = m_streamId != nullptr; } resumeTxBuddies(); resumeRxBuddies(); - m_channelAcquired = true; + m_channelAcquired = success; - return true; + return success; } void USRPOutput::releaseChannel() { + // Hold buddies and device mutexes across suspend...resume, so buddies doing the same at the same time + // can't interleave (which could leave a buddy suspended), and buddy lists can't be changed while we use them. + // This also means the stream is destroyed with the device mutex held. + QMutexLocker buddiesLocker(&DeviceAPI::getBuddiesMutex()); + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + suspendRxBuddies(); suspendTxBuddies(); @@ -377,9 +500,10 @@ void USRPOutput::releaseChannel() void USRPOutput::init() { - applySettings(m_settings, QList(), false, true); + applySettings(m_settings, QList(), true); } +// Called from the device engine thread bool USRPOutput::start() { QMutexLocker mutexLocker(&m_mutex); @@ -388,26 +512,66 @@ bool USRPOutput::start() return true; } - if (!m_deviceShared.m_deviceParams->getDevice()) { + if (!m_deviceShared.m_deviceParams || !m_deviceShared.m_deviceParams->getDevice()) { return false; } - if (!acquireChannel()) { + // Create thread before acquiring the channel, so settings changed while the channel is + // being acquired are queued to it, to be applied once start() has returned. + USRPOutputThread *thread = new USRPOutputThread(m_deviceShared.m_deviceParams, m_deviceShared.m_channel, + &m_sampleSourceFifo, getInputMessageQueue()); + // Publish the thread and take a copy of the settings atomically with respect to applySettings, so + // settings changed in the GUI thread while the channel is being acquired are either in the copy or + // queued to the thread, to be applied once start() has returned + USRPOutputSettings settings; + { + QMutexLocker settingsLocker(&m_settingsMutex); + QMutexLocker threadLocker(&m_threadMutex); + m_usrpOutputThread = thread; + settings = m_settings; + } + + if (!acquireChannel(settings)) + { + { + QMutexLocker threadLocker(&m_threadMutex); + m_usrpOutputThread = nullptr; + } + delete thread; return false; } - m_usrpOutputThread = new USRPOutputThread(m_streamId, m_bufSamples, &m_sampleSourceFifo); - qDebug("USRPOutput::start: thread created"); + { + QMutexLocker threadLocker(&m_threadMutex); + thread->setStream(m_streamId, m_bufSamples); + } + thread->setLog2Interpolation(settings.m_log2SoftInterp); + + // Size FIFO for the sample rate, in case a resize was lost when stopping. + // This is safe here, as we are in the device engine thread (the FIFO writer) and streaming (the reader) hasn't started. + // Any resize requested since the thread was published is queued to it, to be performed after this. + { + unsigned int fifoRate = (unsigned int) settings.m_devSampleRate / (1<m_mutex); + thread->startWork(); + m_deviceShared.m_thread = thread; + } - m_usrpOutputThread->setLog2Interpolation(m_settings.m_log2SoftInterp); - m_usrpOutputThread->startWork(); + qDebug("USRPOutput::start: thread started"); - m_deviceShared.m_thread = m_usrpOutputThread; m_running = true; return true; } +// Usually called from the device engine thread, but can be called from the GUI thread in the destructor void USRPOutput::stop() { QMutexLocker mutexLocker(&m_mutex); @@ -419,14 +583,45 @@ void USRPOutput::stop() qDebug("USRPOutput::stop"); m_running = false; - if (m_usrpOutputThread) + USRPOutputThread *thread; { - m_usrpOutputThread->stopWork(); - delete m_usrpOutputThread; - m_usrpOutputThread = nullptr; + QMutexLocker threadLocker(&m_threadMutex); + thread = m_usrpOutputThread; } - m_deviceShared.m_thread = 0; + if (thread) + { + // Wait for any settings being applied in the device engine thread to complete and prevent any more + thread->detach(); + + { + // Clear before deleting the thread, so buddies can't access it while it's being destroyed. + // Device mutex prevents buddies accessing it while we clear it and stop it + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + m_deviceShared.m_thread = nullptr; + thread->stopWork(); + } + + // Only clear after streaming has stopped, so resizeSampleSourceFifo doesn't resize the FIFO + // directly while it is being read. A resize queued to the detached thread is lost, but the + // FIFO is resized when next started. + { + QMutexLocker threadLocker(&m_threadMutex); + m_usrpOutputThread = nullptr; + } + + // Release stream, so it's destroyed before the device, even if the thread is deleted later + thread->releaseStream(); + + QThread *ownerThread = thread->thread(); + if (!ownerThread || (ownerThread == QThread::currentThread()) || ownerThread->isFinished()) { + delete thread; + } else { + // Called from another thread while the device engine thread is still running, which may have + // a pending call to handleInputMessages, so delete it in the device engine thread + thread->deleteLater(); + } + } releaseChannel(); } @@ -440,10 +635,14 @@ bool USRPOutput::deserialize(const QByteArray& data) { bool success = true; - if (!m_settings.deserialize(data)) { - m_settings.resetToDefaults(); - success = false; + QMutexLocker settingsLocker(&m_settingsMutex); + + if (!m_settings.deserialize(data)) + { + m_settings.resetToDefaults(); + success = false; + } } MsgConfigureUSRP* message = MsgConfigureUSRP::create(m_settings, QList(), true); @@ -496,6 +695,13 @@ int USRPOutput::getChannelIndex() void USRPOutput::getLORange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_loRangeTx.start(); @@ -511,6 +717,13 @@ void USRPOutput::getLORange(float& minF, float& maxF) const void USRPOutput::getSRRange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_srRangeTx.start(); @@ -518,7 +731,7 @@ void USRPOutput::getSRRange(float& minF, float& maxF) const } catch (std::exception& e) { - qDebug() << "USRPOutput::getLORange: exception: " << e.what(); + qDebug() << "USRPOutput::getSRRange: exception: " << e.what(); minF = 0.0f; maxF = 0.0f; } @@ -526,6 +739,13 @@ void USRPOutput::getSRRange(float& minF, float& maxF) const void USRPOutput::getLPRange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_lpfRangeTx.start(); @@ -533,7 +753,7 @@ void USRPOutput::getLPRange(float& minF, float& maxF) const } catch (std::exception& e) { - qDebug() << "USRPOutput::getLORange: exception: " << e.what(); + qDebug() << "USRPOutput::getLPRange: exception: " << e.what(); minF = 0.0f; maxF = 0.0f; } @@ -541,6 +761,13 @@ void USRPOutput::getLPRange(float& minF, float& maxF) const void USRPOutput::getGainRange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_gainRangeTx.start(); @@ -548,7 +775,7 @@ void USRPOutput::getGainRange(float& minF, float& maxF) const } catch (std::exception& e) { - qDebug() << "USRPOutput::getLORange: exception: " << e.what(); + qDebug() << "USRPOutput::getGainRange: exception: " << e.what(); minF = 0.0f; maxF = 0.0f; } @@ -556,12 +783,12 @@ void USRPOutput::getGainRange(float& minF, float& maxF) const QStringList USRPOutput::getTxAntennas() const { - return m_deviceShared.m_deviceParams->m_txAntennas; + return m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->m_txAntennas : QStringList(); } QStringList USRPOutput::getClockSources() const { - return m_deviceShared.m_deviceParams->m_clockSources; + return m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->m_clockSources : QStringList(); } bool USRPOutput::handleMessage(const Message& message) @@ -571,7 +798,7 @@ bool USRPOutput::handleMessage(const Message& message) MsgConfigureUSRP& conf = (MsgConfigureUSRP&) message; qDebug() << "USRPOutput::handleMessage: MsgConfigureUSRP"; - if (!applySettings(conf.getSettings(), conf.getSettingsKeys(), false, conf.getForce())) { + if (!applySettings(conf.getSettings(), conf.getSettingsKeys(), conf.getForce())) { qDebug("USRPOutput::handleMessage config error"); } @@ -599,13 +826,58 @@ bool USRPOutput::handleMessage(const Message& message) return true; } + else if (DeviceUSRPShared::MsgReportDeviceSettings::match(message)) + { + // Settings actually set on the device, as read back in the device engine thread + DeviceUSRPShared::MsgReportDeviceSettings& report = (DeviceUSRPShared::MsgReportDeviceSettings&) message; + QMutexLocker settingsLocker(&m_settingsMutex); + + if (report.getClockSourceValid()) + { + m_settings.m_clockSource = report.getClockSource(); + forwardClockSource(); + } + + if (report.getSampleRateValid()) + { + int devSampleRate = (int) std::round(report.getSampleRate()); + int masterClockRate = (int) std::round(report.getMasterClockRate()); + qDebug() << "USRPOutput::handleMessage: MsgReportDeviceSettings: devSampleRate:" << devSampleRate << "masterClockRate:" << masterClockRate; + + if ((devSampleRate != m_settings.m_devSampleRate) || (masterClockRate != m_settings.m_masterClockRate)) + { + if (devSampleRate != m_settings.m_devSampleRate) { + resizeSampleSourceFifo(devSampleRate, m_settings.m_log2SoftInterp); + } + + m_settings.m_devSampleRate = devSampleRate; + m_settings.m_masterClockRate = masterClockRate; + + if (!report.getForwardToBuddies()) { + notifySampleRateChange(); + } + } + + // Result of our own settings change, so the device has changed and buddies need to be informed, + // even if the rate is as we requested, as buddies won't have been informed when we weren't running + if (report.getForwardToBuddies()) { + forwardChangeAllDSP(); + } + } + + return true; + } else if (DeviceUSRPShared::MsgReportBuddyChange::match(message)) { DeviceUSRPShared::MsgReportBuddyChange& report = (DeviceUSRPShared::MsgReportBuddyChange&) message; + QMutexLocker settingsLocker(&m_settingsMutex); + uhd::usrp::multi_usrp::sptr device = m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->getDevice() : nullptr; + int devSampleRate = m_settings.m_devSampleRate; - if (!report.getRxElseTx()) + // Tx buddy changed settings. Only copy them if the buddy's channel shares our LO (E.g. B210), + // not if it has an independent front-end (E.g. X310 with two daughterboards) + if (!report.getRxElseTx() && DeviceUSRP::channelsShareLO(device, false, report.getChannel(), m_deviceShared.m_channel)) { - // Tx buddy changed settings, we need to copy m_settings.m_devSampleRate = report.getDevSampleRate(); m_settings.m_centerFrequency = report.getCenterFrequency(); m_settings.m_loOffset = report.getLOOffset(); @@ -617,23 +889,28 @@ bool USRPOutput::handleMessage(const Message& message) qDebug() << "USRPOutput::handleMessage MsgReportBuddyChange"; qDebug() << "m_masterClockRate " << m_settings.m_masterClockRate; - DSPSignalNotification *notif = new DSPSignalNotification( - m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); + if (m_settings.m_devSampleRate != devSampleRate) { + resizeSampleSourceFifo(m_settings.m_devSampleRate, m_settings.m_log2SoftInterp); + } - if (getMessageQueueToGUI()) + // A buddy changing the master clock rate may have changed our sample rate, so have the device + // engine thread read back the actual rate, which will be reported via MsgReportDeviceSettings { - DeviceUSRPShared::MsgReportBuddyChange *reportToGUI = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false); - getMessageQueueToGUI()->push(reportToGUI); + QMutexLocker threadLocker(&m_threadMutex); + + if (m_usrpOutputThread) { + m_usrpOutputThread->getInputMessageQueue()->push(DeviceUSRPShared::MsgReadDeviceSampleRate::create()); + } } + notifySampleRateChange(); + return true; } else if (DeviceUSRPShared::MsgReportClockSourceChange::match(message)) { DeviceUSRPShared::MsgReportClockSourceChange& report = (DeviceUSRPShared::MsgReportClockSourceChange&) message; + QMutexLocker settingsLocker(&m_settingsMutex); m_settings.m_clockSource = report.getClockSource(); @@ -646,11 +923,29 @@ bool USRPOutput::handleMessage(const Message& message) return true; } + else if (MsgGetDeviceInfo::match(message)) + { + // Reading a sensor is quick, so do it here, but don't block the GUI thread + // if the device is being configured in a device engine thread + DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams; + + if (deviceParams && deviceParams->getDevice() && deviceParams->m_mutex.tryLock()) + { + double temperature = 0.0; + bool temperatureValid = DeviceUSRP::getTemperature(deviceParams->getDevice(), false, m_deviceShared.m_channel, temperature); + deviceParams->m_mutex.unlock(); + forwardDeviceInfo(temperatureValid, temperature); + } + + return true; + } else if (MsgGetStreamInfo::match(message)) { if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) { - if ((m_streamId != nullptr) && m_channelAcquired) + QMutexLocker threadLocker(&m_threadMutex); + + if (m_usrpOutputThread) { bool active; quint32 underflows; @@ -680,328 +975,277 @@ bool USRPOutput::handleMessage(const Message& message) } } -bool USRPOutput::applySettings(const USRPOutputSettings& settings, const QList& settingsKeys, bool preGetStream, bool force) +void USRPOutput::resizeSampleSourceFifo(int devSampleRate, unsigned int log2Interp) { - qDebug() << "USRPOutput::applySettings: preGetStream:" << preGetStream << " force:" << force << settings.getDebugString(settingsKeys, force); - bool forwardChangeOwnDSP = false; - bool forwardChangeTxDSP = false; - bool forwardChangeAllDSP = false; - bool forwardClockSource = false; - bool checkRates = false; +#if defined(_MSC_VER) + unsigned int fifoRate = (unsigned int) devSampleRate / (1<getInputMessageQueue()->push(DeviceUSRPShared::MsgResizeSampleFifo::create(size)); + } + else + { + m_sampleSourceFifo.resize(size); + } - // apply settings + qDebug("USRPOutput::resizeSampleSourceFifo: rate %u size %u", fifoRate, size); +} - if (settingsKeys.contains("clockSource") || force) - { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - try - { - m_deviceShared.m_deviceParams->getDevice()->set_clock_source(settings.m_clockSource.toStdString(), 0); - forwardClockSource = true; - qDebug() << "USRPOutput::applySettings: clock set to" << settings.m_clockSource; - } - catch (std::exception &e) - { - // An exception will be thrown if the clock is not detected - // however, get_clock_source called below will still say the clock has is set - qCritical() << "USRPOutput::applySettings: could not set clock " << settings.m_clockSource; - // So, default back to internal - m_deviceShared.m_deviceParams->getDevice()->set_clock_source("internal", 0); - // notify GUI that source couldn't be set - forwardClockSource = true; - } - } - else - { - qCritical() << "USRPOutput::applySettings: could not set clock to " << settings.m_clockSource; - } - } +bool USRPOutput::applySettings(const USRPOutputSettings& settings, const QList& settingsKeys, bool force) +{ + QMutexLocker settingsLocker(&m_settingsMutex); + qDebug() << "USRPOutput::applySettings: force:" << force << settings.getDebugString(settingsKeys, force); + bool changeOwnDSP = false; + bool changeTxDSP = false; + bool changeAllDSP = false; - if (settingsKeys.contains("devSampleRate") || force) - { - forwardChangeAllDSP = true; + if (settingsKeys.contains("devSampleRate") || force) { + changeAllDSP = true; + } - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - m_deviceShared.m_deviceParams->getDevice()->set_tx_rate(settings.m_devSampleRate, m_deviceShared.m_channel); - qDebug("USRPOutput::applySettings: set sample rate set to %d", settings.m_devSampleRate); - checkRates = true; - } - } + if (settingsKeys.contains("centerFrequency") + || settingsKeys.contains("loOffset") + || settingsKeys.contains("transverterMode") + || settingsKeys.contains("transverterDeltaFrequency") + || force) + { + changeTxDSP = true; - if (settingsKeys.contains("centerFrequency") - || settingsKeys.contains("loOffset") - || settingsKeys.contains("transverterMode") - || settingsKeys.contains("transverterDeltaFrequency") - || force) - { - forwardChangeTxDSP = true; + qint64 deviceCenterFrequency = settings.m_centerFrequency; + deviceCenterFrequency -= settings.m_transverterMode ? settings.m_transverterDeltaFrequency : 0; + deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; + m_deviceShared.m_centerFrequency = deviceCenterFrequency; // for buddies + } - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - if (settings.m_loOffset != 0) - { - uhd::tune_request_t tune_request(deviceCenterFrequency, settings.m_loOffset); - m_deviceShared.m_deviceParams->getDevice()->set_tx_freq(tune_request, m_deviceShared.m_channel); - } - else - { - uhd::tune_request_t tune_request(deviceCenterFrequency); - m_deviceShared.m_deviceParams->getDevice()->set_tx_freq(tune_request, m_deviceShared.m_channel); - } - m_deviceShared.m_centerFrequency = deviceCenterFrequency; // for buddies - qDebug("USRPOutput::applySettings: frequency set to %lld with LO offset %d", deviceCenterFrequency, settings.m_loOffset); - } - } + if (settingsKeys.contains("devSampleRate") + || settingsKeys.contains("log2SoftInterp") || force) + { + resizeSampleSourceFifo(settings.m_devSampleRate, settings.m_log2SoftInterp); + } - if (settingsKeys.contains("devSampleRate") - || settingsKeys.contains("log2SoftInterp") || force) - { -#if defined(_MSC_VER) - unsigned int fifoRate = (unsigned int) settings.m_devSampleRate / (1<getDevice() && (m_channelAcquired || preGetStream)) - { - m_deviceShared.m_deviceParams->getDevice()->set_tx_gain(settings.m_gain, m_deviceShared.m_channel); - qDebug() << "USRPOutput::applySettings: Gain set to " << settings.m_gain; - } - } + // Applying settings to the device can take a long time (E.g. sample rate, clock source and bandwidth), + // so when running, they are applied in the device engine thread, rather than blocking the GUI thread. + // Values actually set are reported back via DeviceUSRPShared::MsgReportDeviceSettings. + // When not running, they are applied when the channel is acquired in start(), except for GPIO, + // which doesn't require the channel to be acquired. + bool threadRunning = false; + { + QMutexLocker threadLocker(&m_threadMutex); - if (settingsKeys.contains("lpfBW") || force) + if (m_usrpOutputThread) { - // Don't set bandwidth before get_tx_stream (See above) - if (m_deviceShared.m_deviceParams->getDevice() && m_channelAcquired) - { - m_deviceShared.m_deviceParams->getDevice()->set_tx_bandwidth(settings.m_lpfBW, m_deviceShared.m_channel); - qDebug("USRPOutput::applySettings: LPF BW: %f for channel %d", settings.m_lpfBW, m_deviceShared.m_channel); - } + m_usrpOutputThread->getInputMessageQueue()->push(MsgConfigureUSRP::create(settings, settingsKeys, force)); + threadRunning = true; } + } - if (settingsKeys.contains("log2SoftInterp") || force) + if (!threadRunning && m_deviceShared.m_deviceParams && (settingsKeys.contains("gpioDir") || settingsKeys.contains("gpioPins") || force)) + { + // Don't block the GUI thread if a buddy is configuring the device (E.g. waiting for LO lock). Retry later instead. + if (m_deviceShared.m_deviceParams->m_mutex.tryLock()) { - forwardChangeOwnDSP = true; - m_deviceShared.m_log2Soft = settings.m_log2SoftInterp; // for buddies - - if (m_usrpOutputThread) - { - m_usrpOutputThread->setLog2Interpolation(settings.m_log2SoftInterp); - qDebug() << "USRPOutput::applySettings: set soft interpolation to " << (1<m_mutex.unlock(); } - - if (settingsKeys.contains("antennaPath") || force) + else { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - m_deviceShared.m_deviceParams->getDevice()->set_tx_antenna(settings.m_antennaPath.toStdString(), m_deviceShared.m_channel); - qDebug("USRPOutput::applySettings: set antenna path to %s on channel %d", qPrintable(settings.m_antennaPath), m_deviceShared.m_channel); - } + QTimer::singleShot(100, this, [this]() { + m_inputMessageQueue.push(MsgConfigureUSRP::create(m_settings, QList{"gpioDir", "gpioPins"}, false)); + }); } + } - const std::string gpioBank = "FP0"; // Front Panel GPIO + if (settingsKeys.contains("useReverseAPI")) + { + bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) || + settingsKeys.contains("reverseAPIAddress") || + settingsKeys.contains("reverseAPIPort") || + settingsKeys.contains("reverseAPIDeviceIndex"); + webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); + } - if (settingsKeys.contains("gpioDir") || force) - { - if (m_deviceShared.m_deviceParams->getDevice()) - { - std::vector banks = m_deviceShared.m_deviceParams->getDevice()->get_gpio_banks(0); - for (const auto& bank : banks) - { - if (!gpioBank.compare(bank)) - { - m_deviceShared.m_deviceParams->getDevice()->set_gpio_attr(gpioBank, "CTRL", ~settings.m_gpioDir, 0xff); // 0 for GPIO, 1 for ATR - m_deviceShared.m_deviceParams->getDevice()->set_gpio_attr(gpioBank, "DDR", settings.m_gpioDir, 0xff); // 0 for input, 1 for output - qDebug() << "USRPOutput::applySettings: set GPIO dir to" << settings.m_gpioDir; - } - } - } - } + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } - if (settingsKeys.contains("gpioPins") || force) - { - if (m_deviceShared.m_deviceParams->getDevice()) - { - std::vector banks = m_deviceShared.m_deviceParams->getDevice()->get_gpio_banks(0); - for (const auto& bank : banks) - { - if (!gpioBank.compare(bank)) - { - m_deviceShared.m_deviceParams->getDevice()->set_gpio_attr(gpioBank, "OUT", settings.m_gpioPins, 0xff); - qDebug() << "USRPOutput::applySettings: set GPIO pins to" << settings.m_gpioPins; - } - } - } - } + // forward changes to buddies or oneself + // If the device coerces the sample rate, this will be sent again with the actual rate, once reported - if (settingsKeys.contains("useReverseAPI")) - { - bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) || - settingsKeys.contains("reverseAPIAddress") || - settingsKeys.contains("reverseAPIPort") || - settingsKeys.contains("reverseAPIDeviceIndex"); - webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); + // When not running, the device hasn't been changed, so buddies don't need to be informed. + // They will be informed of the actual settings when we are started. + if (!threadRunning) + { + if (changeAllDSP || changeTxDSP || changeOwnDSP) { + forwardChangeOwnDSP(); } + } + else if (changeAllDSP) + { + forwardChangeAllDSP(); + } + else if (changeTxDSP) + { + forwardChangeTxDSP(); + } + else if (changeOwnDSP) + { + forwardChangeOwnDSP(); + } - if (force) { - m_settings = settings; - } else { - m_settings.applySettings(settingsKeys, settings); - } + return true; +} - if (checkRates) - { - // Check if requested rate could actually be met and what master clock rate we ended up with - double actualSampleRate = m_deviceShared.m_deviceParams->getDevice()->get_tx_rate(m_deviceShared.m_channel); - qDebug("USRPOutput::applySettings: actual sample rate %f", actualSampleRate); - double masterClockRate = m_deviceShared.m_deviceParams->getDevice()->get_master_clock_rate(); - qDebug("USRPOutput::applySettings: master_clock_rate %f", masterClockRate); - m_settings.m_devSampleRate = actualSampleRate; - m_settings.m_masterClockRate = masterClockRate; - } +// Forward sample rate and frequency to self, all buddies and GUI +void USRPOutput::forwardChangeAllDSP() +{ + qDebug("USRPOutput::forwardChangeAllDSP"); - // forward changes to buddies or oneself + // send to self first + forwardChangeOwnDSP(); - if (forwardChangeAllDSP) - { - qDebug("USRPOutput::applySettings: forward change to all buddies"); + // send to sink buddies + const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); + std::vector::const_iterator itSink = sinkBuddies.begin(); - // send to self first - DSPSignalNotification *notif = new DSPSignalNotification( - m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); + for (; itSink != sinkBuddies.end(); ++itSink) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false, m_deviceShared.m_channel); + (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); + } - // send to sink buddies - const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); - std::vector::const_iterator itSink = sinkBuddies.begin(); + // send to source buddies + const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); + std::vector::const_iterator itSource = sourceBuddies.begin(); - for (; itSink != sinkBuddies.end(); ++itSink) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false); - (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); - } + for (; itSource != sourceBuddies.end(); ++itSource) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false, m_deviceShared.m_channel); + (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); + } - // send to source buddies - const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); - std::vector::const_iterator itSource = sourceBuddies.begin(); + // send to GUI so it can see master clock rate and if actual rate differs + if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false, m_deviceShared.m_channel); + m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); + } +} - for (; itSource != sourceBuddies.end(); ++itSource) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false); - (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); - } +// Forward sample rate and frequency to self and Tx buddies +void USRPOutput::forwardChangeTxDSP() +{ + qDebug("USRPOutput::forwardChangeTxDSP"); - // send to GUI so it can see master clock rate and if actual rate differs - if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false); - m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); - } - } - else if (forwardChangeTxDSP) - { - qDebug("USRPOutput::applySettings: forward change to Tx buddies"); + // send to self first + forwardChangeOwnDSP(); - int sampleRate = m_settings.m_devSampleRate/(1<& sinkBuddies = m_deviceAPI->getSinkBuddies(); + std::vector::const_iterator itSink = sinkBuddies.begin(); - // send to self first - DSPSignalNotification *notif = new DSPSignalNotification(sampleRate, m_settings.m_centerFrequency); - m_deviceAPI->getDeviceEngineInputMessageQueue()->push(notif); + for (; itSink != sinkBuddies.end(); ++itSink) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false, m_deviceShared.m_channel); + (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); + } +} - // send to sink buddies - const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); - std::vector::const_iterator itSink = sinkBuddies.begin(); +// Forward sample rate and frequency to self only +void USRPOutput::forwardChangeOwnDSP() +{ + int sampleRate = m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); +} - for (; itSink != sinkBuddies.end(); ++itSink) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false); - (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); - } - } - else if (forwardChangeOwnDSP) - { - qDebug("USRPOutput::applySettings: forward change to self only"); +// Forward sample rate and frequency to self and GUI, but not buddies (E.g. when changed by a buddy) +void USRPOutput::notifySampleRateChange() +{ + forwardChangeOwnDSP(); - int sampleRate = m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); - } + if (getMessageQueueToGUI()) + { + DeviceUSRPShared::MsgReportBuddyChange *reportToGUI = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, false); + getMessageQueueToGUI()->push(reportToGUI); + } +} - if (forwardClockSource) - { - // get what clock is actually set, in case requested clock couldn't be set - if (m_deviceShared.m_deviceParams->getDevice()) - { - try - { - m_settings.m_clockSource = QString::fromStdString(m_deviceShared.m_deviceParams->getDevice()->get_clock_source(0)); - qDebug() << "USRPOutput::applySettings: clock source is " << m_settings.m_clockSource; - } - catch (std::exception &e) - { - qDebug() << "USRPOutput::applySettings: could not get clock source"; - } - } +// Forward clock source to GUI and all buddies +void USRPOutput::forwardClockSource() +{ + // send to GUI in case requested clock isn't detected + if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) + { + DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( + m_settings.m_clockSource); + m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); + } - // send to GUI in case requested clock isn't detected - if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) - { - DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( - m_settings.m_clockSource); - m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); - } + // send to source buddies + const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); + std::vector::const_iterator itSource = sourceBuddies.begin(); - // send to source buddies - const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); - std::vector::const_iterator itSource = sourceBuddies.begin(); + for (; itSource != sourceBuddies.end(); ++itSource) + { + DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( + m_settings.m_clockSource); + (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); + } - for (; itSource != sourceBuddies.end(); ++itSource) - { - DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( - m_settings.m_clockSource); - (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); - } + // send to sink buddies + const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); + std::vector::const_iterator itSink = sinkBuddies.begin(); - // send to sink buddies - const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); - std::vector::const_iterator itSink = sinkBuddies.begin(); + for (; itSink != sinkBuddies.end(); ++itSink) + { + DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( + m_settings.m_clockSource); + (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); + } +} - for (; itSink != sinkBuddies.end(); ++itSink) - { - DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( - m_settings.m_clockSource); - (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); - } - } +// Forward device info to our GUI and the GUIs of all buddies +void USRPOutput::forwardDeviceInfo(bool temperatureValid, float temperature) +{ + if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) { + m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); + } - return true; + for (const auto& buddy : m_deviceAPI->getSourceBuddies()) + { + if (buddy->getSamplingDeviceGUIMessageQueue()) { + buddy->getSamplingDeviceGUIMessageQueue()->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); + } } - catch (std::exception &e) + + for (const auto& buddy : m_deviceAPI->getSinkBuddies()) { - qDebug() << "USRPOutput::applySettings: exception: " << e.what(); - return false; + if (buddy->getSamplingDeviceGUIMessageQueue()) { + buddy->getSamplingDeviceGUIMessageQueue()->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); + } } } @@ -1066,7 +1310,7 @@ void USRPOutput::webapiUpdateDeviceSettings( settings.m_gain = response.getUsrpOutputSettings()->getGain(); } if (deviceSettingsKeys.contains("log2SoftInterp")) { - settings.m_log2SoftInterp = response.getUsrpOutputSettings()->getLog2SoftInterp(); + settings.m_log2SoftInterp = qBound(0, response.getUsrpOutputSettings()->getLog2SoftInterp(), 6); } if (deviceSettingsKeys.contains("lpfBW")) { settings.m_lpfBW = response.getUsrpOutputSettings()->getLpfBw(); @@ -1182,7 +1426,9 @@ void USRPOutput::webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response quint32 underflows = 0; quint32 droppedPackets = 0; - if ((m_streamId != nullptr) && (m_usrpOutputThread != nullptr) && m_channelAcquired) + QMutexLocker threadLocker(&m_threadMutex); + + if (m_usrpOutputThread) { m_usrpOutputThread->getStreamStatus(active, underflows, droppedPackets); success = true; diff --git a/plugins/samplesink/usrpoutput/usrpoutput.h b/plugins/samplesink/usrpoutput/usrpoutput.h index b541d9cf2..ef6b10703 100644 --- a/plugins/samplesink/usrpoutput/usrpoutput.h +++ b/plugins/samplesink/usrpoutput/usrpoutput.h @@ -25,6 +25,7 @@ #include #include +#include #include #include @@ -226,6 +227,8 @@ private: QMutex m_mutex; USRPOutputSettings m_settings; USRPOutputThread* m_usrpOutputThread; + QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread in start() + QMutex m_threadMutex; //!< Protects thread pointer, for access from threads other than the device engine thread QString m_deviceDescription; bool m_running; DeviceUSRPShared m_deviceShared; @@ -237,13 +240,21 @@ private: bool openDevice(); void closeDevice(); - bool acquireChannel(); + bool acquireChannel(const USRPOutputSettings& settings); void releaseChannel(); + DeviceUSRPParams *getBuddyDeviceParams() const; void suspendRxBuddies(); void resumeRxBuddies(); void suspendTxBuddies(); void resumeTxBuddies(); - bool applySettings(const USRPOutputSettings& settings, const QList& settingsKeys, bool preGetStream, bool force = false); + bool applySettings(const USRPOutputSettings& settings, const QList& settingsKeys, bool force = false); + void forwardChangeAllDSP(); + void forwardChangeTxDSP(); + void forwardChangeOwnDSP(); + void forwardClockSource(); + void notifySampleRateChange(); + void forwardDeviceInfo(bool temperatureValid, float temperature); + void resizeSampleSourceFifo(int devSampleRate, unsigned int log2Interp); void webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response); void webapiReverseSendSettings(const QList& deviceSettingsKeys, const USRPOutputSettings& settings, bool force); void webapiReverseSendStartStop(bool start); diff --git a/plugins/samplesink/usrpoutput/usrpoutputgui.cpp b/plugins/samplesink/usrpoutput/usrpoutputgui.cpp index ee611d08e..afbec6706 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputgui.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutputgui.cpp @@ -41,7 +41,7 @@ USRPOutputGUI::USRPOutputGUI(DeviceUISet *deviceUISet, QWidget* parent) : m_doApplySettings(true), m_forceSettings(true), m_statusCounter(0), - m_deviceStatusCounter(0) + m_deviceStatusCounter(10) // Get device info on first status update { m_deviceUISet = deviceUISet; setAttribute(Qt::WA_DeleteOnClose, true); @@ -54,9 +54,8 @@ USRPOutputGUI::USRPOutputGUI(DeviceUISet *deviceUISet, QWidget* parent) : float minF, maxF; - m_usrpOutput->getLORange(minF, maxF); ui->centerFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); - ui->centerFrequency->setValueRange(7, ((uint32_t) minF)/1000, ((uint32_t) maxF)/1000); // frequency dial is in kHz + updateFrequencyLimits(); // frequency dial is in kHz m_usrpOutput->getSRRange(minF, maxF); ui->sampleRate->setColorMapper(ColorMapper(ColorMapper::GrayGreenYellow)); @@ -186,10 +185,16 @@ bool USRPOutputGUI::handleMessage(const Message& message) { const USRPOutput::MsgConfigureUSRP& cfg = (USRPOutput::MsgConfigureUSRP&) message; - if (cfg.getForce()) { + if (cfg.getForce()) + { m_settings = cfg.getSettings(); - } else { + } + else + { + // Don't overwrite edits that haven't been sent yet + USRPOutputSettings pending = m_settings; m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); + m_settings.applySettings(m_settingsKeys, pending); } blockApplySettings(true); @@ -202,10 +207,18 @@ bool USRPOutputGUI::handleMessage(const Message& message) DeviceUSRPShared::MsgReportBuddyChange& report = (DeviceUSRPShared::MsgReportBuddyChange&) message; m_settings.m_masterClockRate = report.getMasterClockRate(); - if (!report.getRxElseTx()) { - m_settings.m_devSampleRate = report.getDevSampleRate(); - m_settings.m_centerFrequency = report.getCenterFrequency(); - m_settings.m_loOffset = report.getLOOffset(); + if (!report.getRxElseTx()) + { + // Don't overwrite edits that haven't been sent yet + if (!m_settingsKeys.contains("devSampleRate")) { + m_settings.m_devSampleRate = report.getDevSampleRate(); + } + if (!m_settingsKeys.contains("centerFrequency")) { + m_settings.m_centerFrequency = report.getCenterFrequency(); + } + if (!m_settingsKeys.contains("loOffset")) { + m_settings.m_loOffset = report.getLOOffset(); + } } blockApplySettings(true); @@ -214,6 +227,18 @@ bool USRPOutputGUI::handleMessage(const Message& message) return true; } + else if (DeviceUSRPShared::MsgReportDeviceInfo::match(message)) + { + DeviceUSRPShared::MsgReportDeviceInfo& report = (DeviceUSRPShared::MsgReportDeviceInfo&) message; + + if (report.getTemperatureValid()) { + ui->temperatureText->setText(tr("%1C").arg(QString::number(report.getTemperature(), 'f', 0))); + } + // Hide if device doesn't have a temperature sensor + ui->temperatureText->setVisible(report.getTemperatureValid()); + + return true; + } else if (DeviceUSRPShared::MsgReportClockSourceChange::match(message)) { DeviceUSRPShared::MsgReportClockSourceChange& report = (DeviceUSRPShared::MsgReportClockSourceChange&) message; @@ -229,6 +254,10 @@ bool USRPOutputGUI::handleMessage(const Message& message) { USRPOutput::MsgReportStreamInfo& report = (USRPOutput::MsgReportStreamInfo&) message; + // Accumulate statistics, as the counts reported can be reset while running + m_underrunStats.update(report.getSuccess(), report.getUnderrun()); + m_droppedStats.update(report.getSuccess(), report.getDroppedPackets()); + if (report.getSuccess()) { if (report.getActive()) { @@ -237,13 +266,13 @@ bool USRPOutputGUI::handleMessage(const Message& message) ui->streamStatusLabel->setStyleSheet("QLabel { background-color : blue; }"); } - if (report.getUnderrun() > 0) { + if (m_underrunStats.getCount() > 0) { ui->underrunLabel->setStyleSheet("QLabel { background-color : red; }"); } else { ui->underrunLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); } - if (report.getDroppedPackets() > 0) { + if (m_droppedStats.getCount() > 0) { ui->droppedLabel->setStyleSheet("QLabel { background-color : red; }"); } else { ui->droppedLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); @@ -254,6 +283,9 @@ bool USRPOutputGUI::handleMessage(const Message& message) ui->streamStatusLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); } + ui->underrunLabel->setToolTip(m_underrunStats.getToolTip("Red if underruns occurred. Cleared when restarting", "Underruns")); + ui->droppedLabel->setToolTip(m_droppedStats.getToolTip("Red if packets were dropped. Cleared when restarting", "Dropped packets")); + return true; } @@ -464,6 +496,7 @@ void USRPOutputGUI::updateStatus() } else { + // Only one GUI requests device info, which is then sent to all buddies if (m_deviceUISet->m_deviceAPI->isBuddyLeader()) { USRPOutput::MsgGetDeviceInfo* message = USRPOutput::MsgGetDeviceInfo::create(); diff --git a/plugins/samplesink/usrpoutput/usrpoutputgui.h b/plugins/samplesink/usrpoutput/usrpoutputgui.h index 727852918..6a20fc216 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputgui.h +++ b/plugins/samplesink/usrpoutput/usrpoutputgui.h @@ -24,6 +24,7 @@ #include #include "util/messagequeue.h" +#include "usrp/deviceusrpstreamstats.h" #include "usrpoutput.h" @@ -69,6 +70,8 @@ private: bool m_forceSettings; int m_statusCounter; int m_deviceStatusCounter; + DeviceUSRPStreamStats m_underrunStats; + DeviceUSRPStreamStats m_droppedStats; MessageQueue m_inputMessageQueue; void displaySettings(); diff --git a/plugins/samplesink/usrpoutput/usrpoutputgui.ui b/plugins/samplesink/usrpoutput/usrpoutputgui.ui index b2601cfa6..8e2910f6f 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputgui.ui +++ b/plugins/samplesink/usrpoutput/usrpoutputgui.ui @@ -647,6 +647,25 @@ + + + + + 24 + 0 + + + + Board temperature (degrees C) + + + - + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + diff --git a/plugins/samplesink/usrpoutput/usrpoutputsettings.cpp b/plugins/samplesink/usrpoutput/usrpoutputsettings.cpp index d28f468fa..449cc36bf 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputsettings.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutputsettings.cpp @@ -89,6 +89,7 @@ bool USRPOutputSettings::deserialize(const QByteArray& data) d.readS32(1, &m_devSampleRate, 5000000); d.readU32(2, &m_log2SoftInterp, 0); + m_log2SoftInterp = m_log2SoftInterp > 6 ? 6 : m_log2SoftInterp; d.readFloat(3, &m_lpfBW, 1.5e6); d.readU32(4, &m_gain, 4); d.readString(5, &m_antennaPath, "TX/RX"); diff --git a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp index ceac5c6f4..3a4de678f 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp @@ -18,28 +18,35 @@ #include #include +#include #include #include "dsp/samplesourcefifo.h" +#include "usrp/deviceusrpparam.h" #include "usrpoutputthread.h" +#include "usrpoutput.h" -USRPOutputThread::USRPOutputThread(uhd::tx_streamer::sptr stream, size_t bufSamples, SampleSourceFifo* sampleFifo, QObject* parent) : +USRPOutputThread::USRPOutputThread(DeviceUSRPParams *deviceParams, int channel, SampleSourceFifo* sampleFifo, + MessageQueue *reportQueue, QObject* parent) : QThread(parent), m_running(false), m_packets(0), m_underflows(0), m_droppedPackets(0), - m_stream(stream), - m_bufSamples(bufSamples), + m_buf(nullptr), + m_bufSamples(0), m_sampleFifo(sampleFifo), - m_log2Interp(0) + m_log2Interp(0), + m_deviceParams(deviceParams), + m_channel(channel), + m_reportQueue(reportQueue), + m_detached(false) { setObjectName("USRPOutput"); - // *2 as samples are I+Q - m_buf = new qint16[2 * bufSamples]; - std::fill(m_buf, m_buf + 2 * bufSamples, 0); + // Executes in the thread this object was created in (the device engine thread), not in run() + connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &USRPOutputThread::handleInputMessages); } USRPOutputThread::~USRPOutputThread() @@ -48,10 +55,33 @@ USRPOutputThread::~USRPOutputThread() delete[] m_buf; } +// Set stream once it has been created. Must be called before startWork() +void USRPOutputThread::setStream(uhd::tx_streamer::sptr stream, size_t bufSamples) +{ + m_stream = stream; + m_bufSamples = bufSamples; + delete[] m_buf; + // *2 as samples are I+Q + m_buf = new qint16[2 * bufSamples]; + std::fill(m_buf, m_buf + 2 * bufSamples, 0); +} + +// Release reference to stream, so it's destroyed before the device. Thread must be stopped. +void USRPOutputThread::releaseStream() +{ + m_stream = nullptr; +} + void USRPOutputThread::startWork() { if (m_running) return; // return if running already + if (!m_stream) + { + qWarning("USRPOutputThread::startWork: no stream"); + return; + } + // Reset stats m_packets = 0; m_underflows = 0; @@ -95,6 +125,9 @@ void USRPOutputThread::setLog2Interpolation(unsigned int log2_interp) void USRPOutputThread::run() { uhd::tx_metadata_t md; + + // Higher priority, so streaming isn't delayed by other threads + DeviceUSRP::setStreamingThreadPriority(); md.start_of_burst = false; md.end_of_burst = false; @@ -109,7 +142,7 @@ void USRPOutputThread::run() try { - const size_t sentSamples = m_stream->send(m_buf, writtenSamples, md); + const size_t sentSamples = m_stream->send(m_buf, writtenSamples, md, DeviceUSRP::m_streamTimeout); m_packets++; if (sentSamples != writtenSamples) { qDebug("USRPOutputThread::run sent %ld/%ld samples", sentSamples, writtenSamples); @@ -128,7 +161,9 @@ void USRPOutputThread::run() // Returns the number of samples written to buf, which may be less than len, when the TX buffer is not divisible by the interpolation factor. qint32 USRPOutputThread::callback(qint16* buf, qint32 len) { - const unsigned int interpolationFactor = 1U << m_log2Interp; + // Read once, as it can be changed from another thread, and the same value must be used for the whole buffer + const unsigned int log2Interp = m_log2Interp; + const unsigned int interpolationFactor = 1U << log2Interp; SampleVector& data = m_sampleFifo->getData(); unsigned int iPart1Begin, iPart1End, iPart2Begin, iPart2End; @@ -136,30 +171,30 @@ qint32 USRPOutputThread::callback(qint16* buf, qint32 len) m_sampleFifo->read(static_cast(len)/interpolationFactor, iPart1Begin, iPart1End, iPart2Begin, iPart2End); if (iPart1Begin != iPart1End) { - callbackPart(buf, data, iPart1Begin, iPart1End); + callbackPart(buf, data, iPart1Begin, iPart1End, log2Interp); } const unsigned int shift = (iPart1End - iPart1Begin) * interpolationFactor; if (iPart2Begin != iPart2End) { - callbackPart(buf + 2 * shift, data, iPart2Begin, iPart2End); + callbackPart(buf + 2 * shift, data, iPart2Begin, iPart2End, log2Interp); } return ((iPart1End - iPart1Begin) + (iPart2End - iPart2Begin)) * interpolationFactor; } -void USRPOutputThread::callbackPart(qint16* buf, SampleVector& data, unsigned int iBegin, unsigned int iEnd) +void USRPOutputThread::callbackPart(qint16* buf, SampleVector& data, unsigned int iBegin, unsigned int iEnd, unsigned int log2Interp) { SampleVector::iterator beginRead = data.begin() + iBegin; - const int len = 2 * (iEnd - iBegin) * (1 << m_log2Interp); + const int len = 2 * (iEnd - iBegin) * (1 << log2Interp); - if (m_log2Interp == 0) + if (log2Interp == 0) { m_interpolators.interpolate1(&beginRead, buf, len); } else { - switch (m_log2Interp) + switch (log2Interp) { case 1: m_interpolators.interpolate2_cen(&beginRead, buf, len); @@ -189,19 +224,347 @@ void USRPOutputThread::getStreamStatus(bool& active, quint32& underflows, quint3 { uhd::async_metadata_t md; - if (m_stream->recv_async_msg(md)) + if (!m_stream) { - if ((md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_UNDERFLOW) - || (md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_UNDERFLOW_IN_PACKET)) { - m_underflows++; - } - if ((md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_SEQ_ERROR) - || (md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_SEQ_ERROR_IN_BURST)) { - m_droppedPackets++; + active = false; + underflows = 0; + droppedPackets = 0; + return; + } + + // Don't wait for messages (default timeout is 0.1s), as this is called from the GUI thread + // Drain all pending messages, so counts are accurate + try + { + while (m_stream->recv_async_msg(md, 0.0)) + { + if ((md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_UNDERFLOW) + || (md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_UNDERFLOW_IN_PACKET)) { + m_underflows++; + } + if ((md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_SEQ_ERROR) + || (md.event_code & uhd::async_metadata_t::event_code_t::EVENT_CODE_SEQ_ERROR_IN_BURST)) { + m_droppedPackets++; + } } } + catch (std::exception& e) + { + qDebug() << "USRPOutputThread::getStreamStatus: exception: " << e.what(); + } //qDebug() << "USRPOutputThread::getStreamStatus " << m_packets << " " << m_underflows << " " << m_droppedPackets; active = m_packets > 0; underflows = m_underflows; droppedPackets = m_droppedPackets; } + + +// Stop applying settings to the device and sending reports, waiting for any settings being applied to complete. +// Used when stopping from a thread other than the device engine thread (E.g. when USRPOutput is being destroyed) +void USRPOutputThread::detach() +{ + QMutexLocker mutexLocker(&m_configMutex); + m_detached = true; +} + +void USRPOutputThread::handleInputMessages() +{ + QMutexLocker mutexLocker(&m_configMutex); + Message* message; + + // Merge consecutive configuration messages, so we only apply the latest settings. + // This avoids a backlog of slow device calls (E.g. when a slider is dragged) + bool pendingConfig = false; + USRPOutputSettings settings; + QList settingsKeys; + bool force = false; + + auto applyPendingConfig = [&]() { + if (pendingConfig) + { + if (settingsKeys.contains("log2SoftInterp") || force) { + setLog2Interpolation(settings.m_log2SoftInterp); + } + applyDeviceSettings(m_deviceParams, m_channel, settings, settingsKeys, force, true, true, m_reportQueue); + pendingConfig = false; + settingsKeys.clear(); + force = false; + } + }; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (m_detached) + { + delete message; + continue; + } + + if (USRPOutput::MsgConfigureUSRP::match(*message)) + { + const USRPOutput::MsgConfigureUSRP& conf = (const USRPOutput::MsgConfigureUSRP&) *message; + + if (conf.getForce() || !pendingConfig) + { + settings = conf.getSettings(); + settingsKeys = conf.getSettingsKeys(); + force = force || conf.getForce(); + } + else + { + settings.applySettings(conf.getSettingsKeys(), conf.getSettings()); + for (const auto& key : conf.getSettingsKeys()) + { + if (!settingsKeys.contains(key)) { + settingsKeys.append(key); + } + } + } + pendingConfig = true; + } + else + { + // Keep ordering with respect to other messages + applyPendingConfig(); + + if (DeviceUSRPShared::MsgReadDeviceSampleRate::match(*message)) { + readBackSampleRate(); + } else if (DeviceUSRPShared::MsgResizeSampleFifo::match(*message)) { + resizeSampleFifo(((const DeviceUSRPShared::MsgResizeSampleFifo&) *message).getSize()); + } else { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + } + + delete message; + } + + if (!m_detached) { + applyPendingConfig(); + } +} + +// Resize the sample FIFO. This executes in the device engine thread, which writes to the FIFO, +// so the only other thread that accesses it is the streaming thread, which is paused while it is resized. +void USRPOutputThread::resizeSampleFifo(unsigned int size) +{ + // Prevent buddies suspending / resuming the streaming thread at the same time + QMutexLocker mutexLocker(&m_deviceParams->m_mutex); + bool wasRunning = m_running; + + if (wasRunning) { + stopWork(); + } + + m_sampleFifo->resize(size); + qDebug("USRPOutputThread::resizeSampleFifo: %u", size); + + if (wasRunning) { + startWork(); + } +} + +void USRPOutputThread::readBackSampleRate() +{ + uhd::usrp::multi_usrp::sptr device = m_deviceParams ? m_deviceParams->getDevice() : nullptr; + + if (!device) { + return; + } + + QMutexLocker mutexLocker(&m_deviceParams->m_mutex); + + try + { + double sampleRate = DeviceUSRP::getSampleRate(device, false, m_channel); + double masterClockRate = device->get_master_clock_rate(); + + if (m_reportQueue) { + m_reportQueue->push(DeviceUSRPShared::MsgReportDeviceSettings::create(true, sampleRate, masterClockRate, false, "", false)); + } + } + catch (std::exception& e) + { + qDebug() << "USRPOutputThread::readBackSampleRate: exception: " << e.what(); + } +} + +// Apply settings to the device and send what was actually set to reportQueue. +// applyChannelSettings - apply settings that require the channel to be acquired. If false, only GPIO settings are applied. +// applyBandwidth - apply LPF bandwidth, which shouldn't be applied until after the stream is created +void USRPOutputThread::applyDeviceSettings( + DeviceUSRPParams *deviceParams, + int channel, + const USRPOutputSettings& settings, + const QList& settingsKeys, + bool force, + bool applyChannelSettings, + bool applyBandwidth, + MessageQueue *reportQueue) +{ + uhd::usrp::multi_usrp::sptr device = deviceParams ? deviceParams->getDevice() : nullptr; + + if (!device) { + return; + } + + QMutexLocker mutexLocker(&deviceParams->m_mutex); + bool reapplySomeSettings = false; + bool checkRates = false; + bool checkClockSource = false; + + // Apply each setting separately, so a failure (E.g. an antenna name not supported by the + // daughterboard) doesn't prevent other settings from being applied + auto apply = [](const char *what, const std::function& func) { + try { + func(); + } catch (std::exception &e) { + qWarning() << "USRPOutputThread::applyDeviceSettings: failed to set" << what << ":" << e.what(); + } + }; + + if (applyChannelSettings) + { + if (settingsKeys.contains("clockSource") || force) + { + try + { + device->set_clock_source(settings.m_clockSource.toStdString(), 0); + qDebug() << "USRPOutputThread::applyDeviceSettings: clock set to " << settings.m_clockSource; + } + catch (std::exception &e) + { + // An exception will be thrown if the clock is not detected + // however, get_clock_source called below will still say the clock has is set + qCritical() << "USRPOutputThread::applyDeviceSettings: could not set clock " << settings.m_clockSource; + // So, default back to internal + apply("clock source to internal", [&]() { device->set_clock_source("internal", 0); }); + } + // Report actual clock source, in case requested clock couldn't be set + checkClockSource = true; + reapplySomeSettings = true; + } + + if (settingsKeys.contains("devSampleRate") || force) + { + apply("sample rate", [&]() { + DeviceUSRP::setSampleRate(device, false, channel, settings.m_devSampleRate); + qDebug("USRPOutputThread::applyDeviceSettings: sample rate set to %d", settings.m_devSampleRate); + }); + checkRates = true; + reapplySomeSettings = true; + } + + if (settingsKeys.contains("centerFrequency") + || settingsKeys.contains("loOffset") + || settingsKeys.contains("transverterMode") + || settingsKeys.contains("transverterDeltaFrequency") + || force) + { + apply("frequency", [&]() { + qint64 deviceCenterFrequency = settings.m_centerFrequency; + deviceCenterFrequency -= settings.m_transverterMode ? settings.m_transverterDeltaFrequency : 0; + deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; + uhd::tune_request_t tuneRequest = settings.m_loOffset != 0 + ? uhd::tune_request_t(deviceCenterFrequency, settings.m_loOffset) + : uhd::tune_request_t(deviceCenterFrequency); + device->set_tx_freq(tuneRequest, channel); + qDebug("USRPOutputThread::applyDeviceSettings: frequency set to %lld with LO offset %d", deviceCenterFrequency, settings.m_loOffset); + }); + } + + if (settingsKeys.contains("gain") || force) { + apply("gain", [&]() { device->set_tx_gain(settings.m_gain, channel); }); + } + + if (applyBandwidth && (settingsKeys.contains("lpfBW") || force)) + { + apply("LPF bandwidth", [&]() { + device->set_tx_bandwidth(settings.m_lpfBW, channel); + qDebug("USRPOutputThread::applyDeviceSettings: LPF BW: %f for channel %d", settings.m_lpfBW, channel); + }); + } + + if (settingsKeys.contains("antennaPath") || force) + { + apply("antenna", [&]() { + device->set_tx_antenna(settings.m_antennaPath.toStdString(), channel); + qDebug("USRPOutputThread::applyDeviceSettings: antenna set to %s on channel %d", qPrintable(settings.m_antennaPath), channel); + }); + } + } + + const std::string gpioBank = "FP0"; // Front Panel GPIO + + if (settingsKeys.contains("gpioDir") || force) + { + apply("GPIO direction", [&]() { + std::vector banks = device->get_gpio_banks(0); + + if (std::find(banks.begin(), banks.end(), gpioBank) != banks.end()) + { + device->set_gpio_attr(gpioBank, "CTRL", ~settings.m_gpioDir, 0xff); // 0 for GPIO, 1 for ATR + device->set_gpio_attr(gpioBank, "DDR", settings.m_gpioDir, 0xff); // 0 for input, 1 for output + qDebug() << "USRPOutputThread::applyDeviceSettings: set GPIO dir to" << settings.m_gpioDir; + } + }); + } + + if (settingsKeys.contains("gpioPins") || force) + { + apply("GPIO pins", [&]() { + std::vector banks = device->get_gpio_banks(0); + + if (std::find(banks.begin(), banks.end(), gpioBank) != banks.end()) + { + device->set_gpio_attr(gpioBank, "OUT", settings.m_gpioPins, 0xff); + qDebug() << "USRPOutputThread::applyDeviceSettings: set GPIO pins to" << settings.m_gpioPins; + } + }); + } + + if (reapplySomeSettings && applyBandwidth) + { + // Need to re-set bandwidth (and AGC / gain for Rx) after changing sample rate or clock source + apply("LPF bandwidth", [&]() { device->set_tx_bandwidth(settings.m_lpfBW, channel); }); + } + + // Report what was actually set, so USRPOutput can update its settings and inform buddies and GUI + double sampleRate = 0.0; + double masterClockRate = 0.0; + QString clockSource; + + if (checkRates) + { + try + { + // Check if requested rate could actually be met and what master clock rate we ended up with + sampleRate = DeviceUSRP::getSampleRate(device, false, channel); + masterClockRate = device->get_master_clock_rate(); + qDebug("USRPOutputThread::applyDeviceSettings: actual sample rate %f master_clock_rate %f", sampleRate, masterClockRate); + } + catch (std::exception &e) + { + qDebug() << "USRPOutputThread::applyDeviceSettings: could not get sample rate: " << e.what(); + checkRates = false; + } + } + + if (checkClockSource) + { + try + { + clockSource = QString::fromStdString(device->get_clock_source(0)); + qDebug() << "USRPOutputThread::applyDeviceSettings: clock source is " << clockSource; + } + catch (std::exception &e) + { + qDebug() << "USRPOutputThread::applyDeviceSettings: could not get clock source: " << e.what(); + checkClockSource = false; + } + } + + if ((checkRates || checkClockSource) && reportQueue) { + reportQueue->push(DeviceUSRPShared::MsgReportDeviceSettings::create(checkRates, sampleRate, masterClockRate, checkClockSource, clockSource, true)); + } +} diff --git a/plugins/samplesink/usrpoutput/usrpoutputthread.h b/plugins/samplesink/usrpoutput/usrpoutputthread.h index cc0073a1a..d87a4649f 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputthread.h +++ b/plugins/samplesink/usrpoutput/usrpoutputthread.h @@ -24,6 +24,8 @@ #ifndef PLUGINS_SAMPLESOURCE_USRPOUTPUT_USRPOUTPUTTHREAD_H_ #define PLUGINS_SAMPLESOURCE_USRPOUTPUT_USRPOUTPUTTHREAD_H_ +#include + #include #include #include @@ -34,28 +36,53 @@ #include "dsp/interpolators.h" #include "usrp/deviceusrpshared.h" #include "usrp/deviceusrp.h" +#include "util/messagequeue.h" +#include "usrpoutputsettings.h" class SampleSourceFifo; +/** + * Sends samples to the device in its own thread (run()). + * + * Also applies device settings, which can take a long time (E.g. sample rate, clock source and bandwidth), + * via its input message queue, so they don't block the GUI thread. As this object is created in + * USRPOutput::start(), which is called from the device engine thread, its slots execute in the device + * engine thread, which is also where the channel is acquired and released, so these can't race. + */ class USRPOutputThread : public QThread, public DeviceUSRPShared::ThreadInterface { Q_OBJECT public: - USRPOutputThread(uhd::tx_streamer::sptr stream, size_t bufSamples, SampleSourceFifo* sampleFifo, QObject* parent = 0); + USRPOutputThread(DeviceUSRPParams *deviceParams, int channel, SampleSourceFifo* sampleFifo, + MessageQueue *reportQueue, QObject* parent = nullptr); ~USRPOutputThread(); + void setStream(uhd::tx_streamer::sptr stream, size_t bufSamples); + void releaseStream(); virtual void startWork(); virtual void stopWork(); virtual void setDeviceSampleRate(int sampleRate) { (void) sampleRate; } virtual bool isRunning() { return m_running; } void setLog2Interpolation(unsigned int log2_ioterp); void getStreamStatus(bool& active, quint32& underflows, quint32& droppedPackets); + MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + void detach(); + + static void applyDeviceSettings( + DeviceUSRPParams *deviceParams, + int channel, + const USRPOutputSettings& settings, + const QList& settingsKeys, + bool force, + bool applyChannelSettings, + bool applyBandwidth, + MessageQueue *reportQueue); private: QMutex m_startWaitMutex; QWaitCondition m_startWaiter; - bool m_running; + std::atomic m_running; quint64 m_packets; quint32 m_underflows; @@ -66,15 +93,25 @@ private: size_t m_bufSamples; SampleSourceFifo* m_sampleFifo; - unsigned int m_log2Interp; // soft decimation + std::atomic m_log2Interp; // soft interpolation + + Interpolators m_interpolators; //!< UHD's sc16 format is 16-bit, converted by UHD to device wire format (E.g. 12-bit for B2xx) - Interpolators m_interpolators; + DeviceUSRPParams *m_deviceParams; + int m_channel; + MessageQueue *m_reportQueue; //!< Where to send MsgReportDeviceSettings (USRPOutput's input queue) + MessageQueue m_inputMessageQueue; //!< Settings to apply to the device + QMutex m_configMutex; //!< Held while applying settings, so detach() can wait for it to complete + bool m_detached; //!< When set, no longer access device or report queue void run(); qint32 callback(qint16* buf, qint32 len); - void callbackPart(qint16* buf, SampleVector& data, unsigned int iBegin, unsigned int iEnd); -}; - + void callbackPart(qint16* buf, SampleVector& data, unsigned int iBegin, unsigned int iEnd, unsigned int log2Interp); + void readBackSampleRate(); + void resizeSampleFifo(unsigned int size); +private slots: + void handleInputMessages(); +}; #endif /* PLUGINS_SAMPLESOURCE_USRPOUTPUT_USRPOUTPUTTHREAD_H_ */ diff --git a/plugins/samplesource/usrpinput/readme.md b/plugins/samplesource/usrpinput/readme.md index 39feeb1d6..616c2a38c 100644 --- a/plugins/samplesource/usrpinput/readme.md +++ b/plugins/samplesource/usrpinput/readme.md @@ -129,6 +129,8 @@ This adjusts the Rx local oscillator (LO) frequency from the centre frequency by This label turns green when data is being received from the device. +The board temperature in degrees C is displayed to the left of this indicator, for devices that have a temperature sensor (E.g. the AD9361 on the B2xx). +

16: Stream warning indicators

- **O**: turns red if stream experiences overruns @@ -136,6 +138,8 @@ This label turns green when data is being received from the device. The stream warning indicators are reset when the acquisition is started. +Hovering over an indicator shows statistics for the current (or last) run: the total number of events, the average number per minute, the number in the last minute and the time of the last event. +

Dependencies

On Ubuntu 20, the libuhd-dev package should be installed. The FPGA images then need to be downloaded with: diff --git a/plugins/samplesource/usrpinput/usrpinput.cpp b/plugins/samplesource/usrpinput/usrpinput.cpp index c4dab0928..7dcff9af6 100644 --- a/plugins/samplesource/usrpinput/usrpinput.cpp +++ b/plugins/samplesource/usrpinput/usrpinput.cpp @@ -17,12 +17,14 @@ /////////////////////////////////////////////////////////////////////////////////// #include +#include #include #include #include #include #include +#include #include @@ -59,12 +61,24 @@ USRPInput::USRPInput(DeviceAPI *deviceAPI) : { m_sampleFifo.setLabel(m_deviceDescription); m_streamId = nullptr; + // Hold the shared device mutex (if there are buddies) across suspend...resume, so it can't interleave + // with buddies doing the same in their device engine threads + DeviceUSRPParams *buddyDeviceParams = getBuddyDeviceParams(); + + if (buddyDeviceParams) { + buddyDeviceParams->m_mutex.lock(); + } + suspendRxBuddies(); suspendTxBuddies(); openDevice(); resumeTxBuddies(); resumeRxBuddies(); + if (buddyDeviceParams) { + buddyDeviceParams->m_mutex.unlock(); + } + m_deviceAPI->setNbSourceStreams(1); m_networkManager = new QNetworkAccessManager(); @@ -90,11 +104,32 @@ USRPInput::~USRPInput() stop(); } + DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams; + bool hasBuddies = (m_deviceAPI->getSourceBuddies().size() > 0) || (m_deviceAPI->getSinkBuddies().size() > 0); + + if (deviceParams) + { + // Prevent buddies using our shared data after we've been deleted, but before buddy lists are cleared. + // Buddies read this in their device engine threads with the device mutex held. + QMutexLocker deviceLocker(&deviceParams->m_mutex); + m_deviceAPI->setBuddySharedPtr(nullptr); + } + + // Hold device mutex across suspend...resume, so it can't interleave with buddies doing the same. + // If there are no buddies, the device params are deleted in closeDevice, but then there's nothing to protect. + if (hasBuddies && deviceParams) { + deviceParams->m_mutex.lock(); + } + suspendRxBuddies(); suspendTxBuddies(); closeDevice(); resumeTxBuddies(); resumeRxBuddies(); + + if (hasBuddies && deviceParams) { + deviceParams->m_mutex.unlock(); + } } void USRPInput::destroy() @@ -106,6 +141,9 @@ bool USRPInput::openDevice() { bool ret = true; + // Set shared pointer first, so it is valid for buddies, even if we return early on error + m_deviceAPI->setBuddySharedPtr(&m_deviceShared); // propagate common parameters to API + // B210 supports up to 50MSa/s, so a fairly large FIFO is probably a good idea // Should it be bigger still? if (!m_sampleFifo.setSize(2000000)) @@ -167,7 +205,7 @@ bool USRPInput::openDevice() DeviceAPI *buddy = m_deviceAPI->getSourceBuddies()[i]; DeviceUSRPShared *buddyShared = (DeviceUSRPShared *) buddy->getBuddySharedPtr(); - if (buddyShared->m_channel == requestedChannel) + if (buddyShared && (buddyShared->m_channel == requestedChannel)) { qCritical("USRPInput::openDevice: cannot open busy channel %u", requestedChannel); return false; @@ -236,11 +274,33 @@ bool USRPInput::openDevice() m_deviceShared.m_channel = requestedChannel; // acknowledge the requested channel } - m_deviceAPI->setBuddySharedPtr(&m_deviceShared); // propagate common parameters to API - return ret; } +// Get device parameters shared with buddies, or nullptr if there are no buddies. Called from GUI thread. +DeviceUSRPParams *USRPInput::getBuddyDeviceParams() const +{ + for (const auto& buddy : m_deviceAPI->getSourceBuddies()) + { + DeviceUSRPShared *buddyShared = (DeviceUSRPShared *) buddy->getBuddySharedPtr(); + + if (buddyShared && buddyShared->m_deviceParams) { + return buddyShared->m_deviceParams; + } + } + + for (const auto& buddy : m_deviceAPI->getSinkBuddies()) + { + DeviceUSRPShared *buddyShared = (DeviceUSRPShared *) buddy->getBuddySharedPtr(); + + if (buddyShared && buddyShared->m_deviceParams) { + return buddyShared->m_deviceParams; + } + } + + return nullptr; +} + void USRPInput::suspendRxBuddies() { const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); @@ -252,6 +312,13 @@ void USRPInput::suspendRxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSource)->getBuddySharedPtr(); + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + if (buddySharedPtr->m_thread && buddySharedPtr->m_thread->isRunning()) { buddySharedPtr->m_thread->stopWork(); @@ -275,6 +342,13 @@ void USRPInput::suspendTxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSink)->getBuddySharedPtr(); + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + if ((buddySharedPtr->m_thread) && buddySharedPtr->m_thread->isRunning()) { buddySharedPtr->m_thread->stopWork(); @@ -298,7 +372,14 @@ void USRPInput::resumeRxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSource)->getBuddySharedPtr(); - if (buddySharedPtr->m_threadWasRunning) { + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + + if (buddySharedPtr->m_threadWasRunning && buddySharedPtr->m_thread) { buddySharedPtr->m_thread->startWork(); } } @@ -315,7 +396,14 @@ void USRPInput::resumeTxBuddies() { DeviceUSRPShared *buddySharedPtr = (DeviceUSRPShared *) (*itSink)->getBuddySharedPtr(); - if (buddySharedPtr->m_threadWasRunning) { + if (!buddySharedPtr || !buddySharedPtr->m_deviceParams) { + continue; + } + + // Device mutex prevents the buddy deleting its thread while we use it + QMutexLocker deviceLocker(&buddySharedPtr->m_deviceParams->m_mutex); + + if (buddySharedPtr->m_threadWasRunning && buddySharedPtr->m_thread) { buddySharedPtr->m_thread->startWork(); } } @@ -323,38 +411,50 @@ void USRPInput::resumeTxBuddies() void USRPInput::closeDevice() { - if (m_deviceShared.m_deviceParams->getDevice() == 0) { // was never open - return; - } - if (m_running) { stop(); } - m_deviceShared.m_channel = -1; + m_deviceShared.m_channel = -1; // effectively release the channel for the possible buddies + + if (m_deviceShared.m_deviceParams == nullptr) { // was never created + return; + } // No buddies so effectively close the device + // (params are deleted even if the device failed to open, to avoid a leak) - if ((m_deviceAPI->getSinkBuddies().size() == 0) && (m_deviceAPI->getSourceBuddies().size() == 0)) + if ((m_deviceAPI->getSourceBuddies().size() == 0) && (m_deviceAPI->getSinkBuddies().size() == 0)) { m_deviceShared.m_deviceParams->close(); delete m_deviceShared.m_deviceParams; - m_deviceShared.m_deviceParams = 0; + m_deviceShared.m_deviceParams = nullptr; } } -bool USRPInput::acquireChannel() +bool USRPInput::acquireChannel(const USRPInputSettings& settings) { + bool success = true; + + // Hold buddies and device mutexes across suspend...resume, so buddies doing the same at the same time + // can't interleave (which could leave a buddy suspended), and buddy lists can't be changed while we use them + QMutexLocker buddiesLocker(&DeviceAPI::getBuddiesMutex()); + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + suspendRxBuddies(); suspendTxBuddies(); if (m_streamId == nullptr) { + // Prevent buddies from configuring the device while we set up the stream + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + try { uhd::usrp::multi_usrp::sptr usrp = m_deviceShared.m_deviceParams->getDevice(); // Apply settings before creating stream // However, don't set LPF to <10MHz at this stage, otherwise there is massive TX LO leakage - applySettings(m_settings, QList(), true, true); + // Actual settings are reported back to handleMessage, which forwards them to buddies and GUI + USRPInputThread::applyDeviceSettings(m_deviceShared.m_deviceParams, m_deviceShared.m_channel, settings, QList(), true, true, false, getInputMessageQueue()); usrp->set_rx_bandwidth(56000000, m_deviceShared.m_channel); // set up the stream @@ -366,36 +466,42 @@ bool USRPInput::acquireChannel() uhd::stream_args_t stream_args(cpu_format, wire_format); stream_args.channels = channel_nums; - m_streamId = m_deviceShared.m_deviceParams->getDevice()->get_rx_stream(stream_args); + m_streamId = usrp->get_rx_stream(stream_args); - // Decimators require buffers to sized as powers of two (See #1161) - m_bufSamples = m_streamId->get_max_num_samps(); - if (!isPowerOfTwo(m_bufSamples)) { - m_bufSamples = lowerPowerOfTwo(m_bufSamples); - } + // Read multiple packets per recv() call at high sample rates, to reduce overhead + m_bufSamples = DeviceUSRP::getRecvBufferSamples(m_streamId->get_max_num_samps(), settings.m_devSampleRate); - // Wait for reference and LO to lock - DeviceUSRP::waitForLock(usrp, m_settings.m_clockSource, m_deviceShared.m_channel); + // Wait for reference and LO to lock. Use actual clock source, in case requested clock wasn't detected + DeviceUSRP::waitForLock(usrp, QString::fromStdString(usrp->get_clock_source(0)), m_deviceShared.m_channel, true); // Now we can set desired bandwidth - usrp->set_rx_bandwidth(m_settings.m_lpfBW, m_deviceShared.m_channel); + usrp->set_rx_bandwidth(settings.m_lpfBW, m_deviceShared.m_channel); } catch (std::exception& e) { - qDebug() << "USRPInput::acquireChannel: exception: " << e.what(); + qCritical() << "USRPInput::acquireChannel: exception: " << e.what(); } + + // Can't run without a stream + success = m_streamId != nullptr; } resumeTxBuddies(); resumeRxBuddies(); - m_channelAcquired = true; + m_channelAcquired = success; - return true; + return success; } void USRPInput::releaseChannel() { + // Hold buddies and device mutexes across suspend...resume, so buddies doing the same at the same time + // can't interleave (which could leave a buddy suspended), and buddy lists can't be changed while we use them. + // This also means the stream is destroyed with the device mutex held. + QMutexLocker buddiesLocker(&DeviceAPI::getBuddiesMutex()); + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + suspendRxBuddies(); suspendTxBuddies(); @@ -412,9 +518,10 @@ void USRPInput::releaseChannel() void USRPInput::init() { - applySettings(m_settings, QList(), false, true); + applySettings(m_settings, QList(), true); } +// Called from the device engine thread bool USRPInput::start() { QMutexLocker mutexLocker(&m_mutex); @@ -423,28 +530,58 @@ bool USRPInput::start() return true; } - if (!m_deviceShared.m_deviceParams->getDevice()) { + if (!m_deviceShared.m_deviceParams || !m_deviceShared.m_deviceParams->getDevice()) { return false; } - if (!acquireChannel()) { + // Create thread before acquiring the channel, so settings changed while the channel is + // being acquired are queued to it, to be applied once start() has returned. + // start / stop streaming is done in the thread. + USRPInputThread *thread = new USRPInputThread(m_deviceShared.m_deviceParams, m_deviceShared.m_channel, + &m_sampleFifo, &m_replayBuffer, getInputMessageQueue()); + // Publish the thread and take a copy of the settings atomically with respect to applySettings, so + // settings changed in the GUI thread while the channel is being acquired are either in the copy or + // queued to the thread, to be applied once start() has returned + USRPInputSettings settings; + { + QMutexLocker settingsLocker(&m_settingsMutex); + QMutexLocker threadLocker(&m_threadMutex); + m_usrpInputThread = thread; + settings = m_settings; + } + + if (!acquireChannel(settings)) + { + { + QMutexLocker threadLocker(&m_threadMutex); + m_usrpInputThread = nullptr; + } + delete thread; return false; } - // start / stop streaming is done in the thread. + { + QMutexLocker threadLocker(&m_threadMutex); + thread->setStream(m_streamId, m_bufSamples); + } + thread->setLog2Decimation(settings.m_log2SoftDecim); - m_usrpInputThread = new USRPInputThread(m_streamId, m_bufSamples, &m_sampleFifo, &m_replayBuffer); - qDebug("USRPInput::start: thread created"); + { + // Start streaming and make the thread visible to buddies atomically, so a buddy that is acquiring + // its channel (holding the device mutex) can't miss suspending us + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + thread->startWork(); + m_deviceShared.m_thread = thread; + } - m_usrpInputThread->setLog2Decimation(m_settings.m_log2SoftDecim); - m_usrpInputThread->startWork(); + qDebug("USRPInput::start: thread started"); - m_deviceShared.m_thread = m_usrpInputThread; m_running = true; return true; } +// Usually called from the device engine thread, but can be called from the GUI thread in the destructor void USRPInput::stop() { QMutexLocker mutexLocker(&m_mutex); @@ -456,14 +593,38 @@ void USRPInput::stop() qDebug("USRPInput::stop"); m_running = false; - if (m_usrpInputThread) + USRPInputThread *thread; { - m_usrpInputThread->stopWork(); - delete m_usrpInputThread; + QMutexLocker threadLocker(&m_threadMutex); + thread = m_usrpInputThread; m_usrpInputThread = nullptr; } - m_deviceShared.m_thread = 0; + if (thread) + { + // Wait for any settings being applied in the device engine thread to complete and prevent any more + thread->detach(); + + { + // Clear before deleting the thread, so buddies can't access it while it's being destroyed. + // Device mutex prevents buddies accessing it while we clear it and stop it + QMutexLocker deviceLocker(&m_deviceShared.m_deviceParams->m_mutex); + m_deviceShared.m_thread = nullptr; + thread->stopWork(); + } + + // Release stream, so it's destroyed before the device, even if the thread is deleted later + thread->releaseStream(); + + QThread *ownerThread = thread->thread(); + if (!ownerThread || (ownerThread == QThread::currentThread()) || ownerThread->isFinished()) { + delete thread; + } else { + // Called from another thread while the device engine thread is still running, which may have + // a pending call to handleInputMessages, so delete it in the device engine thread + thread->deleteLater(); + } + } releaseChannel(); } @@ -477,10 +638,14 @@ bool USRPInput::deserialize(const QByteArray& data) { bool success = true; - if (!m_settings.deserialize(data)) { - m_settings.resetToDefaults(); - success = false; + QMutexLocker settingsLocker(&m_settingsMutex); + + if (!m_settings.deserialize(data)) + { + m_settings.resetToDefaults(); + success = false; + } } MsgConfigureUSRP* message = MsgConfigureUSRP::create(m_settings, QList(), true); @@ -533,6 +698,13 @@ int USRPInput::getChannelIndex() void USRPInput::getLORange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_loRangeRx.start(); @@ -548,6 +720,13 @@ void USRPInput::getLORange(float& minF, float& maxF) const void USRPInput::getSRRange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_srRangeRx.start(); @@ -563,6 +742,13 @@ void USRPInput::getSRRange(float& minF, float& maxF) const void USRPInput::getLPRange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_lpfRangeRx.start(); @@ -578,6 +764,13 @@ void USRPInput::getLPRange(float& minF, float& maxF) const void USRPInput::getGainRange(float& minF, float& maxF) const { + if (!m_deviceShared.m_deviceParams) + { + minF = 0.0f; + maxF = 0.0f; + return; + } + try { minF = m_deviceShared.m_deviceParams->m_gainRangeRx.start(); @@ -593,17 +786,17 @@ void USRPInput::getGainRange(float& minF, float& maxF) const QStringList USRPInput::getRxAntennas() const { - return m_deviceShared.m_deviceParams->m_rxAntennas; + return m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->m_rxAntennas : QStringList(); } QStringList USRPInput::getRxGainNames() const { - return m_deviceShared.m_deviceParams->m_rxGainNames; + return m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->m_rxGainNames : QStringList(); } QStringList USRPInput::getClockSources() const { - return m_deviceShared.m_deviceParams->m_clockSources; + return m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->m_clockSources : QStringList(); } bool USRPInput::handleMessage(const Message& message) @@ -613,20 +806,67 @@ bool USRPInput::handleMessage(const Message& message) MsgConfigureUSRP& conf = (MsgConfigureUSRP&) message; qDebug() << "USRPInput::handleMessage: MsgConfigureUSRP"; - if (!applySettings(conf.getSettings(), conf.getSettingsKeys(), false, conf.getForce())) + if (!applySettings(conf.getSettings(), conf.getSettingsKeys(), conf.getForce())) { qDebug("USRPInput::handleMessage config error"); } return true; } + else if (DeviceUSRPShared::MsgReportDeviceSettings::match(message)) + { + // Settings actually set on the device, as read back in the device engine thread + DeviceUSRPShared::MsgReportDeviceSettings& report = (DeviceUSRPShared::MsgReportDeviceSettings&) message; + QMutexLocker settingsLocker(&m_settingsMutex); + + if (report.getClockSourceValid()) + { + m_settings.m_clockSource = report.getClockSource(); + forwardClockSource(); + } + + if (report.getSampleRateValid()) + { + int devSampleRate = (int) std::round(report.getSampleRate()); + int masterClockRate = (int) std::round(report.getMasterClockRate()); + qDebug() << "USRPInput::handleMessage: MsgReportDeviceSettings: devSampleRate:" << devSampleRate << "masterClockRate:" << masterClockRate; + + if ((devSampleRate != m_settings.m_devSampleRate) || (masterClockRate != m_settings.m_masterClockRate)) + { + if (devSampleRate != m_settings.m_devSampleRate) + { + m_replayBuffer.clear(); + m_replayBuffer.setSize(m_settings.m_replayLength, devSampleRate); + m_replayBuffer.setReadOffset(((unsigned)(m_settings.m_replayOffset * devSampleRate)) * 2); + } + + m_settings.m_devSampleRate = devSampleRate; + m_settings.m_masterClockRate = masterClockRate; + + if (!report.getForwardToBuddies()) { + notifySampleRateChange(); + } + } + + // Result of our own settings change, so the device has changed and buddies need to be informed, + // even if the rate is as we requested, as buddies won't have been informed when we weren't running + if (report.getForwardToBuddies()) { + forwardChangeAllDSP(); + } + } + + return true; + } else if (DeviceUSRPShared::MsgReportBuddyChange::match(message)) { DeviceUSRPShared::MsgReportBuddyChange& report = (DeviceUSRPShared::MsgReportBuddyChange&) message; + QMutexLocker settingsLocker(&m_settingsMutex); + uhd::usrp::multi_usrp::sptr device = m_deviceShared.m_deviceParams ? m_deviceShared.m_deviceParams->getDevice() : nullptr; - if (report.getRxElseTx()) + // Rx buddy changed settings. Only copy them if the buddy's channel shares our LO (E.g. B210), + // not if it has an independent front-end (E.g. X310 with two daughterboards) + if (report.getRxElseTx() && DeviceUSRP::channelsShareLO(device, true, report.getChannel(), m_deviceShared.m_channel)) { - // Rx buddy changed settings, we need to copy m_settings.m_devSampleRate = report.getDevSampleRate(); m_settings.m_centerFrequency = report.getCenterFrequency(); m_settings.m_loOffset = report.getLOOffset(); @@ -638,23 +878,24 @@ bool USRPInput::handleMessage(const Message& message) qDebug() << "USRPInput::handleMessage MsgReportBuddyChange"; qDebug() << "m_masterClockRate " << m_settings.m_masterClockRate; - DSPSignalNotification *notif = new DSPSignalNotification( - m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); - - if (getMessageQueueToGUI()) + // A buddy changing the master clock rate may have changed our sample rate, so have the device + // engine thread read back the actual rate, which will be reported via MsgReportDeviceSettings { - DeviceUSRPShared::MsgReportBuddyChange *reportToGUI = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true); - getMessageQueueToGUI()->push(reportToGUI); + QMutexLocker threadLocker(&m_threadMutex); + + if (m_usrpInputThread) { + m_usrpInputThread->getInputMessageQueue()->push(DeviceUSRPShared::MsgReadDeviceSampleRate::create()); + } } + notifySampleRateChange(); + return true; } else if (DeviceUSRPShared::MsgReportClockSourceChange::match(message)) { DeviceUSRPShared::MsgReportClockSourceChange& report = (DeviceUSRPShared::MsgReportClockSourceChange&) message; + QMutexLocker settingsLocker(&m_settingsMutex); m_settings.m_clockSource = report.getClockSource(); @@ -667,11 +908,29 @@ bool USRPInput::handleMessage(const Message& message) return true; } + else if (MsgGetDeviceInfo::match(message)) + { + // Reading a sensor is quick, so do it here, but don't block the GUI thread + // if the device is being configured in a device engine thread + DeviceUSRPParams *deviceParams = m_deviceShared.m_deviceParams; + + if (deviceParams && deviceParams->getDevice() && deviceParams->m_mutex.tryLock()) + { + double temperature = 0.0; + bool temperatureValid = DeviceUSRP::getTemperature(deviceParams->getDevice(), true, m_deviceShared.m_channel, temperature); + deviceParams->m_mutex.unlock(); + forwardDeviceInfo(temperatureValid, temperature); + } + + return true; + } else if (MsgGetStreamInfo::match(message)) { if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) { - if (m_streamId != nullptr) + QMutexLocker threadLocker(&m_threadMutex); + + if (m_usrpInputThread) { bool active; quint32 overflows; @@ -729,396 +988,262 @@ bool USRPInput::handleMessage(const Message& message) } } -bool USRPInput::applySettings(const USRPInputSettings& settings, const QList& settingsKeys, bool preGetStream, bool force) +bool USRPInput::applySettings(const USRPInputSettings& settings, const QList& settingsKeys, bool force) { - qDebug() << "USRPInput::applySettings: preGetStream:" << preGetStream << " force:" << force << settings.getDebugString(settingsKeys, force); - bool forwardChangeOwnDSP = false; - bool forwardChangeRxDSP = false; - bool forwardChangeAllDSP = false; - bool forwardClockSource = false; - bool reapplySomeSettings = false; - bool checkRates = false; + QMutexLocker settingsLocker(&m_settingsMutex); + qDebug() << "USRPInput::applySettings: force:" << force << settings.getDebugString(settingsKeys, force); + bool changeOwnDSP = false; + bool changeRxDSP = false; + bool changeAllDSP = false; - try + if (settingsKeys.contains("devSampleRate") || force) { - qint64 deviceCenterFrequency = settings.m_centerFrequency; - deviceCenterFrequency -= settings.m_transverterMode ? settings.m_transverterDeltaFrequency : 0; - deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; - - // apply settings - - if (settingsKeys.contains("clockSource") || force) - { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - try - { - m_deviceShared.m_deviceParams->getDevice()->set_clock_source(settings.m_clockSource.toStdString(), 0); - forwardClockSource = true; - reapplySomeSettings = true; - qDebug() << "USRPInput::applySettings: clock set to " << settings.m_clockSource; - } - catch (std::exception &e) - { - // An exception will be thrown if the clock is not detected - // however, get_clock_source called below will still say the clock has is set - qCritical() << "USRPInput::applySettings: could not set clock " << settings.m_clockSource; - // So, default back to internal - m_deviceShared.m_deviceParams->getDevice()->set_clock_source("internal", 0); - // notify GUI that source couldn't be set - forwardClockSource = true; - } - } - else - { - qCritical() << "USRPInput::applySettings: could not set clock " << settings.m_clockSource; - } - } - - if (settingsKeys.contains("devSampleRate") || force) - { - forwardChangeAllDSP = true; + changeAllDSP = true; - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - m_deviceShared.m_deviceParams->getDevice()->set_rx_rate(settings.m_devSampleRate, m_deviceShared.m_channel); - qDebug("USRPInput::applySettings: set sample rate set to %d", settings.m_devSampleRate); - checkRates = true; - reapplySomeSettings = true; - } - - if (settings.m_devSampleRate != m_settings.m_devSampleRate) { - m_replayBuffer.clear(); - } - } - - if (settingsKeys.contains("centerFrequency") - || settingsKeys.contains("loOffset") - || settingsKeys.contains("transverterMode") - || settingsKeys.contains("transverterDeltaFrequency") - || force) - { - forwardChangeRxDSP = true; - - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - if (settings.m_loOffset != 0) - { - uhd::tune_request_t tune_request(deviceCenterFrequency, settings.m_loOffset); - m_deviceShared.m_deviceParams->getDevice()->set_rx_freq(tune_request, m_deviceShared.m_channel); - } - else - { - uhd::tune_request_t tune_request(deviceCenterFrequency); - m_deviceShared.m_deviceParams->getDevice()->set_rx_freq(tune_request, m_deviceShared.m_channel); - } - m_deviceShared.m_centerFrequency = deviceCenterFrequency; // for buddies - qDebug("USRPInput::applySettings: frequency set to %lld with LO offset %d", deviceCenterFrequency, settings.m_loOffset); - } + if (settings.m_devSampleRate != m_settings.m_devSampleRate) { + m_replayBuffer.clear(); } + } - if (settingsKeys.contains("dcBlock") || force) - { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - m_deviceShared.m_deviceParams->getDevice()->set_rx_dc_offset(settings.m_dcBlock, m_deviceShared.m_channel); - } + if (settingsKeys.contains("centerFrequency") + || settingsKeys.contains("loOffset") + || settingsKeys.contains("transverterMode") + || settingsKeys.contains("transverterDeltaFrequency") + || force) + { + changeRxDSP = true; - if (settingsKeys.contains("iqCorrection") || force) - { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - m_deviceShared.m_deviceParams->getDevice()->set_rx_iq_balance(settings.m_iqCorrection, m_deviceShared.m_channel); - } + qint64 deviceCenterFrequency = settings.m_centerFrequency; + deviceCenterFrequency -= settings.m_transverterMode ? settings.m_transverterDeltaFrequency : 0; + deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; + m_deviceShared.m_centerFrequency = deviceCenterFrequency; // for buddies + } - if (settingsKeys.contains("gainMode") || force) - { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - if (settings.m_gainMode == USRPInputSettings::GAIN_AUTO) - { - try - { - m_deviceShared.m_deviceParams->getDevice()->set_rx_agc(true, m_deviceShared.m_channel); - qDebug() << "USRPInput::applySettings: AGC enabled for channel " << m_deviceShared.m_channel; - } - catch (uhd::not_implemented_error &e) - { - qDebug() << "USRPInput::applySettings: AGC not implemented on this radio. Please set to manual."; - } - } - else - { - try { - m_deviceShared.m_deviceParams->getDevice()->set_rx_agc(false, m_deviceShared.m_channel); - } catch (uhd::not_implemented_error &e) { - // Ignore - } - m_deviceShared.m_deviceParams->getDevice()->set_rx_gain(settings.m_gain, m_deviceShared.m_channel); - qDebug() << "USRPInput::applySettings: AGC disabled for channel " << m_deviceShared.m_channel << " set to " << settings.m_gain; - } - } - } + if (settingsKeys.contains("log2SoftDecim") || force) + { + changeOwnDSP = true; + m_deviceShared.m_log2Soft = settings.m_log2SoftDecim; // for buddies + } - if (settingsKeys.contains("gain") || force) - { - if ((settings.m_gainMode != USRPInputSettings::GAIN_AUTO) && m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - m_deviceShared.m_deviceParams->getDevice()->set_rx_gain(settings.m_gain, m_deviceShared.m_channel); - qDebug() << "USRPInput::applySettings: Gain set to " << settings.m_gain << " for channel " << m_deviceShared.m_channel; - } - } + // Applying settings to the device can take a long time (E.g. sample rate, clock source and bandwidth), + // so when running, they are applied in the device engine thread, rather than blocking the GUI thread. + // Values actually set are reported back via DeviceUSRPShared::MsgReportDeviceSettings. + // When not running, they are applied when the channel is acquired in start(), except for GPIO, + // which doesn't require the channel to be acquired. + bool threadRunning = false; + { + QMutexLocker threadLocker(&m_threadMutex); - if (settingsKeys.contains("lpfBW") || force) + if (m_usrpInputThread) { - // Don't set bandwidth before get_rx_stream (See above) - if (m_deviceShared.m_deviceParams->getDevice() && m_channelAcquired) - { - m_deviceShared.m_deviceParams->getDevice()->set_rx_bandwidth(settings.m_lpfBW, m_deviceShared.m_channel); - qDebug("USRPInput::applySettings: LPF BW: %f for channel %d", settings.m_lpfBW, m_deviceShared.m_channel); - } + m_usrpInputThread->getInputMessageQueue()->push(MsgConfigureUSRP::create(settings, settingsKeys, force)); + threadRunning = true; } + } - if (settingsKeys.contains("log2SoftDecim") || force) + if (!threadRunning && m_deviceShared.m_deviceParams && (settingsKeys.contains("gpioDir") || settingsKeys.contains("gpioPins") || force)) + { + // Don't block the GUI thread if a buddy is configuring the device (E.g. waiting for LO lock). Retry later instead. + if (m_deviceShared.m_deviceParams->m_mutex.tryLock()) { - forwardChangeOwnDSP = true; - m_deviceShared.m_log2Soft = settings.m_log2SoftDecim; // for buddies - - if (m_usrpInputThread) - { - m_usrpInputThread->setLog2Decimation(settings.m_log2SoftDecim); - qDebug() << "USRPInput::applySettings: set soft decimation to " << (1<m_mutex.unlock(); } - - if (settingsKeys.contains("antennaPath") || force) + else { - if (m_deviceShared.m_deviceParams->getDevice() && (m_channelAcquired || preGetStream)) - { - m_deviceShared.m_deviceParams->getDevice()->set_rx_antenna(settings.m_antennaPath.toStdString(), m_deviceShared.m_channel); - qDebug("USRPInput::applySettings: set antenna path to %s on channel %d", qPrintable(settings.m_antennaPath), m_deviceShared.m_channel); - } + QTimer::singleShot(100, this, [this]() { + m_inputMessageQueue.push(MsgConfigureUSRP::create(m_settings, QList{"gpioDir", "gpioPins"}, false)); + }); } + } - const std::string gpioBank = "FP0"; // Front Panel GPIO + if (settingsKeys.contains("useReverseAPI")) + { + bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) || + settingsKeys.contains("reverseAPIAddress") || + settingsKeys.contains("reverseAPIPort") || + settingsKeys.contains("reverseAPIDeviceIndex"); + webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); + } - if (settingsKeys.contains("gpioDir") || force) - { - if (m_deviceShared.m_deviceParams->getDevice()) - { - std::vector banks = m_deviceShared.m_deviceParams->getDevice()->get_gpio_banks(0); - for (const auto& bank : banks) - { - if (!gpioBank.compare(bank)) - { - m_deviceShared.m_deviceParams->getDevice()->set_gpio_attr(gpioBank, "CTRL", ~settings.m_gpioDir, 0xff); // 0 for GPIO, 1 for ATR - m_deviceShared.m_deviceParams->getDevice()->set_gpio_attr(gpioBank, "DDR", settings.m_gpioDir, 0xff); // 0 for input, 1 for output - qDebug() << "USRPInput::applySettings: set GPIO dir to" << settings.m_gpioDir; - } - } - } - } + if (force) { + m_settings = settings; + } else { + m_settings.applySettings(settingsKeys, settings); + } - if (settingsKeys.contains("gpioPins") || force) - { - if (m_deviceShared.m_deviceParams->getDevice()) - { - std::vector banks = m_deviceShared.m_deviceParams->getDevice()->get_gpio_banks(0); - for (const auto& bank : banks) - { - if (!gpioBank.compare(bank)) - { - m_deviceShared.m_deviceParams->getDevice()->set_gpio_attr(gpioBank, "OUT", settings.m_gpioPins, 0xff); - qDebug() << "USRPInput::applySettings: set GPIO pins to" << settings.m_gpioPins; - } - } - } - } + if (settingsKeys.contains("replayLength") || settingsKeys.contains("devSampleRate") || force) { + m_replayBuffer.setSize(m_settings.m_replayLength, m_settings.m_devSampleRate); + } - if (settingsKeys.contains("useReverseAPI")) - { - bool fullUpdate = (settingsKeys.contains("useReverseAPI") && settings.m_useReverseAPI) || - settingsKeys.contains("reverseAPIAddress") || - settingsKeys.contains("reverseAPIPort") || - settingsKeys.contains("reverseAPIDeviceIndex"); - webapiReverseSendSettings(settingsKeys, settings, fullUpdate || force); - } + if (settingsKeys.contains("replayOffset") || settingsKeys.contains("devSampleRate") || force) { + m_replayBuffer.setReadOffset(((unsigned)(m_settings.m_replayOffset * m_settings.m_devSampleRate)) * 2); + } - if (reapplySomeSettings) - { - // Need to re-set bandwidth and AGG after changing samplerate (and possibly clock source) - m_deviceShared.m_deviceParams->getDevice()->set_rx_bandwidth(settings.m_lpfBW, m_deviceShared.m_channel); - if (settings.m_gainMode == USRPInputSettings::GAIN_AUTO) - { - try { - m_deviceShared.m_deviceParams->getDevice()->set_rx_agc(true, m_deviceShared.m_channel); - } catch (uhd::not_implemented_error &e) { - // Error message should have been output above - } - } - else - { - try { - m_deviceShared.m_deviceParams->getDevice()->set_rx_agc(false, m_deviceShared.m_channel); - } catch (uhd::not_implemented_error &e) { - // Ignore - } - m_deviceShared.m_deviceParams->getDevice()->set_rx_gain(settings.m_gain, m_deviceShared.m_channel); - } - } + if (settingsKeys.contains("replayLoop") || force) { + m_replayBuffer.setLoop(m_settings.m_replayLoop); + } - if (force) { - m_settings = settings; - } else { - m_settings.applySettings(settingsKeys, settings); - } + // forward changes to buddies or oneself + // If the device coerces the sample rate, this will be sent again with the actual rate, once reported - if (settingsKeys.contains("replayLength") || settingsKeys.contains("devSampleRate") || force) { - m_replayBuffer.setSize(m_settings.m_replayLength, m_settings.m_devSampleRate); + // When not running, the device hasn't been changed, so buddies don't need to be informed. + // They will be informed of the actual settings when we are started. + if (!threadRunning) + { + if (changeAllDSP || changeRxDSP || changeOwnDSP) { + forwardChangeOwnDSP(); } + } + else if (changeAllDSP) + { + forwardChangeAllDSP(); + } + else if (changeRxDSP) + { + forwardChangeRxDSP(); + } + else if (changeOwnDSP) + { + forwardChangeOwnDSP(); + } - if (settingsKeys.contains("replayOffset") || settingsKeys.contains("devSampleRate") || force) { - m_replayBuffer.setReadOffset(((unsigned)(m_settings.m_replayOffset * m_settings.m_devSampleRate)) * 2); - } + return true; +} - if (settingsKeys.contains("replayLoop") || force) { - m_replayBuffer.setLoop(m_settings.m_replayLoop); - } +// Forward sample rate and frequency to self, all buddies and GUI +void USRPInput::forwardChangeAllDSP() +{ + qDebug("USRPInput::forwardChangeAllDSP"); - if (checkRates) - { - // Check if requested rate could actually be met and what master clock rate we ended up with - double actualSampleRate = m_deviceShared.m_deviceParams->getDevice()->get_rx_rate(m_deviceShared.m_channel); - qDebug("USRPInput::applySettings: actual sample rate %f", actualSampleRate); - double masterClockRate = m_deviceShared.m_deviceParams->getDevice()->get_master_clock_rate(); - qDebug("USRPInput::applySettings: master_clock_rate %f", masterClockRate); - m_settings.m_devSampleRate = actualSampleRate; - m_settings.m_masterClockRate = masterClockRate; - } + // send to self first + forwardChangeOwnDSP(); - // forward changes to buddies or oneself + // send to source buddies + const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); + std::vector::const_iterator itSource = sourceBuddies.begin(); - if (forwardChangeAllDSP) - { - qDebug("USRPInput::applySettings: forward change to all buddies"); + for (; itSource != sourceBuddies.end(); ++itSource) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true, m_deviceShared.m_channel); + (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); + } - // send to self first - DSPSignalNotification *notif = new DSPSignalNotification( - m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); + // send to sink buddies + const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); + std::vector::const_iterator itSink = sinkBuddies.begin(); - // send to source buddies - const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); - std::vector::const_iterator itSource = sourceBuddies.begin(); + for (; itSink != sinkBuddies.end(); ++itSink) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true, m_deviceShared.m_channel); + (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); + } - for (; itSource != sourceBuddies.end(); ++itSource) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true); - (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); - } + // send to GUI so it can see master clock rate and if actual rate differs + if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) + { + DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true, m_deviceShared.m_channel); + m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); + } +} - // send to sink buddies - const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); - std::vector::const_iterator itSink = sinkBuddies.begin(); +// Forward sample rate and frequency to self and Rx buddies +void USRPInput::forwardChangeRxDSP() +{ + qDebug("USRPInput::forwardChangeRxDSP"); - for (; itSink != sinkBuddies.end(); ++itSink) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true); - (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); - } + // send to self first + forwardChangeOwnDSP(); - // send to GUI so it can see master clock rate and if actual rate differs - if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true); - m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); - } - } - else if (forwardChangeRxDSP) - { - qDebug("USRPInput::applySettings: forward change to Rx buddies"); + // send to source buddies + const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); + std::vector::const_iterator itSource = sourceBuddies.begin(); - int sampleRate = m_settings.m_devSampleRate/(1<getSamplingDeviceInputMessageQueue()->push(report); + } +} - // send to self first - DSPSignalNotification *notif = new DSPSignalNotification(sampleRate, m_settings.m_centerFrequency); - m_deviceAPI->getDeviceEngineInputMessageQueue()->push(notif); +// Forward sample rate and frequency to self only +void USRPInput::forwardChangeOwnDSP() +{ + int sampleRate = m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); +} - // send to source buddies - const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); - std::vector::const_iterator itSource = sourceBuddies.begin(); +// Forward sample rate and frequency to self and GUI, but not buddies (E.g. when changed by a buddy) +void USRPInput::notifySampleRateChange() +{ + forwardChangeOwnDSP(); - for (; itSource != sourceBuddies.end(); ++itSource) - { - DeviceUSRPShared::MsgReportBuddyChange *report = DeviceUSRPShared::MsgReportBuddyChange::create( - m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true); - (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); - } - } - else if (forwardChangeOwnDSP) - { - qDebug("USRPInput::applySettings: forward change to self only"); + if (getMessageQueueToGUI()) + { + DeviceUSRPShared::MsgReportBuddyChange *reportToGUI = DeviceUSRPShared::MsgReportBuddyChange::create( + m_settings.m_devSampleRate, m_settings.m_centerFrequency, m_settings.m_loOffset, m_settings.m_masterClockRate, true); + getMessageQueueToGUI()->push(reportToGUI); + } +} - int sampleRate = m_settings.m_devSampleRate/(1<getDeviceEngineInputMessageQueue()->push(notif); - } +// Forward clock source to GUI and all buddies +void USRPInput::forwardClockSource() +{ + // send to GUI in case requested clock isn't detected + if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) + { + DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( + m_settings.m_clockSource); + m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); + } - if (forwardClockSource) - { - // get what clock is actually set, in case requested clock couldn't be set - if (m_deviceShared.m_deviceParams->getDevice()) - { - try - { - m_settings.m_clockSource = QString::fromStdString(m_deviceShared.m_deviceParams->getDevice()->get_clock_source(0)); - qDebug() << "USRPInput::applySettings: clock source is " << m_settings.m_clockSource; - } - catch (std::exception &e) - { - qDebug() << "USRPInput::applySettings: could not get clock source"; - } - } + // send to source buddies + const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); + std::vector::const_iterator itSource = sourceBuddies.begin(); - // send to GUI in case requested clock isn't detected - if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) - { - DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( - m_settings.m_clockSource); - m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(report); - } + for (; itSource != sourceBuddies.end(); ++itSource) + { + DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( + m_settings.m_clockSource); + (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); + } - // send to source buddies - const std::vector& sourceBuddies = m_deviceAPI->getSourceBuddies(); - std::vector::const_iterator itSource = sourceBuddies.begin(); + // send to sink buddies + const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); + std::vector::const_iterator itSink = sinkBuddies.begin(); - for (; itSource != sourceBuddies.end(); ++itSource) - { - DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( - m_settings.m_clockSource); - (*itSource)->getSamplingDeviceInputMessageQueue()->push(report); - } + for (; itSink != sinkBuddies.end(); ++itSink) + { + DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( + m_settings.m_clockSource); + (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); + } +} - // send to sink buddies - const std::vector& sinkBuddies = m_deviceAPI->getSinkBuddies(); - std::vector::const_iterator itSink = sinkBuddies.begin(); +// Forward device info to our GUI and the GUIs of all buddies +void USRPInput::forwardDeviceInfo(bool temperatureValid, float temperature) +{ + if (m_deviceAPI->getSamplingDeviceGUIMessageQueue()) { + m_deviceAPI->getSamplingDeviceGUIMessageQueue()->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); + } - for (; itSink != sinkBuddies.end(); ++itSink) - { - DeviceUSRPShared::MsgReportClockSourceChange *report = DeviceUSRPShared::MsgReportClockSourceChange::create( - m_settings.m_clockSource); - (*itSink)->getSamplingDeviceInputMessageQueue()->push(report); - } + for (const auto& buddy : m_deviceAPI->getSourceBuddies()) + { + if (buddy->getSamplingDeviceGUIMessageQueue()) { + buddy->getSamplingDeviceGUIMessageQueue()->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); } - - return true; } - catch (std::exception &e) + + for (const auto& buddy : m_deviceAPI->getSinkBuddies()) { - qDebug() << "USRPInput::applySettings: exception: " << e.what(); - return false; + if (buddy->getSamplingDeviceGUIMessageQueue()) { + buddy->getSamplingDeviceGUIMessageQueue()->push(DeviceUSRPShared::MsgReportDeviceInfo::create(temperatureValid, temperature)); + } } } @@ -1192,7 +1317,7 @@ void USRPInput::webapiUpdateDeviceSettings( settings.m_iqCorrection = response.getUsrpInputSettings()->getIqCorrection() != 0; } if (deviceSettingsKeys.contains("log2SoftDecim")) { - settings.m_log2SoftDecim = response.getUsrpInputSettings()->getLog2SoftDecim(); + settings.m_log2SoftDecim = qBound(0, response.getUsrpInputSettings()->getLog2SoftDecim(), 6); } if (deviceSettingsKeys.contains("lpfBW")) { settings.m_lpfBW = response.getUsrpInputSettings()->getLpfBw(); @@ -1312,7 +1437,9 @@ void USRPInput::webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response) quint32 overflows = 0; quint32 timeouts = 0; - if (m_streamId != nullptr) + QMutexLocker threadLocker(&m_threadMutex); + + if (m_usrpInputThread) { m_usrpInputThread->getStreamStatus(active, overflows, timeouts); success = true; diff --git a/plugins/samplesource/usrpinput/usrpinput.h b/plugins/samplesource/usrpinput/usrpinput.h index e0b232295..2fbdf577a 100644 --- a/plugins/samplesource/usrpinput/usrpinput.h +++ b/plugins/samplesource/usrpinput/usrpinput.h @@ -25,6 +25,7 @@ #include #include +#include #include #include @@ -247,6 +248,8 @@ private: QMutex m_mutex; USRPInputSettings m_settings; USRPInputThread* m_usrpInputThread; + QRecursiveMutex m_settingsMutex; //!< Protects m_settings, which is written in GUI thread and read in device engine thread in start() + QMutex m_threadMutex; //!< Protects thread pointer, for access from threads other than the device engine thread QString m_deviceDescription; bool m_running; DeviceUSRPShared m_deviceShared; @@ -259,13 +262,20 @@ private: bool openDevice(); void closeDevice(); - bool acquireChannel(); + bool acquireChannel(const USRPInputSettings& settings); void releaseChannel(); + DeviceUSRPParams *getBuddyDeviceParams() const; void suspendRxBuddies(); void resumeRxBuddies(); void suspendTxBuddies(); void resumeTxBuddies(); - bool applySettings(const USRPInputSettings& settings, const QList& settingsKeys, bool preGetStream, bool force = false); + bool applySettings(const USRPInputSettings& settings, const QList& settingsKeys, bool force = false); + void forwardChangeAllDSP(); + void forwardChangeRxDSP(); + void forwardChangeOwnDSP(); + void forwardClockSource(); + void notifySampleRateChange(); + void forwardDeviceInfo(bool temperatureValid, float temperature); void webapiFormatDeviceReport(SWGSDRangel::SWGDeviceReport& response); void webapiReverseSendSettings(const QList& deviceSettingsKeys, const USRPInputSettings& settings, bool force); void webapiReverseSendStartStop(bool start); diff --git a/plugins/samplesource/usrpinput/usrpinputgui.cpp b/plugins/samplesource/usrpinput/usrpinputgui.cpp index 1fd2552f5..4f912c86a 100644 --- a/plugins/samplesource/usrpinput/usrpinputgui.cpp +++ b/plugins/samplesource/usrpinput/usrpinputgui.cpp @@ -45,7 +45,7 @@ USRPInputGUI::USRPInputGUI(DeviceUISet *deviceUISet, QWidget* parent) : m_doApplySettings(true), m_forceSettings(true), m_statusCounter(0), - m_deviceStatusCounter(0) + m_deviceStatusCounter(10) // Get device info on first status update { m_deviceUISet = deviceUISet; setAttribute(Qt::WA_DeleteOnClose, true); @@ -58,9 +58,8 @@ USRPInputGUI::USRPInputGUI(DeviceUISet *deviceUISet, QWidget* parent) : float minF, maxF; - m_usrpInput->getLORange(minF, maxF); ui->centerFrequency->setColorMapper(ColorMapper(ColorMapper::GrayGold)); - ui->centerFrequency->setValueRange(7, ((uint32_t) minF)/1000, ((uint32_t) maxF)/1000); // frequency dial is in kHz + updateFrequencyLimits(); // frequency dial is in kHz m_usrpInput->getSRRange(minF, maxF); ui->sampleRate->setColorMapper(ColorMapper(ColorMapper::GrayGreenYellow)); @@ -168,7 +167,10 @@ bool USRPInputGUI::handleMessage(const Message& message) if (cfg.getForce()) { m_settings = cfg.getSettings(); } else { + // Don't overwrite edits that haven't been sent yet + USRPInputSettings pending = m_settings; m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); + m_settings.applySettings(m_settingsKeys, pending); } blockApplySettings(true); @@ -182,9 +184,16 @@ bool USRPInputGUI::handleMessage(const Message& message) m_settings.m_masterClockRate = report.getMasterClockRate(); if (report.getRxElseTx()) { - m_settings.m_devSampleRate = report.getDevSampleRate(); - m_settings.m_centerFrequency = report.getCenterFrequency(); - m_settings.m_loOffset = report.getLOOffset(); + // Don't overwrite edits that haven't been sent yet + if (!m_settingsKeys.contains("devSampleRate")) { + m_settings.m_devSampleRate = report.getDevSampleRate(); + } + if (!m_settingsKeys.contains("centerFrequency")) { + m_settings.m_centerFrequency = report.getCenterFrequency(); + } + if (!m_settingsKeys.contains("loOffset")) { + m_settings.m_loOffset = report.getLOOffset(); + } } blockApplySettings(true); @@ -193,6 +202,18 @@ bool USRPInputGUI::handleMessage(const Message& message) return true; } + else if (DeviceUSRPShared::MsgReportDeviceInfo::match(message)) + { + DeviceUSRPShared::MsgReportDeviceInfo& report = (DeviceUSRPShared::MsgReportDeviceInfo&) message; + + if (report.getTemperatureValid()) { + ui->temperatureText->setText(tr("%1C").arg(QString::number(report.getTemperature(), 'f', 0))); + } + // Hide if device doesn't have a temperature sensor + ui->temperatureText->setVisible(report.getTemperatureValid()); + + return true; + } else if (DeviceUSRPShared::MsgReportClockSourceChange::match(message)) { qDebug("USRPInputGUI::handleMessage MsgReportClockSourceChange"); @@ -209,6 +230,10 @@ bool USRPInputGUI::handleMessage(const Message& message) { USRPInput::MsgReportStreamInfo& report = (USRPInput::MsgReportStreamInfo&) message; + // Accumulate statistics, as the counts reported can be reset while running + m_overrunStats.update(report.getSuccess(), report.getOverruns()); + m_timeoutStats.update(report.getSuccess(), report.getTimeouts()); + if (report.getSuccess()) { if (report.getActive()) { @@ -217,13 +242,13 @@ bool USRPInputGUI::handleMessage(const Message& message) ui->streamStatusLabel->setStyleSheet("QLabel { background-color : blue; }"); } - if (report.getOverruns() > 0) { + if (m_overrunStats.getCount() > 0) { ui->overrunLabel->setStyleSheet("QLabel { background-color : red; }"); } else { ui->overrunLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); } - if (report.getTimeouts() > 0) { + if (m_timeoutStats.getCount() > 0) { ui->timeoutLabel->setStyleSheet("QLabel { background-color : red; }"); } else { ui->timeoutLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); @@ -234,6 +259,9 @@ bool USRPInputGUI::handleMessage(const Message& message) ui->streamStatusLabel->setStyleSheet("QLabel { background:rgb(79,79,79); }"); } + ui->overrunLabel->setToolTip(m_overrunStats.getToolTip("Red if overruns occurred. Cleared when restarting acquisition", "Overruns")); + ui->timeoutLabel->setToolTip(m_timeoutStats.getToolTip("Red if timeouts occurred. Cleared when restarting acquisition", "Timeouts")); + return true; } else if (USRPInput::MsgStartStop::match(message)) @@ -298,7 +326,10 @@ void USRPInputGUI::handleInputMessages() if (cfg.getForce()) { m_settings = cfg.getSettings(); } else { + // Don't overwrite edits that haven't been sent yet + USRPInputSettings pending = m_settings; m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); + m_settings.applySettings(m_settingsKeys, pending); } displaySettings(); @@ -500,6 +531,7 @@ void USRPInputGUI::updateStatus() } else { + // Only one GUI requests device info, which is then sent to all buddies if (m_deviceUISet->m_deviceAPI->isBuddyLeader()) { USRPInput::MsgGetDeviceInfo* message = USRPInput::MsgGetDeviceInfo::create(); diff --git a/plugins/samplesource/usrpinput/usrpinputgui.h b/plugins/samplesource/usrpinput/usrpinputgui.h index 1a5fa8107..d3e5166fd 100644 --- a/plugins/samplesource/usrpinput/usrpinputgui.h +++ b/plugins/samplesource/usrpinput/usrpinputgui.h @@ -24,6 +24,7 @@ #include #include "util/messagequeue.h" +#include "usrp/deviceusrpstreamstats.h" #include "usrpinput.h" @@ -68,6 +69,8 @@ private: bool m_forceSettings; int m_statusCounter; int m_deviceStatusCounter; + DeviceUSRPStreamStats m_overrunStats; + DeviceUSRPStreamStats m_timeoutStats; MessageQueue m_inputMessageQueue; void displaySettings(); diff --git a/plugins/samplesource/usrpinput/usrpinputgui.ui b/plugins/samplesource/usrpinput/usrpinputgui.ui index 4ed145cb6..4907d46a7 100644 --- a/plugins/samplesource/usrpinput/usrpinputgui.ui +++ b/plugins/samplesource/usrpinput/usrpinputgui.ui @@ -696,6 +696,25 @@
+ + + + + 24 + 0 + + + + Board temperature (degrees C) + + + - + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + diff --git a/plugins/samplesource/usrpinput/usrpinputsettings.cpp b/plugins/samplesource/usrpinput/usrpinputsettings.cpp index e4f913528..1439b0153 100644 --- a/plugins/samplesource/usrpinput/usrpinputsettings.cpp +++ b/plugins/samplesource/usrpinput/usrpinputsettings.cpp @@ -105,6 +105,7 @@ bool USRPInputSettings::deserialize(const QByteArray& data) d.readBool(2, &m_dcBlock, false); d.readBool(3, &m_iqCorrection, false); d.readU32(4, &m_log2SoftDecim, 0); + m_log2SoftDecim = m_log2SoftDecim > 6 ? 6 : m_log2SoftDecim; d.readFloat(5, &m_lpfBW, 1.5e6); d.readU32(6, &m_gain, 50); d.readString(7, &m_antennaPath, "TX/RX"); diff --git a/plugins/samplesource/usrpinput/usrpinputthread.cpp b/plugins/samplesource/usrpinput/usrpinputthread.cpp index aea4a2f74..889b9e285 100644 --- a/plugins/samplesource/usrpinput/usrpinputthread.cpp +++ b/plugins/samplesource/usrpinput/usrpinputthread.cpp @@ -18,37 +18,57 @@ #include #include +#include +#include #include #include +#include "usrp/deviceusrpparam.h" #include "usrpinputthread.h" +#include "usrpinput.h" -USRPInputThread::USRPInputThread(uhd::rx_streamer::sptr stream, size_t bufSamples, - SampleSinkFifo* sampleFifo, ReplayBuffer *replayBuffer, QObject* parent) : +USRPInputThread::USRPInputThread(DeviceUSRPParams *deviceParams, int channel, SampleSinkFifo* sampleFifo, + ReplayBuffer *replayBuffer, MessageQueue *reportQueue, QObject* parent) : QThread(parent), m_running(false), + m_started(false), + m_runStarted(false), m_packets(0), m_overflows(0), m_timeouts(0), - m_stream(stream), - m_bufSamples(bufSamples), - m_convertBuffer(bufSamples), + m_buf(nullptr), + m_bufSamples(0), m_sampleFifo(sampleFifo), m_replayBuffer(replayBuffer), - m_log2Decim(0) + m_log2Decim(0), + m_deviceParams(deviceParams), + m_channel(channel), + m_reportQueue(reportQueue), + m_detached(false) { setObjectName("USRPInput"); - // *2 as samples are I+Q - m_buf = new qint16[2*bufSamples]; - std::fill(m_buf, m_buf + 2*bufSamples, 0); + // Executes in the thread this object was created in (the device engine thread), not in run() + connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &USRPInputThread::handleInputMessages); } USRPInputThread::~USRPInputThread() { stopWork(); - delete m_buf; + delete[] m_buf; +} + +// Set stream once it has been created. Must be called before startWork() +void USRPInputThread::setStream(uhd::rx_streamer::sptr stream, size_t bufSamples) +{ + m_stream = stream; + m_bufSamples = bufSamples; + m_convertBuffer.resize(bufSamples); + delete[] m_buf; + // *2 as samples are I+Q + m_buf = new qint16[2*bufSamples]; + std::fill(m_buf, m_buf + 2*bufSamples, 0); } void USRPInputThread::issueStreamCmd(bool start) @@ -69,9 +89,21 @@ void USRPInputThread::issueStreamCmd(bool start) } } +// Release reference to stream, so it's destroyed before the device. Thread must be stopped. +void USRPInputThread::releaseStream() +{ + m_stream = nullptr; +} + void USRPInputThread::startWork() { - if (m_running) return; // return if running already + if (m_started) return; // return if running already + + if (!m_stream) + { + qWarning("USRPInputThread::startWork: no stream"); + return; + } try { @@ -90,17 +122,22 @@ void USRPInputThread::startWork() qDebug() << "USRPInputThread::startWork: exception: " << e.what(); } + // Wait for run() to start. Use a separate flag to m_running, as run() may exit immediately on error + m_runStarted = false; + m_started = true; m_startWaitMutex.lock(); start(); - while(!m_running) + while (!m_runStarted) { m_startWaiter.wait(&m_startWaitMutex, 100); + } m_startWaitMutex.unlock(); } void USRPInputThread::stopWork() { - if (!m_running) return; // return if not running + if (!m_started) return; // return if not running + m_started = false; m_running = false; wait(); @@ -113,18 +150,21 @@ void USRPInputThread::stopWork() // Clear out any data left in the stream, otherwise we'll get an // exception 'recv buffer smaller than vrt packet offset' when restarting + // Limit number of iterations, in case device has been disconnected + const int maxFlushes = 1000; md.end_of_burst = false; md.error_code = uhd::rx_metadata_t::ERROR_CODE_NONE; - while (!md.end_of_burst && (md.error_code != uhd::rx_metadata_t::ERROR_CODE_TIMEOUT)) + for (int i = 0; (i < maxFlushes) && !md.end_of_burst && (md.error_code != uhd::rx_metadata_t::ERROR_CODE_TIMEOUT); i++) { try { md.reset(); - m_stream->recv(m_buf, m_bufSamples, md); + recv(md, 0.1); } catch (std::exception& e) { - qDebug() << "USRPInputThread::stopWork: exception ignored while flushing buffers: " << e.what(); + qDebug() << "USRPInputThread::stopWork: exception while flushing buffers: " << e.what(); + break; } } @@ -136,6 +176,21 @@ void USRPInputThread::stopWork() } } +// Receive samples into m_buf. recv() calls for different streams on the same device +// may need to be serialised (See DeviceUSRPRecvLock) +size_t USRPInputThread::recv(uhd::rx_metadata_t& md, double timeout) +{ + if (m_deviceParams) + { + std::lock_guard recvLock(m_deviceParams->m_recvLock); + return m_stream->recv(m_buf, m_bufSamples, md, timeout); + } + else + { + return m_stream->recv(m_buf, m_bufSamples, md, timeout); + } +} + void USRPInputThread::setLog2Decimation(unsigned int log2_decim) { m_log2Decim = log2_decim; @@ -145,7 +200,11 @@ void USRPInputThread::run() { uhd::rx_metadata_t md; + // Higher priority, so streaming isn't delayed by other threads + DeviceUSRP::setStreamingThreadPriority(); + m_running = true; + m_runStarted = true; m_startWaiter.wakeAll(); try @@ -153,7 +212,7 @@ void USRPInputThread::run() while (m_running) { md.reset(); - const size_t samples_received = m_stream->recv(m_buf, m_bufSamples, md); + const size_t samples_received = recv(md, DeviceUSRP::m_streamTimeout); m_packets++; if (samples_received != m_bufSamples) @@ -260,3 +319,323 @@ void USRPInputThread::getStreamStatus(bool& active, quint32& overflows, quint32& overflows = m_overflows; timeouts = m_timeouts; } + + +// Stop applying settings to the device and sending reports, waiting for any settings being applied to complete. +// Used when stopping from a thread other than the device engine thread (E.g. when USRPInput is being destroyed) +void USRPInputThread::detach() +{ + QMutexLocker mutexLocker(&m_configMutex); + m_detached = true; +} + +void USRPInputThread::handleInputMessages() +{ + QMutexLocker mutexLocker(&m_configMutex); + Message* message; + + // Merge consecutive configuration messages, so we only apply the latest settings. + // This avoids a backlog of slow device calls (E.g. when a slider is dragged) + bool pendingConfig = false; + USRPInputSettings settings; + QList settingsKeys; + bool force = false; + + auto applyPendingConfig = [&]() { + if (pendingConfig) + { + if (settingsKeys.contains("log2SoftDecim") || force) { + setLog2Decimation(settings.m_log2SoftDecim); + } + applyDeviceSettings(m_deviceParams, m_channel, settings, settingsKeys, force, true, true, m_reportQueue); + pendingConfig = false; + settingsKeys.clear(); + force = false; + } + }; + + while ((message = m_inputMessageQueue.pop()) != nullptr) + { + if (m_detached) + { + delete message; + continue; + } + + if (USRPInput::MsgConfigureUSRP::match(*message)) + { + const USRPInput::MsgConfigureUSRP& conf = (const USRPInput::MsgConfigureUSRP&) *message; + + if (conf.getForce() || !pendingConfig) + { + settings = conf.getSettings(); + settingsKeys = conf.getSettingsKeys(); + force = force || conf.getForce(); + } + else + { + settings.applySettings(conf.getSettingsKeys(), conf.getSettings()); + for (const auto& key : conf.getSettingsKeys()) + { + if (!settingsKeys.contains(key)) { + settingsKeys.append(key); + } + } + } + pendingConfig = true; + } + else + { + // Keep ordering with respect to other messages + applyPendingConfig(); + + if (DeviceUSRPShared::MsgReadDeviceSampleRate::match(*message)) { + readBackSampleRate(); + } else { + qDebug("%s: unhandled message: %s", Q_FUNC_INFO, message->getIdentifier()); + } + } + + delete message; + } + + if (!m_detached) { + applyPendingConfig(); + } +} + +void USRPInputThread::readBackSampleRate() +{ + uhd::usrp::multi_usrp::sptr device = m_deviceParams ? m_deviceParams->getDevice() : nullptr; + + if (!device) { + return; + } + + QMutexLocker mutexLocker(&m_deviceParams->m_mutex); + + try + { + double sampleRate = DeviceUSRP::getSampleRate(device, true, m_channel); + double masterClockRate = device->get_master_clock_rate(); + + if (m_reportQueue) { + m_reportQueue->push(DeviceUSRPShared::MsgReportDeviceSettings::create(true, sampleRate, masterClockRate, false, "", false)); + } + } + catch (std::exception& e) + { + qDebug() << "USRPInputThread::readBackSampleRate: exception: " << e.what(); + } +} + +// Apply settings to the device and send what was actually set to reportQueue. +// applyChannelSettings - apply settings that require the channel to be acquired. If false, only GPIO settings are applied. +// applyBandwidth - apply LPF bandwidth, which shouldn't be applied until after the stream is created +void USRPInputThread::applyDeviceSettings( + DeviceUSRPParams *deviceParams, + int channel, + const USRPInputSettings& settings, + const QList& settingsKeys, + bool force, + bool applyChannelSettings, + bool applyBandwidth, + MessageQueue *reportQueue) +{ + uhd::usrp::multi_usrp::sptr device = deviceParams ? deviceParams->getDevice() : nullptr; + + if (!device) { + return; + } + + QMutexLocker mutexLocker(&deviceParams->m_mutex); + bool reapplySomeSettings = false; + bool checkRates = false; + bool checkClockSource = false; + + // Apply each setting separately, so a failure (E.g. an antenna name not supported by the + // daughterboard) doesn't prevent other settings from being applied + auto apply = [](const char *what, const std::function& func) { + try { + func(); + } catch (std::exception &e) { + qWarning() << "USRPInputThread::applyDeviceSettings: failed to set" << what << ":" << e.what(); + } + }; + + auto setGain = [&]() { + if (settings.m_gainMode == USRPInputSettings::GAIN_AUTO) + { + try { + device->set_rx_agc(true, channel); + qDebug() << "USRPInputThread::applyDeviceSettings: AGC enabled for channel " << channel; + } catch (uhd::not_implemented_error &e) { + qDebug() << "USRPInputThread::applyDeviceSettings: AGC not implemented on this radio. Please set to manual."; + } + } + else + { + try { + device->set_rx_agc(false, channel); + } catch (uhd::not_implemented_error &e) { + // Ignore + } + device->set_rx_gain(settings.m_gain, channel); + qDebug() << "USRPInputThread::applyDeviceSettings: gain set to " << settings.m_gain << " for channel " << channel; + } + }; + + if (applyChannelSettings) + { + if (settingsKeys.contains("clockSource") || force) + { + try + { + device->set_clock_source(settings.m_clockSource.toStdString(), 0); + qDebug() << "USRPInputThread::applyDeviceSettings: clock set to " << settings.m_clockSource; + } + catch (std::exception &e) + { + // An exception will be thrown if the clock is not detected + // however, get_clock_source called below will still say the clock has is set + qCritical() << "USRPInputThread::applyDeviceSettings: could not set clock " << settings.m_clockSource; + // So, default back to internal + apply("clock source to internal", [&]() { device->set_clock_source("internal", 0); }); + } + // Report actual clock source, in case requested clock couldn't be set + checkClockSource = true; + reapplySomeSettings = true; + } + + if (settingsKeys.contains("devSampleRate") || force) + { + apply("sample rate", [&]() { + DeviceUSRP::setSampleRate(device, true, channel, settings.m_devSampleRate); + qDebug("USRPInputThread::applyDeviceSettings: sample rate set to %d", settings.m_devSampleRate); + }); + checkRates = true; + reapplySomeSettings = true; + } + + if (settingsKeys.contains("centerFrequency") + || settingsKeys.contains("loOffset") + || settingsKeys.contains("transverterMode") + || settingsKeys.contains("transverterDeltaFrequency") + || force) + { + apply("frequency", [&]() { + qint64 deviceCenterFrequency = settings.m_centerFrequency; + deviceCenterFrequency -= settings.m_transverterMode ? settings.m_transverterDeltaFrequency : 0; + deviceCenterFrequency = deviceCenterFrequency < 0 ? 0 : deviceCenterFrequency; + uhd::tune_request_t tuneRequest = settings.m_loOffset != 0 + ? uhd::tune_request_t(deviceCenterFrequency, settings.m_loOffset) + : uhd::tune_request_t(deviceCenterFrequency); + device->set_rx_freq(tuneRequest, channel); + qDebug("USRPInputThread::applyDeviceSettings: frequency set to %lld with LO offset %d", deviceCenterFrequency, settings.m_loOffset); + }); + } + + if (settingsKeys.contains("dcBlock") || force) { + apply("DC offset correction", [&]() { device->set_rx_dc_offset(settings.m_dcBlock, channel); }); + } + + if (settingsKeys.contains("iqCorrection") || force) { + apply("IQ correction", [&]() { device->set_rx_iq_balance(settings.m_iqCorrection, channel); }); + } + + if (settingsKeys.contains("gainMode") || settingsKeys.contains("gain") || force) { + apply("gain", setGain); + } + + if (applyBandwidth && (settingsKeys.contains("lpfBW") || force)) + { + apply("LPF bandwidth", [&]() { + device->set_rx_bandwidth(settings.m_lpfBW, channel); + qDebug("USRPInputThread::applyDeviceSettings: LPF BW: %f for channel %d", settings.m_lpfBW, channel); + }); + } + + if (settingsKeys.contains("antennaPath") || force) + { + apply("antenna", [&]() { + device->set_rx_antenna(settings.m_antennaPath.toStdString(), channel); + qDebug("USRPInputThread::applyDeviceSettings: antenna set to %s on channel %d", qPrintable(settings.m_antennaPath), channel); + }); + } + } + + const std::string gpioBank = "FP0"; // Front Panel GPIO + + if (settingsKeys.contains("gpioDir") || force) + { + apply("GPIO direction", [&]() { + std::vector banks = device->get_gpio_banks(0); + + if (std::find(banks.begin(), banks.end(), gpioBank) != banks.end()) + { + device->set_gpio_attr(gpioBank, "CTRL", ~settings.m_gpioDir, 0xff); // 0 for GPIO, 1 for ATR + device->set_gpio_attr(gpioBank, "DDR", settings.m_gpioDir, 0xff); // 0 for input, 1 for output + qDebug() << "USRPInputThread::applyDeviceSettings: set GPIO dir to" << settings.m_gpioDir; + } + }); + } + + if (settingsKeys.contains("gpioPins") || force) + { + apply("GPIO pins", [&]() { + std::vector banks = device->get_gpio_banks(0); + + if (std::find(banks.begin(), banks.end(), gpioBank) != banks.end()) + { + device->set_gpio_attr(gpioBank, "OUT", settings.m_gpioPins, 0xff); + qDebug() << "USRPInputThread::applyDeviceSettings: set GPIO pins to" << settings.m_gpioPins; + } + }); + } + + if (reapplySomeSettings && applyBandwidth) + { + // Need to re-set bandwidth (and AGC / gain for Rx) after changing sample rate or clock source + apply("LPF bandwidth", [&]() { device->set_rx_bandwidth(settings.m_lpfBW, channel); }); + apply("gain", setGain); + } + + // Report what was actually set, so USRPInput can update its settings and inform buddies and GUI + double sampleRate = 0.0; + double masterClockRate = 0.0; + QString clockSource; + + if (checkRates) + { + try + { + // Check if requested rate could actually be met and what master clock rate we ended up with + sampleRate = DeviceUSRP::getSampleRate(device, true, channel); + masterClockRate = device->get_master_clock_rate(); + qDebug("USRPInputThread::applyDeviceSettings: actual sample rate %f master_clock_rate %f", sampleRate, masterClockRate); + } + catch (std::exception &e) + { + qDebug() << "USRPInputThread::applyDeviceSettings: could not get sample rate: " << e.what(); + checkRates = false; + } + } + + if (checkClockSource) + { + try + { + clockSource = QString::fromStdString(device->get_clock_source(0)); + qDebug() << "USRPInputThread::applyDeviceSettings: clock source is " << clockSource; + } + catch (std::exception &e) + { + qDebug() << "USRPInputThread::applyDeviceSettings: could not get clock source: " << e.what(); + checkClockSource = false; + } + } + + if ((checkRates || checkClockSource) && reportQueue) { + reportQueue->push(DeviceUSRPShared::MsgReportDeviceSettings::create(checkRates, sampleRate, masterClockRate, checkClockSource, clockSource, true)); + } +} diff --git a/plugins/samplesource/usrpinput/usrpinputthread.h b/plugins/samplesource/usrpinput/usrpinputthread.h index 95e2c1380..6979dc380 100644 --- a/plugins/samplesource/usrpinput/usrpinputthread.h +++ b/plugins/samplesource/usrpinput/usrpinputthread.h @@ -22,6 +22,8 @@ #ifndef PLUGINS_SAMPLESOURCE_USRPINPUT_USRPINPUTTHREAD_H_ #define PLUGINS_SAMPLESOURCE_USRPINPUT_USRPINPUTTHREAD_H_ +#include + #include #include #include @@ -32,30 +34,57 @@ #include "dsp/samplesinkfifo.h" #include "dsp/decimators.h" #include "dsp/replaybuffer.h" +#include "util/messagequeue.h" #include "usrp/deviceusrpshared.h" #include "usrp/deviceusrp.h" - +#include "usrpinputsettings.h" + +/** + * Receives samples from the device in its own thread (run()). + * + * Also applies device settings, which can take a long time (E.g. sample rate, clock source and bandwidth), + * via its input message queue, so they don't block the GUI thread. As this object is created in + * USRPInput::start(), which is called from the device engine thread, its slots execute in the device + * engine thread, which is also where the channel is acquired and released, so these can't race. + */ class USRPInputThread : public QThread, public DeviceUSRPShared::ThreadInterface { Q_OBJECT public: - USRPInputThread(uhd::rx_streamer::sptr stream, size_t bufSamples, SampleSinkFifo* sampleFifo, - ReplayBuffer *replayBuffer, QObject* parent = 0); + USRPInputThread(DeviceUSRPParams *deviceParams, int channel, SampleSinkFifo* sampleFifo, + ReplayBuffer *replayBuffer, MessageQueue *reportQueue, QObject* parent = nullptr); ~USRPInputThread(); + void setStream(uhd::rx_streamer::sptr stream, size_t bufSamples); + void releaseStream(); virtual void startWork(); virtual void stopWork(); virtual void setDeviceSampleRate(int sampleRate) { (void) sampleRate; } - virtual bool isRunning() { return m_running; } + virtual bool isRunning() { return m_started; } void setLog2Decimation(unsigned int log2_decim); void getStreamStatus(bool& active, quint32& overflows, quint32& m_timeouts); void issueStreamCmd(bool start); + size_t recv(uhd::rx_metadata_t& md, double timeout); + MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } + void detach(); + + static void applyDeviceSettings( + DeviceUSRPParams *deviceParams, + int channel, + const USRPInputSettings& settings, + const QList& settingsKeys, + bool force, + bool applyChannelSettings, + bool applyBandwidth, + MessageQueue *reportQueue); private: QMutex m_startWaitMutex; QWaitCondition m_startWaiter; - bool m_running; + std::atomic m_running; //!< Set while run() loop should continue + std::atomic m_started; //!< Set from startWork() to stopWork() + std::atomic m_runStarted; //!< Set when run() has started quint64 m_packets; quint32 m_overflows; @@ -66,16 +95,25 @@ private: size_t m_bufSamples; SampleVector m_convertBuffer; SampleSinkFifo* m_sampleFifo; - ReplayBuffer *m_replayBuffer; + ReplayBuffer *m_replayBuffer; - unsigned int m_log2Decim; // soft decimation + std::atomic m_log2Decim; // soft decimation Decimators m_decimatorsIQ; + DeviceUSRPParams *m_deviceParams; + int m_channel; + MessageQueue *m_reportQueue; //!< Where to send MsgReportDeviceSettings (USRPInput's input queue) + MessageQueue m_inputMessageQueue; //!< Settings to apply to the device + QMutex m_configMutex; //!< Held while applying settings, so detach() can wait for it to complete + bool m_detached; //!< When set, no longer access device or report queue + void run(); void callbackIQ(const qint16* buf, qint32 len); -}; - + void readBackSampleRate(); +private slots: + void handleInputMessages(); +}; #endif /* PLUGINS_SAMPLESOURCE_USRPINPUT_USRPINPUTTHREAD_H_ */ diff --git a/sdrbase/resources/webapi/doc/swagger/include/DeviceReports.yaml b/sdrbase/resources/webapi/doc/swagger/include/DeviceReports.yaml index 19918e64c..653dbb41e 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/DeviceReports.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/DeviceReports.yaml @@ -97,6 +97,9 @@ DeviceReport: usrpOutputReport: $ref: "/doc/swagger/include/USRP.yaml#/USRPOutputReport" description: "Usrp output report data for Device." + usrpMIMOReport: + $ref: "/doc/swagger/include/USRP.yaml#/USRPMIMOReport" + description: "USRP MIMO report data for Device." xtrxInputReport: $ref: "/doc/swagger/include/Xtrx.yaml#/XtrxInputReport" description: "Xtrx input report data for Device." diff --git a/sdrbase/resources/webapi/doc/swagger/include/DeviceSettings.yaml b/sdrbase/resources/webapi/doc/swagger/include/DeviceSettings.yaml index 57a03a71b..1b9b975b0 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/DeviceSettings.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/DeviceSettings.yaml @@ -142,6 +142,9 @@ DeviceSettings: usrpOutputSettings: $ref: "/doc/swagger/include/USRP.yaml#/USRPOutputSettings" description: "Usrp output settings configuration for Device." + usrpMIMOSettings: + $ref: "/doc/swagger/include/USRP.yaml#/USRPMIMOSettings" + description: "USRP MIMO settings configuration for Device." xtrxInputSettings: $ref: "/doc/swagger/include/Xtrx.yaml#/XtrxInputSettings" description: "Xtrx input settings configuration for Device." diff --git a/sdrbase/resources/webapi/doc/swagger/include/USRP.yaml b/sdrbase/resources/webapi/doc/swagger/include/USRP.yaml index b48947103..d665da467 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/USRP.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/USRP.yaml @@ -178,3 +178,158 @@ USRPOutputReport: droppedPacketsCount: type: integer description: "Number of dropped packets." + +USRPMIMOSettings: + description: USRP + properties: + title: + type: string + description: "User-visible title." + devSampleRate: + type: integer + description: "Device I/Q sample rate in samples per second before software decimation or interpolation. Common to Rx and Tx." + clockSource: + type: string + description: "Clock source (E.g. internal, external or gpsdo)." + gpioDir: + type: integer + description: "GPIO direction bit mask, with one bit per pin (0 for ATR, 1 for output)." + gpioPins: + type: integer + description: "GPIO pin-state bit mask, with one bit per pin." + rxCenterFrequency: + type: integer + format: int64 + description: "Rx center frequency in Hz." + rxLOOffset: + type: integer + description: "Rx LO offset in Hz. The LO is offset from the center frequency by this amount and a digital NCO is used to compensate." + log2SoftDecim: + type: integer + description: "Base-2 exponent of the software decimation factor." + rxLpfBW: + type: integer + description: "Rx analog low-pass filter bandwidth in Hz." + dcBlock: + type: integer + description: "Enable Rx DC offset correction (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + iqCorrection: + type: integer + description: "Enable Rx IQ imbalance correction (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + rxTransverterMode: + type: integer + description: "Enable Rx transverter frequency translation (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + rxTransverterDeltaFrequency: + type: integer + format: int64 + description: "Frequency translation applied in Rx transverter mode in Hz." + rx0GainMode: + type: integer + description: "Rx channel 0 gain mode (0 automatic, 1 manual)." + minimum: 0 + maximum: 1 + rx0Gain: + type: integer + description: "Rx channel 0 gain in dB." + rx0AntennaPath: + type: string + description: "Rx channel 0 antenna path." + rx1GainMode: + type: integer + description: "Rx channel 1 gain mode (0 automatic, 1 manual)." + minimum: 0 + maximum: 1 + rx1Gain: + type: integer + description: "Rx channel 1 gain in dB." + rx1AntennaPath: + type: string + description: "Rx channel 1 antenna path." + txCenterFrequency: + type: integer + format: int64 + description: "Tx center frequency in Hz." + txLOOffset: + type: integer + description: "Tx LO offset in Hz. The LO is offset from the center frequency by this amount and a digital NCO is used to compensate." + log2SoftInterp: + type: integer + description: "Base-2 exponent of the software interpolation factor." + txLpfBW: + type: integer + description: "Tx analog low-pass filter bandwidth in Hz." + txTransverterMode: + type: integer + description: "Enable Tx transverter frequency translation (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + txTransverterDeltaFrequency: + type: integer + format: int64 + description: "Frequency translation applied in Tx transverter mode in Hz." + tx0Gain: + type: integer + description: "Tx channel 0 gain in dB." + tx0AntennaPath: + type: string + description: "Tx channel 0 antenna path." + tx1Gain: + type: integer + description: "Tx channel 1 gain in dB." + tx1AntennaPath: + type: string + description: "Tx channel 1 antenna path." + useReverseAPI: + type: integer + description: "Synchronize with reverse API (1 for yes, 0 for no)." + minimum: 0 + maximum: 1 + reverseAPIAddress: + type: string + description: "IPv4 address or host name of the reverse API peer." + reverseAPIPort: + type: integer + description: "TCP port of the reverse API peer." + minimum: 1 + maximum: 65535 + reverseAPIDeviceIndex: + type: integer + description: "Device-set index used by the reverse API peer." + +USRPMIMOReport: + description: USRP + properties: + success: + type: integer + description: "1 if info was successfully retrieved else 0" + rxStreamActive: + type: integer + description: "1 if Rx stream is active else 0" + rxOverrunCount: + type: integer + description: "Number of Rx stream overrun events." + rxTimeoutCount: + type: integer + description: "Number of Rx stream timeout events." + txStreamActive: + type: integer + description: "1 if Tx stream is active else 0" + txUnderrunCount: + type: integer + description: "Number of Tx stream underrun events." + txDroppedPacketsCount: + type: integer + description: "Number of Tx dropped packets." + masterClockRate: + type: integer + description: "Master clock rate (FPGA/RFIC sample rate) in samples per second." + temperature: + type: number + format: float + description: "Board temperature in degrees C, if the device has a temperature sensor." diff --git a/sdrbase/webapi/webapirequestmapper.cpp b/sdrbase/webapi/webapirequestmapper.cpp index 972d199f9..4e2f05646 100644 --- a/sdrbase/webapi/webapirequestmapper.cpp +++ b/sdrbase/webapi/webapirequestmapper.cpp @@ -5612,6 +5612,11 @@ bool WebAPIRequestMapper::getDeviceSettings( deviceSettings->setUsrpOutputSettings(new SWGSDRangel::SWGUSRPOutputSettings()); deviceSettings->getUsrpOutputSettings()->fromJsonObject(settingsJsonObject); } + else if (deviceSettingsKey == "usrpMIMOSettings") + { + deviceSettings->setUsrpMimoSettings(new SWGSDRangel::SWGUSRPMIMOSettings()); + deviceSettings->getUsrpMimoSettings()->fromJsonObject(settingsJsonObject); + } else if (deviceSettingsKey == "xtrxInputSettings") { deviceSettings->setXtrxInputSettings(new SWGSDRangel::SWGXtrxInputSettings()); @@ -6015,6 +6020,7 @@ void WebAPIRequestMapper::resetDeviceSettings(SWGSDRangel::SWGDeviceSettings& de deviceSettings.setTestSourceSettings(nullptr); deviceSettings.setUsrpInputSettings(nullptr); deviceSettings.setUsrpOutputSettings(nullptr); + deviceSettings.setUsrpMimoSettings(nullptr); } void WebAPIRequestMapper::resetDeviceReport(SWGSDRangel::SWGDeviceReport& deviceReport) @@ -6037,6 +6043,7 @@ void WebAPIRequestMapper::resetDeviceReport(SWGSDRangel::SWGDeviceReport& device deviceReport.setSdrPlayReport(nullptr); deviceReport.setSdrPlayV3Report(nullptr); deviceReport.setUsrpOutputReport(nullptr); + deviceReport.setUsrpMimoReport(nullptr); } void WebAPIRequestMapper::resetDeviceActions(SWGSDRangel::SWGDeviceActions& deviceActions) diff --git a/sdrbase/webapi/webapiutils.cpp b/sdrbase/webapi/webapiutils.cpp index 2ac8bcd57..4183a7588 100644 --- a/sdrbase/webapi/webapiutils.cpp +++ b/sdrbase/webapi/webapiutils.cpp @@ -151,6 +151,7 @@ const QMap WebAPIUtils::m_deviceIdToSettingsKey = { {"sdrangel.samplemimo.testmosync", "testMOSyncSettings"}, {"sdrangel.samplesource.usrp", "usrpInputSettings"}, {"sdrangel.samplesink.usrp", "usrpOutputSettings"}, + {"sdrangel.samplemimo.usrpmimo", "usrpMIMOSettings"}, {"sdrangel.samplesource.xtrx", "xtrxInputSettings"}, {"sdrangel.samplesink.xtrx", "xtrxOutputSettings"}, {"sdrangel.samplemimo.xtrxmimo", "xtrxMIMOSettings"} @@ -318,6 +319,7 @@ const QMap WebAPIUtils::m_mimoDeviceHwIdToSettingsKey = { {"MetisMISO", "metisMISOSettings"}, {"TestMI", "testMISettings"}, {"TestMOSync", "testMOSyncSettings"}, + {"USRP", "usrpMIMOSettings"}, {"XTRX", "xtrxMIMOSettings"} }; diff --git a/swagger/sdrangel/api/swagger/include/DeviceReports.yaml b/swagger/sdrangel/api/swagger/include/DeviceReports.yaml index d571ab71a..a06f82c6a 100644 --- a/swagger/sdrangel/api/swagger/include/DeviceReports.yaml +++ b/swagger/sdrangel/api/swagger/include/DeviceReports.yaml @@ -97,6 +97,9 @@ DeviceReport: usrpOutputReport: $ref: "http://swgserver:8081/api/swagger/include/USRP.yaml#/USRPOutputReport" description: "Usrp output report data for Device." + usrpMIMOReport: + $ref: "http://swgserver:8081/api/swagger/include/USRP.yaml#/USRPMIMOReport" + description: "USRP MIMO report data for Device." xtrxInputReport: $ref: "http://swgserver:8081/api/swagger/include/Xtrx.yaml#/XtrxInputReport" description: "Xtrx input report data for Device." diff --git a/swagger/sdrangel/api/swagger/include/DeviceSettings.yaml b/swagger/sdrangel/api/swagger/include/DeviceSettings.yaml index 3f8ad4f06..6bf06e56f 100644 --- a/swagger/sdrangel/api/swagger/include/DeviceSettings.yaml +++ b/swagger/sdrangel/api/swagger/include/DeviceSettings.yaml @@ -142,6 +142,9 @@ DeviceSettings: usrpOutputSettings: $ref: "http://swgserver:8081/api/swagger/include/USRP.yaml#/USRPOutputSettings" description: "Usrp output settings configuration for Device." + usrpMIMOSettings: + $ref: "http://swgserver:8081/api/swagger/include/USRP.yaml#/USRPMIMOSettings" + description: "USRP MIMO settings configuration for Device." xtrxInputSettings: $ref: "http://swgserver:8081/api/swagger/include/Xtrx.yaml#/XtrxInputSettings" description: "Xtrx input settings configuration for Device." diff --git a/swagger/sdrangel/api/swagger/include/USRP.yaml b/swagger/sdrangel/api/swagger/include/USRP.yaml index b48947103..d665da467 100644 --- a/swagger/sdrangel/api/swagger/include/USRP.yaml +++ b/swagger/sdrangel/api/swagger/include/USRP.yaml @@ -178,3 +178,158 @@ USRPOutputReport: droppedPacketsCount: type: integer description: "Number of dropped packets." + +USRPMIMOSettings: + description: USRP + properties: + title: + type: string + description: "User-visible title." + devSampleRate: + type: integer + description: "Device I/Q sample rate in samples per second before software decimation or interpolation. Common to Rx and Tx." + clockSource: + type: string + description: "Clock source (E.g. internal, external or gpsdo)." + gpioDir: + type: integer + description: "GPIO direction bit mask, with one bit per pin (0 for ATR, 1 for output)." + gpioPins: + type: integer + description: "GPIO pin-state bit mask, with one bit per pin." + rxCenterFrequency: + type: integer + format: int64 + description: "Rx center frequency in Hz." + rxLOOffset: + type: integer + description: "Rx LO offset in Hz. The LO is offset from the center frequency by this amount and a digital NCO is used to compensate." + log2SoftDecim: + type: integer + description: "Base-2 exponent of the software decimation factor." + rxLpfBW: + type: integer + description: "Rx analog low-pass filter bandwidth in Hz." + dcBlock: + type: integer + description: "Enable Rx DC offset correction (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + iqCorrection: + type: integer + description: "Enable Rx IQ imbalance correction (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + rxTransverterMode: + type: integer + description: "Enable Rx transverter frequency translation (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + rxTransverterDeltaFrequency: + type: integer + format: int64 + description: "Frequency translation applied in Rx transverter mode in Hz." + rx0GainMode: + type: integer + description: "Rx channel 0 gain mode (0 automatic, 1 manual)." + minimum: 0 + maximum: 1 + rx0Gain: + type: integer + description: "Rx channel 0 gain in dB." + rx0AntennaPath: + type: string + description: "Rx channel 0 antenna path." + rx1GainMode: + type: integer + description: "Rx channel 1 gain mode (0 automatic, 1 manual)." + minimum: 0 + maximum: 1 + rx1Gain: + type: integer + description: "Rx channel 1 gain in dB." + rx1AntennaPath: + type: string + description: "Rx channel 1 antenna path." + txCenterFrequency: + type: integer + format: int64 + description: "Tx center frequency in Hz." + txLOOffset: + type: integer + description: "Tx LO offset in Hz. The LO is offset from the center frequency by this amount and a digital NCO is used to compensate." + log2SoftInterp: + type: integer + description: "Base-2 exponent of the software interpolation factor." + txLpfBW: + type: integer + description: "Tx analog low-pass filter bandwidth in Hz." + txTransverterMode: + type: integer + description: "Enable Tx transverter frequency translation (1 enabled, 0 disabled)." + minimum: 0 + maximum: 1 + txTransverterDeltaFrequency: + type: integer + format: int64 + description: "Frequency translation applied in Tx transverter mode in Hz." + tx0Gain: + type: integer + description: "Tx channel 0 gain in dB." + tx0AntennaPath: + type: string + description: "Tx channel 0 antenna path." + tx1Gain: + type: integer + description: "Tx channel 1 gain in dB." + tx1AntennaPath: + type: string + description: "Tx channel 1 antenna path." + useReverseAPI: + type: integer + description: "Synchronize with reverse API (1 for yes, 0 for no)." + minimum: 0 + maximum: 1 + reverseAPIAddress: + type: string + description: "IPv4 address or host name of the reverse API peer." + reverseAPIPort: + type: integer + description: "TCP port of the reverse API peer." + minimum: 1 + maximum: 65535 + reverseAPIDeviceIndex: + type: integer + description: "Device-set index used by the reverse API peer." + +USRPMIMOReport: + description: USRP + properties: + success: + type: integer + description: "1 if info was successfully retrieved else 0" + rxStreamActive: + type: integer + description: "1 if Rx stream is active else 0" + rxOverrunCount: + type: integer + description: "Number of Rx stream overrun events." + rxTimeoutCount: + type: integer + description: "Number of Rx stream timeout events." + txStreamActive: + type: integer + description: "1 if Tx stream is active else 0" + txUnderrunCount: + type: integer + description: "Number of Tx stream underrun events." + txDroppedPacketsCount: + type: integer + description: "Number of Tx dropped packets." + masterClockRate: + type: integer + description: "Master clock rate (FPGA/RFIC sample rate) in samples per second." + temperature: + type: number + format: float + description: "Board temperature in degrees C, if the device has a temperature sensor." diff --git a/swagger/sdrangel/code/qt5/client/SWGDeviceReport.cpp b/swagger/sdrangel/code/qt5/client/SWGDeviceReport.cpp index d4b553c0b..1ca4faeed 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDeviceReport.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGDeviceReport.cpp @@ -88,6 +88,8 @@ SWGDeviceReport::SWGDeviceReport() { m_usrp_input_report_isSet = false; usrp_output_report = nullptr; m_usrp_output_report_isSet = false; + usrp_mimo_report = nullptr; + m_usrp_mimo_report_isSet = false; xtrx_input_report = nullptr; m_xtrx_input_report_isSet = false; xtrx_output_report = nullptr; @@ -166,6 +168,8 @@ SWGDeviceReport::init() { m_usrp_input_report_isSet = false; usrp_output_report = new SWGUSRPOutputReport(); m_usrp_output_report_isSet = false; + usrp_mimo_report = new SWGUSRPMIMOReport(); + m_usrp_mimo_report_isSet = false; xtrx_input_report = new SWGXtrxInputReport(); m_xtrx_input_report_isSet = false; xtrx_output_report = new SWGXtrxOutputReport(); @@ -268,6 +272,9 @@ SWGDeviceReport::cleanup() { if(usrp_output_report != nullptr) { delete usrp_output_report; } + if(usrp_mimo_report != nullptr) { + delete usrp_mimo_report; + } if(xtrx_input_report != nullptr) { delete xtrx_input_report; } @@ -356,6 +363,8 @@ SWGDeviceReport::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&usrp_output_report, pJson["usrpOutputReport"], "SWGUSRPOutputReport", "SWGUSRPOutputReport"); + ::SWGSDRangel::setValue(&usrp_mimo_report, pJson["usrpMIMOReport"], "SWGUSRPMIMOReport", "SWGUSRPMIMOReport"); + ::SWGSDRangel::setValue(&xtrx_input_report, pJson["xtrxInputReport"], "SWGXtrxInputReport", "SWGXtrxInputReport"); ::SWGSDRangel::setValue(&xtrx_output_report, pJson["xtrxOutputReport"], "SWGXtrxOutputReport", "SWGXtrxOutputReport"); @@ -472,6 +481,9 @@ SWGDeviceReport::asJsonObject() { if((usrp_output_report != nullptr) && (usrp_output_report->isSet())){ toJsonValue(QString("usrpOutputReport"), usrp_output_report, obj, QString("SWGUSRPOutputReport")); } + if((usrp_mimo_report != nullptr) && (usrp_mimo_report->isSet())){ + toJsonValue(QString("usrpMIMOReport"), usrp_mimo_report, obj, QString("SWGUSRPMIMOReport")); + } if((xtrx_input_report != nullptr) && (xtrx_input_report->isSet())){ toJsonValue(QString("xtrxInputReport"), xtrx_input_report, obj, QString("SWGXtrxInputReport")); } @@ -791,6 +803,16 @@ SWGDeviceReport::setUsrpOutputReport(SWGUSRPOutputReport* usrp_output_report) { this->m_usrp_output_report_isSet = true; } +SWGUSRPMIMOReport* +SWGDeviceReport::getUsrpMimoReport() { + return usrp_mimo_report; +} +void +SWGDeviceReport::setUsrpMimoReport(SWGUSRPMIMOReport* usrp_mimo_report) { + this->usrp_mimo_report = usrp_mimo_report; + this->m_usrp_mimo_report_isSet = true; +} + SWGXtrxInputReport* SWGDeviceReport::getXtrxInputReport() { return xtrx_input_report; @@ -936,6 +958,9 @@ SWGDeviceReport::isSet(){ if(usrp_output_report && usrp_output_report->isSet()){ isObjectUpdated = true; break; } + if(usrp_mimo_report && usrp_mimo_report->isSet()){ + isObjectUpdated = true; break; + } if(xtrx_input_report && xtrx_input_report->isSet()){ isObjectUpdated = true; break; } diff --git a/swagger/sdrangel/code/qt5/client/SWGDeviceReport.h b/swagger/sdrangel/code/qt5/client/SWGDeviceReport.h index 3c1a7c8da..2b8523e28 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDeviceReport.h +++ b/swagger/sdrangel/code/qt5/client/SWGDeviceReport.h @@ -51,6 +51,7 @@ #include "SWGSoapySDRReport.h" #include "SWGUSRPInputReport.h" #include "SWGUSRPOutputReport.h" +#include "SWGUSRPMIMOReport.h" #include "SWGXtrxInputReport.h" #include "SWGXtrxMIMOReport.h" #include "SWGXtrxOutputReport.h" @@ -164,6 +165,9 @@ public: SWGUSRPOutputReport* getUsrpOutputReport(); void setUsrpOutputReport(SWGUSRPOutputReport* usrp_output_report); + SWGUSRPMIMOReport* getUsrpMimoReport(); + void setUsrpMimoReport(SWGUSRPMIMOReport* usrp_mimo_report); + SWGXtrxInputReport* getXtrxInputReport(); void setXtrxInputReport(SWGXtrxInputReport* xtrx_input_report); @@ -273,6 +277,9 @@ private: SWGUSRPOutputReport* usrp_output_report; bool m_usrp_output_report_isSet; + SWGUSRPMIMOReport* usrp_mimo_report; + bool m_usrp_mimo_report_isSet; + SWGXtrxInputReport* xtrx_input_report; bool m_xtrx_input_report_isSet; diff --git a/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.cpp index 4bdf22929..07b55514c 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.cpp @@ -118,6 +118,8 @@ SWGDeviceSettings::SWGDeviceSettings() { m_usrp_input_settings_isSet = false; usrp_output_settings = nullptr; m_usrp_output_settings_isSet = false; + usrp_mimo_settings = nullptr; + m_usrp_mimo_settings_isSet = false; xtrx_input_settings = nullptr; m_xtrx_input_settings_isSet = false; xtrx_output_settings = nullptr; @@ -226,6 +228,8 @@ SWGDeviceSettings::init() { m_usrp_input_settings_isSet = false; usrp_output_settings = new SWGUSRPOutputSettings(); m_usrp_output_settings_isSet = false; + usrp_mimo_settings = new SWGUSRPMIMOSettings(); + m_usrp_mimo_settings_isSet = false; xtrx_input_settings = new SWGXtrxInputSettings(); m_xtrx_input_settings_isSet = false; xtrx_output_settings = new SWGXtrxOutputSettings(); @@ -371,6 +375,9 @@ SWGDeviceSettings::cleanup() { if(usrp_output_settings != nullptr) { delete usrp_output_settings; } + if(usrp_mimo_settings != nullptr) { + delete usrp_mimo_settings; + } if(xtrx_input_settings != nullptr) { delete xtrx_input_settings; } @@ -489,6 +496,8 @@ SWGDeviceSettings::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&usrp_output_settings, pJson["usrpOutputSettings"], "SWGUSRPOutputSettings", "SWGUSRPOutputSettings"); + ::SWGSDRangel::setValue(&usrp_mimo_settings, pJson["usrpMIMOSettings"], "SWGUSRPMIMOSettings", "SWGUSRPMIMOSettings"); + ::SWGSDRangel::setValue(&xtrx_input_settings, pJson["xtrxInputSettings"], "SWGXtrxInputSettings", "SWGXtrxInputSettings"); ::SWGSDRangel::setValue(&xtrx_output_settings, pJson["xtrxOutputSettings"], "SWGXtrxOutputSettings", "SWGXtrxOutputSettings"); @@ -650,6 +659,9 @@ SWGDeviceSettings::asJsonObject() { if((usrp_output_settings != nullptr) && (usrp_output_settings->isSet())){ toJsonValue(QString("usrpOutputSettings"), usrp_output_settings, obj, QString("SWGUSRPOutputSettings")); } + if((usrp_mimo_settings != nullptr) && (usrp_mimo_settings->isSet())){ + toJsonValue(QString("usrpMIMOSettings"), usrp_mimo_settings, obj, QString("SWGUSRPMIMOSettings")); + } if((xtrx_input_settings != nullptr) && (xtrx_input_settings->isSet())){ toJsonValue(QString("xtrxInputSettings"), xtrx_input_settings, obj, QString("SWGXtrxInputSettings")); } @@ -1119,6 +1131,16 @@ SWGDeviceSettings::setUsrpOutputSettings(SWGUSRPOutputSettings* usrp_output_sett this->m_usrp_output_settings_isSet = true; } +SWGUSRPMIMOSettings* +SWGDeviceSettings::getUsrpMimoSettings() { + return usrp_mimo_settings; +} +void +SWGDeviceSettings::setUsrpMimoSettings(SWGUSRPMIMOSettings* usrp_mimo_settings) { + this->usrp_mimo_settings = usrp_mimo_settings; + this->m_usrp_mimo_settings_isSet = true; +} + SWGXtrxInputSettings* SWGDeviceSettings::getXtrxInputSettings() { return xtrx_input_settings; @@ -1309,6 +1331,9 @@ SWGDeviceSettings::isSet(){ if(usrp_output_settings && usrp_output_settings->isSet()){ isObjectUpdated = true; break; } + if(usrp_mimo_settings && usrp_mimo_settings->isSet()){ + isObjectUpdated = true; break; + } if(xtrx_input_settings && xtrx_input_settings->isSet()){ isObjectUpdated = true; break; } diff --git a/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.h b/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.h index 7c6575a29..38de23227 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.h +++ b/swagger/sdrangel/code/qt5/client/SWGDeviceSettings.h @@ -66,6 +66,7 @@ #include "SWGTestSourceSettings.h" #include "SWGUSRPInputSettings.h" #include "SWGUSRPOutputSettings.h" +#include "SWGUSRPMIMOSettings.h" #include "SWGXtrxInputSettings.h" #include "SWGXtrxMIMOSettings.h" #include "SWGXtrxOutputSettings.h" @@ -224,6 +225,9 @@ public: SWGUSRPOutputSettings* getUsrpOutputSettings(); void setUsrpOutputSettings(SWGUSRPOutputSettings* usrp_output_settings); + SWGUSRPMIMOSettings* getUsrpMimoSettings(); + void setUsrpMimoSettings(SWGUSRPMIMOSettings* usrp_mimo_settings); + SWGXtrxInputSettings* getXtrxInputSettings(); void setXtrxInputSettings(SWGXtrxInputSettings* xtrx_input_settings); @@ -378,6 +382,9 @@ private: SWGUSRPOutputSettings* usrp_output_settings; bool m_usrp_output_settings_isSet; + SWGUSRPMIMOSettings* usrp_mimo_settings; + bool m_usrp_mimo_settings_isSet; + SWGXtrxInputSettings* xtrx_input_settings; bool m_xtrx_input_settings_isSet; diff --git a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h index 700df3d9f..8593198b9 100644 --- a/swagger/sdrangel/code/qt5/client/SWGModelFactory.h +++ b/swagger/sdrangel/code/qt5/client/SWGModelFactory.h @@ -404,6 +404,8 @@ #include "SWGUDPSourceSettings.h" #include "SWGUSRPInputReport.h" #include "SWGUSRPInputSettings.h" +#include "SWGUSRPMIMOReport.h" +#include "SWGUSRPMIMOSettings.h" #include "SWGUSRPOutputReport.h" #include "SWGUSRPOutputSettings.h" #include "SWGVORDemodReport.h" @@ -2378,6 +2380,16 @@ namespace SWGSDRangel { obj->init(); return obj; } + if(QString("SWGUSRPMIMOReport").compare(type) == 0) { + SWGUSRPMIMOReport *obj = new SWGUSRPMIMOReport(); + obj->init(); + return obj; + } + if(QString("SWGUSRPMIMOSettings").compare(type) == 0) { + SWGUSRPMIMOSettings *obj = new SWGUSRPMIMOSettings(); + obj->init(); + return obj; + } if(QString("SWGUSRPOutputReport").compare(type) == 0) { SWGUSRPOutputReport *obj = new SWGUSRPOutputReport(); obj->init(); diff --git a/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.cpp b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.cpp new file mode 100644 index 000000000..f76fef9d6 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.cpp @@ -0,0 +1,292 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +#include "SWGUSRPMIMOReport.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace SWGSDRangel { + +SWGUSRPMIMOReport::SWGUSRPMIMOReport(QString* json) { + init(); + this->fromJson(*json); +} + +SWGUSRPMIMOReport::SWGUSRPMIMOReport() { + success = 0; + m_success_isSet = false; + rx_stream_active = 0; + m_rx_stream_active_isSet = false; + rx_overrun_count = 0; + m_rx_overrun_count_isSet = false; + rx_timeout_count = 0; + m_rx_timeout_count_isSet = false; + tx_stream_active = 0; + m_tx_stream_active_isSet = false; + tx_underrun_count = 0; + m_tx_underrun_count_isSet = false; + tx_dropped_packets_count = 0; + m_tx_dropped_packets_count_isSet = false; + master_clock_rate = 0; + m_master_clock_rate_isSet = false; + temperature = 0.0f; + m_temperature_isSet = false; +} + +SWGUSRPMIMOReport::~SWGUSRPMIMOReport() { + this->cleanup(); +} + +void +SWGUSRPMIMOReport::init() { + success = 0; + m_success_isSet = false; + rx_stream_active = 0; + m_rx_stream_active_isSet = false; + rx_overrun_count = 0; + m_rx_overrun_count_isSet = false; + rx_timeout_count = 0; + m_rx_timeout_count_isSet = false; + tx_stream_active = 0; + m_tx_stream_active_isSet = false; + tx_underrun_count = 0; + m_tx_underrun_count_isSet = false; + tx_dropped_packets_count = 0; + m_tx_dropped_packets_count_isSet = false; + master_clock_rate = 0; + m_master_clock_rate_isSet = false; + temperature = 0.0f; + m_temperature_isSet = false; +} + +void +SWGUSRPMIMOReport::cleanup() { + + + + + + + + + +} + +SWGUSRPMIMOReport* +SWGUSRPMIMOReport::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGUSRPMIMOReport::fromJsonObject(QJsonObject &pJson) { + ::SWGSDRangel::setValue(&success, pJson["success"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_stream_active, pJson["rxStreamActive"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_overrun_count, pJson["rxOverrunCount"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_timeout_count, pJson["rxTimeoutCount"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx_stream_active, pJson["txStreamActive"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx_underrun_count, pJson["txUnderrunCount"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx_dropped_packets_count, pJson["txDroppedPacketsCount"], "qint32", ""); + + ::SWGSDRangel::setValue(&master_clock_rate, pJson["masterClockRate"], "qint32", ""); + + ::SWGSDRangel::setValue(&temperature, pJson["temperature"], "float", ""); + +} + +QString +SWGUSRPMIMOReport::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + delete obj; + return QString(bytes); +} + +QJsonObject* +SWGUSRPMIMOReport::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + if(m_success_isSet){ + obj->insert("success", QJsonValue(success)); + } + if(m_rx_stream_active_isSet){ + obj->insert("rxStreamActive", QJsonValue(rx_stream_active)); + } + if(m_rx_overrun_count_isSet){ + obj->insert("rxOverrunCount", QJsonValue(rx_overrun_count)); + } + if(m_rx_timeout_count_isSet){ + obj->insert("rxTimeoutCount", QJsonValue(rx_timeout_count)); + } + if(m_tx_stream_active_isSet){ + obj->insert("txStreamActive", QJsonValue(tx_stream_active)); + } + if(m_tx_underrun_count_isSet){ + obj->insert("txUnderrunCount", QJsonValue(tx_underrun_count)); + } + if(m_tx_dropped_packets_count_isSet){ + obj->insert("txDroppedPacketsCount", QJsonValue(tx_dropped_packets_count)); + } + if(m_master_clock_rate_isSet){ + obj->insert("masterClockRate", QJsonValue(master_clock_rate)); + } + if(m_temperature_isSet){ + obj->insert("temperature", QJsonValue(temperature)); + } + + return obj; +} + +qint32 +SWGUSRPMIMOReport::getSuccess() { + return success; +} +void +SWGUSRPMIMOReport::setSuccess(qint32 success) { + this->success = success; + this->m_success_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getRxStreamActive() { + return rx_stream_active; +} +void +SWGUSRPMIMOReport::setRxStreamActive(qint32 rx_stream_active) { + this->rx_stream_active = rx_stream_active; + this->m_rx_stream_active_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getRxOverrunCount() { + return rx_overrun_count; +} +void +SWGUSRPMIMOReport::setRxOverrunCount(qint32 rx_overrun_count) { + this->rx_overrun_count = rx_overrun_count; + this->m_rx_overrun_count_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getRxTimeoutCount() { + return rx_timeout_count; +} +void +SWGUSRPMIMOReport::setRxTimeoutCount(qint32 rx_timeout_count) { + this->rx_timeout_count = rx_timeout_count; + this->m_rx_timeout_count_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getTxStreamActive() { + return tx_stream_active; +} +void +SWGUSRPMIMOReport::setTxStreamActive(qint32 tx_stream_active) { + this->tx_stream_active = tx_stream_active; + this->m_tx_stream_active_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getTxUnderrunCount() { + return tx_underrun_count; +} +void +SWGUSRPMIMOReport::setTxUnderrunCount(qint32 tx_underrun_count) { + this->tx_underrun_count = tx_underrun_count; + this->m_tx_underrun_count_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getTxDroppedPacketsCount() { + return tx_dropped_packets_count; +} +void +SWGUSRPMIMOReport::setTxDroppedPacketsCount(qint32 tx_dropped_packets_count) { + this->tx_dropped_packets_count = tx_dropped_packets_count; + this->m_tx_dropped_packets_count_isSet = true; +} + +qint32 +SWGUSRPMIMOReport::getMasterClockRate() { + return master_clock_rate; +} +void +SWGUSRPMIMOReport::setMasterClockRate(qint32 master_clock_rate) { + this->master_clock_rate = master_clock_rate; + this->m_master_clock_rate_isSet = true; +} + +float +SWGUSRPMIMOReport::getTemperature() { + return temperature; +} +void +SWGUSRPMIMOReport::setTemperature(float temperature) { + this->temperature = temperature; + this->m_temperature_isSet = true; +} + + +bool +SWGUSRPMIMOReport::isSet(){ + bool isObjectUpdated = false; + do{ + if(m_success_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_stream_active_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_overrun_count_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_timeout_count_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_stream_active_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_underrun_count_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_dropped_packets_count_isSet){ + isObjectUpdated = true; break; + } + if(m_master_clock_rate_isSet){ + isObjectUpdated = true; break; + } + if(m_temperature_isSet){ + isObjectUpdated = true; break; + } + }while(false); + return isObjectUpdated; +} +} + diff --git a/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.h b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.h new file mode 100644 index 000000000..3af76f045 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOReport.h @@ -0,0 +1,106 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +/* + * SWGUSRPMIMOReport.h + * + * USRP + */ + +#ifndef SWGUSRPMIMOReport_H_ +#define SWGUSRPMIMOReport_H_ + +#include + + + +#include "SWGObject.h" +#include "export.h" + +namespace SWGSDRangel { + +class SWG_API SWGUSRPMIMOReport: public SWGObject { +public: + SWGUSRPMIMOReport(); + SWGUSRPMIMOReport(QString* json); + virtual ~SWGUSRPMIMOReport(); + void init(); + void cleanup(); + + virtual QString asJson () override; + virtual QJsonObject* asJsonObject() override; + virtual void fromJsonObject(QJsonObject &json) override; + virtual SWGUSRPMIMOReport* fromJson(QString &jsonString) override; + + qint32 getSuccess(); + void setSuccess(qint32 success); + + qint32 getRxStreamActive(); + void setRxStreamActive(qint32 rx_stream_active); + + qint32 getRxOverrunCount(); + void setRxOverrunCount(qint32 rx_overrun_count); + + qint32 getRxTimeoutCount(); + void setRxTimeoutCount(qint32 rx_timeout_count); + + qint32 getTxStreamActive(); + void setTxStreamActive(qint32 tx_stream_active); + + qint32 getTxUnderrunCount(); + void setTxUnderrunCount(qint32 tx_underrun_count); + + qint32 getTxDroppedPacketsCount(); + void setTxDroppedPacketsCount(qint32 tx_dropped_packets_count); + + qint32 getMasterClockRate(); + void setMasterClockRate(qint32 master_clock_rate); + + float getTemperature(); + void setTemperature(float temperature); + + + virtual bool isSet() override; + +private: + qint32 success; + bool m_success_isSet; + + qint32 rx_stream_active; + bool m_rx_stream_active_isSet; + + qint32 rx_overrun_count; + bool m_rx_overrun_count_isSet; + + qint32 rx_timeout_count; + bool m_rx_timeout_count_isSet; + + qint32 tx_stream_active; + bool m_tx_stream_active_isSet; + + qint32 tx_underrun_count; + bool m_tx_underrun_count_isSet; + + qint32 tx_dropped_packets_count; + bool m_tx_dropped_packets_count_isSet; + + qint32 master_clock_rate; + bool m_master_clock_rate_isSet; + + float temperature; + bool m_temperature_isSet; + +}; + +} + +#endif /* SWGUSRPMIMOReport_H_ */ diff --git a/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.cpp new file mode 100644 index 000000000..8f96d0bb7 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.cpp @@ -0,0 +1,858 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +#include "SWGUSRPMIMOSettings.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace SWGSDRangel { + +SWGUSRPMIMOSettings::SWGUSRPMIMOSettings(QString* json) { + init(); + this->fromJson(*json); +} + +SWGUSRPMIMOSettings::SWGUSRPMIMOSettings() { + title = nullptr; + m_title_isSet = false; + dev_sample_rate = 0; + m_dev_sample_rate_isSet = false; + clock_source = nullptr; + m_clock_source_isSet = false; + gpio_dir = 0; + m_gpio_dir_isSet = false; + gpio_pins = 0; + m_gpio_pins_isSet = false; + rx_center_frequency = 0L; + m_rx_center_frequency_isSet = false; + rx_lo_offset = 0; + m_rx_lo_offset_isSet = false; + log2_soft_decim = 0; + m_log2_soft_decim_isSet = false; + rx_lpf_bw = 0; + m_rx_lpf_bw_isSet = false; + dc_block = 0; + m_dc_block_isSet = false; + iq_correction = 0; + m_iq_correction_isSet = false; + rx_transverter_mode = 0; + m_rx_transverter_mode_isSet = false; + rx_transverter_delta_frequency = 0L; + m_rx_transverter_delta_frequency_isSet = false; + rx0_gain_mode = 0; + m_rx0_gain_mode_isSet = false; + rx0_gain = 0; + m_rx0_gain_isSet = false; + rx0_antenna_path = nullptr; + m_rx0_antenna_path_isSet = false; + rx1_gain_mode = 0; + m_rx1_gain_mode_isSet = false; + rx1_gain = 0; + m_rx1_gain_isSet = false; + rx1_antenna_path = nullptr; + m_rx1_antenna_path_isSet = false; + tx_center_frequency = 0L; + m_tx_center_frequency_isSet = false; + tx_lo_offset = 0; + m_tx_lo_offset_isSet = false; + log2_soft_interp = 0; + m_log2_soft_interp_isSet = false; + tx_lpf_bw = 0; + m_tx_lpf_bw_isSet = false; + tx_transverter_mode = 0; + m_tx_transverter_mode_isSet = false; + tx_transverter_delta_frequency = 0L; + m_tx_transverter_delta_frequency_isSet = false; + tx0_gain = 0; + m_tx0_gain_isSet = false; + tx0_antenna_path = nullptr; + m_tx0_antenna_path_isSet = false; + tx1_gain = 0; + m_tx1_gain_isSet = false; + tx1_antenna_path = nullptr; + m_tx1_antenna_path_isSet = false; + use_reverse_api = 0; + m_use_reverse_api_isSet = false; + reverse_api_address = nullptr; + m_reverse_api_address_isSet = false; + reverse_api_port = 0; + m_reverse_api_port_isSet = false; + reverse_api_device_index = 0; + m_reverse_api_device_index_isSet = false; +} + +SWGUSRPMIMOSettings::~SWGUSRPMIMOSettings() { + this->cleanup(); +} + +void +SWGUSRPMIMOSettings::init() { + title = new QString(""); + m_title_isSet = false; + dev_sample_rate = 0; + m_dev_sample_rate_isSet = false; + clock_source = new QString(""); + m_clock_source_isSet = false; + gpio_dir = 0; + m_gpio_dir_isSet = false; + gpio_pins = 0; + m_gpio_pins_isSet = false; + rx_center_frequency = 0L; + m_rx_center_frequency_isSet = false; + rx_lo_offset = 0; + m_rx_lo_offset_isSet = false; + log2_soft_decim = 0; + m_log2_soft_decim_isSet = false; + rx_lpf_bw = 0; + m_rx_lpf_bw_isSet = false; + dc_block = 0; + m_dc_block_isSet = false; + iq_correction = 0; + m_iq_correction_isSet = false; + rx_transverter_mode = 0; + m_rx_transverter_mode_isSet = false; + rx_transverter_delta_frequency = 0L; + m_rx_transverter_delta_frequency_isSet = false; + rx0_gain_mode = 0; + m_rx0_gain_mode_isSet = false; + rx0_gain = 0; + m_rx0_gain_isSet = false; + rx0_antenna_path = new QString(""); + m_rx0_antenna_path_isSet = false; + rx1_gain_mode = 0; + m_rx1_gain_mode_isSet = false; + rx1_gain = 0; + m_rx1_gain_isSet = false; + rx1_antenna_path = new QString(""); + m_rx1_antenna_path_isSet = false; + tx_center_frequency = 0L; + m_tx_center_frequency_isSet = false; + tx_lo_offset = 0; + m_tx_lo_offset_isSet = false; + log2_soft_interp = 0; + m_log2_soft_interp_isSet = false; + tx_lpf_bw = 0; + m_tx_lpf_bw_isSet = false; + tx_transverter_mode = 0; + m_tx_transverter_mode_isSet = false; + tx_transverter_delta_frequency = 0L; + m_tx_transverter_delta_frequency_isSet = false; + tx0_gain = 0; + m_tx0_gain_isSet = false; + tx0_antenna_path = new QString(""); + m_tx0_antenna_path_isSet = false; + tx1_gain = 0; + m_tx1_gain_isSet = false; + tx1_antenna_path = new QString(""); + m_tx1_antenna_path_isSet = false; + use_reverse_api = 0; + m_use_reverse_api_isSet = false; + reverse_api_address = new QString(""); + m_reverse_api_address_isSet = false; + reverse_api_port = 0; + m_reverse_api_port_isSet = false; + reverse_api_device_index = 0; + m_reverse_api_device_index_isSet = false; +} + +void +SWGUSRPMIMOSettings::cleanup() { + if(title != nullptr) { + delete title; + } + + if(clock_source != nullptr) { + delete clock_source; + } + + + + + + + + + + + + + if(rx0_antenna_path != nullptr) { + delete rx0_antenna_path; + } + + + if(rx1_antenna_path != nullptr) { + delete rx1_antenna_path; + } + + + + + + + + if(tx0_antenna_path != nullptr) { + delete tx0_antenna_path; + } + + if(tx1_antenna_path != nullptr) { + delete tx1_antenna_path; + } + + if(reverse_api_address != nullptr) { + delete reverse_api_address; + } + + +} + +SWGUSRPMIMOSettings* +SWGUSRPMIMOSettings::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGUSRPMIMOSettings::fromJsonObject(QJsonObject &pJson) { + ::SWGSDRangel::setValue(&title, pJson["title"], "QString", "QString"); + + ::SWGSDRangel::setValue(&dev_sample_rate, pJson["devSampleRate"], "qint32", ""); + + ::SWGSDRangel::setValue(&clock_source, pJson["clockSource"], "QString", "QString"); + + ::SWGSDRangel::setValue(&gpio_dir, pJson["gpioDir"], "qint32", ""); + + ::SWGSDRangel::setValue(&gpio_pins, pJson["gpioPins"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_center_frequency, pJson["rxCenterFrequency"], "qint64", ""); + + ::SWGSDRangel::setValue(&rx_lo_offset, pJson["rxLOOffset"], "qint32", ""); + + ::SWGSDRangel::setValue(&log2_soft_decim, pJson["log2SoftDecim"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_lpf_bw, pJson["rxLpfBW"], "qint32", ""); + + ::SWGSDRangel::setValue(&dc_block, pJson["dcBlock"], "qint32", ""); + + ::SWGSDRangel::setValue(&iq_correction, pJson["iqCorrection"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_transverter_mode, pJson["rxTransverterMode"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx_transverter_delta_frequency, pJson["rxTransverterDeltaFrequency"], "qint64", ""); + + ::SWGSDRangel::setValue(&rx0_gain_mode, pJson["rx0GainMode"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx0_gain, pJson["rx0Gain"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx0_antenna_path, pJson["rx0AntennaPath"], "QString", "QString"); + + ::SWGSDRangel::setValue(&rx1_gain_mode, pJson["rx1GainMode"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx1_gain, pJson["rx1Gain"], "qint32", ""); + + ::SWGSDRangel::setValue(&rx1_antenna_path, pJson["rx1AntennaPath"], "QString", "QString"); + + ::SWGSDRangel::setValue(&tx_center_frequency, pJson["txCenterFrequency"], "qint64", ""); + + ::SWGSDRangel::setValue(&tx_lo_offset, pJson["txLOOffset"], "qint32", ""); + + ::SWGSDRangel::setValue(&log2_soft_interp, pJson["log2SoftInterp"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx_lpf_bw, pJson["txLpfBW"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx_transverter_mode, pJson["txTransverterMode"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx_transverter_delta_frequency, pJson["txTransverterDeltaFrequency"], "qint64", ""); + + ::SWGSDRangel::setValue(&tx0_gain, pJson["tx0Gain"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx0_antenna_path, pJson["tx0AntennaPath"], "QString", "QString"); + + ::SWGSDRangel::setValue(&tx1_gain, pJson["tx1Gain"], "qint32", ""); + + ::SWGSDRangel::setValue(&tx1_antenna_path, pJson["tx1AntennaPath"], "QString", "QString"); + + ::SWGSDRangel::setValue(&use_reverse_api, pJson["useReverseAPI"], "qint32", ""); + + ::SWGSDRangel::setValue(&reverse_api_address, pJson["reverseAPIAddress"], "QString", "QString"); + + ::SWGSDRangel::setValue(&reverse_api_port, pJson["reverseAPIPort"], "qint32", ""); + + ::SWGSDRangel::setValue(&reverse_api_device_index, pJson["reverseAPIDeviceIndex"], "qint32", ""); + +} + +QString +SWGUSRPMIMOSettings::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + delete obj; + return QString(bytes); +} + +QJsonObject* +SWGUSRPMIMOSettings::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + if(title != nullptr && *title != QString("")){ + toJsonValue(QString("title"), title, obj, QString("QString")); + } + if(m_dev_sample_rate_isSet){ + obj->insert("devSampleRate", QJsonValue(dev_sample_rate)); + } + if(clock_source != nullptr && *clock_source != QString("")){ + toJsonValue(QString("clockSource"), clock_source, obj, QString("QString")); + } + if(m_gpio_dir_isSet){ + obj->insert("gpioDir", QJsonValue(gpio_dir)); + } + if(m_gpio_pins_isSet){ + obj->insert("gpioPins", QJsonValue(gpio_pins)); + } + if(m_rx_center_frequency_isSet){ + obj->insert("rxCenterFrequency", QJsonValue(rx_center_frequency)); + } + if(m_rx_lo_offset_isSet){ + obj->insert("rxLOOffset", QJsonValue(rx_lo_offset)); + } + if(m_log2_soft_decim_isSet){ + obj->insert("log2SoftDecim", QJsonValue(log2_soft_decim)); + } + if(m_rx_lpf_bw_isSet){ + obj->insert("rxLpfBW", QJsonValue(rx_lpf_bw)); + } + if(m_dc_block_isSet){ + obj->insert("dcBlock", QJsonValue(dc_block)); + } + if(m_iq_correction_isSet){ + obj->insert("iqCorrection", QJsonValue(iq_correction)); + } + if(m_rx_transverter_mode_isSet){ + obj->insert("rxTransverterMode", QJsonValue(rx_transverter_mode)); + } + if(m_rx_transverter_delta_frequency_isSet){ + obj->insert("rxTransverterDeltaFrequency", QJsonValue(rx_transverter_delta_frequency)); + } + if(m_rx0_gain_mode_isSet){ + obj->insert("rx0GainMode", QJsonValue(rx0_gain_mode)); + } + if(m_rx0_gain_isSet){ + obj->insert("rx0Gain", QJsonValue(rx0_gain)); + } + if(rx0_antenna_path != nullptr && *rx0_antenna_path != QString("")){ + toJsonValue(QString("rx0AntennaPath"), rx0_antenna_path, obj, QString("QString")); + } + if(m_rx1_gain_mode_isSet){ + obj->insert("rx1GainMode", QJsonValue(rx1_gain_mode)); + } + if(m_rx1_gain_isSet){ + obj->insert("rx1Gain", QJsonValue(rx1_gain)); + } + if(rx1_antenna_path != nullptr && *rx1_antenna_path != QString("")){ + toJsonValue(QString("rx1AntennaPath"), rx1_antenna_path, obj, QString("QString")); + } + if(m_tx_center_frequency_isSet){ + obj->insert("txCenterFrequency", QJsonValue(tx_center_frequency)); + } + if(m_tx_lo_offset_isSet){ + obj->insert("txLOOffset", QJsonValue(tx_lo_offset)); + } + if(m_log2_soft_interp_isSet){ + obj->insert("log2SoftInterp", QJsonValue(log2_soft_interp)); + } + if(m_tx_lpf_bw_isSet){ + obj->insert("txLpfBW", QJsonValue(tx_lpf_bw)); + } + if(m_tx_transverter_mode_isSet){ + obj->insert("txTransverterMode", QJsonValue(tx_transverter_mode)); + } + if(m_tx_transverter_delta_frequency_isSet){ + obj->insert("txTransverterDeltaFrequency", QJsonValue(tx_transverter_delta_frequency)); + } + if(m_tx0_gain_isSet){ + obj->insert("tx0Gain", QJsonValue(tx0_gain)); + } + if(tx0_antenna_path != nullptr && *tx0_antenna_path != QString("")){ + toJsonValue(QString("tx0AntennaPath"), tx0_antenna_path, obj, QString("QString")); + } + if(m_tx1_gain_isSet){ + obj->insert("tx1Gain", QJsonValue(tx1_gain)); + } + if(tx1_antenna_path != nullptr && *tx1_antenna_path != QString("")){ + toJsonValue(QString("tx1AntennaPath"), tx1_antenna_path, obj, QString("QString")); + } + if(m_use_reverse_api_isSet){ + obj->insert("useReverseAPI", QJsonValue(use_reverse_api)); + } + if(reverse_api_address != nullptr && *reverse_api_address != QString("")){ + toJsonValue(QString("reverseAPIAddress"), reverse_api_address, obj, QString("QString")); + } + if(m_reverse_api_port_isSet){ + obj->insert("reverseAPIPort", QJsonValue(reverse_api_port)); + } + if(m_reverse_api_device_index_isSet){ + obj->insert("reverseAPIDeviceIndex", QJsonValue(reverse_api_device_index)); + } + + return obj; +} + +QString* +SWGUSRPMIMOSettings::getTitle() { + return title; +} +void +SWGUSRPMIMOSettings::setTitle(QString* title) { + this->title = title; + this->m_title_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getDevSampleRate() { + return dev_sample_rate; +} +void +SWGUSRPMIMOSettings::setDevSampleRate(qint32 dev_sample_rate) { + this->dev_sample_rate = dev_sample_rate; + this->m_dev_sample_rate_isSet = true; +} + +QString* +SWGUSRPMIMOSettings::getClockSource() { + return clock_source; +} +void +SWGUSRPMIMOSettings::setClockSource(QString* clock_source) { + this->clock_source = clock_source; + this->m_clock_source_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getGpioDir() { + return gpio_dir; +} +void +SWGUSRPMIMOSettings::setGpioDir(qint32 gpio_dir) { + this->gpio_dir = gpio_dir; + this->m_gpio_dir_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getGpioPins() { + return gpio_pins; +} +void +SWGUSRPMIMOSettings::setGpioPins(qint32 gpio_pins) { + this->gpio_pins = gpio_pins; + this->m_gpio_pins_isSet = true; +} + +qint64 +SWGUSRPMIMOSettings::getRxCenterFrequency() { + return rx_center_frequency; +} +void +SWGUSRPMIMOSettings::setRxCenterFrequency(qint64 rx_center_frequency) { + this->rx_center_frequency = rx_center_frequency; + this->m_rx_center_frequency_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRxLoOffset() { + return rx_lo_offset; +} +void +SWGUSRPMIMOSettings::setRxLoOffset(qint32 rx_lo_offset) { + this->rx_lo_offset = rx_lo_offset; + this->m_rx_lo_offset_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getLog2SoftDecim() { + return log2_soft_decim; +} +void +SWGUSRPMIMOSettings::setLog2SoftDecim(qint32 log2_soft_decim) { + this->log2_soft_decim = log2_soft_decim; + this->m_log2_soft_decim_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRxLpfBw() { + return rx_lpf_bw; +} +void +SWGUSRPMIMOSettings::setRxLpfBw(qint32 rx_lpf_bw) { + this->rx_lpf_bw = rx_lpf_bw; + this->m_rx_lpf_bw_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getDcBlock() { + return dc_block; +} +void +SWGUSRPMIMOSettings::setDcBlock(qint32 dc_block) { + this->dc_block = dc_block; + this->m_dc_block_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getIqCorrection() { + return iq_correction; +} +void +SWGUSRPMIMOSettings::setIqCorrection(qint32 iq_correction) { + this->iq_correction = iq_correction; + this->m_iq_correction_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRxTransverterMode() { + return rx_transverter_mode; +} +void +SWGUSRPMIMOSettings::setRxTransverterMode(qint32 rx_transverter_mode) { + this->rx_transverter_mode = rx_transverter_mode; + this->m_rx_transverter_mode_isSet = true; +} + +qint64 +SWGUSRPMIMOSettings::getRxTransverterDeltaFrequency() { + return rx_transverter_delta_frequency; +} +void +SWGUSRPMIMOSettings::setRxTransverterDeltaFrequency(qint64 rx_transverter_delta_frequency) { + this->rx_transverter_delta_frequency = rx_transverter_delta_frequency; + this->m_rx_transverter_delta_frequency_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRx0GainMode() { + return rx0_gain_mode; +} +void +SWGUSRPMIMOSettings::setRx0GainMode(qint32 rx0_gain_mode) { + this->rx0_gain_mode = rx0_gain_mode; + this->m_rx0_gain_mode_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRx0Gain() { + return rx0_gain; +} +void +SWGUSRPMIMOSettings::setRx0Gain(qint32 rx0_gain) { + this->rx0_gain = rx0_gain; + this->m_rx0_gain_isSet = true; +} + +QString* +SWGUSRPMIMOSettings::getRx0AntennaPath() { + return rx0_antenna_path; +} +void +SWGUSRPMIMOSettings::setRx0AntennaPath(QString* rx0_antenna_path) { + this->rx0_antenna_path = rx0_antenna_path; + this->m_rx0_antenna_path_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRx1GainMode() { + return rx1_gain_mode; +} +void +SWGUSRPMIMOSettings::setRx1GainMode(qint32 rx1_gain_mode) { + this->rx1_gain_mode = rx1_gain_mode; + this->m_rx1_gain_mode_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getRx1Gain() { + return rx1_gain; +} +void +SWGUSRPMIMOSettings::setRx1Gain(qint32 rx1_gain) { + this->rx1_gain = rx1_gain; + this->m_rx1_gain_isSet = true; +} + +QString* +SWGUSRPMIMOSettings::getRx1AntennaPath() { + return rx1_antenna_path; +} +void +SWGUSRPMIMOSettings::setRx1AntennaPath(QString* rx1_antenna_path) { + this->rx1_antenna_path = rx1_antenna_path; + this->m_rx1_antenna_path_isSet = true; +} + +qint64 +SWGUSRPMIMOSettings::getTxCenterFrequency() { + return tx_center_frequency; +} +void +SWGUSRPMIMOSettings::setTxCenterFrequency(qint64 tx_center_frequency) { + this->tx_center_frequency = tx_center_frequency; + this->m_tx_center_frequency_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getTxLoOffset() { + return tx_lo_offset; +} +void +SWGUSRPMIMOSettings::setTxLoOffset(qint32 tx_lo_offset) { + this->tx_lo_offset = tx_lo_offset; + this->m_tx_lo_offset_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getLog2SoftInterp() { + return log2_soft_interp; +} +void +SWGUSRPMIMOSettings::setLog2SoftInterp(qint32 log2_soft_interp) { + this->log2_soft_interp = log2_soft_interp; + this->m_log2_soft_interp_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getTxLpfBw() { + return tx_lpf_bw; +} +void +SWGUSRPMIMOSettings::setTxLpfBw(qint32 tx_lpf_bw) { + this->tx_lpf_bw = tx_lpf_bw; + this->m_tx_lpf_bw_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getTxTransverterMode() { + return tx_transverter_mode; +} +void +SWGUSRPMIMOSettings::setTxTransverterMode(qint32 tx_transverter_mode) { + this->tx_transverter_mode = tx_transverter_mode; + this->m_tx_transverter_mode_isSet = true; +} + +qint64 +SWGUSRPMIMOSettings::getTxTransverterDeltaFrequency() { + return tx_transverter_delta_frequency; +} +void +SWGUSRPMIMOSettings::setTxTransverterDeltaFrequency(qint64 tx_transverter_delta_frequency) { + this->tx_transverter_delta_frequency = tx_transverter_delta_frequency; + this->m_tx_transverter_delta_frequency_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getTx0Gain() { + return tx0_gain; +} +void +SWGUSRPMIMOSettings::setTx0Gain(qint32 tx0_gain) { + this->tx0_gain = tx0_gain; + this->m_tx0_gain_isSet = true; +} + +QString* +SWGUSRPMIMOSettings::getTx0AntennaPath() { + return tx0_antenna_path; +} +void +SWGUSRPMIMOSettings::setTx0AntennaPath(QString* tx0_antenna_path) { + this->tx0_antenna_path = tx0_antenna_path; + this->m_tx0_antenna_path_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getTx1Gain() { + return tx1_gain; +} +void +SWGUSRPMIMOSettings::setTx1Gain(qint32 tx1_gain) { + this->tx1_gain = tx1_gain; + this->m_tx1_gain_isSet = true; +} + +QString* +SWGUSRPMIMOSettings::getTx1AntennaPath() { + return tx1_antenna_path; +} +void +SWGUSRPMIMOSettings::setTx1AntennaPath(QString* tx1_antenna_path) { + this->tx1_antenna_path = tx1_antenna_path; + this->m_tx1_antenna_path_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getUseReverseApi() { + return use_reverse_api; +} +void +SWGUSRPMIMOSettings::setUseReverseApi(qint32 use_reverse_api) { + this->use_reverse_api = use_reverse_api; + this->m_use_reverse_api_isSet = true; +} + +QString* +SWGUSRPMIMOSettings::getReverseApiAddress() { + return reverse_api_address; +} +void +SWGUSRPMIMOSettings::setReverseApiAddress(QString* reverse_api_address) { + this->reverse_api_address = reverse_api_address; + this->m_reverse_api_address_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getReverseApiPort() { + return reverse_api_port; +} +void +SWGUSRPMIMOSettings::setReverseApiPort(qint32 reverse_api_port) { + this->reverse_api_port = reverse_api_port; + this->m_reverse_api_port_isSet = true; +} + +qint32 +SWGUSRPMIMOSettings::getReverseApiDeviceIndex() { + return reverse_api_device_index; +} +void +SWGUSRPMIMOSettings::setReverseApiDeviceIndex(qint32 reverse_api_device_index) { + this->reverse_api_device_index = reverse_api_device_index; + this->m_reverse_api_device_index_isSet = true; +} + + +bool +SWGUSRPMIMOSettings::isSet(){ + bool isObjectUpdated = false; + do{ + if(title && *title != QString("")){ + isObjectUpdated = true; break; + } + if(m_dev_sample_rate_isSet){ + isObjectUpdated = true; break; + } + if(clock_source && *clock_source != QString("")){ + isObjectUpdated = true; break; + } + if(m_gpio_dir_isSet){ + isObjectUpdated = true; break; + } + if(m_gpio_pins_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_center_frequency_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_lo_offset_isSet){ + isObjectUpdated = true; break; + } + if(m_log2_soft_decim_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_lpf_bw_isSet){ + isObjectUpdated = true; break; + } + if(m_dc_block_isSet){ + isObjectUpdated = true; break; + } + if(m_iq_correction_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_transverter_mode_isSet){ + isObjectUpdated = true; break; + } + if(m_rx_transverter_delta_frequency_isSet){ + isObjectUpdated = true; break; + } + if(m_rx0_gain_mode_isSet){ + isObjectUpdated = true; break; + } + if(m_rx0_gain_isSet){ + isObjectUpdated = true; break; + } + if(rx0_antenna_path && *rx0_antenna_path != QString("")){ + isObjectUpdated = true; break; + } + if(m_rx1_gain_mode_isSet){ + isObjectUpdated = true; break; + } + if(m_rx1_gain_isSet){ + isObjectUpdated = true; break; + } + if(rx1_antenna_path && *rx1_antenna_path != QString("")){ + isObjectUpdated = true; break; + } + if(m_tx_center_frequency_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_lo_offset_isSet){ + isObjectUpdated = true; break; + } + if(m_log2_soft_interp_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_lpf_bw_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_transverter_mode_isSet){ + isObjectUpdated = true; break; + } + if(m_tx_transverter_delta_frequency_isSet){ + isObjectUpdated = true; break; + } + if(m_tx0_gain_isSet){ + isObjectUpdated = true; break; + } + if(tx0_antenna_path && *tx0_antenna_path != QString("")){ + isObjectUpdated = true; break; + } + if(m_tx1_gain_isSet){ + isObjectUpdated = true; break; + } + if(tx1_antenna_path && *tx1_antenna_path != QString("")){ + isObjectUpdated = true; break; + } + if(m_use_reverse_api_isSet){ + isObjectUpdated = true; break; + } + if(reverse_api_address && *reverse_api_address != QString("")){ + isObjectUpdated = true; break; + } + if(m_reverse_api_port_isSet){ + isObjectUpdated = true; break; + } + if(m_reverse_api_device_index_isSet){ + isObjectUpdated = true; break; + } + }while(false); + return isObjectUpdated; +} +} + diff --git a/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.h b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.h new file mode 100644 index 000000000..6e381a2d3 --- /dev/null +++ b/swagger/sdrangel/code/qt5/client/SWGUSRPMIMOSettings.h @@ -0,0 +1,251 @@ +/** + * SDRangel + * This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time --- + * + * OpenAPI spec version: 7.0.0 + * Contact: f4exb06@gmail.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +/* + * SWGUSRPMIMOSettings.h + * + * USRP + */ + +#ifndef SWGUSRPMIMOSettings_H_ +#define SWGUSRPMIMOSettings_H_ + +#include + + +#include + +#include "SWGObject.h" +#include "export.h" + +namespace SWGSDRangel { + +class SWG_API SWGUSRPMIMOSettings: public SWGObject { +public: + SWGUSRPMIMOSettings(); + SWGUSRPMIMOSettings(QString* json); + virtual ~SWGUSRPMIMOSettings(); + void init(); + void cleanup(); + + virtual QString asJson () override; + virtual QJsonObject* asJsonObject() override; + virtual void fromJsonObject(QJsonObject &json) override; + virtual SWGUSRPMIMOSettings* fromJson(QString &jsonString) override; + + QString* getTitle(); + void setTitle(QString* title); + + qint32 getDevSampleRate(); + void setDevSampleRate(qint32 dev_sample_rate); + + QString* getClockSource(); + void setClockSource(QString* clock_source); + + qint32 getGpioDir(); + void setGpioDir(qint32 gpio_dir); + + qint32 getGpioPins(); + void setGpioPins(qint32 gpio_pins); + + qint64 getRxCenterFrequency(); + void setRxCenterFrequency(qint64 rx_center_frequency); + + qint32 getRxLoOffset(); + void setRxLoOffset(qint32 rx_lo_offset); + + qint32 getLog2SoftDecim(); + void setLog2SoftDecim(qint32 log2_soft_decim); + + qint32 getRxLpfBw(); + void setRxLpfBw(qint32 rx_lpf_bw); + + qint32 getDcBlock(); + void setDcBlock(qint32 dc_block); + + qint32 getIqCorrection(); + void setIqCorrection(qint32 iq_correction); + + qint32 getRxTransverterMode(); + void setRxTransverterMode(qint32 rx_transverter_mode); + + qint64 getRxTransverterDeltaFrequency(); + void setRxTransverterDeltaFrequency(qint64 rx_transverter_delta_frequency); + + qint32 getRx0GainMode(); + void setRx0GainMode(qint32 rx0_gain_mode); + + qint32 getRx0Gain(); + void setRx0Gain(qint32 rx0_gain); + + QString* getRx0AntennaPath(); + void setRx0AntennaPath(QString* rx0_antenna_path); + + qint32 getRx1GainMode(); + void setRx1GainMode(qint32 rx1_gain_mode); + + qint32 getRx1Gain(); + void setRx1Gain(qint32 rx1_gain); + + QString* getRx1AntennaPath(); + void setRx1AntennaPath(QString* rx1_antenna_path); + + qint64 getTxCenterFrequency(); + void setTxCenterFrequency(qint64 tx_center_frequency); + + qint32 getTxLoOffset(); + void setTxLoOffset(qint32 tx_lo_offset); + + qint32 getLog2SoftInterp(); + void setLog2SoftInterp(qint32 log2_soft_interp); + + qint32 getTxLpfBw(); + void setTxLpfBw(qint32 tx_lpf_bw); + + qint32 getTxTransverterMode(); + void setTxTransverterMode(qint32 tx_transverter_mode); + + qint64 getTxTransverterDeltaFrequency(); + void setTxTransverterDeltaFrequency(qint64 tx_transverter_delta_frequency); + + qint32 getTx0Gain(); + void setTx0Gain(qint32 tx0_gain); + + QString* getTx0AntennaPath(); + void setTx0AntennaPath(QString* tx0_antenna_path); + + qint32 getTx1Gain(); + void setTx1Gain(qint32 tx1_gain); + + QString* getTx1AntennaPath(); + void setTx1AntennaPath(QString* tx1_antenna_path); + + qint32 getUseReverseApi(); + void setUseReverseApi(qint32 use_reverse_api); + + QString* getReverseApiAddress(); + void setReverseApiAddress(QString* reverse_api_address); + + qint32 getReverseApiPort(); + void setReverseApiPort(qint32 reverse_api_port); + + qint32 getReverseApiDeviceIndex(); + void setReverseApiDeviceIndex(qint32 reverse_api_device_index); + + + virtual bool isSet() override; + +private: + QString* title; + bool m_title_isSet; + + qint32 dev_sample_rate; + bool m_dev_sample_rate_isSet; + + QString* clock_source; + bool m_clock_source_isSet; + + qint32 gpio_dir; + bool m_gpio_dir_isSet; + + qint32 gpio_pins; + bool m_gpio_pins_isSet; + + qint64 rx_center_frequency; + bool m_rx_center_frequency_isSet; + + qint32 rx_lo_offset; + bool m_rx_lo_offset_isSet; + + qint32 log2_soft_decim; + bool m_log2_soft_decim_isSet; + + qint32 rx_lpf_bw; + bool m_rx_lpf_bw_isSet; + + qint32 dc_block; + bool m_dc_block_isSet; + + qint32 iq_correction; + bool m_iq_correction_isSet; + + qint32 rx_transverter_mode; + bool m_rx_transverter_mode_isSet; + + qint64 rx_transverter_delta_frequency; + bool m_rx_transverter_delta_frequency_isSet; + + qint32 rx0_gain_mode; + bool m_rx0_gain_mode_isSet; + + qint32 rx0_gain; + bool m_rx0_gain_isSet; + + QString* rx0_antenna_path; + bool m_rx0_antenna_path_isSet; + + qint32 rx1_gain_mode; + bool m_rx1_gain_mode_isSet; + + qint32 rx1_gain; + bool m_rx1_gain_isSet; + + QString* rx1_antenna_path; + bool m_rx1_antenna_path_isSet; + + qint64 tx_center_frequency; + bool m_tx_center_frequency_isSet; + + qint32 tx_lo_offset; + bool m_tx_lo_offset_isSet; + + qint32 log2_soft_interp; + bool m_log2_soft_interp_isSet; + + qint32 tx_lpf_bw; + bool m_tx_lpf_bw_isSet; + + qint32 tx_transverter_mode; + bool m_tx_transverter_mode_isSet; + + qint64 tx_transverter_delta_frequency; + bool m_tx_transverter_delta_frequency_isSet; + + qint32 tx0_gain; + bool m_tx0_gain_isSet; + + QString* tx0_antenna_path; + bool m_tx0_antenna_path_isSet; + + qint32 tx1_gain; + bool m_tx1_gain_isSet; + + QString* tx1_antenna_path; + bool m_tx1_antenna_path_isSet; + + qint32 use_reverse_api; + bool m_use_reverse_api_isSet; + + QString* reverse_api_address; + bool m_reverse_api_address_isSet; + + qint32 reverse_api_port; + bool m_reverse_api_port_isSet; + + qint32 reverse_api_device_index; + bool m_reverse_api_device_index_isSet; + +}; + +} + +#endif /* SWGUSRPMIMOSettings_H_ */