Dokit
Internal development documentation
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Pages
dsocommand.cpp
1// SPDX-FileCopyrightText: 2022-2025 Paul Colby <git@colby.id.au>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
4#include "dsocommand.h"
6
8
9#include <QJsonDocument>
10#include <QJsonObject>
11
12#include <iostream>
13
15
16/*!
17 * \class DsoCommand
18 *
19 * The DsoCommand class implements the `dso` CLI command.
20 */
21
22/*!
23 * Construct a new DsoCommand object with \a parent.
24 */
29
31{
33 u"mode"_s,
34 u"range"_s,
35 };
36}
37
39{
41 u"interval"_s,
42 u"samples"_s,
43 u"trigger-level"_s,
44 u"trigger-mode"_s,
45 };
46}
47
48/*!
49 * \copybrief DeviceCommand::processOptions
50 *
51 * This implementation extends DeviceCommand::processOptions to process additional CLI options
52 * supported (or required) by this command.
53 */
55{
57 if (!errors.isEmpty()) {
58 return errors;
59 }
60
61 // Parse the (required) mode option.
62 if (const QString mode = parser.value(u"mode"_s).trimmed().toLower();
63 mode.startsWith(u"ac v"_s) || mode.startsWith(u"vac"_s)) {
65 } else if (mode.startsWith(u"dc v"_s) || mode.startsWith(u"vdc"_s)) {
67 } else if (mode.startsWith(u"ac c"_s) || mode.startsWith(u"aac"_s)) {
69 } else if (mode.startsWith(u"dc c"_s) || mode.startsWith(u"adc"_s)) {
71 } else {
72 errors.append(tr("Unknown DSO mode: %1").arg(parser.value(u"mode"_s)));
73 return errors;
74 }
75
76 // Parse the (required) range option.
77 QString unit;
78 {
79 const QString value = parser.value(u"range"_s);
80 quint32 sensibleMinimum = 0;
81 switch (settings.mode) {
83 Q_ASSERT(false); // Not possible, since the mode parsing above never allows Idle.
84 break;
88 unit = u"V"_s;
89 sensibleMinimum = 50; // mV.
90 break;
94 unit = u"A"_s;
95 sensibleMinimum = 5; // mA.
96 break;
97 }
98 Q_ASSERT(!unit.isEmpty());
99 rangeOptionValue = parseNumber<std::milli>(value, unit, sensibleMinimum);
100 if (rangeOptionValue == 0) {
101 errors.append(tr("Invalid range value: %1").arg(value));
102 }
103 }
104
105 // Parse the trigger-level option.
106 if (parser.isSet(u"trigger-level"_s)) {
107 const QString value = parser.value(u"trigger-level"_s);
108 const quint32 level = parseNumber<std::micro>(value, unit);
109 if (level == 0) {
110 errors.append(tr("Invalid trigger-level value: %1").arg(value));
111 } else {
112 settings.triggerLevel = (float)(level/1'000'000.0);
113 }
114 }
115
116 // Parse the trigger-mode option.
117 if (parser.isSet(u"trigger-mode"_s)) {
118 const QString triggerMode = parser.value(u"trigger-mode"_s).trimmed().toLower();
119 if (triggerMode.startsWith(u"free"_s)) {
121 } else if (triggerMode.startsWith(u"ris"_s)) {
123 } else if (triggerMode.startsWith(u"fall"_s)) {
125 } else {
126 errors.append(tr("Unknown trigger mode: %1").arg(parser.value(u"trigger-mode"_s)));
127 }
128 }
129
130 // Ensure that if either trigger option is present, then both are.
131 if (parser.isSet(u"trigger-level"_s) != parser.isSet(u"trigger-mode"_s)) {
132 errors.append(tr("If either option is provided, then both must be: trigger-level, trigger-mode"));
133 }
134
135 // Parse the interval option.
136 if (parser.isSet(u"interval"_s)) {
137 const QString value = parser.value(u"interval"_s);
138 const quint32 interval = parseNumber<std::micro>(value, u"s"_s, 500'000);
139 if (interval == 0) {
140 errors.append(tr("Invalid interval value: %1").arg(value));
141 } else {
142 settings.samplingWindow = interval;
143 }
144 }
145
146 // Parse the samples option.
147 if (parser.isSet(u"samples"_s)) {
148 const QString value = parser.value(u"samples"_s);
149 const quint32 samples = parseNumber<std::ratio<1>>(value, u"S"_s);
150 if (samples == 0) {
151 errors.append(tr("Invalid samples value: %1").arg(value));
152 } else if (samples > std::numeric_limits<quint16>::max()) {
153 errors.append(tr("Samples value (%1) must be no greater than %2")
154 .arg(value).arg(std::numeric_limits<quint16>::max()));
155 } else {
156 if (samples > 8192) {
157 qCWarning(lc).noquote() << tr("Pokit devices do not officially support great than 8192 samples");
158 }
159 settings.numberOfSamples = (quint16)samples;
160 }
161 }
162 return errors;
163}
164
165/*!
166 * \copybrief DeviceCommand::getService
167 *
168 * This override returns a pointer to a DsoService object.
169 */
171{
172 Q_ASSERT(device);
173 if (!service) {
174 service = device->dso();
175 Q_ASSERT(service);
178 }
179 return service;
180}
181
182/*!
183 * \copybrief DeviceCommand::serviceDetailsDiscovered
184 *
185 * This override fetches the current device's status, and outputs it in the selected format.
186 */
188{
189 DeviceCommand::serviceDetailsDiscovered(); // Just logs consistently.
190 settings.range = (minRangeFunc == nullptr) ? 0 : minRangeFunc(*service->pokitProduct(), rangeOptionValue);
191 const QString range = service->toString(settings.range, settings.mode);
192 qCInfo(lc).noquote() << tr("Sampling %1, with range %2, %Ln sample/s over %L3us", nullptr, settings.numberOfSamples)
193 .arg(DsoService::toString(settings.mode), (range.isNull()) ? QString::fromLatin1("N/A") : range)
194 .arg(settings.samplingWindow);
195 service->setSettings(settings);
196}
197
198/*!
199 * \var DsoCommand::minRangeFunc
200 *
201 * Pointer to function for converting #rangeOptionValue to a Pokit device's range enumerator. This function pointer
202 * is assigned during the command line parsing, but is not invoked until after the device's services are discovered,
203 * because prior to that discovery, we don't know which product (Meter vs Pro vs Clamp, etc) we're talking to and thus
204 * which enumerator list to be using.
205 *
206 * If the current mode does not support ranges (eg diode, and continuity modes), then this member will be \c nullptr.
207 *
208 * \see processOptions
209 * \see serviceDetailsDiscovered
210 */
211
212/*!
213 * Invoked when the DSO settings have been written.
214 */
216{
217 Q_ASSERT(service);
218 qCDebug(lc).noquote() << tr("Settings written; DSO has started.");
221 service->enableMetadataNotifications();
222 service->enableReadingNotifications();
223}
224
225/*!
226 * Invoked when \a metadata has been received from the DSO.
227 */
229{
230 qCDebug(lc) << "status:" << (int)(data.status);
231 qCDebug(lc) << "scale:" << data.scale;
232 qCDebug(lc) << "mode:" << DsoService::toString(data.mode);
233 qCDebug(lc) << "range:" << service->toString(data.range, data.mode);
234 qCDebug(lc) << "samplingWindow:" << (int)data.samplingWindow;
235 qCDebug(lc) << "numberOfSamples:" << data.numberOfSamples;
236 qCDebug(lc) << "samplingRate:" << data.samplingRate << "Hz";
237 this->metadata = data;
238 this->samplesToGo = data.numberOfSamples;
239}
240
241/*!
242 * Outputs DSO \a samples in the selected output format.
243 */
245{
246 QString unit;
247 switch (metadata.mode) {
248 case DsoService::Mode::DcVoltage: unit = u"Vdc"_s; break;
249 case DsoService::Mode::AcVoltage: unit = u"Vac"_s; break;
250 case DsoService::Mode::DcCurrent: unit = u"Adc"_s; break;
251 case DsoService::Mode::AcCurrent: unit = u"Aac"_s; break;
252 default:
253 qCDebug(lc).noquote() << tr(R"(No known unit for mode %1 "%2".)").arg((int)metadata.mode)
255 }
256 const QString range = service->toString(metadata.range, metadata.mode);
257
258 for (const qint16 &sample: samples) {
259 static int sampleNumber = 0; ++sampleNumber;
260 const float value = sample * metadata.scale;
261 switch (format) {
263 for (; showCsvHeader; showCsvHeader = false) {
264 std::cout << qUtf8Printable(tr("sample_number,value,unit,range\n"));
265 }
266 std::cout << qUtf8Printable(QString::fromLatin1("%1,%2,%3,%4\n")
267 .arg(sampleNumber).arg(value).arg(unit, range));
268 break;
270 std::cout << QJsonDocument(QJsonObject{
271 { u"value"_s, value },
272 { u"unit"_s, unit },
273 { u"range"_s, range },
274 { u"mode"_s, DsoService::toString(metadata.mode) },
275 }).toJson().toStdString();
276 break;
278 std::cout << qUtf8Printable(tr("%1 %2 %3\n").arg(sampleNumber).arg(value).arg(unit));
279 break;
280 }
281 --samplesToGo;
282 }
283 if (samplesToGo <= 0) {
284 qCInfo(lc).noquote() << tr("Finished fetching %Ln sample/s (with %L2 to remaining).",
285 nullptr, metadata.numberOfSamples).arg(samplesToGo);
286 if (device) disconnect(); // Will exit the application once disconnected.
287 }
288}
virtual QStringList supportedOptions(const QCommandLineParser &parser) const
Returns a list of CLI option names supported by this command.
static quint32 parseNumber(const QString &value, const QString &unit, const quint32 sensibleMinimum=0)
Returns value as an integer multiple of the ratio R.
OutputFormat format
Selected output format.
@ Text
Plain unstructured text.
@ Csv
RFC 4180 compliant CSV text.
@ Json
RFC 8259 compliant JSON text.
virtual QStringList processOptions(const QCommandLineParser &parser)
Processes the relevant options from the command line parser.
virtual QStringList requiredOptions(const QCommandLineParser &parser) const
Returns a list of CLI option names required by this command.
The AbstractPokitService class provides a common base for Pokit services classes.
PokitDevice * device
Pokit Bluetooth device (if any) this command interacts with.
DeviceCommand(QObject *const parent=nullptr)
Construct a new DeviceCommand object with parent.
virtual void serviceDetailsDiscovered()
Handles service detail discovery events.
static quint8 minVoltageRange(const PokitProduct product, const quint32 maxValue)
t Returns the product's lowest voltage range that can measure at least up to maxValue (mV),...
static quint8 minCurrentRange(const PokitProduct product, const quint32 maxValue)
Returns the product's lowest current range that can measure at least up to maxValue (µA),...
void disconnect(int exitCode=EXIT_SUCCESS)
Disconnects the underlying Pokit device, and sets exitCode to be return to the OS once the disconnect...
DsoService::Settings settings
Settings for the Pokit device's DSO mode.
Definition dsocommand.h:33
quint8(* minRangeFunc)(const PokitProduct product, const quint32 maxValue)
Pointer to function for converting rangeOptionValue to a Pokit device's range enumerator.
Definition dsocommand.h:30
qint32 samplesToGo
Number of samples we're expecting in the current window.
Definition dsocommand.h:38
bool showCsvHeader
Whether or not to show a header as the first line of CSV output.
Definition dsocommand.h:39
void serviceDetailsDiscovered() override
Handles service detail discovery events.
void outputSamples(const DsoService::Samples &samples)
Outputs DSO samples in the selected output format.
QStringList supportedOptions(const QCommandLineParser &parser) const override
Returns a list of CLI option names supported by this command.
DsoCommand(QObject *const parent=nullptr)
Construct a new DsoCommand object with parent.
DsoService * service
Bluetooth service this command interacts with.
Definition dsocommand.h:32
QStringList processOptions(const QCommandLineParser &parser) override
Processes the relevant options from the command line parser.
void settingsWritten()
Invoked when the DSO settings have been written.
quint32 rangeOptionValue
The parsed value of range option.
Definition dsocommand.h:31
QStringList requiredOptions(const QCommandLineParser &parser) const override
Returns a list of CLI option names required by this command.
AbstractPokitService * getService() override
Returns a Pokit service object for the derived command class.
DsoService::Metadata metadata
Most recent DSO metadata.
Definition dsocommand.h:37
void metadataRead(const DsoService::Metadata &data)
Invoked when metadata has been received from the DSO.
void metadataRead(const DsoService::Metadata &meta)
This signal is emitted when the Metadata characteristic has been read successfully.
QVector< qint16 > Samples
Raw samples from the Reading characteristic.
Definition dsoservice.h:94
void settingsWritten()
This signal is emitted when the Settings characteristic has been written successfully.
static QString toString(const Mode &mode)
Returns mode as a user-friendly string.
@ DcVoltage
Measure DC voltage.
Definition dsoservice.h:54
@ AcCurrent
Measure AC current.
Definition dsoservice.h:57
@ AcVoltage
Measure AC voltage.
Definition dsoservice.h:55
@ Idle
Make device idle.
Definition dsoservice.h:53
@ DcCurrent
Measure DC current.
Definition dsoservice.h:56
@ FreeRunning
Run free, without waiting for edge triggers.
Definition dsoservice.h:45
@ RisingEdgeTrigger
Trigger on a rising edge.
Definition dsoservice.h:46
@ FallingEdgeTrigger
Trigger on a falling edge.
Definition dsoservice.h:47
void samplesRead(const DsoService::Samples &samples)
This signal is emitted when the Reading characteristic has been notified.
Declares the PokitDevice class.
bool isSet(const QString &name) const const
QString value(const QString &optionName) const const
void append(const T &value)
bool isEmpty() const const
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QObject * parent() const const
QString tr(const char *sourceText, const char *disambiguation, int n)
QString arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const const
QString fromLatin1(const char *str, int size)
bool isEmpty() const const
bool isNull() const const
bool startsWith(const QString &s, Qt::CaseSensitivity cs) const const
QString toLower() const const
QString trimmed() const const
Declares the DOKIT_USE_STRINGLITERALS macro, and related functions.
#define DOKIT_USE_STRINGLITERALS
Internal macro for using either official Qt string literals (added in Qt 6.4), or our own equivalent ...
Attributes included in the Metadata characteristic.
Definition dsoservice.h:84
quint32 samplingRate
Sampling rate used during last acquisition (1 to 1MHz).
Definition dsoservice.h:91
DsoStatus status
Current DSO status.
Definition dsoservice.h:85
float scale
Scale to apply to read samples.
Definition dsoservice.h:86
quint16 numberOfSamples
Number of samples acquired (1 to 8192).
Definition dsoservice.h:90
quint8 range
Range used during last acquisition.
Definition dsoservice.h:88
Mode mode
Operation mode used during last acquisition.
Definition dsoservice.h:87
quint32 samplingWindow
Sampling window (microseconds) used during last acquisition.
Definition dsoservice.h:89