moved USB/packet log into LibreVNA driver, cleanup old device class

This commit is contained in:
Jan Käberich 2023-02-12 21:43:51 +01:00
parent 9e858feeba
commit 9b5bb1678c
26 changed files with 147 additions and 1955 deletions

View File

@ -3,7 +3,6 @@
#include "caldevice.h"
#include "usbdevice.h"
#include "Device/virtualdevice.h"
#include "CustomWidgets/informationbox.h"
#include <set>

View File

@ -1,7 +1,7 @@
#include "compounddeviceeditdialog.h"
#include "ui_compounddeviceeditdialog.h"
#include "../../device.h"
#include "compounddriver.h"
#include <QPushButton>
#include <QDrag>
@ -513,13 +513,9 @@ void DeviceFrame::update()
port2->setCurrentIndex(0);
}
auto devices = Device::GetDevices();
for(auto d : devices) {
for(auto d : CompoundDriver::getIndividualDeviceSerials()) {
serial->addItem(d);
}
// if(!serial->findText(s) >= 0) {
// serial->addItem(s);
// }
serial->setCurrentText(s);
if(dev->sync == LibreVNADriver::Synchronization::GUI) {

View File

@ -449,6 +449,21 @@ bool CompoundDriver::setExtRef(QString option_in, QString option_out)
return success;
}
std::set<QString> CompoundDriver::getIndividualDeviceSerials()
{
std::vector<LibreVNADriver*> drivers;
drivers.push_back(new LibreVNAUSBDriver);
drivers.push_back(new LibreVNATCPDriver);
auto &p = Preferences::getInstance();
std::set<QString> ret;
for(auto d : drivers) {
p.load(d->driverSpecificSettings());
ret.merge(d->GetAvailableDevices());
}
return ret;
}
void CompoundDriver::parseCompoundJSON()
{
try {

View File

@ -167,6 +167,8 @@ public:
*/
virtual bool setExtRef(QString option_in, QString option_out) override;
static std::set<QString> getIndividualDeviceSerials();
private:
void parseCompoundJSON();
void createCompoundJSON();

View File

@ -1,4 +1,4 @@
#include "deviceusblog.h"
#include "devicepacketlog.h"
#include "preferences.h"
@ -8,26 +8,26 @@
using namespace std;
DeviceUSBLog::DeviceUSBLog()
DevicePacketLog::DevicePacketLog()
: usedStorageSize(0)
{
auto &pref = Preferences::getInstance();
maxStorageSize = pref.Debug.USBlogSizeLimit;
}
DeviceUSBLog::~DeviceUSBLog()
DevicePacketLog::~DevicePacketLog()
{
}
void DeviceUSBLog::reset()
void DevicePacketLog::reset()
{
std::lock_guard<mutex> guard(access);
entries.clear();
usedStorageSize = 0;
}
void DeviceUSBLog::addPacket(Protocol::PacketInfo &p, QString serial)
void DevicePacketLog::addPacket(Protocol::PacketInfo &p, QString serial)
{
LogEntry e;
e.timestamp = QDateTime::currentDateTimeUtc();
@ -43,7 +43,7 @@ void DeviceUSBLog::addPacket(Protocol::PacketInfo &p, QString serial)
addEntry(e);
}
void DeviceUSBLog::addInvalidBytes(const uint8_t *bytes, uint16_t len, QString serial)
void DevicePacketLog::addInvalidBytes(const uint8_t *bytes, uint16_t len, QString serial)
{
LogEntry e;
e.timestamp = QDateTime::currentDateTimeUtc();
@ -55,7 +55,7 @@ void DeviceUSBLog::addInvalidBytes(const uint8_t *bytes, uint16_t len, QString s
addEntry(e);
}
nlohmann::json DeviceUSBLog::toJSON()
nlohmann::json DevicePacketLog::toJSON()
{
nlohmann::json j;
for(auto &e : entries) {
@ -64,7 +64,7 @@ nlohmann::json DeviceUSBLog::toJSON()
return j;
}
void DeviceUSBLog::fromJSON(nlohmann::json j)
void DevicePacketLog::fromJSON(nlohmann::json j)
{
reset();
for(auto jd : j) {
@ -74,7 +74,7 @@ void DeviceUSBLog::fromJSON(nlohmann::json j)
}
}
DeviceUSBLog::LogEntry DeviceUSBLog::getEntry(unsigned int index)
DevicePacketLog::LogEntry DevicePacketLog::getEntry(unsigned int index)
{
std::lock_guard<mutex> guard(access);
if(index < entries.size()) {
@ -84,7 +84,7 @@ DeviceUSBLog::LogEntry DeviceUSBLog::getEntry(unsigned int index)
}
}
void DeviceUSBLog::addEntry(const DeviceUSBLog::LogEntry &e)
void DevicePacketLog::addEntry(const DevicePacketLog::LogEntry &e)
{
std::lock_guard<mutex> guard(access);
usedStorageSize += e.storageSize();
@ -96,17 +96,17 @@ void DeviceUSBLog::addEntry(const DeviceUSBLog::LogEntry &e)
emit entryAdded(e);
}
unsigned long DeviceUSBLog::getMaxStorageSize() const
unsigned long DevicePacketLog::getMaxStorageSize() const
{
return maxStorageSize;
}
unsigned long DeviceUSBLog::getUsedStorageSize() const
unsigned long DevicePacketLog::getUsedStorageSize() const
{
return usedStorageSize;
}
DeviceUSBLog::LogEntry::LogEntry(const DeviceUSBLog::LogEntry &e)
DevicePacketLog::LogEntry::LogEntry(const DevicePacketLog::LogEntry &e)
{
timestamp = e.timestamp;
type = e.type;
@ -115,12 +115,18 @@ DeviceUSBLog::LogEntry::LogEntry(const DeviceUSBLog::LogEntry &e)
if(e.p) {
p = new Protocol::PacketInfo;
*p = *e.p;
if(p->type == Protocol::PacketType::VNADatapoint) {
datapoint = new Protocol::VNADatapoint<32>(*e.datapoint);
} else {
datapoint = nullptr;
}
} else {
datapoint = nullptr;
p = nullptr;
}
}
nlohmann::json DeviceUSBLog::LogEntry::toJSON()
nlohmann::json DevicePacketLog::LogEntry::toJSON()
{
nlohmann::json j;
j["type"] = type == Type::Packet ? "Packet" : "InvalidBytes";
@ -131,6 +137,13 @@ nlohmann::json DeviceUSBLog::LogEntry::toJSON()
for(unsigned int i=0;i<sizeof(Protocol::PacketInfo);i++) {
jdata.push_back(*(((uint8_t*) p) + i));
}
if(datapoint) {
nlohmann::json jdatapoint;
for(unsigned int i=0;i<sizeof(*datapoint);i++) {
jdatapoint.push_back(*(((uint8_t*) datapoint) + i));
}
j["datapoint"] = jdatapoint;
}
} else {
for(auto b : bytes) {
jdata.push_back(b);
@ -140,17 +153,26 @@ nlohmann::json DeviceUSBLog::LogEntry::toJSON()
return j;
}
void DeviceUSBLog::LogEntry::fromJSON(nlohmann::json j)
void DevicePacketLog::LogEntry::fromJSON(nlohmann::json j)
{
type = QString::fromStdString(j.value("type", "")) == "Packet" ? Type::Packet : Type::InvalidBytes;
timestamp = QDateTime::fromMSecsSinceEpoch(j.value("timestamp", 0UL), Qt::TimeSpec::UTC);
serial = QString::fromStdString(j.value("serial", ""));
datapoint = nullptr;
p = nullptr;
if(type == Type::Packet) {
p = new Protocol::PacketInfo;
auto jdata = j["data"];
for(unsigned int i=0;i<sizeof(Protocol::PacketInfo);i++) {
*(((uint8_t*) p) + i) = jdata[i];
}
if(j.contains("datapoint")) {
datapoint = new Protocol::VNADatapoint<32>();
auto jdatapoint = j["datapoint"];
for(unsigned int i=0;i<sizeof(*datapoint);i++) {
*(((uint8_t*) datapoint) + i) = jdatapoint[i];
}
}
} else {
for(auto v : j["data"]) {
bytes.push_back(v);

View File

@ -11,16 +11,16 @@
#include <QObject>
#include <mutex>
class DeviceUSBLog : public QObject, public Savable
class DevicePacketLog : public QObject, public Savable
{
Q_OBJECT
public:
static DeviceUSBLog& getInstance() {
static DeviceUSBLog instance;
static DevicePacketLog& getInstance() {
static DevicePacketLog instance;
return instance;
}
DeviceUSBLog(const DeviceUSBLog&) = delete;
virtual ~DeviceUSBLog();
DevicePacketLog(const DevicePacketLog&) = delete;
virtual ~DevicePacketLog();
void reset();
@ -34,9 +34,10 @@ public:
class LogEntry : public Savable {
public:
LogEntry()
: type(Type::InvalidBytes), timestamp(QDateTime()), serial(""), p(nullptr) {}
: type(Type::InvalidBytes), timestamp(QDateTime()), serial(""), p(nullptr), datapoint(nullptr) {}
~LogEntry() {
delete p;
delete datapoint;
}
LogEntry(const LogEntry &e);
@ -55,7 +56,12 @@ public:
unsigned long size = sizeof(type) + sizeof(timestamp) + serial.size();
switch(type) {
case Type::InvalidBytes: size += bytes.size(); break;
case Type::Packet: size += sizeof(Protocol::PacketInfo); break;
case Type::Packet:
size += sizeof(Protocol::PacketInfo);
if(p && p->type == Protocol::PacketType::VNADatapoint) {
size += sizeof(Protocol::VNADatapoint<32>);
}
break;
}
return size;
}
@ -73,7 +79,7 @@ signals:
void entryAdded(const LogEntry &e);
private:
DeviceUSBLog();
DevicePacketLog();
void addEntry(const LogEntry &e);

View File

@ -1,5 +1,5 @@
#include "deviceusblogview.h"
#include "ui_deviceusblogview.h"
#include "devicepacketlogview.h"
#include "ui_devicepacketlogview.h"
#include "CustomWidgets/informationbox.h"
#include "unit.h"
@ -13,16 +13,16 @@
using namespace std;
DeviceUSBLogView::DeviceUSBLogView(QWidget *parent) :
DevicePacketLogView::DevicePacketLogView(QWidget *parent) :
QDialog(parent),
ui(new Ui::DeviceUSBLogView)
ui(new Ui::DevicePacketLogView)
{
setAttribute(Qt::WA_DeleteOnClose);
ui->setupUi(this);
// connect(&log, &DeviceUSBLog::entryAdded, this, &DeviceUSBLogView::addEntry);
connect(ui->buttonBox->button(QDialogButtonBox::Reset), &QPushButton::clicked, [=](){
DeviceUSBLog::getInstance().reset();
DevicePacketLog::getInstance().reset();
updateTree();
});
connect(ui->buttonBox->button(QDialogButtonBox::Save), &QPushButton::clicked, [=](){
@ -36,7 +36,7 @@ DeviceUSBLogView::DeviceUSBLogView(QWidget *parent) :
}
ofstream file;
file.open(filename.toStdString());
file << setw(1) << DeviceUSBLog::getInstance().toJSON() << endl;
file << setw(1) << DevicePacketLog::getInstance().toJSON() << endl;
file.close();
});
connect(ui->buttonBox->button(QDialogButtonBox::Open), &QPushButton::clicked, [=](){
@ -62,21 +62,21 @@ DeviceUSBLogView::DeviceUSBLogView(QWidget *parent) :
return;
}
file.close();
DeviceUSBLog::getInstance().fromJSON(j);
DevicePacketLog::getInstance().fromJSON(j);
updateTree();
});
updateTree();
}
DeviceUSBLogView::~DeviceUSBLogView()
DevicePacketLogView::~DevicePacketLogView()
{
delete ui;
}
void DeviceUSBLogView::updateTree()
void DevicePacketLogView::updateTree()
{
auto &log = DeviceUSBLog::getInstance();
auto &log = DevicePacketLog::getInstance();
ui->tree->clear();
ui->tree->setColumnCount(4);
@ -96,13 +96,13 @@ void DeviceUSBLogView::updateTree()
ui->status->setText(status);
}
void DeviceUSBLogView::addEntry(const DeviceUSBLog::LogEntry &e)
void DevicePacketLogView::addEntry(const DevicePacketLog::LogEntry &e)
{
auto item = new QTreeWidgetItem;
item->setData(0, Qt::DisplayRole, e.timestamp.toString(Qt::DateFormat::ISODateWithMs));
item->setData(1, Qt::DisplayRole, e.serial.size() > 0 ? e.serial : "LibreVNA-GUI");
item->setData(2, Qt::DisplayRole, e.type == DeviceUSBLog::LogEntry::Type::Packet ? "Packet" : "Invalid bytes");
if(e.type == DeviceUSBLog::LogEntry::Type::Packet) {
item->setData(2, Qt::DisplayRole, e.type == DevicePacketLog::LogEntry::Type::Packet ? "Packet" : "Invalid bytes");
if(e.type == DevicePacketLog::LogEntry::Type::Packet) {
item->setData(2, Qt::DisplayRole, "Packet");
static const QStringList packetNames = {"None", "Datapoint", "SweepSettings", "ManualStatusV1", "ManualControlV1", "DeviceInfo", "FirmwarePacket", "Ack",

View File

@ -0,0 +1,27 @@
#ifndef DEVICEUSBLOGVIEW_H
#define DEVICEUSBLOGVIEW_H
#include "devicepacketlog.h"
#include <QDialog>
namespace Ui {
class DevicePacketLogView;
}
class DevicePacketLogView : public QDialog
{
Q_OBJECT
public:
explicit DevicePacketLogView(QWidget *parent = nullptr);
~DevicePacketLogView();
private slots:
void updateTree();
void addEntry(const DevicePacketLog::LogEntry &e);
private:
Ui::DevicePacketLogView *ui;
};
#endif // DEVICEUSBLOGVIEW_H

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DeviceUSBLogView</class>
<widget class="QDialog" name="DeviceUSBLogView">
<class>DevicePacketLogView</class>
<widget class="QDialog" name="DevicePacketLogView">
<property name="geometry">
<rect>
<x>0</x>

View File

@ -7,6 +7,7 @@
#include "receivercaldialog.h"
#include "unit.h"
#include "CustomWidgets/informationbox.h"
#include "devicepacketlogview.h"
#include "ui_librevnadriversettingswidget.h"
@ -147,6 +148,17 @@ LibreVNADriver::LibreVNADriver()
d->show();
});
specificActions.push_back(freqcal);
sep = new QAction();
sep->setSeparator(true);
specificActions.push_back(sep);
auto log = new QAction("View Packet Log");
connect(log, &QAction::triggered, this, [=](){
auto d = new DevicePacketLogView();
d->show();
});
specificActions.push_back(log);
}
std::set<DeviceDriver::Flag> LibreVNADriver::getFlags()

View File

@ -1,7 +1,7 @@
#include "librevnatcpdriver.h"
#include "CustomWidgets/informationbox.h"
#include "../deviceusblog.h"
#include "devicepacketlog.h"
#include "Util/util.h"
#include <QTimer>
@ -224,7 +224,7 @@ void LibreVNATCPDriver::ReceivedData()
handled_len = Protocol::DecodeBuffer((uint8_t*) dataBuffer.data(), dataBuffer.size(), &packet);
// qDebug() << "Handled" << handled_len << "Bytes, type:" << (int) packet.type;
if(handled_len > 0) {
auto &log = DeviceUSBLog::getInstance();
auto &log = DevicePacketLog::getInstance();
if(packet.type != Protocol::PacketType::None) {
log.addPacket(packet, serial);
} else {
@ -354,7 +354,7 @@ bool LibreVNATCPDriver::startNextTransmission()
qCritical() << "Failed to encode packet";
return false;
}
auto &log = DeviceUSBLog::getInstance();
auto &log = DevicePacketLog::getInstance();
log.addPacket(t.packet);
auto ret = dataSocket.write((char*) buffer, length);
if(ret < 0) {

View File

@ -1,7 +1,7 @@
#include "librevnausbdriver.h"
#include "CustomWidgets/informationbox.h"
#include "../deviceusblog.h"
#include "devicepacketlog.h"
#include <QTimer>
@ -271,7 +271,7 @@ void LibreVNAUSBDriver::ReceivedData()
handled_len = Protocol::DecodeBuffer(dataBuffer->getBuffer(), dataBuffer->getReceived(), &packet);
// qDebug() << "Handled" << handled_len << "Bytes, type:" << (int) packet.type;
if(handled_len > 0) {
auto &log = DeviceUSBLog::getInstance();
auto &log = DevicePacketLog::getInstance();
if(packet.type != Protocol::PacketType::None) {
log.addPacket(packet, serial);
} else {
@ -458,7 +458,7 @@ bool LibreVNAUSBDriver::startNextTransmission()
return false;
}
int actual_length;
auto &log = DeviceUSBLog::getInstance();
auto &log = DevicePacketLog::getInstance();
log.addPacket(t.packet);
auto ret = libusb_bulk_transfer(m_handle, EP_Data_Out_Addr, buffer, length, &actual_length, 0);
if(ret < 0) {

View File

@ -1,654 +0,0 @@
#include "device.h"
#include "CustomWidgets/informationbox.h"
#include "deviceusblog.h"
#include <signal.h>
#include <QDebug>
#include <QString>
#include <QMessageBox>
#include <mutex>
#include "devicedriver.h"
using namespace std;
using USBID = struct {
int VID;
int PID;
};
static constexpr USBID IDs[] = {
{0x0483, 0x564e},
{0x0483, 0x4121},
};
//USBInBuffer::USBInBuffer(libusb_device_handle *handle, unsigned char endpoint, int buffer_size) :
// buffer_size(buffer_size),
// received_size(0),
// inCallback(false),
// cancelling(false)
//{
// buffer = new unsigned char[buffer_size];
// memset(buffer, 0, buffer_size);
// transfer = libusb_alloc_transfer(0);
// libusb_fill_bulk_transfer(transfer, handle, endpoint, buffer, buffer_size, CallbackTrampoline, this, 0);
// libusb_submit_transfer(transfer);
//}
//USBInBuffer::~USBInBuffer()
//{
// if(transfer) {
// cancelling = true;
// libusb_cancel_transfer(transfer);
// // wait for cancellation to complete
// mutex mtx;
// unique_lock<mutex> lck(mtx);
// using namespace std::chrono_literals;
// if(cv.wait_for(lck, 100ms) == cv_status::timeout) {
// qWarning() << "Timed out waiting for mutex acquisition during disconnect";
// }
// }
// delete[] buffer;
//}
//void USBInBuffer::removeBytes(int handled_bytes)
//{
// if(!inCallback) {
// throw runtime_error("Removing of bytes is only allowed from within receive callback");
// }
// if(handled_bytes >= received_size) {
// received_size = 0;
// } else {
// // not removing all bytes, have to move remaining data to the beginning of the buffer
// memmove(buffer, &buffer[handled_bytes], received_size - handled_bytes);
// received_size -= handled_bytes;
// }
//}
//int USBInBuffer::getReceived() const
//{
// return received_size;
//}
//void USBInBuffer::Callback(libusb_transfer *transfer)
//{
// if(cancelling || (transfer->status == LIBUSB_TRANSFER_CANCELLED)) {
// // destructor called, do not resubmit
// libusb_free_transfer(transfer);
// this->transfer = nullptr;
// cv.notify_all();
// return;
// }
//// qDebug() << libusb_error_name(transfer->status);
// switch(transfer->status) {
// case LIBUSB_TRANSFER_COMPLETED:
// received_size += transfer->actual_length;
// // Change/insert/delete random data to check the data handling for robustness
//// srand((unsigned)time(0));
//// for(unsigned int i=0;i<received_size;i++) {
//// auto r = rand() % 100;
//// if(r == 0) {
//// // modify this byte
//// buffer[i] = rand() % 256;
//// } else if(r == 1) {
//// // insert random byte
//// memmove(&buffer[i+1], &buffer[i], received_size - i);
//// buffer[i] = rand() % 256;
//// received_size++;
//// } else if(r == 2) {
//// // remove byte
//// memmove(&buffer[i], &buffer[i+1], received_size - i - 1);
//// received_size--;
//// }
//// }
//// qDebug() << transfer->actual_length <<"total:" << received_size;
// inCallback = true;
// emit DataReceived();
// inCallback = false;
// break;
// case LIBUSB_TRANSFER_NO_DEVICE:
// qCritical() << "LIBUSB_TRANSFER_NO_DEVICE";
// libusb_free_transfer(transfer);
// return;
// case LIBUSB_TRANSFER_ERROR:
// case LIBUSB_TRANSFER_OVERFLOW:
// case LIBUSB_TRANSFER_STALL:
// qCritical() << "LIBUSB_ERROR" << transfer->status;
// libusb_free_transfer(transfer);
// this->transfer = nullptr;
// emit TransferError();
// return;
// break;
// case LIBUSB_TRANSFER_TIMED_OUT:
// // nothing to do
// break;
// case LIBUSB_TRANSFER_CANCELLED:
// // already handled before switch-case
// break;
// }
// // Resubmit the transfer
// transfer->buffer = &buffer[received_size];
// transfer->length = buffer_size - received_size;
// libusb_submit_transfer(transfer);
//}
//void USBInBuffer::CallbackTrampoline(libusb_transfer *transfer)
//{
// auto usb = (USBInBuffer*) transfer->user_data;
// usb->Callback(transfer);
//}
//uint8_t *USBInBuffer::getBuffer() const
//{
// return buffer;
//}
static constexpr Protocol::DeviceInfo defaultInfo = {
.ProtocolVersion = Protocol::Version,
.FW_major = 0,
.FW_minor = 0,
.FW_patch = 0,
.hardware_version = 1,
.HW_Revision = '0',
.limits_minFreq = 0,
.limits_maxFreq = 6000000000,
.limits_minIFBW = 10,
.limits_maxIFBW = 1000000,
.limits_maxPoints = 10000,
.limits_cdbm_min = -10000,
.limits_cdbm_max = 1000,
.limits_minRBW = 1,
.limits_maxRBW = 1000000,
.limits_maxAmplitudePoints = 255,
.limits_maxFreqHarmonic = 18000000000,
};
static constexpr Protocol::DeviceStatusV1 defaultStatusV1 = {
.extRefAvailable = 0,
.extRefInUse = 0,
.FPGA_configured = 0,
.source_locked = 0,
.LO1_locked = 0,
.ADC_overload = 0,
.unlevel = 0,
.temp_source = 0,
.temp_LO1 = 0,
.temp_MCU = 0,
};
Device::Device(QString serial, bool ignoreOpenError)
{
info = defaultInfo;
status = {};
m_handle = nullptr;
infoValid = false;
libusb_init(&m_context);
#if LIBUSB_API_VERSION >= 0x01000106
libusb_set_option(m_context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO);
#endif
SearchDevices([=](libusb_device_handle *handle, QString found_serial) -> bool {
if(serial.isEmpty() || serial == found_serial) {
// accept connection to this device
m_serial = found_serial;
m_handle = handle;
// abort device search
return false;
} else {
// not the requested device, continue search
return true;
}
}, m_context, ignoreOpenError);
if(!m_handle) {
QString message = "No device found";
if(!serial.isEmpty()) {
// only show error message if specific device was requested
InformationBox::ShowError("Error opening device", message);
}
libusb_exit(m_context);
throw std::runtime_error(message.toStdString());
return;
}
// Found the correct device, now connect
/* claim the interface */
int ret = libusb_claim_interface(m_handle, 0);
if (ret < 0) {
libusb_close(m_handle);
/* Failed to open */
QString message = "Failed to claim interface: \"";
message.append(libusb_strerror((libusb_error) ret));
message.append("\" Maybe you are already connected to this device?");
qWarning() << message;
InformationBox::ShowError("Error opening device", message);
libusb_exit(m_context);
throw std::runtime_error(message.toStdString());
}
qInfo() << "USB connection established" << flush;
m_connected = true;
m_receiveThread = new std::thread(&Device::USBHandleThread, this);
dataBuffer = new USBInBuffer(m_handle, EP_Data_In_Addr, 65536);
logBuffer = new USBInBuffer(m_handle, EP_Log_In_Addr, 65536);
connect(dataBuffer, &USBInBuffer::DataReceived, this, &Device::ReceivedData, Qt::DirectConnection);
connect(dataBuffer, &USBInBuffer::TransferError, this, &Device::ConnectionLost);
connect(logBuffer, &USBInBuffer::DataReceived, this, &Device::ReceivedLog, Qt::DirectConnection);
connect(&transmissionTimer, &QTimer::timeout, this, &Device::transmissionTimeout);
connect(this, &Device::receivedAnswer, this, &Device::transmissionFinished, Qt::QueuedConnection);
transmissionTimer.setSingleShot(true);
transmissionActive = false;
}
Device::~Device()
{
if(m_connected) {
SetIdle();
delete dataBuffer;
delete logBuffer;
m_connected = false;
for (int if_num = 0; if_num < 1; if_num++) {
int ret = libusb_release_interface(m_handle, if_num);
if (ret < 0) {
qCritical() << "Error releasing interface" << libusb_error_name(ret);
}
}
libusb_release_interface(m_handle, 0);
libusb_close(m_handle);
m_receiveThread->join();
libusb_exit(m_context);
delete m_receiveThread;
}
}
void Device::RegisterTypes()
{
qRegisterMetaType<Protocol::Datapoint>("Datapoint");
qRegisterMetaType<Protocol::ManualStatusV1>("ManualV1");
qRegisterMetaType<Protocol::SpectrumAnalyzerResult>("SpectrumAnalyzerResult");
qRegisterMetaType<Protocol::AmplitudeCorrectionPoint>("AmplitudeCorrection");
}
bool Device::SendPacket(const Protocol::PacketInfo& packet, std::function<void(TransmissionResult)> cb, unsigned int timeout)
{
Transmission t;
t.packet = packet;
t.timeout = timeout;
t.callback = cb;
lock_guard<mutex> lock(transmissionMutex);
transmissionQueue.enqueue(t);
// qDebug() << "Enqueued packet, queue at " << transmissionQueue.size();
if(!transmissionActive) {
startNextTransmission();
}
return true;
}
bool Device::Configure(Protocol::SweepSettings settings, std::function<void(TransmissionResult)> cb)
{
Protocol::PacketInfo p;
p.type = Protocol::PacketType::SweepSettings;
p.settings = settings;
return SendPacket(p, cb);
}
bool Device::Configure(Protocol::SpectrumAnalyzerSettings settings, std::function<void (Device::TransmissionResult)> cb)
{
Protocol::PacketInfo p;
p.type = Protocol::PacketType::SpectrumAnalyzerSettings;
p.spectrumSettings = settings;
return SendPacket(p, cb);
}
bool Device::SetManual(Protocol::ManualControlV1 manual)
{
Protocol::PacketInfo p;
p.type = Protocol::PacketType::ManualControlV1;
p.manual = manual;
return SendPacket(p);
}
bool Device::SetIdle(std::function<void(TransmissionResult)> cb)
{
return SendCommandWithoutPayload(Protocol::PacketType::SetIdle, cb);
}
bool Device::SendFirmwareChunk(Protocol::FirmwarePacket &fw)
{
Protocol::PacketInfo p;
p.type = Protocol::PacketType::FirmwarePacket;
p.firmware = fw;
return SendPacket(p);
}
bool Device::SendCommandWithoutPayload(Protocol::PacketType type, std::function<void(TransmissionResult)> cb)
{
Protocol::PacketInfo p;
p.type = type;
return SendPacket(p, cb);
}
std::set<QString> Device::GetDevices()
{
std::set<QString> serials;
libusb_context *ctx;
libusb_init(&ctx);
#if LIBUSB_API_VERSION >= 0x01000106
libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO);
#endif
SearchDevices([&serials](libusb_device_handle *, QString serial) -> bool {
serials.insert(serial);
return true;
}, ctx, true);
libusb_exit(ctx);
return serials;
}
void Device::SetTrigger(bool set)
{
if(set) {
SendCommandWithoutPayload(Protocol::PacketType::SetTrigger);
} else {
SendCommandWithoutPayload(Protocol::PacketType::ClearTrigger);
}
}
void Device::USBHandleThread()
{
qDebug() << "Receive thread started";
while (m_connected) {
libusb_handle_events(m_context);
}
qDebug() << "Disconnected, receive thread exiting";
}
void Device::SearchDevices(std::function<bool (libusb_device_handle *, QString)> foundCallback, libusb_context *context, bool ignoreOpenError)
{
libusb_device **devList;
auto ndevices = libusb_get_device_list(context, &devList);
for (ssize_t idx = 0; idx < ndevices; idx++) {
int ret;
libusb_device *device = devList[idx];
libusb_device_descriptor desc = {};
ret = libusb_get_device_descriptor(device, &desc);
if (ret) {
/* some error occured */
qCritical() << "Failed to get device descriptor: "
<< libusb_strerror((libusb_error) ret);
continue;
}
bool correctID = false;
int numIDs = sizeof(IDs)/sizeof(IDs[0]);
for(int i=0;i<numIDs;i++) {
if(desc.idVendor == IDs[i].VID && desc.idProduct == IDs[i].PID) {
correctID = true;
break;
}
}
if(!correctID) {
continue;
}
/* Try to open the device */
libusb_device_handle *handle = nullptr;
ret = libusb_open(device, &handle);
if (ret) {
qDebug() << libusb_strerror((enum libusb_error) ret);
/* Failed to open */
if(!ignoreOpenError) {
QString message = "Found potential device but failed to open usb connection: \"";
message.append(libusb_strerror((libusb_error) ret));
message.append("\" On Linux this is most likely caused by a missing udev rule. "
"On Windows this most likely means that you are already connected to "
"this device (is another instance of the application already runnning?)");
qWarning() << message;
InformationBox::ShowError("Error opening device", message);
}
continue;
}
char c_product[256];
char c_serial[256];
libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber,
(unsigned char*) c_serial, sizeof(c_serial));
ret = libusb_get_string_descriptor_ascii(handle, desc.iProduct,
(unsigned char*) c_product, sizeof(c_product));
if (ret > 0) {
/* managed to read the product string */
QString product(c_product);
if (product == "VNA") {
// this is a match
if(!foundCallback(handle, QString(c_serial))) {
// abort search
break;
}
}
} else {
qWarning() << "Failed to get product descriptor: "
<< libusb_strerror((libusb_error) ret);
}
libusb_close(handle);
}
libusb_free_device_list(devList, 1);
}
const Protocol::DeviceInfo &Device::Info()
{
return info;
}
const Protocol::DeviceInfo &Device::Info(Device *dev)
{
if(dev) {
return dev->Info();
} else {
return defaultInfo;
}
}
Protocol::DeviceStatusV1 &Device::StatusV1()
{
lock_guard<mutex> guard(accessMutex);
return status.v1;
}
const Protocol::DeviceStatusV1 &Device::StatusV1(Device *dev)
{
if(dev) {
return dev->StatusV1();
} else {
return defaultStatusV1;
}
}
QString Device::getLastDeviceInfoString()
{
lock_guard<mutex> guard(accessMutex);
QString ret;
if(!infoValid) {
ret.append("No device information available yet");
} else {
ret.append("HW Rev.");
ret.append(info.HW_Revision);
ret.append(" FW "+QString::number(info.FW_major)+"."+QString::number(info.FW_minor)+"."+QString::number(info.FW_patch));
ret.append(" Temps: "+QString::number(status.v1.temp_source)+"°C/"+QString::number(status.v1.temp_LO1)+"°C/"+QString::number(status.v1.temp_MCU)+"°C");
ret.append(" Reference:");
if(status.v1.extRefInUse) {
ret.append("External");
} else {
ret.append("Internal");
if(status.v1.extRefAvailable) {
ret.append(" (External available)");
}
}
}
return ret;
}
void Device::ReceivedData()
{
Protocol::PacketInfo packet;
uint16_t handled_len;
// qDebug() << "Received data";
do {
// qDebug() << "Decoding" << dataBuffer->getReceived() << "Bytes";
handled_len = Protocol::DecodeBuffer(dataBuffer->getBuffer(), dataBuffer->getReceived(), &packet);
// qDebug() << "Handled" << handled_len << "Bytes, type:" << (int) packet.type;
if(handled_len > 0) {
auto &log = DeviceUSBLog::getInstance();
if(packet.type != Protocol::PacketType::None) {
log.addPacket(packet, m_serial);
} else {
log.addInvalidBytes(dataBuffer->getBuffer(), handled_len, m_serial);
}
}
dataBuffer->removeBytes(handled_len);
switch(packet.type) {
case Protocol::PacketType::VNADatapoint:
// qDebug() << "Got point" << packet.VNAdatapoint->pointNum;
emit DatapointReceived(this, packet.VNAdatapoint);
break;
case Protocol::PacketType::ManualStatusV1:
emit ManualStatusReceived(packet.manualStatusV1);
break;
case Protocol::PacketType::SpectrumAnalyzerResult:
emit SpectrumResultReceived(this, packet.spectrumResult);
break;
case Protocol::PacketType::SourceCalPoint:
case Protocol::PacketType::ReceiverCalPoint:
emit AmplitudeCorrectionPointReceived(packet.amplitudePoint);
break;
case Protocol::PacketType::DeviceInfo:
{
lock_guard<mutex> guard(accessMutex);
if(packet.info.ProtocolVersion != Protocol::Version) {
if(!infoValid) {
emit NeedsFirmwareUpdate(packet.info.ProtocolVersion, Protocol::Version);
}
} else {
info = packet.info;
}
infoValid = true;
}
emit DeviceInfoUpdated(this);
break;
case Protocol::PacketType::DeviceStatusV1:
{
lock_guard<mutex> guard(accessMutex);
status.v1 = packet.statusV1;
}
emit DeviceStatusUpdated(this);
break;
case Protocol::PacketType::Ack:
emit AckReceived();
emit receivedAnswer(TransmissionResult::Ack);
break;
case Protocol::PacketType::Nack:
emit NackReceived();
emit receivedAnswer(TransmissionResult::Nack);
break;
case Protocol::PacketType::FrequencyCorrection:
emit FrequencyCorrectionReceived(packet.frequencyCorrection.ppm);
break;
case Protocol::PacketType::SetTrigger:
emit TriggerReceived(true);
break;
case Protocol::PacketType::ClearTrigger:
emit TriggerReceived(false);
break;
default:
break;
}
} while (handled_len > 0);
}
void Device::ReceivedLog()
{
uint16_t handled_len;
do {
handled_len = 0;
auto firstLinebreak = (uint8_t*) memchr(logBuffer->getBuffer(), '\n', logBuffer->getReceived());
if(firstLinebreak) {
handled_len = firstLinebreak - logBuffer->getBuffer();
auto line = QString::fromLatin1((const char*) logBuffer->getBuffer(), handled_len - 1);
emit LogLineReceived(line);
logBuffer->removeBytes(handled_len + 1);
}
} while(handled_len > 0);
}
QString Device::serial() const
{
return m_serial;
}
bool Device::startNextTransmission()
{
if(transmissionQueue.isEmpty() || !m_connected) {
// nothing more to transmit
transmissionActive = false;
return false;
}
transmissionActive = true;
auto t = transmissionQueue.head();
unsigned char buffer[1024];
unsigned int length = Protocol::EncodePacket(t.packet, buffer, sizeof(buffer));
if(!length) {
qCritical() << "Failed to encode packet";
return false;
}
int actual_length;
auto &log = DeviceUSBLog::getInstance();
log.addPacket(t.packet);
auto ret = libusb_bulk_transfer(m_handle, EP_Data_Out_Addr, buffer, length, &actual_length, 0);
if(ret < 0) {
qCritical() << "Error sending data: "
<< libusb_strerror((libusb_error) ret);
return false;
}
transmissionTimer.start(t.timeout);
// qDebug() << "Transmission started, queue at " << transmissionQueue.size();
return true;
}
void Device::transmissionFinished(TransmissionResult result)
{
lock_guard<mutex> lock(transmissionMutex);
// remove transmitted packet
// qDebug() << "Transmission finsished (" << result << "), queue at " << transmissionQueue.size() << " Outstanding ACKs:"<<outstandingAckCount;
if(transmissionQueue.empty()) {
qWarning() << "transmissionFinished with empty transmission queue, stray Ack? Result:" << result;
return;
}
auto t = transmissionQueue.dequeue();
if(result == TransmissionResult::Timeout) {
qWarning() << "transmissionFinished with timeout, packettype:" << (int) t.packet.type << "Device:" << serial();
}
if(result == TransmissionResult::Nack) {
qWarning() << "transmissionFinished with NACK";
}
if(t.callback) {
t.callback(result);
}
transmissionTimer.stop();
bool success = false;
while(!transmissionQueue.isEmpty() && !success) {
success = startNextTransmission();
if(!success) {
// failed to send this packet
auto t = transmissionQueue.dequeue();
if(t.callback) {
t.callback(TransmissionResult::InternalError);
}
}
}
if(transmissionQueue.isEmpty()) {
transmissionActive = false;
}
}

View File

@ -1,27 +0,0 @@
#ifndef DEVICEUSBLOGVIEW_H
#define DEVICEUSBLOGVIEW_H
#include "deviceusblog.h"
#include <QDialog>
namespace Ui {
class DeviceUSBLogView;
}
class DeviceUSBLogView : public QDialog
{
Q_OBJECT
public:
explicit DeviceUSBLogView(QWidget *parent = nullptr);
~DeviceUSBLogView();
private slots:
void updateTree();
void addEntry(const DeviceUSBLog::LogEntry &e);
private:
Ui::DeviceUSBLogView *ui;
};
#endif // DEVICEUSBLOGVIEW_H

View File

@ -1,928 +0,0 @@
//#include "virtualdevice.h"
//#include "preferences.h"
//#include "CustomWidgets/informationbox.h"
//#include "../../VNA_embedded/Application/Communication/Protocol.hpp"
//#include <cmath>
//static VirtualDevice *connected = nullptr;
//using namespace std;
//class Reference
//{
//public:
// enum class TypeIn {
// Internal,
// External,
// Auto,
// None
// };
// enum class OutFreq {
// MHZ10,
// MHZ100,
// Off,
// None
// };
// static QString OutFreqToLabel(Reference::OutFreq t)
// {
// switch(t) {
// case OutFreq::MHZ10: return "10 MHz";
// case OutFreq::MHZ100: return "100 MHz";
// case OutFreq::Off: return "Off";
// default: return "Invalid";
// }
// }
// static QString OutFreqToKey(Reference::OutFreq f)
// {
// switch(f) {
// case OutFreq::MHZ10: return "10 MHz";
// case OutFreq::MHZ100: return "100 MHz";
// case OutFreq::Off: return "Off";
// default: return "Invalid";
// }
// }
// static Reference::OutFreq KeyToOutFreq(QString key)
// {
// for (auto r: Reference::getOutFrequencies()) {
// if(OutFreqToKey(r) == key|| OutFreqToLabel(r) == key) {
// return r;
// }
// }
// // not found
// return Reference::OutFreq::None;
// }
// static QString TypeToLabel(TypeIn t)
// {
// switch(t) {
// case TypeIn::Internal: return "Internal";
// case TypeIn::External: return "External";
// case TypeIn::Auto: return "Auto";
// default: return "Invalid";
// }
// }
// static const QString TypeToKey(TypeIn t)
// {
// switch(t) {
// case TypeIn::Internal: return "Int";
// case TypeIn::External: return "Ext";
// case TypeIn::Auto: return "Auto";
// default: return "Invalid";
// }
// }
// static TypeIn KeyToType(QString key)
// {
// for (auto r: Reference::getReferencesIn()) {
// if(TypeToKey(r) == key || TypeToLabel(r) == key) {
// return r;
// }
// }
// // not found
// return TypeIn::None;
// }
// static std::vector<Reference::TypeIn> getReferencesIn()
// {
// return {TypeIn::Internal, TypeIn::External, TypeIn::Auto};
// }
// static std::vector<Reference::OutFreq> getOutFrequencies()
// {
// return {OutFreq::Off, OutFreq::MHZ10, OutFreq::MHZ100};
// }
//};
//VirtualDevice::VirtualDevice(QString serial)
// : QObject(),
// info{},
// status{}
//{
// cdev = nullptr;
// zerospan = false;
// // Check if this is a compound device
// auto& pref = Preferences::getInstance();
// for(auto cd : pref.compoundDevices) {
// if(cd->name == serial) {
// // connect request to this compound device
// cdev = cd;
// break;
// }
// }
// if(!isCompoundDevice()) {
// // just acting as a wrapper for device, pass on signals
// auto dev = new Device(serial);
// devices.push_back(dev);
// connect(dev, &Device::ConnectionLost, this, &VirtualDevice::ConnectionLost, Qt::QueuedConnection);
// connect(dev, &Device::DeviceInfoUpdated, this, [=](){
// info = Info(devices[0]);
// emit InfoUpdated();
// }, Qt::QueuedConnection);
// connect(dev, &Device::LogLineReceived, this, &VirtualDevice::LogLineReceived, Qt::QueuedConnection);
// connect(dev, &Device::DeviceStatusUpdated, this, [=](){
// status = Status(devices[0]);
// emit StatusUpdated(status);
// }, Qt::QueuedConnection);
// connect(dev, &Device::NeedsFirmwareUpdate, this, &VirtualDevice::NeedsFirmwareUpdate, Qt::QueuedConnection);
// connect(dev, &Device::SpectrumResultReceived, this, &VirtualDevice::singleSpectrumResultReceived, Qt::QueuedConnection);
// connect(dev, &Device::DatapointReceived, this, &VirtualDevice::singleDatapointReceived, Qt::QueuedConnection);
// } else {
// // Connect to the actual devices
// for(auto devSerial : cdev->deviceSerials) {
// auto dev = new Device(devSerial, true);
// devices.push_back(dev);
// // Create device connections
// connect(dev, &Device::ConnectionLost, this, &VirtualDevice::ConnectionLost, Qt::QueuedConnection);
// connect(dev, &Device::NeedsFirmwareUpdate, this, &VirtualDevice::NeedsFirmwareUpdate, Qt::QueuedConnection);
// connect(dev, &Device::LogLineReceived, this, [=](QString line){
// emit LogLineReceived(line.prepend(dev->serial()+": "));
// }, Qt::QueuedConnection);
// connect(dev, &Device::DeviceInfoUpdated, this, &VirtualDevice::compoundInfoUpdated, Qt::QueuedConnection);
// connect(dev, &Device::DeviceStatusUpdated, this, &VirtualDevice::compoundStatusUpdated, Qt::QueuedConnection);
// connect(dev, &Device::DatapointReceived, this, &VirtualDevice::compoundDatapointReceivecd, Qt::QueuedConnection);
// connect(dev, &Device::SpectrumResultReceived, this, &VirtualDevice::compoundSpectrumResultReceived, Qt::QueuedConnection);
// }
// if(cdev->sync == CompoundDevice::Synchronization::USB) {
// // create trigger connections for USB synchronization
// for(unsigned int i=0;i<devices.size() - 1;i++) {
// connect(devices[i], &Device::TriggerReceived, devices[i+1], &Device::SetTrigger, Qt::QueuedConnection);
// }
// connect(devices.back(), &Device::TriggerReceived, devices.front(), &Device::SetTrigger, Qt::QueuedConnection);
// }
// }
// connected = this;
//}
//VirtualDevice::~VirtualDevice()
//{
// connected = nullptr;
// for(auto dev : devices) {
// delete dev;
// }
//}
//void VirtualDevice::RegisterTypes()
//{
// qRegisterMetaType<VirtualDevice::Status>("Status");
// qRegisterMetaType<VirtualDevice::VNAMeasurement>("VNAMeasurement");
// qRegisterMetaType<VirtualDevice::SAMeasurement>("SAMeasurement");
//}
//void VirtualDevice::initialize()
//{
// for(auto dev : devices) {
// dev->SendCommandWithoutPayload(Protocol::PacketType::RequestDeviceInfo);
// dev->SendCommandWithoutPayload(Protocol::PacketType::RequestDeviceStatus);
// }
//}
//bool VirtualDevice::isCompoundDevice() const
//{
// return cdev != nullptr;
//}
//Device *VirtualDevice::getDevice()
//{
// if(isCompoundDevice() || devices.size() < 1) {
// return nullptr;
// } else {
// return devices[0];
// }
//}
//CompoundDevice *VirtualDevice::getCompoundDevice()
//{
// return cdev;
//}
//std::vector<Device *> VirtualDevice::getDevices()
//{
// return devices;
//}
//const VirtualDevice::Info &VirtualDevice::getInfo() const
//{
// return info;
//}
//VirtualDevice::Info VirtualDevice::getInfo(VirtualDevice *vdev)
//{
// if(vdev) {
// return vdev->info;
// } else {
// return Info();
// }
//}
//const VirtualDevice::Status &VirtualDevice::getStatus() const
//{
// return status;
//}
//VirtualDevice::Status VirtualDevice::getStatus(VirtualDevice *vdev)
//{
// if(vdev) {
// return vdev->status;
// } else {
// return Status();
// }
//}
//QStringList VirtualDevice::availableVNAMeasurements()
//{
// QStringList ret;
// for(unsigned int i=1;i<=info.ports;i++) {
// for(unsigned int j=1;j<=info.ports;j++) {
// ret.push_back("S"+QString::number(i)+QString::number(j));
// }
// }
// auto &pref = Preferences::getInstance();
// if(pref.Debug.makeRawReceiverValuesAvailable) {
// for(unsigned int i=1;i<=info.ports;i++) {
// for(unsigned int j=0;j<info.ports;j++) {
// ret.push_back("RawPort"+QString::number(i)+"Stage"+QString::number(j));
// ret.push_back("RawPort"+QString::number(i)+"Stage"+QString::number(j)+"Ref");
// }
// }
// }
// return ret;
//}
//bool VirtualDevice::setVNA(const VirtualDevice::VNASettings &s, std::function<void (bool)> cb)
//{
// if(!info.supportsVNAmode) {
// return false;
// }
// if(s.excitedPorts.size() == 0) {
// return setIdle(cb);
// }
// // create port->stage mapping
// portStageMapping.clear();
// for(unsigned int i=0;i<s.excitedPorts.size();i++) {
// portStageMapping[s.excitedPorts[i]] = i;
// }
// auto& pref = Preferences::getInstance();
// Protocol::SweepSettings sd = {};
// sd.f_start = s.freqStart;
// sd.f_stop = s.freqStop;
// sd.points = s.points;
// sd.if_bandwidth = s.IFBW;
// sd.cdbm_excitation_start = s.dBmStart * 100;
// sd.cdbm_excitation_stop = s.dBmStop * 100;
// sd.stages = s.excitedPorts.size() - 1;
// sd.suppressPeaks = pref.Acquisition.suppressPeaks ? 1 : 0;
// sd.fixedPowerSetting = pref.Acquisition.adjustPowerLevel || s.dBmStart != s.dBmStop ? 0 : 1;
// sd.logSweep = s.logSweep ? 1 : 0;
// zerospan = (s.freqStart == s.freqStop) && (s.dBmStart == s.dBmStop);
// if(!isCompoundDevice()) {
// sd.port1Stage = find(s.excitedPorts.begin(), s.excitedPorts.end(), 0) - s.excitedPorts.begin();
// sd.port2Stage = find(s.excitedPorts.begin(), s.excitedPorts.end(), 1) - s.excitedPorts.begin();
// sd.syncMode = 0;
// sd.syncMaster = 0;
// return devices[0]->Configure(sd, [=](Device::TransmissionResult r){
// if(cb) {
// cb(r == Device::TransmissionResult::Ack);
// }
// });
// } else {
// // set the synchronization mode
// switch(cdev->sync) {
// case CompoundDevice::Synchronization::USB: sd.syncMode = 1; break;
// case CompoundDevice::Synchronization::ExtRef: sd.syncMode = 2; break;
// case CompoundDevice::Synchronization::Trigger: sd.syncMode = 3; break;
// case CompoundDevice::Synchronization::Last: sd.syncMode = 1; break; // should never get here
// }
// // create vector of currently used stimulus ports
// vector<CompoundDevice::PortMapping> activeMapping;
// for(auto p : s.excitedPorts) {
// activeMapping.push_back(cdev->portMapping[p]);
// }
// // Configure the devices
// results.clear();
// bool success = true;
// for(unsigned int i=0;i<devices.size();i++) {
// sd.port1Stage = CompoundDevice::PortMapping::findActiveStage(activeMapping, i, 0);
// sd.port2Stage = CompoundDevice::PortMapping::findActiveStage(activeMapping, i, 1);
// sd.syncMaster = i == 0 ? 1 : 0;
// success &= devices[i]->Configure(sd, [=](Device::TransmissionResult r){
// if(cb) {
// results[devices[i]] = r;
// checkIfAllTransmissionsComplete(cb);
// }
// });
// }
// return success;
// }
//}
//QString VirtualDevice::serial()
//{
// if(!isCompoundDevice()) {
// return devices[0]->serial();
// } else {
// return cdev->name;
// }
//}
//QStringList VirtualDevice::availableSAMeasurements()
//{
// QStringList ret;
// for(unsigned int i=1;i<=info.ports;i++) {
// ret.push_back("PORT"+QString::number(i));
// }
// return ret;
//}
//bool VirtualDevice::setSA(const VirtualDevice::SASettings &s, std::function<void (bool)> cb)
//{
// if(!info.supportsSAmode) {
// return false;
// }
// zerospan = s.freqStart == s.freqStop;
// auto& pref = Preferences::getInstance();
// Protocol::SpectrumAnalyzerSettings sd = {};
// sd.f_start = s.freqStart;
// sd.f_stop = s.freqStop;
// sd.pointNum = s.points;
// sd.RBW = s.RBW;
// sd.WindowType = (int) s.window;
// sd.SignalID = s.signalID ? 1 : 0;
// sd.Detector = (int) s.detector;
// sd.UseDFT = 0;
// if(!s.trackingGenerator && pref.Acquisition.useDFTinSAmode && s.RBW <= pref.Acquisition.RBWLimitForDFT) {
// sd.UseDFT = 1;
// }
// sd.applyReceiverCorrection = 1;
// sd.trackingGeneratorOffset = s.trackingOffset;
// sd.trackingPower = s.trackingPower;
// if(!isCompoundDevice()) {
// sd.trackingGenerator = s.trackingGenerator ? 1 : 0;
// sd.trackingGeneratorPort = s.trackingPort;
// sd.syncMode = 0;
// sd.syncMaster = 0;
// return devices[0]->Configure(sd, [=](Device::TransmissionResult r){
// if(cb) {
// cb(r == Device::TransmissionResult::Ack);
// }
// });
// } else {
// // set the synchronization mode
// switch(cdev->sync) {
// case CompoundDevice::Synchronization::USB: sd.syncMode = 1; break;
// case CompoundDevice::Synchronization::ExtRef: sd.syncMode = 2; break;
// case CompoundDevice::Synchronization::Trigger: sd.syncMode = 3; break;
// case CompoundDevice::Synchronization::Last: sd.syncMode = 1; break; // should never get here
// }
// // Configure the devices
// results.clear();
// bool success = true;
// for(unsigned int i=0;i<devices.size();i++) {
// sd.trackingGenerator = 0;
// sd.trackingGeneratorPort = 0;
// if(s.trackingGenerator) {
// if(CompoundDevice::PortMapping::findActiveStage(cdev->portMapping, i, 0) == s.trackingPort) {
// sd.trackingGenerator = 1;
// sd.trackingGeneratorPort = 0;
// } else if(CompoundDevice::PortMapping::findActiveStage(cdev->portMapping, i, 1) == s.trackingPort) {
// sd.trackingGenerator = 1;
// sd.trackingGeneratorPort = 1;
// }
// }
// sd.syncMaster = i == 0 ? 1 : 0;
// success &= devices[i]->Configure(sd, [=](Device::TransmissionResult r){
// if(cb) {
// results[devices[i]] = r;
// checkIfAllTransmissionsComplete(cb);
// }
// });
// }
// return success;
// }
//}
//QStringList VirtualDevice::availableSGPorts()
//{
// QStringList ret;
// for(unsigned int i=1;i<info.ports;i++) {
// ret.push_back("PORT"+QString::number(i));
// }
// return ret;
//}
//bool VirtualDevice::setSG(const SGSettings &s)
//{
// if(!info.supportsSGmode) {
// return false;
// }
// Protocol::PacketInfo packet = {};
// packet.type = Protocol::PacketType::Generator;
// Protocol::GeneratorSettings &sd = packet.generator;
// sd.frequency = s.freq;
// sd.cdbm_level = s.dBm * 100;
// sd.applyAmplitudeCorrection = 1;
// if(!isCompoundDevice()) {
// sd.activePort = s.port;
// return devices[0]->SendPacket(packet);
// } else {
// // configure all devices
// bool success = true;
// for(unsigned int i=0;i<devices.size();i++) {
// sd.activePort = 0;
// if(s.port > 0) {
// if(cdev->portMapping[s.port-1].device == i) {
// // this device has the active port
// sd.activePort = cdev->portMapping[s.port-1].port+1;
// }
// }
// success &= devices[i]->SendPacket(packet);
// }
// return success;
// }
//}
//bool VirtualDevice::setIdle(std::function<void (bool)> cb)
//{
// auto success = true;
// results.clear();
// for(auto dev : devices) {
// success &= dev->SetIdle([=](Device::TransmissionResult r){
// if(cb) {
// results[dev] = r;
// checkIfAllTransmissionsComplete(cb);
// }
// });
// }
// return success;
//}
//QStringList VirtualDevice::availableExtRefInSettings()
//{
// QStringList ret;
// for(auto r : Reference::getReferencesIn()) {
// ret.push_back(Reference::TypeToLabel(r));
// }
// return ret;
//}
//QStringList VirtualDevice::availableExtRefOutSettings()
//{
// QStringList ret;
// for(auto r : Reference::getOutFrequencies()) {
// ret.push_back(Reference::OutFreqToLabel(r));
// }
// return ret;
//}
//bool VirtualDevice::setExtRef(QString option_in, QString option_out)
//{
// if(!info.supportsExtRef) {
// return false;
// }
// auto refIn = Reference::KeyToType(option_in);
// if(refIn == Reference::TypeIn::None) {
// refIn = Reference::TypeIn::Internal;
// }
// auto refOut = Reference::KeyToOutFreq(option_out);
// if(refOut == Reference::OutFreq::None) {
// refOut = Reference::OutFreq::Off;
// }
// Protocol::PacketInfo p = {};
// p.type = Protocol::PacketType::Reference;
// switch(refIn) {
// case Reference::TypeIn::Internal:
// case Reference::TypeIn::None:
// p.reference.UseExternalRef = 0;
// p.reference.AutomaticSwitch = 0;
// break;
// case Reference::TypeIn::Auto:
// p.reference.UseExternalRef = 0;
// p.reference.AutomaticSwitch = 1;
// break;
// case Reference::TypeIn::External:
// p.reference.UseExternalRef = 1;
// p.reference.AutomaticSwitch = 0;
// break;
// }
// switch(refOut) {
// case Reference::OutFreq::None:
// case Reference::OutFreq::Off: p.reference.ExtRefOuputFreq = 0; break;
// case Reference::OutFreq::MHZ10: p.reference.ExtRefOuputFreq = 10000000; break;
// case Reference::OutFreq::MHZ100: p.reference.ExtRefOuputFreq = 100000000; break;
// }
// bool success = true;
// for(auto dev : devices) {
// success &= dev->SendPacket(p);
// }
// return success;
//}
//std::set<QString> VirtualDevice::GetAvailableVirtualDevices()
//{
// auto& pref = Preferences::getInstance();
// auto ret = Device::GetDevices();
// // Add compound devices as well
// for(auto vdev : pref.compoundDevices) {
// // check if all serial number required for this compound device are available
// bool serialMissing = false;
// for(auto s : vdev->deviceSerials) {
// if(ret.count(s) == 0) {
// serialMissing = true;
// break;
// }
// }
// if(!serialMissing) {
// // this compound device is available
// ret.insert(vdev->name);
// }
// }
// return ret;
//}
//VirtualDevice *VirtualDevice::getConnected()
//{
// return connected;
//}
//void VirtualDevice::singleDatapointReceived(Device *dev, Protocol::VNADatapoint<32> *res)
//{
// Q_UNUSED(dev)
// auto &pref = Preferences::getInstance();
// VNAMeasurement m;
// m.pointNum = res->pointNum;
// m.Z0 = 50.0;
// if(zerospan) {
// m.us = res->us;
// } else {
// m.frequency = res->frequency;
// m.dBm = (double) res->cdBm / 100;
// }
// for(auto map : portStageMapping) {
// // map.first is the port (starts at zero)
// // map.second is the stage at which this port had the stimulus (starts at zero)
// complex<double> ref = res->getValue(map.second, map.first, true);
// for(unsigned int i=0;i<info.ports;i++) {
// complex<double> input = res->getValue(map.second, i, false);
// if(!std::isnan(ref.real()) && !std::isnan(input.real())) {
// // got both required measurements
// QString name = "S"+QString::number(i+1)+QString::number(map.first+1);
// m.measurements[name] = input / ref;
// }
// if(pref.Debug.makeRawReceiverValuesAvailable) {
// QString name = "RawPort"+QString::number(i+1)+"Stage"+QString::number(map.first);
// m.measurements[name] = input;
// name = "RawPort"+QString::number(i+1)+"Stage"+QString::number(map.first)+"Ref";
// m.measurements[name] = res->getValue(map.second, i, true);
// }
// }
// }
// delete res;
// emit VNAmeasurementReceived(m);
//}
//void VirtualDevice::compoundDatapointReceivecd(Device *dev, Protocol::VNADatapoint<32> *data)
//{
// if(!compoundVNABuffer.count(data->pointNum)) {
// compoundVNABuffer[data->pointNum] = std::map<Device*, Protocol::VNADatapoint<32>*>();
// }
// auto &buf = compoundVNABuffer[data->pointNum];
// buf[dev] = data;
// if(buf.size() == devices.size()) {
// // Got datapoints from all devices, can create merged VNA result
// VNAMeasurement m;
// m.pointNum = data->pointNum;
// m.Z0 = 50.0;
// if(zerospan) {
// m.us = data->us;
// } else {
// m.frequency = data->frequency;
// m.dBm = (double) data->cdBm / 100;
// }
// // assemble data
// for(auto map : portStageMapping) {
// // map.first is the port (starts at zero)
// // map.second is the stage at which this port had the stimulus (starts at zero)
// // figure out which device had the stimulus for the port...
// auto stimulusDev = devices[cdev->portMapping[map.first].device];
// // ...and which device port was used for the stimulus...
// auto stimulusDevPort = cdev->portMapping[map.first].port;
// // ...grab the reference receiver data
// complex<double> ref = buf[stimulusDev]->getValue(map.second, stimulusDevPort, true);
// // for all ports of the compound device...
// for(unsigned int i=0;i<cdev->portMapping.size();i++) {
// // ...figure out which physical device and port was used for this input...
// auto inputDevice = devices[cdev->portMapping[i].device];
// // ...and grab the data
// auto inputPort = cdev->portMapping[i].port;
// complex<double> input = buf[inputDevice]->getValue(map.second, inputPort, false);
// if(!std::isnan(ref.real()) && !std::isnan(input.real())) {
// // got both required measurements
// QString name = "S"+QString::number(i+1)+QString::number(map.first+1);
// auto S = input / ref;
// if(inputDevice != stimulusDev) {
// // can't use phase information when measuring across devices
// S = abs(S);
// }
// m.measurements[name] = S;
// }
// }
// }
// emit VNAmeasurementReceived(m);
// // Clear this and all (incomplete) older datapoint buffers
// int pointNum = data->pointNum;
// auto it = compoundVNABuffer.begin();
// while(it != compoundVNABuffer.end()) {
// if(it->first <= pointNum) {
// for(auto d : it->second) {
// delete d.second;
// }
// it = compoundVNABuffer.erase(it);
// } else {
// it++;
// }
// }
// }
//}
//void VirtualDevice::singleSpectrumResultReceived(Device *dev, Protocol::SpectrumAnalyzerResult res)
//{
// Q_UNUSED(dev)
// SAMeasurement m;
// m.pointNum = res.pointNum;
// if(zerospan) {
// m.us = res.us;
// } else {
// m.frequency = res.frequency;
// }
// m.measurements["PORT1"] = res.port1;
// m.measurements["PORT2"] = res.port2;
// emit SAmeasurementReceived(m);
//}
//void VirtualDevice::compoundSpectrumResultReceived(Device *dev, Protocol::SpectrumAnalyzerResult res)
//{
// if(!compoundSABuffer.count(res.pointNum)) {
// compoundSABuffer[res.pointNum] = std::map<Device*, Protocol::SpectrumAnalyzerResult>();
// }
// auto &buf = compoundSABuffer[res.pointNum];
// buf[dev] = res;
// if(buf.size() == devices.size()) {
// // Got datapoints from all devices, can create merged VNA result
// SAMeasurement m;
// m.pointNum = res.pointNum;
// if(zerospan) {
// m.us = res.us;
// } else {
// m.frequency = res.frequency;
// }
// // assemble data
// for(unsigned int port=0;port<cdev->portMapping.size();port++) {
// auto device = devices[cdev->portMapping[port].device];
// auto devicePort = cdev->portMapping[port].port;
// QString name = "PORT"+QString::number(port+1);
// if(devicePort == 0) {
// m.measurements[name] = buf[device].port1;
// } else {
// m.measurements[name] = buf[device].port2;
// }
// }
// emit SAmeasurementReceived(m);
// // Clear this and all (incomplete) older datapoint buffers
// auto it = compoundSABuffer.begin();
// while(it != compoundSABuffer.end()) {
// if(it->first <= res.pointNum) {
// it = compoundSABuffer.erase(it);
// } else {
// it++;
// }
// }
// }
//}
//void VirtualDevice::compoundInfoUpdated(Device *dev)
//{
// compoundInfoBuffer[dev] = dev->Info();
// if(compoundInfoBuffer.size() == devices.size()) {
// // got information of all devices
// info = Info(devices[0]);
// for(unsigned int i=1;i<devices.size();i++) {
// try {
// info.subset(Info(devices[i]));
// } catch (exception &e) {
// InformationBox::ShowError("Failed to get device information", e.what());
// emit ConnectionLost();
// return;
// }
// }
// if(cdev->sync == CompoundDevice::Synchronization::ExtRef) {
// // can't use the external reference if it is used for synchronization
// info.supportsExtRef = false;
// }
// info.ports = cdev->portMapping.size();
// emit InfoUpdated();
// }
//}
//void VirtualDevice::compoundStatusUpdated(Device *dev)
//{
// compoundStatusBuffer[dev] = dev->StatusV1();
// if(compoundStatusBuffer.size() == devices.size()) {
// // got status of all devices
// status = Status(devices[0]);
// for(unsigned int i=1;i<devices.size();i++) {
// status.merge(Status(devices[i]));
// }
// emit StatusUpdated(status);
// }
//}
//void VirtualDevice::checkIfAllTransmissionsComplete(std::function<void (bool)> cb)
//{
// if(results.size() == devices.size()) {
// // got all responses
// bool success = true;
// for(auto res : results) {
// if(res.second != Device::TransmissionResult::Ack) {
// success = false;
// break;
// }
// }
// if(cb) {
// cb(success);
// }
// }
//}
//Sparam VirtualDevice::VNAMeasurement::toSparam(int port1, int port2) const
//{
// Sparam S;
// S.m11 = measurements.at("S"+QString::number(port1)+QString::number(port1));
// S.m12 = measurements.at("S"+QString::number(port1)+QString::number(port2));
// S.m21 = measurements.at("S"+QString::number(port2)+QString::number(port1));
// S.m22 = measurements.at("S"+QString::number(port2)+QString::number(port2));
// return S;
//}
//void VirtualDevice::VNAMeasurement::fromSparam(Sparam S, int port1, int port2)
//{
// QString s11 = "S"+QString::number(port1)+QString::number(port1);
// QString s12 = "S"+QString::number(port1)+QString::number(port2);
// QString s21 = "S"+QString::number(port2)+QString::number(port1);
// QString s22 = "S"+QString::number(port2)+QString::number(port2);
// if(measurements.count(s11)) {
// measurements[s11] = S.m11;
// }
// if(measurements.count(s12)) {
// measurements[s12] = S.m12;
// }
// if(measurements.count(s21)) {
// measurements[s21] = S.m21;
// }
// if(measurements.count(s22)) {
// measurements[s22] = S.m22;
// }
//}
//VirtualDevice::VNAMeasurement VirtualDevice::VNAMeasurement::interpolateTo(const VirtualDevice::VNAMeasurement &to, double a)
//{
// VNAMeasurement ret;
// ret.frequency = frequency * (1.0 - a) + to.frequency * a;
// ret.dBm = dBm * (1.0 - a) + to.dBm * a;
// ret.Z0 = Z0 * (1.0 - a) + to.Z0 * a;
// for(auto m : measurements) {
// if(to.measurements.count(m.first) == 0) {
// throw runtime_error("Nothing to interpolate to, expected measurement +\""+m.first.toStdString()+"\"");
// }
// ret.measurements[m.first] = measurements[m.first] * (1.0 - a) + to.measurements.at(m.first) * a;
// }
// return ret;
//}
//VirtualDevice::Info::Info()
//{
// ProtocolVersion = Protocol::Version;
// FW_major = 0;
// FW_minor = 0;
// FW_patch = 0;
// hardware_version = 1;
// HW_Revision = '0';
// ports = 2;
// supportsVNAmode = true;
// supportsSAmode = true;
// supportsSGmode = true;
// supportsExtRef = true;
// Limits = {
// .minFreq = 0,
// .maxFreq = 6000000000,
// .maxFreqHarmonic = 18000000000,
// .minIFBW = 10,
// .maxIFBW = 1000000,
// .maxPoints = 10000,
// .mindBm = -100,
// .maxdBm = 30,
// .minRBW = 1,
// .maxRBW = 1000000,
// };
//}
//VirtualDevice::Info::Info(Device *dev)
//{
// auto info = dev->Info();
// ProtocolVersion = info.ProtocolVersion;
// FW_major = info.FW_major;
// FW_minor = info.FW_minor;
// FW_patch = info.FW_patch;
// hardware_version = info.hardware_version;
// HW_Revision = info.HW_Revision;
// ports = 2;
// supportsVNAmode = true;
// supportsSAmode = true;
// supportsSGmode = true;
// supportsExtRef = true;
// Limits.minFreq = info.limits_minFreq;
// Limits.maxFreq = info.limits_maxFreq;
// Limits.maxFreqHarmonic = info.limits_maxFreqHarmonic;
// Limits.minIFBW = info.limits_minIFBW;
// Limits.maxIFBW = info.limits_maxIFBW;
// Limits.maxPoints = info.limits_maxPoints;
// Limits.mindBm = (double) info.limits_cdbm_min / 100;
// Limits.maxdBm = (double) info.limits_cdbm_max / 100;
// Limits.minRBW = info.limits_minRBW;
// Limits.maxRBW = info.limits_maxRBW;
//}
//void VirtualDevice::Info::subset(const VirtualDevice::Info &merge)
//{
// if((merge.ProtocolVersion != ProtocolVersion)
// || (merge.FW_major != FW_major)
// || (merge.FW_minor != FW_minor)
// || (merge.FW_patch != FW_patch)) {
// throw runtime_error("Incompatible device, unable to create compound device. All devices must run the same firmware version.");
// }
// ports += merge.ports;
// supportsVNAmode &= merge.supportsVNAmode;
// supportsSGmode &= merge.supportsSGmode;
// supportsSAmode &= merge.supportsSAmode;
// supportsExtRef &= merge.supportsExtRef;
// Limits.minFreq = max(Limits.minFreq, merge.Limits.minFreq);
// Limits.maxFreq = min(Limits.maxFreq, merge.Limits.maxFreq);
// Limits.maxFreqHarmonic = min(Limits.maxFreqHarmonic, merge.Limits.maxFreqHarmonic);
// Limits.minIFBW = max(Limits.minIFBW, merge.Limits.minIFBW);
// Limits.maxIFBW = min(Limits.maxIFBW, merge.Limits.maxIFBW);
// Limits.maxPoints = min(Limits.maxPoints, merge.Limits.maxPoints);
// Limits.mindBm = max(Limits.mindBm, merge.Limits.mindBm);
// Limits.maxdBm = min(Limits.maxdBm, merge.Limits.maxdBm);
// Limits.minRBW = max(Limits.minRBW, merge.Limits.minRBW);
// Limits.maxRBW = min(Limits.maxRBW, merge.Limits.maxRBW);
//}
//VirtualDevice::Status::Status()
//{
// statusString = "";
// overload = false;
// unlocked = false;
// unlevel = false;
// extRef = false;
//}
//VirtualDevice::Status::Status(Device *dev)
//{
// auto status = dev->StatusV1();
// statusString = dev->getLastDeviceInfoString();
// overload = status.ADC_overload;
// unlevel = status.unlevel;
// unlocked = !status.LO1_locked || !status.source_locked;
// extRef = status.extRefInUse;
//}
//void VirtualDevice::Status::merge(const VirtualDevice::Status &merge)
//{
// statusString += " / "+merge.statusString;
// overload |= merge.overload;
// unlevel |= merge.unlevel;
// unlocked |= merge.unlocked;
// extRef &= merge.extRef;
//}

View File

@ -1,220 +0,0 @@
//#ifndef VIRTUALDEVICE_H
//#define VIRTUALDEVICE_H
//#include "device.h"
//#include "Tools/parameters.h"
//#include "compounddevice.h"
//#include <set>
//#include <complex>
//#include <QObject>
//class VirtualDevice : public QObject
//{
// Q_OBJECT
//public:
// VirtualDevice(QString serial = "");
// ~VirtualDevice();
// class Info {
// public:
// Info();
// Info(Device *dev);
// void subset(const Info &merge);
// uint16_t ProtocolVersion;
// uint8_t FW_major;
// uint8_t FW_minor;
// uint8_t FW_patch;
// uint8_t hardware_version;
// char HW_Revision;
// unsigned int ports;
// bool supportsVNAmode;
// bool supportsSAmode;
// bool supportsSGmode;
// bool supportsExtRef;
// struct {
// double minFreq, maxFreq, maxFreqHarmonic;
// double minIFBW, maxIFBW;
// unsigned int maxPoints;
// double mindBm;
// double maxdBm;
// double minRBW, maxRBW;
// } Limits;
// };
// class Status {
// public:
// Status();
// Status(Device *dev);
// void merge(const Status &merge);
// QString statusString;
// bool overload;
// bool unlocked;
// bool unlevel;
// bool extRef;
// };
// static void RegisterTypes();
// void initialize(); // call this after creating the virtual device and all connections to signals have been made
// bool isCompoundDevice() const;
// Device *getDevice();
// CompoundDevice *getCompoundDevice();
// std::vector<Device*> getDevices();
// const Info& getInfo() const;
// static VirtualDevice::Info getInfo(VirtualDevice *vdev);
// const Status &getStatus() const;
// static VirtualDevice::Status getStatus(VirtualDevice *vdev);
// class VNASettings {
// public:
// double freqStart, freqStop;
// double dBmStart, dBmStop;
// double IFBW;
// int points;
// bool logSweep;
// std::vector<int> excitedPorts; // port count starts at one
// };
// class VNAMeasurement {
// public:
// unsigned int pointNum;
// double Z0;
// union {
// struct {
// // for non-zero span
// double frequency;
// double dBm;
// };
// struct {
// // for zero span
// double us; // time in us since first datapoint
// };
// };
// std::map<QString, std::complex<double>> measurements;
// Sparam toSparam(int port1, int port2) const;
// void fromSparam(Sparam S, int port1, int port2);
// VNAMeasurement interpolateTo(const VNAMeasurement &to, double a);
// };
// QStringList availableVNAMeasurements();
// bool setVNA(const VNASettings &s, std::function<void(bool)> cb = nullptr);
// QString serial();
// class SASettings {
// public:
// enum class Window {
// None = 0,
// Kaiser = 1,
// Hann = 2,
// FlatTop = 3,
// Last
// };
// enum class Detector {
// PPeak = 0,
// NPeak = 1,
// Sample = 2,
// Normal = 3,
// Average = 4,
// Last
// };
// double freqStart, freqStop;
// double RBW;
// int points;
// Window window;
// Detector detector;
// bool signalID;
// bool trackingGenerator;
// int trackingPort; // counting starts at zero
// double trackingOffset;
// double trackingPower;
// };
// class SAMeasurement {
// public:
// int pointNum;
// union {
// struct {
// // for non-zero span
// double frequency;
// };
// struct {
// // for zero span
// double us; // time in us since first datapoint
// };
// };
// std::map<QString, double> measurements;
// };
// QStringList availableSAMeasurements();
// bool setSA(const SASettings &s, std::function<void(bool)> cb = nullptr);
// class SGSettings {
// public:
// double freq;
// double dBm;
// int port; // starts at one, set to zero to disable all ports
// };
// QStringList availableSGPorts();
// bool setSG(const SGSettings &s);
// bool setIdle(std::function<void(bool)> cb = nullptr);
// QStringList availableExtRefInSettings();
// QStringList availableExtRefOutSettings();
// bool setExtRef(QString option_in, QString option_out);
// static std::set<QString> GetAvailableVirtualDevices();
// static VirtualDevice* getConnected();
// static constexpr unsigned int maximumSupportedPorts = 8;
//signals:
// void VNAmeasurementReceived(VNAMeasurement m);
// void SAmeasurementReceived(SAMeasurement m);
// void ConnectionLost();
// void InfoUpdated();
// void StatusUpdated(Status status);
// void LogLineReceived(QString line);
// void NeedsFirmwareUpdate(int usedProtocol, int requiredProtocol);
//private slots:
// void singleDatapointReceived(Device *dev, Protocol::VNADatapoint<32> *res);
// void compoundDatapointReceivecd(Device *dev, Protocol::VNADatapoint<32> *data);
// void singleSpectrumResultReceived(Device *dev, Protocol::SpectrumAnalyzerResult res);
// void compoundSpectrumResultReceived(Device *dev, Protocol::SpectrumAnalyzerResult res);
// void compoundInfoUpdated(Device *dev);
// void compoundStatusUpdated(Device *dev);
//private:
// void checkIfAllTransmissionsComplete(std::function<void(bool)> cb = nullptr);
// Info info;
// Status status;
// std::vector<Device*> devices;
// bool zerospan;
// std::map<Device*, Device::TransmissionResult> results;
// CompoundDevice *cdev;
// std::map<int, std::map<Device*, Protocol::VNADatapoint<32>*>> compoundVNABuffer;
// std::map<int, std::map<Device*, Protocol::SpectrumAnalyzerResult>> compoundSABuffer;
// std::map<Device*, Protocol::DeviceInfo> compoundInfoBuffer;
// std::map<Device*, Protocol::DeviceStatusV1> compoundStatusBuffer;
// std::map<int, int> portStageMapping; // maps from excitedPort (count starts at zero) to stage (count starts at zero)
//};
//Q_DECLARE_METATYPE(VirtualDevice::Status)
//Q_DECLARE_METATYPE(VirtualDevice::VNAMeasurement)
//Q_DECLARE_METATYPE(VirtualDevice::SAMeasurement)
//#endif // VIRTUALDEVICE_H

View File

@ -23,6 +23,8 @@ HEADERS += \
Device/LibreVNA/Compound/compounddeviceeditdialog.h \
Device/LibreVNA/Compound/compounddriver.h \
Device/LibreVNA/amplitudecaldialog.h \
Device/LibreVNA/devicepacketlog.h \
Device/LibreVNA/devicepacketlogview.h \
Device/LibreVNA/firmwareupdatedialog.h \
Device/LibreVNA/frequencycaldialog.h \
Device/LibreVNA/librevnadriver.h \
@ -32,13 +34,9 @@ HEADERS += \
Device/LibreVNA/receivercaldialog.h \
Device/LibreVNA/sourcecaldialog.h \
Device/SSA3000X/ssa3000xdriver.h \
Device/device.h \
Device/devicedriver.h \
Device/devicelog.h \
Device/deviceusblog.h \
Device/deviceusblogview.h \
Device/tracedifferencegenerator.h \
Device/virtualdevice.h \
Generator/generator.h \
Generator/signalgenwidget.h \
SpectrumAnalyzer/spectrumanalyzer.h \
@ -178,6 +176,8 @@ SOURCES += \
Device/LibreVNA/Compound/compounddeviceeditdialog.cpp \
Device/LibreVNA/Compound/compounddriver.cpp \
Device/LibreVNA/amplitudecaldialog.cpp \
Device/LibreVNA/devicepacketlog.cpp \
Device/LibreVNA/devicepacketlogview.cpp \
Device/LibreVNA/firmwareupdatedialog.cpp \
Device/LibreVNA/frequencycaldialog.cpp \
Device/LibreVNA/librevnadriver.cpp \
@ -187,12 +187,8 @@ SOURCES += \
Device/LibreVNA/receivercaldialog.cpp \
Device/LibreVNA/sourcecaldialog.cpp \
Device/SSA3000X/ssa3000xdriver.cpp \
Device/device.cpp \
Device/devicedriver.cpp \
Device/devicelog.cpp \
Device/deviceusblog.cpp \
Device/deviceusblogview.cpp \
Device/virtualdevice.cpp \
Generator/generator.cpp \
Generator/signalgenwidget.cpp \
SpectrumAnalyzer/spectrumanalyzer.cpp \
@ -323,12 +319,12 @@ FORMS += \
Device/LibreVNA/addamplitudepointsdialog.ui \
Device/LibreVNA/amplitudecaldialog.ui \
Device/LibreVNA/automaticamplitudedialog.ui \
Device/LibreVNA/devicepacketlogview.ui \
Device/LibreVNA/firmwareupdatedialog.ui \
Device/LibreVNA/frequencycaldialog.ui \
Device/LibreVNA/librevnadriversettingswidget.ui \
Device/LibreVNA/manualcontroldialog.ui \
Device/devicelog.ui \
Device/deviceusblogview.ui \
Generator/signalgenwidget.ui \
Tools/impedancematchdialog.ui \
Tools/mixedmodeconversion.ui \

View File

@ -6,7 +6,6 @@
#include "CustomWidgets/tilewidget.h"
#include "scpi.h"
#include "Traces/tracewidget.h"
#include "Device/virtualdevice.h"
#include <QObject>
#include <QWidget>

View File

@ -2,7 +2,6 @@
#include "unit.h"
#include "CustomWidgets/toggleswitch.h"
#include "Device/deviceusblogview.h"
#include "Traces/tracemodel.h"
#include "Traces/tracewidget.h"
#include "Traces/tracesmithchart.h"
@ -232,13 +231,6 @@ void AppWindow::SetupMenu()
modeHandler->getActiveMode()->saveSreenshot();
});
// connect(ui->actionManual_Control, &QAction::triggered, this, &AppWindow::StartManualControl);
connect(ui->actionDevice_log, &QAction::triggered, this, &AppWindow::ShowDeviceLog);
// connect(ui->actionFirmware_Update, &QAction::triggered, this, &AppWindow::StartFirmwareUpdateDialog);
// connect(ui->actionSource_Calibration, &QAction::triggered, this, &AppWindow::SourceCalibrationDialog);
// connect(ui->actionReceiver_Calibration, &QAction::triggered, this, &AppWindow::ReceiverCalibrationDialog);
// connect(ui->actionFrequency_Calibration, &QAction::triggered, this, &AppWindow::FrequencyCalibrationDialog);
connect(ui->actionPreset, &QAction::triggered, [=](){
modeHandler->getActiveMode()->preset();
});
@ -1080,14 +1072,6 @@ void AppWindow::UpdateReference()
device->setExtRef(toolbars.reference.type->currentText(), toolbars.reference.outFreq->currentText());
}
void AppWindow::ShowDeviceLog()
{
auto d = new DeviceUSBLogView();
if(AppWindow::showGUI()) {
d->exec();
}
}
//void AppWindow::DeviceNeedsUpdate(int reported, int expected)
//{
// auto ret = InformationBox::AskQuestion("Warning",

View File

@ -1,7 +1,6 @@
#ifndef APPWINDOW_H
#define APPWINDOW_H
#include "Device/virtualdevice.h"
#include "Traces/traceplot.h"
#include "Traces/tracemodel.h"
#include "Traces/Marker/markermodel.h"
@ -11,7 +10,6 @@
#include "scpi.h"
#include "tcpserver.h"
#include "Device/devicedriver.h"
//#include "modehandler.h"
#include <QWidget>
#include <QMainWindow>
@ -65,16 +63,9 @@ private slots:
// void StartManualControl();
void UpdateReferenceToolbar();
void UpdateReference();
// void UpdateAcquisitionFrequencies();
void ShowDeviceLog();
// void StartFirmwareUpdateDialog();
// void DeviceNeedsUpdate(int reported, int expected);
void DeviceStatusUpdated();
void DeviceFlagsUpdated();
void DeviceInfoUpdated();
// void SourceCalibrationDialog();
// void ReceiverCalibrationDialog();
// void FrequencyCalibrationDialog();
nlohmann::json SaveSetup();
void SaveSetup(QString filename);
void LoadSetup(QString filename);

View File

@ -1,6 +1,5 @@
#include "appwindow.h"
#include <QtWidgets/QApplication>
#include "Device/device.h"
#ifdef Q_OS_UNIX
#include <signal.h>
#endif
@ -20,8 +19,6 @@ int main(int argc, char *argv[]) {
qSetMessagePattern("%{time process}: [%{type}] %{message}");
Device::RegisterTypes();
app = new QApplication(argc, argv);
QCoreApplication::setOrganizationName("LibreVNA");
QCoreApplication::setApplicationName("LibreVNA-GUI");

View File

@ -49,8 +49,6 @@
<addaction name="menuConnect_to"/>
<addaction name="actionDisconnect"/>
<addaction name="separator"/>
<addaction name="separator"/>
<addaction name="actionDevice_log"/>
</widget>
<widget class="QMenu" name="menuWindow">
<property name="title">

View File

@ -45,7 +45,6 @@ PreferencesDialog::PreferencesDialog(Preferences *pref, QWidget *parent) :
ui->StartupSAWindow->setEnabled(en);
ui->StartupSADetector->setEnabled(en);
ui->StartupSAAveraging->setEnabled(en);
ui->StartupSASignalID->setEnabled(en);
};
// Setup GUI connections and adjustments
@ -246,7 +245,6 @@ void PreferencesDialog::setInitialGUIState()
ui->StartupSAWindow->setCurrentIndex(p->Startup.SA.window);
ui->StartupSADetector->setCurrentIndex(p->Startup.SA.detector);
ui->StartupSAAveraging->setValue(p->Startup.SA.averaging);
ui->StartupSASignalID->setChecked(p->Startup.SA.signalID);
ui->AcquisitionAlwaysExciteBoth->setChecked(p->Acquisition.alwaysExciteAllPorts);
ui->AcquisitionAllowSegmentedSweep->setChecked(p->Acquisition.allowSegmentedSweep);
@ -342,7 +340,6 @@ void PreferencesDialog::updateFromGUI()
p->Startup.SA.RBW = ui->StartupSARBW->value();
p->Startup.SA.window = ui->StartupSAWindow->currentIndex();
p->Startup.SA.detector = ui->StartupSADetector->currentIndex();
p->Startup.SA.signalID = ui->StartupSASignalID->isChecked();
p->Acquisition.alwaysExciteAllPorts = ui->AcquisitionAlwaysExciteBoth->isChecked();
p->Acquisition.allowSegmentedSweep = ui->AcquisitionAllowSegmentedSweep->isChecked();

View File

@ -92,7 +92,6 @@ public:
int window;
int detector;
int averaging;
bool signalID;
} SA;
} Startup;
struct {
@ -197,7 +196,6 @@ private:
{&Startup.SA.window, "Startup.SA.window", 1},
{&Startup.SA.detector, "Startup.SA.detector", 0},
{&Startup.SA.averaging, "Startup.SA.averaging", 1},
{&Startup.SA.signalID, "Startup.SA.signalID", true},
{&Acquisition.alwaysExciteAllPorts, "Acquisition.alwaysExciteBothPorts", true},
{&Acquisition.allowSegmentedSweep, "Acquisition.allowSegmentedSweep", false},
{&Acquisition.useMedianAveraging, "Acquisition.useMedianAveraging", false},

View File

@ -93,7 +93,7 @@
</size>
</property>
<property name="currentIndex">
<number>3</number>
<number>0</number>
</property>
<widget class="QWidget" name="Startup">
<layout class="QHBoxLayout" name="horizontalLayout_4">
@ -106,9 +106,9 @@
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<y>-334</y>
<width>683</width>
<height>920</height>
<height>897</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_13">
@ -638,20 +638,6 @@
</item>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="label_14">
<property name="text">
<string>Signal Identification:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QCheckBox" name="StartupSASignalID">
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_19">
<property name="text">
@ -712,8 +698,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>565</width>
<height>365</height>
<width>697</width>
<height>563</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_21">
@ -869,8 +855,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>553</width>
<height>969</height>
<width>683</width>
<height>952</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_22">

View File

@ -38,12 +38,10 @@ SOURCES += \
../LibreVNA-GUI/Device/LibreVNA/Compound/compounddriver.cpp \
../LibreVNA-GUI/Device/LibreVNA/Compound/compounddeviceeditdialog.cpp \
../LibreVNA-GUI/Device/SSA3000X/ssa3000xdriver.cpp \
../LibreVNA-GUI/Device/device.cpp \
../LibreVNA-GUI/Device/devicedriver.cpp \
../LibreVNA-GUI/Device/devicelog.cpp \
../LibreVNA-GUI/Device/deviceusblog.cpp \
../LibreVNA-GUI/Device/deviceusblogview.cpp \
../LibreVNA-GUI/Device/virtualdevice.cpp \
../LibreVNA-GUI/Device/LibreVNA/devicepacketlog.cpp \
../LibreVNA-GUI/Device/LibreVNA/devicepacketlogview.cpp \
../LibreVNA-GUI/Generator/generator.cpp \
../LibreVNA-GUI/Generator/signalgenwidget.cpp \
../LibreVNA-GUI/SpectrumAnalyzer/spectrumanalyzer.cpp \
@ -211,12 +209,10 @@ HEADERS += \
../LibreVNA-GUI/Device/LibreVNA/Compound/compounddriver.h \
../LibreVNA-GUI/Device/LibreVNA/Compound/compounddeviceeditdialog.h \
../LibreVNA-GUI/Device/SSA3000X/ssa3000xdriver.h \
../LibreVNA-GUI/Device/device.h \
../LibreVNA-GUI/Device/devicedriver.h \
../LibreVNA-GUI/Device/devicelog.h \
../LibreVNA-GUI/Device/deviceusblog.h \
../LibreVNA-GUI/Device/deviceusblogview.h \
../LibreVNA-GUI/Device/virtualdevice.h \
../LibreVNA-GUI/Device/LibreVNA/devicepacketlog.h \
../LibreVNA-GUI/Device/LibreVNA/devicepacketlogview.h \
../LibreVNA-GUI/Generator/generator.h \
../LibreVNA-GUI/Generator/signalgenwidget.h \
../LibreVNA-GUI/SpectrumAnalyzer/spectrumanalyzer.h \
@ -361,7 +357,7 @@ FORMS += \
../LibreVNA-GUI/Device/LibreVNA/manualcontroldialog.ui \
../LibreVNA-GUI/Device/LibreVNA/Compound/compounddeviceeditdialog.ui \
../LibreVNA-GUI/Device/devicelog.ui \
../LibreVNA-GUI/Device/deviceusblogview.ui \
../LibreVNA-GUI/Device/LibreVNA/devicepacketlogview.ui \
../LibreVNA-GUI/Generator/signalgenwidget.ui \
../LibreVNA-GUI/Tools/impedancematchdialog.ui \
../LibreVNA-GUI/Tools/mixedmodeconversion.ui \