added mutexes

This commit is contained in:
Jan Käberich 2022-11-01 01:12:04 +01:00
parent 22542a81b6
commit 5ace021e41
14 changed files with 112 additions and 21 deletions

View File

@ -134,7 +134,7 @@ AmplitudeCalDialog::AmplitudeCalDialog(Device *dev, ModeHandler *handler, QWidge
}); });
connect(ui->automatic, &QPushButton::clicked, this, &AmplitudeCalDialog::AutomaticMeasurementDialog); connect(ui->automatic, &QPushButton::clicked, this, &AmplitudeCalDialog::AutomaticMeasurementDialog);
connect(dev, &Device::SpectrumResultReceived, this, &AmplitudeCalDialog::ReceivedMeasurement); connect(dev, &Device::SpectrumResultReceived, this, &AmplitudeCalDialog::ReceivedMeasurement, Qt::QueuedConnection);
} }
AmplitudeCalDialog::~AmplitudeCalDialog() AmplitudeCalDialog::~AmplitudeCalDialog()
@ -211,7 +211,7 @@ void AmplitudeCalDialog::LoadFromDevice()
dev->SetIdle(); dev->SetIdle();
RemoveAllPoints(); RemoveAllPoints();
// qDebug() << "Asking for amplitude calibration"; // qDebug() << "Asking for amplitude calibration";
connect(dev, &Device::AmplitudeCorrectionPointReceived, this, &AmplitudeCalDialog::ReceivedPoint); connect(dev, &Device::AmplitudeCorrectionPointReceived, this, &AmplitudeCalDialog::ReceivedPoint, Qt::QueuedConnection);
dev->SendCommandWithoutPayload(requestCommand()); dev->SendCommandWithoutPayload(requestCommand());
edited = false; edited = false;
UpdateSaveButton(); UpdateSaveButton();
@ -401,7 +401,7 @@ void AmplitudeCalDialog::AutomaticMeasurementDialog()
disconnect(dev, &Device::AmplitudeCorrectionPointReceived, this, nullptr); disconnect(dev, &Device::AmplitudeCorrectionPointReceived, this, nullptr);
qDebug() << "Received" << p.totalPoints << "points for automatic calibration"; qDebug() << "Received" << p.totalPoints << "points for automatic calibration";
} }
}); }, Qt::QueuedConnection);
// request points of otherCal // request points of otherCal
// switch between source/receiver calibration // switch between source/receiver calibration
auto request = automatic.isSourceCal ? Protocol::PacketType::RequestReceiverCal : Protocol::PacketType::RequestSourceCal; auto request = automatic.isSourceCal ? Protocol::PacketType::RequestReceiverCal : Protocol::PacketType::RequestSourceCal;
@ -414,7 +414,7 @@ void AmplitudeCalDialog::AutomaticMeasurementDialog()
AddPoint(p.frequency); AddPoint(p.frequency);
} }
// intialize measurement state machine // intialize measurement state machine
connect(dev, &Device::SpectrumResultReceived, this, &AmplitudeCalDialog::ReceivedAutomaticMeasurementResult); connect(dev, &Device::SpectrumResultReceived, this, &AmplitudeCalDialog::ReceivedAutomaticMeasurementResult, Qt::QueuedConnection);
automatic.measuringPort2 = false; automatic.measuringPort2 = false;
automatic.measuringCount = 0; automatic.measuringCount = 0;
ui->status->setText("Taking measurements..."); ui->status->setText("Taking measurements...");

View File

