Dokit
Internal development documentation
Loading...
Searching...
No Matches
metercommand.cpp
1// SPDX-FileCopyrightText: 2022-2024 Paul Colby <git@colby.id.au>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
4#include "metercommand.h"
5
7
8#include <QJsonDocument>
9#include <QJsonObject>
10
11#include <iostream>
12
13/*!
14 * \class MeterCommand
15 *
16 * The MeterCommand class implements the `meter` CLI command.
17 */
18
19/*!
20 * Construct a new MeterCommand object with \a parent.
21 */
23{
24
25}
26
33
35{
37 QLatin1String("interval"),
38 QLatin1String("range"),
39 QLatin1String("samples"),
40 };
41}
42
43/*!
44 * \copybrief DeviceCommand::processOptions
45 *
46 * This implementation extends DeviceCommand::processOptions to process additional CLI options
47 * supported (or required) by this command.
48 */
50{
52 if (!errors.isEmpty()) {
53 return errors;
54 }
55
56 // Parse the (required) mode option.
57 if (const QString mode = parser.value(QLatin1String("mode")).trimmed().toLower();
58 mode.startsWith(QLatin1String("ac v")) || mode.startsWith(QLatin1String("vac"))) {
61 } else if (mode.startsWith(QLatin1String("dc v")) || mode.startsWith(QLatin1String("vdc"))) {
64 } else if (mode.startsWith(QLatin1String("ac c")) || mode.startsWith(QLatin1String("aac"))) {
67 } else if (mode.startsWith(QLatin1String("dc c")) || mode.startsWith(QLatin1String("adc"))) {
70 } else if (mode.startsWith(QLatin1String("res"))) {
73 } else if (mode.startsWith(QLatin1String("dio"))) {
75 minRangeFunc = nullptr;
76 } else if (mode.startsWith(QLatin1String("cont"))) {
78 minRangeFunc = nullptr;
79 } else if (mode.startsWith(QLatin1String("temp"))) {
81 minRangeFunc = nullptr;
82 } else if (mode.startsWith(QLatin1String("cap"))) {
85 } else {
86 errors.append(tr("Unknown meter mode: %1").arg(parser.value(QLatin1String("mode"))));
87 return errors;
88 }
89
90 // Parse the interval option.
91 if (parser.isSet(QLatin1String("interval"))) {
92 const QString value = parser.value(QLatin1String("interval"));
93 const quint32 interval = parseNumber<std::milli>(value, QLatin1String("s"), 500);
94 if (interval == 0) {
95 errors.append(tr("Invalid interval value: %1").arg(value));
96 } else {
97 settings.updateInterval = interval;
98 }
99 }
100
101 // Parse the range option.
102 rangeOptionValue = 0; // Default to auto.
103 if (parser.isSet(QLatin1String("range"))) {
104 const QString value = parser.value(QLatin1String("range"));
105 if (value.trimmed().compare(QLatin1String("auto"), Qt::CaseInsensitive) != 0) {
106 switch (settings.mode) {
110 break;
114 break;
117 break;
119 rangeOptionValue = parseNumber<std::nano>(value, QLatin1String("F"), 500); // pF.
120 break;
121 default:
122 qCInfo(lc).noquote() << tr("Ignoring range value: %1").arg(value);
123 }
124 if ((minRangeFunc != nullptr) && (rangeOptionValue == 0)) {
125 errors.append(tr("Invalid range value: %1").arg(value));
126 }
127 }
128 }
129
130 // Parse the samples option.
131 if (parser.isSet(QLatin1String("samples"))) {
132 const QString value = parser.value(QLatin1String("samples"));
133 const quint32 samples = parseNumber<std::ratio<1>>(value, QLatin1String("S"));
134 if (samples == 0) {
135 errors.append(tr("Invalid samples value: %1").arg(value));
136 } else {
137 samplesToGo = samples;
138 }
139 }
140 return errors;
141}
142
143/*!
144 * \copybrief DeviceCommand::getService
145 *
146 * This override returns a pointer to a MultimeterService object.
147 */
149{
150 Q_ASSERT(device);
151 if (!service) {
153 Q_ASSERT(service);
156 }
157 return service;
158}
159
160/*!
161 * \copybrief DeviceCommand::serviceDetailsDiscovered
162 *
163 * This override fetches the current device's status, and outputs it in the selected format.
164 */
166{
167 DeviceCommand::serviceDetailsDiscovered(); // Just logs consistently.
170 qCInfo(lc).noquote() << tr("Measuring %1, with range %2, every %L3ms.").arg(
172 (range.isNull()) ? QString::fromLatin1("N/A") : range).arg(settings.updateInterval);
174}
175
176/*!
177 * \var MeterCommand::minRangeFunc
178 *
179 * Pointer to function for converting #rangeOptionValue to a Pokit device's range enumerator. This function pointer
180 * is assigned during the command line parsing, but is not invoked until after the device's services are discovere,
181 * because prior to that discovery, we don't know which product (Meter vs Pro vs Clamp, etc) we're talking to and thus
182 * which enumerator list to be using.
183 *
184 * If the current mode does not support ranges (eg diode, and continuity modes), then this member will be \c nullptr.
185 *
186 * \see processOptions
187 * \see serviceDetailsDiscovered
188 */
189
190/*!
191 * Invoked when the multimeter settings have been written, to begin reading the meter values.
192 */
194{
195 qCDebug(lc).noquote() << tr("Settings written; starting meter readings...");
199}
200
201/*!
202 * Outputs meter \a reading in the selected ouput format.
203 */
205{
206 QString status;
208 status = QLatin1String("Error");
209 } else switch (reading.mode) {
211 break;
219 ? tr("Auto Range On") : tr("Auto Range Off");
220 break;
223 ? tr("Continuity") : tr("No continuity");
224 break;
228 status = tr("Ok");
229 break;
230 }
231
232 QString unit;
233 switch (reading.mode) {
235 case MultimeterService::Mode::DcVoltage: unit = QLatin1String("Vdc"); break;
236 case MultimeterService::Mode::AcVoltage: unit = QLatin1String("Vac"); break;
237 case MultimeterService::Mode::DcCurrent: unit = QLatin1String("Adc"); break;
238 case MultimeterService::Mode::AcCurrent: unit = QLatin1String("Aac"); break;
245 }
246
247 const QString range = service->toString(reading.range, reading.mode);
248
249 switch (format) {
251 for (; showCsvHeader; showCsvHeader = false) {
252 std::cout << qUtf8Printable(tr("mode,value,unit,status,range\n"));
253 }
254 std::cout << qUtf8Printable(QString::fromLatin1("%1,%2,%3,%4,%5\n")
256 .arg(reading.value, 0, 'f').arg(unit, status, range)
257 );
258 break;
259 case OutputFormat::Json: {
260 QJsonObject object{
261 { QLatin1String("status"), status },
262 { QLatin1String("value"), qIsInf(reading.value) ?
263 QJsonValue(tr("Infinity")) : QJsonValue(reading.value) },
264 { QLatin1String("mode"), MultimeterService::toString(reading.mode) },
265 };
266 if (!unit.isNull()) {
267 object.insert(QLatin1String("unit"), unit);
268 }
269 if (!range.isNull()) {
270 object.insert(QLatin1String("range"), range);
271 }
272 std::cout << QJsonDocument(object).toJson().toStdString();
273 } break;
275 std::cout << qUtf8Printable(tr("Mode: %1 (0x%2)\n").arg(MultimeterService::toString(reading.mode))
276 .arg((quint8)reading.mode,2,16,QLatin1Char('0')));
277 std::cout << qUtf8Printable(tr("Value: %1 %2\n").arg(reading.value,0,'f').arg(unit));
278 std::cout << qUtf8Printable(tr("Status: %1 (0x%2)\n").arg(status)
279 .arg((quint8)reading.status,2,16,QLatin1Char('0')));
280 std::cout << qUtf8Printable(tr("Range: %1 (0x%2)\n").arg(range)
281 .arg((quint8)reading.range,2,16,QLatin1Char('0')));
282 break;
283 }
284
285 if ((samplesToGo > 0) && (--samplesToGo == 0)) {
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.
static QString escapeCsvField(const QString &field)
Returns an RFC 4180 compliant version of field.
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.
std::optional< PokitProduct > pokitProduct() const
Returns the Pokit product this service is attached to.
The AbstractCommand class extends AbstractCommand to add a PokitDevice instance.
static quint8 minResistanceRange(const PokitProduct product, const quint32 maxValue)
Returns the product's lowest resistance range that can measure at least up to maxValue (Ω),...
PokitDevice * device
Pokit Bluetooth device (if any) this command interracts with.
static quint8 minCapacitanceRange(const PokitProduct product, const quint32 maxValue)
Returns the product's lowest capacitance range that can measure at least up to maxValue (nF),...
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...
QStringList requiredOptions(const QCommandLineParser &parser) const override
Returns a list of CLI option names required by this command.
quint32 rangeOptionValue
The parsed value of range option, if one was supplied.
MultimeterService::Settings settings
< Settings for the Pokit device's multimeter mode.
bool showCsvHeader
Whether or not to show a header as the first line of CSV output.
void outputReading(const MultimeterService::Reading &reading)
Outputs meter reading in the selected ouput format.
QStringList processOptions(const QCommandLineParser &parser) override
Processes the relevant options from the command line parser.
void settingsWritten()
Invoked when the multimeter settings have been written, to begin reading the meter values.
QStringList supportedOptions(const QCommandLineParser &parser) const override
Returns a list of CLI option names supported by this command.
AbstractPokitService * getService() override
Returns a Pokit service object for the derived command class.
void serviceDetailsDiscovered() override
Handles service detail discovery events.
MeterCommand(QObject *const parent=nullptr)
Construct a new MeterCommand object with parent.
int samplesToGo
Number of samples to read, if specified on the CLI.
quint8(* minRangeFunc)(const PokitProduct product, const quint32 maxValue)
Pointer to function for converting rangeOptionValue to a Pokit device's range enumerator.
MultimeterService * service
Bluetooth service this command interracts with.
void settingsWritten()
This signal is emitted when the Settings characteristic has been written successfully.
bool enableReadingNotifications()
Enables client-side notifications of meter readings.
@ AutoRangeOn
Auto-range is enabled (voltage, current and resistance modes only).
@ Error
Error (all modes).
@ Continuity
Continuity (continuity mode only).
@ Diode
Measure diode.
@ DcVoltage
Measure DC voltage.
@ Capacitance
Measure capacitance.
@ AcCurrent
Measure AC current.
@ ExternalTemperature
Measure temperature via an external temperature probe.
@ Resistance
Measure resistance.
@ AcVoltage
Measure AC voltage.
@ Idle
Make device idle.
@ Temperature
Measure temperature.
@ DcCurrent
Measure DC current.
@ Continuity
Measure continuity.
static QString toString(const Mode &mode)
Returns mode as a user-friendly string.
void readingRead(const MultimeterService::Reading &reading)
This signal is emitted when the Reading characteristic has been read successfully.
bool setSettings(const Settings &settings)
Configures the Pokit device's multimeter mode.
MultimeterService * multimeter()
Returns a pointer to MultimeterService instance that uses this device's controller for access.
Declares the PokitDevice class.
std::string toStdString() const const
bool isSet(const QString &name) const const
QString value(const QString &optionName) const const
QByteArray toJson() const const
void append(const T &value)
bool isEmpty() const const
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QString tr(const char *sourceText, const char *disambiguation, int n)
QString arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const const
int compare(const QString &other, Qt::CaseSensitivity cs) const const
QString fromLatin1(const char *str, int size)
QString fromUtf8(const char *str, int size)
QString & insert(int position, QChar ch)
bool isNull() const const
bool startsWith(const QString &s, Qt::CaseSensitivity cs) const const
QString trimmed() const const
CaseInsensitive
Attributes included in the Reading characterstic.
MeterStatus status
Current multimeter status.
Mode mode
Current operation mode.
float value
Last acquired value.
quint8 range
Current range.
quint32 updateInterval
Desired update interval in milliseconds.
Mode mode
Desired operation mode.