@ -315,6 +315,7 @@ Calibration::Type Calibration::TypeFromString(QString s)
void Calibration::correctMeasurement(VirtualDevice::VNAMeasurement &d) void Calibration::correctMeasurement(VirtualDevice::VNAMeasurement &d)
{ {
lock_guard<recursive_mutex> guard(access);
if(caltype.type == Type::None) { if(caltype.type == Type::None) {
// no calibration active, nothing to do // no calibration active, nothing to do
return; return;
@ -422,6 +423,7 @@ void Calibration::edit()
} }
auto updateCalStatistics = [=](){ auto updateCalStatistics = [=](){
lock_guard<recursive_mutex> guard(access);
ui->activeCalibration->setText(caltype.getReadableDescription()); ui->activeCalibration->setText(caltype.getReadableDescription());
ui->calPoints->setValue(points.size()); ui->calPoints->setValue(points.size());
if(points.size() > 0) { if(points.size() > 0) {
@ -434,6 +436,7 @@ void Calibration::edit()
}; };
auto updateCalButtons = [=](){ auto updateCalButtons = [=](){
lock_guard<recursive_mutex> guard(access);
auto row = ui->calibrationList->currentRow(); auto row = ui->calibrationList->currentRow();
if(row < 0) { if(row < 0) {
ui->activate->setEnabled(false); ui->activate->setEnabled(false);
@ -993,6 +996,7 @@ Calibration::CalType Calibration::getCaltype() const
Calibration::InterpolationType Calibration::getInterpolation(double f_start, double f_stop, int npoints) Calibration::InterpolationType Calibration::getInterpolation(double f_start, double f_stop, int npoints)
{ {
lock_guard<recursive_mutex> guard(access);
if(!points.size()) { if(!points.size()) {
return InterpolationType::NoCalibration; return InterpolationType::NoCalibration;
} }
@ -1026,6 +1030,7 @@ Calibration::InterpolationType Calibration::getInterpolation(double f_start, dou
std::vector<Trace *> Calibration::getErrorTermTraces() std::vector<Trace *> Calibration::getErrorTermTraces()
{ {
lock_guard<recursive_mutex> guard(access);
vector<Trace*> ret; vector<Trace*> ret;
if(points.size() == 0) { if(points.size() == 0) {
return ret; return ret;
@ -1088,6 +1093,7 @@ std::vector<Trace *> Calibration::getErrorTermTraces()
std::vector<Trace *> Calibration::getMeasurementTraces() std::vector<Trace *> Calibration::getMeasurementTraces()
{ {
lock_guard<recursive_mutex> guard(access);
vector<Trace*> ret; vector<Trace*> ret;
for(auto m : measurements) { for(auto m : measurements) {
switch(m->getType()) { switch(m->getType()) {
@ -1249,6 +1255,7 @@ Calkit &Calibration::getKit()
nlohmann::json Calibration::toJSON() nlohmann::json Calibration::toJSON()
{ {
lock_guard<recursive_mutex> guard(access);
nlohmann::json j; nlohmann::json j;
j["format"] = 3; j["format"] = 3;
nlohmann::json jmeasurements; nlohmann::json jmeasurements;
@ -1276,6 +1283,7 @@ nlohmann::json Calibration::toJSON()
void Calibration::fromJSON(nlohmann::json j) void Calibration::fromJSON(nlohmann::json j)
{ {
reset(); reset();
lock_guard<recursive_mutex> guard(access);
if(j.contains("calkit")) { if(j.contains("calkit")) {
kit.fromJSON(j["calkit"]); kit.fromJSON(j["calkit"]);
} }
@ -1642,6 +1650,7 @@ bool Calibration::canCompute(Calibration::CalType type, double *startFreq, doubl
bool Calibration::compute(Calibration::CalType type) bool Calibration::compute(Calibration::CalType type)
{ {
lock_guard<recursive_mutex> guard(access);
if(type.type == Type::None) { if(type.type == Type::None) {
deactivate(); deactivate();
return true; return true;
@ -1719,6 +1728,7 @@ void Calibration::measurementsComplete()
void Calibration::deactivate() void Calibration::deactivate()
{ {
lock_guard<recursive_mutex> guard(access);
points.clear(); points.clear();
caltype.type = Type::None; caltype.type = Type::None;
caltype.usedPorts.clear(); caltype.usedPorts.clear();
@ -1740,6 +1750,7 @@ QString Calibration::DefaultMeasurementsToString(Calibration::DefaultMeasurement
void Calibration::createDefaultMeasurements(Calibration::DefaultMeasurements dm) void Calibration::createDefaultMeasurements(Calibration::DefaultMeasurements dm)
{ {
lock_guard<recursive_mutex> guard(access);
auto createSOL = [=](int port) { auto createSOL = [=](int port) {
auto _short = new CalibrationMeasurement::Short(this); auto _short = new CalibrationMeasurement::Short(this);
_short->setPort(port); _short->setPort(port);
@ -1793,6 +1804,7 @@ void Calibration::createDefaultMeasurements(Calibration::DefaultMeasurements dm)
void Calibration::deleteMeasurements() void Calibration::deleteMeasurements()
{ {
lock_guard<recursive_mutex> guard(access);
for(auto m : measurements) { for(auto m : measurements) {
delete m; delete m;
} }

View File

@ -155,6 +155,8 @@ private:
QString currentCalFile; QString currentCalFile;
bool unsavedChanges; bool unsavedChanges;
std::recursive_mutex access;
}; };
#endif // CALIBRATION2_H #endif // CALIBRATION2_H

View File

@ -13,7 +13,7 @@ FrequencyCalDialog::FrequencyCalDialog(Device *dev, ModeHandler *handler, QWidg
ui->ppm->setPrecision(4); ui->ppm->setPrecision(4);
ui->ppm->setValue(0.0); ui->ppm->setValue(0.0);
connect(dev, &Device::FrequencyCorrectionReceived, ui->ppm, &SIUnitEdit::setValueQuiet); connect(dev, &Device::FrequencyCorrectionReceived, ui->ppm, &SIUnitEdit::setValueQuiet, Qt::QueuedConnection);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
connect(ui->buttonBox, &QDialogButtonBox::accepted, [=](){ connect(ui->buttonBox, &QDialogButtonBox::accepted, [=](){
// get value and transfer to device // get value and transfer to device

View File

@ -453,6 +453,7 @@ const Protocol::DeviceInfo &Device::Info(Device *dev)
Protocol::DeviceStatusV1 &Device::StatusV1() Protocol::DeviceStatusV1 &Device::StatusV1()
{ {
lock_guard<mutex> guard(accessMutex);
return status.v1; return status.v1;
} }
@ -467,6 +468,7 @@ const Protocol::DeviceStatusV1 &Device::StatusV1(Device *dev)
QString Device::getLastDeviceInfoString() QString Device::getLastDeviceInfoString()
{ {
lock_guard<mutex> guard(accessMutex);
QString ret; QString ret;
if(!infoValid) { if(!infoValid) {
ret.append("No device information available yet"); ret.append("No device information available yet");
@ -521,18 +523,24 @@ void Device::ReceivedData()
emit AmplitudeCorrectionPointReceived(packet.amplitudePoint); emit AmplitudeCorrectionPointReceived(packet.amplitudePoint);
break; break;
case Protocol::PacketType::DeviceInfo: case Protocol::PacketType::DeviceInfo:
if(packet.info.ProtocolVersion != Protocol::Version) { {
if(!infoValid) { lock_guard<mutex> guard(accessMutex);
emit NeedsFirmwareUpdate(packet.info.ProtocolVersion, Protocol::Version); if(packet.info.ProtocolVersion != Protocol::Version) {
if(!infoValid) {
emit NeedsFirmwareUpdate(packet.info.ProtocolVersion, Protocol::Version);
}
} else {
info = packet.info;
} }
} else { infoValid = true;
info = packet.info;
} }
infoValid = true;
emit DeviceInfoUpdated(this); emit DeviceInfoUpdated(this);
break; break;
case Protocol::PacketType::DeviceStatusV1: case Protocol::PacketType::DeviceStatusV1:
status.v1 = packet.statusV1; {
lock_guard<mutex> guard(accessMutex);
status.v1 = packet.statusV1;
}
emit DeviceStatusUpdated(this); emit DeviceStatusUpdated(this);
break; break;
case Protocol::PacketType::Ack: case Protocol::PacketType::Ack:

View File

@ -140,6 +140,8 @@ private:
union { union {
Protocol::DeviceStatusV1 v1; Protocol::DeviceStatusV1 v1;
} status; } status;
std::mutex accessMutex;
}; };
#endif // DEVICE_H #endif // DEVICE_H

View File

@ -2,8 +2,12 @@
#include "preferences.h" #include "preferences.h"
#include <exception>
#include <QDateTime> #include <QDateTime>
using namespace std;
DeviceUSBLog::DeviceUSBLog() DeviceUSBLog::DeviceUSBLog()
: usedStorageSize(0) : usedStorageSize(0)
{ {
@ -18,6 +22,7 @@ DeviceUSBLog::~DeviceUSBLog()
void DeviceUSBLog::reset() void DeviceUSBLog::reset()
{ {
std::lock_guard<mutex> guard(access);
entries.clear(); entries.clear();
usedStorageSize = 0; usedStorageSize = 0;
} }
@ -64,8 +69,19 @@ void DeviceUSBLog::fromJSON(nlohmann::json j)
} }
} }
DeviceUSBLog::LogEntry DeviceUSBLog::getEntry(unsigned int index)
{
std::lock_guard<mutex> guard(access);
if(index < entries.size()) {
return entries[index];
} else {
throw std::runtime_error("Index too high");
}
}
void DeviceUSBLog::addEntry(const DeviceUSBLog::LogEntry &e) void DeviceUSBLog::addEntry(const DeviceUSBLog::LogEntry &e)
{ {
std::lock_guard<mutex> guard(access);
usedStorageSize += e.storageSize(); usedStorageSize += e.storageSize();
while(usedStorageSize > maxStorageSize) { while(usedStorageSize > maxStorageSize) {
usedStorageSize -= entries.front().storageSize(); usedStorageSize -= entries.front().storageSize();
@ -75,9 +91,28 @@ void DeviceUSBLog::addEntry(const DeviceUSBLog::LogEntry &e)
emit entryAdded(e); emit entryAdded(e);
} }
std::deque<DeviceUSBLog::LogEntry> DeviceUSBLog::getEntries() const unsigned long DeviceUSBLog::getMaxStorageSize() const
{ {
return entries; return maxStorageSize;
}
unsigned long DeviceUSBLog::getUsedStorageSize() const
{
return usedStorageSize;
}
DeviceUSBLog::LogEntry::LogEntry(const DeviceUSBLog::LogEntry &e)
{
timestamp = e.timestamp;
type = e.type;
serial = e.serial;
bytes = e.bytes;
if(e.p) {
p = new Protocol::PacketInfo;
*p = *e.p;
} else {
p = nullptr;
}
} }
nlohmann::json DeviceUSBLog::LogEntry::toJSON() nlohmann::json DeviceUSBLog::LogEntry::toJSON()

View File

@ -9,6 +9,7 @@
#include <cstdint> #include <cstdint>
#include <QDateTime> #include <QDateTime>
#include <QObject> #include <QObject>
#include <mutex>
class DeviceUSBLog : public QObject, public Savable class DeviceUSBLog : public QObject, public Savable
{ {
@ -34,6 +35,11 @@ public:
public: public:
LogEntry() LogEntry()
: type(Type::InvalidBytes), timestamp(QDateTime()), serial(""), p(nullptr) {} : type(Type::InvalidBytes), timestamp(QDateTime()), serial(""), p(nullptr) {}
~LogEntry() {
delete p;
}
LogEntry(const LogEntry &e);
enum class Type { enum class Type {
Packet, Packet,
@ -57,7 +63,10 @@ public:
virtual void fromJSON(nlohmann::json j) override; virtual void fromJSON(nlohmann::json j) override;
}; };
std::deque<LogEntry> getEntries() const; LogEntry getEntry(unsigned int index);
unsigned long getUsedStorageSize() const;
unsigned long getMaxStorageSize() const;
signals: signals:
void entryAdded(const LogEntry &e); void entryAdded(const LogEntry &e);
@ -70,6 +79,8 @@ private:
unsigned long maxStorageSize; unsigned long maxStorageSize;
unsigned long usedStorageSize; unsigned long usedStorageSize;
std::deque<LogEntry> entries; std::deque<LogEntry> entries;
std::mutex access;
}; };
#endif // DEVICEUSBLOG_H #endif // DEVICEUSBLOG_H

View File

@ -82,9 +82,18 @@ void DeviceUSBLogView::updateTree()
ui->tree->setColumnCount(4); ui->tree->setColumnCount(4);
ui->tree->setHeaderLabels({"Timestamp","Source","Type","Content"}); ui->tree->setHeaderLabels({"Timestamp","Source","Type","Content"});
for(auto &e : log.getEntries()) { unsigned int i=0;
addEntry(e); try {
// will throw once all entries have been added (number of entries may change while the loop is running)
for(i=0;;i++) {
addEntry(log.getEntry(i));
}
} catch (...) {
} }
QString status = "Log contains "+QString::number(i) + " entries, using ";
status += Unit::ToString(log.getUsedStorageSize(), "B", " kMG") + " (maximum: "+Unit::ToString(log.getMaxStorageSize(), "B", " kMG")+")";
ui->status->setText(status);
} }
void DeviceUSBLogView::addEntry(const DeviceUSBLog::LogEntry &e) void DeviceUSBLogView::addEntry(const DeviceUSBLog::LogEntry &e)

View File

@ -21,6 +21,13 @@
</property> </property>
</widget> </widget>
</item> </item>
<item>
<widget class="QLabel" name="status">
<property name="text">
<string/>
</property>
</widget>
</item>
<item> <item>
<widget class="QDialogButtonBox" name="buttonBox"> <widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation"> <property name="orientation">

View File

@ -61,8 +61,8 @@ void FirmwareUpdateDialog::on_bStart_clicked()
} }
file->seek(0); file->seek(0);
state = State::ErasingFLASH; state = State::ErasingFLASH;
connect(dev, &Device::AckReceived, this, &FirmwareUpdateDialog::receivedAck); connect(dev, &Device::AckReceived, this, &FirmwareUpdateDialog::receivedAck, Qt::QueuedConnection);
connect(dev, &Device::NackReceived, this, &FirmwareUpdateDialog::receivedNack); connect(dev, &Device::NackReceived, this, &FirmwareUpdateDialog::receivedNack, Qt::QueuedConnection);
addStatus("Erasing device memory..."); addStatus("Erasing device memory...");
dev->SendCommandWithoutPayload(Protocol::PacketType::ClearFlash); dev->SendCommandWithoutPayload(Protocol::PacketType::ClearFlash);
timer.setSingleShot(true); timer.setSingleShot(true);

View File

@ -148,7 +148,7 @@ ManualControlDialog::ManualControlDialog(Device &dev, QWidget *parent) :
MakeReadOnly(ui->refmag); MakeReadOnly(ui->refmag);
MakeReadOnly(ui->refphase); MakeReadOnly(ui->refphase);
connect(&dev, &Device::ManualStatusReceived, this, &ManualControlDialog::NewStatus); connect(&dev, &Device::ManualStatusReceived, this, &ManualControlDialog::NewStatus, Qt::QueuedConnection);
connect(ui->SourceCE, &QCheckBox::toggled, [=](bool) { UpdateDevice(); }); connect(ui->SourceCE, &QCheckBox::toggled, [=](bool) { UpdateDevice(); });
connect(ui->SourceRFEN, &QCheckBox::toggled, [=](bool) { UpdateDevice(); }); connect(ui->SourceRFEN, &QCheckBox::toggled, [=](bool) { UpdateDevice(); });

View File

@ -38,6 +38,7 @@ TracePlot::TracePlot(TraceModel &model, QWidget *parent)
connect(&replotTimer, &QTimer::timeout, this, qOverload<>(&TracePlot::update)); connect(&replotTimer, &QTimer::timeout, this, qOverload<>(&TracePlot::update));
sweep_fmin = std::numeric_limits<double>::lowest(); sweep_fmin = std::numeric_limits<double>::lowest();
sweep_fmax = std::numeric_limits<double>::max(); sweep_fmax = std::numeric_limits<double>::max();
xSweep = std::numeric_limits<double>::quiet_NaN();
// get notified when the span changes // get notified when the span changes
connect(&model, &TraceModel::SpanChanged, this, qOverload<double, double>(&TracePlot::updateSpan)); connect(&model, &TraceModel::SpanChanged, this, qOverload<double, double>(&TracePlot::updateSpan));
plots.insert(this); plots.insert(this);

View File

@ -939,6 +939,8 @@ void AppWindow::StartManualControl()
void AppWindow::UpdateReferenceToolbar() void AppWindow::UpdateReferenceToolbar()
{ {
toolbars.reference.type->blockSignals(true);
toolbars.reference.outFreq->blockSignals(true);
if(!vdevice || !vdevice->getInfo().supportsExtRef) { if(!vdevice || !vdevice->getInfo().supportsExtRef) {
toolbars.reference.type->setEnabled(false); toolbars.reference.type->setEnabled(false);
toolbars.reference.outFreq->setEnabled(false); toolbars.reference.outFreq->setEnabled(false);
@ -968,6 +970,9 @@ void AppWindow::UpdateReferenceToolbar()
} else { } else {
toolbars.reference.outFreq->setCurrentIndex(0); toolbars.reference.outFreq->setCurrentIndex(0);
} }
toolbars.reference.type->blockSignals(false);
toolbars.reference.outFreq->blockSignals(false);
UpdateReference();
} }
void AppWindow::UpdateReference() void AppWindow::UpdateReference()
@ -1046,7 +1051,6 @@ void AppWindow::DeviceInfoUpdated()
modeHandler->getActiveMode()->initializeDevice(); modeHandler->getActiveMode()->initializeDevice();
} }
UpdateReferenceToolbar(); UpdateReferenceToolbar();
UpdateReference();
} }
void AppWindow::SourceCalibrationDialog() void AppWindow::SourceCalibrationDialog()