Dokit
Internal development documentation
Loading...
Searching...
No Matches
dsoservice.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2022-2024 Paul Colby <git@colby.id.au>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
4/*!
5 * \file
6 * Defines the DsoService and DsoServicePrivate classes.
7 */
8
10#include <qtpokit/pokitmeter.h>
11#include <qtpokit/pokitpro.h>
12#include "dsoservice_p.h"
13#include "pokitproducts_p.h"
14
15#include <QDataStream>
16#include <QIODevice>
17#include <QtEndian>
18
19/*!
20 * \class DsoService
21 *
22 * The DsoService class accesses the `DSO` (Digital Storage Oscilloscope) service of Pokit devices.
23 */
24
25/// Returns \a mode as a user-friendly string.
27{
28 switch (mode) {
29 case Mode::Idle: return tr("Idle");
30 case Mode::DcVoltage: return tr("DC voltage");
31 case Mode::AcVoltage: return tr("AC voltage");
32 case Mode::DcCurrent: return tr("DC current");
33 case Mode::AcCurrent: return tr("AC current");
34 default: return QString();
35 }
36}
37
38/// Returns \a range as a user-friendly string, or a null QString if \a mode has no ranges.
39QString DsoService::toString(const PokitProduct product, const quint8 range, const Mode mode)
40{
41 switch (mode) {
42 case Mode::Idle:
43 break;
44 case Mode::DcVoltage:
45 case Mode::AcVoltage:
46 return VoltageRange::toString(product, range);
47 case Mode::DcCurrent:
48 case Mode::AcCurrent:
49 return CurrentRange::toString(product, range);
50 }
51 return QString();
52}
53
54/// Returns \a range as a user-friendly string, or a null QString if \a mode has no ranges.
55QString DsoService::toString(const quint8 range, const Mode mode) const
56{
57 return toString(*pokitProduct(), range, mode);
58}
59
60/*!
61 * Returns the maximum value for \a range, or the string "Auto".
62 *
63 * If \a range is not a known valid enumeration value for \a product's \a mode, then a null QVariant is returned.
64 */
65QVariant DsoService::maxValue(const PokitProduct product, const quint8 range, const Mode mode)
66{
67 switch (mode) {
68 case Mode::Idle:
69 break;
70 case Mode::DcVoltage:
71 case Mode::AcVoltage:
72 return VoltageRange::maxValue(product, range);
73 case Mode::DcCurrent:
74 case Mode::AcCurrent:
75 return CurrentRange::maxValue(product, range);
76 }
77 return QVariant();
78}
79
80/*!
81 * Returns the maximum value for \a range, or the string "Auto".
82 *
83 * If \a range is not a known valid enumeration value for the current \a product's \a mode,
84 * then a null QVariant is returned.
85 */
86QVariant DsoService::maxValue(const quint8 range, const Mode mode) const
87{
88 return maxValue(*pokitProduct(), range, mode);
89}
90
91/*!
92 * \typedef DsoService::Samples
93 *
94 * Raw samples from the `Reading` characteristic. These raw samples are (supposedly) wihtin the
95 * range -2048 to +2047, and need to be multiplied by the Metadata::scale value from the `Metadata`
96 * characteristc to get the true values.
97 *
98 * Also supposedly, there should be no more than 10 samples at a time, according to Pokit's current
99 * API docs. There is not artificial limitation imposed by QtPokit, so devices may begin batching
100 * more samples in future.
101 */
102
103/*!
104 * Constructs a new Pokit service with \a parent.
105 */
107 : AbstractPokitService(new DsoServicePrivate(controller, this), parent)
108{
109
110}
111
112/*!
113 * \cond internal
114 * Constructs a new Pokit service with \a parent, and private implementation \a d.
115 */
117 DsoServicePrivate * const d, QObject * const parent)
118 : AbstractPokitService(d, parent)
119{
120
121}
122/// \endcond
123
128
129/*!
130 * Reads the `DSO` service's `Metadata` characteristic.
131 *
132 * Returns `true` is the read request is succesfully queued, `false` otherwise (ie if the
133 * underlying controller it not yet connected to the Pokit device, or the device's services have
134 * not yet been discovered).
135 *
136 * Emits metadataRead() if/when the characteristic has been read successfully.
137 */
139{
140 Q_D(DsoService);
141 return d->readCharacteristic(CharacteristicUuids::metadata);
142}
143
144/*!
145 * Configures the Pokit device's DSO mode.
146 *
147 * Returns `true` if the write request was successfully queued, `false` otherwise.
148 *
149 * Emits settingsWritten() if/when the \a settings have been writtem successfully.
150 */
152{
153 Q_D(const DsoService);
154 const QLowEnergyCharacteristic characteristic =
155 d->getCharacteristic(CharacteristicUuids::settings);
156 if (!characteristic.isValid()) {
157 return false;
158 }
159
160 const QByteArray value = DsoServicePrivate::encodeSettings(settings);
161 if (value.isNull()) {
162 return false;
163 }
164
165 d->service->writeCharacteristic(characteristic, value);
166 return (d->service->error() != QLowEnergyService::ServiceError::CharacteristicWriteError);
167}
168
169/*!
170 * Start the DSO with \a settings.
171 *
172 * This is just a synonym for setSettings() except makes the caller's intention more explicit, and
173 * sanity-checks that the settings's command is not DsoService::Command::ResendData.
174 */
175bool DsoService::startDso(const Settings &settings)
176{
177 Q_D(const DsoService);
178 Q_ASSERT(settings.command != DsoService::Command::ResendData);
180 qCWarning(d->lc).noquote() << tr("Settings command must not be 'ResendData'.");
181 return false;
182 }
183 return setSettings(settings);
184}
185
186/*!
187 * Fetch DSO samples.
188 *
189 * This is just a convenience function equivalent to calling setSettings() with the command set to
190 * DsoService::Command::Refresh.
191 *
192 * Once the Pokit device has processed this request succesffully, the device will begin notifying
193 * the `Metadata` and `Reading` characteristic, resulting in emits of metadataRead and samplesRead
194 * respectively.
195 */
197{
198 // Note, only the Settings::command member need be set, since the others are all ignored by the
199 // Pokit device when the command is Refresh. However, we still explicitly initialise all other
200 // members just to ensure we're never exposing uninitialised RAM to an external device.
202}
203
204/*!
205 * Returns the most recent value of the `DSO` service's `Metadata` characteristic.
206 *
207 * The returned value, if any, is from the underlying Bluetooth stack's cache. If no such value is
208 * currently available (ie the serviceDetailsDiscovered signal has not been emitted yet), then the
209 * returned DsoService::Metadata::scale member will be a quiet NaN, which can be checked like:
210 *
211 * ```
212 * const DsoService::Metadata metadata = multimeterService->metadata();
213 * if (qIsNaN(metadata.scale)) {
214 * // Handle failure.
215 * }
216 * ```
217 */
219{
220 Q_D(const DsoService);
221 const QLowEnergyCharacteristic characteristic =
222 d->getCharacteristic(CharacteristicUuids::metadata);
223 return (characteristic.isValid()) ? DsoServicePrivate::parseMetadata(characteristic.value())
224 : Metadata{ DsoStatus::Error, std::numeric_limits<float>::quiet_NaN(), Mode::Idle, 0, 0, 0, 0 };
225}
226
227/*!
228 * Enables client-side notifications of DSO metadata changes.
229 *
230 * This is an alternative to manually requesting individual reads via readMetadataCharacteristic().
231 *
232 * Returns `true` is the request was successfully submited to the device queue, `false` otherwise.
233 *
234 * Successfully read values (if any) will be emitted via the metadataRead() signal.
235 */
237{
238 Q_D(DsoService);
239 return d->enableCharacteristicNotificatons(CharacteristicUuids::metadata);
240}
241
242/*!
243 * Disables client-side notifications of DSO metadata changes.
244 *
245 * Instantaneous reads can still be fetched by readMetadataCharacteristic().
246 *
247 * Returns `true` is the request was successfully submited to the device queue, `false` otherwise.
248 */
250{
251 Q_D(DsoService);
252 return d->disableCharacteristicNotificatons(CharacteristicUuids::metadata);
253}
254
255/*!
256 * Enables client-side notifications of DSO readings.
257 *
258 * Returns `true` is the request was successfully submited to the device queue, `false` otherwise.
259 *
260 * Successfully read samples (if any) will be emitted via the samplesRead() signal.
261 */
263{
264 Q_D(DsoService);
265 return d->enableCharacteristicNotificatons(CharacteristicUuids::reading);
266}
267
268/*!
269 * Disables client-side notifications of DSO readings.
270 *
271 * Returns `true` is the request was successfully submited to the device queue, `false` otherwise.
272 */
274{
275 Q_D(DsoService);
276 return d->disableCharacteristicNotificatons(CharacteristicUuids::reading);
277}
278
279/*!
280 * \fn DsoService::settingsWritten
281 *
282 * This signal is emitted when the `Settings` characteristic has been written successfully.
283 *
284 * \see setSettings
285 */
286
287/*!
288 * \fn DsoService::metadataRead
289 *
290 * This signal is emitted when the `Metadata` characteristic has been read successfully.
291 *
292 * \see readMetadataCharacteristic
293 */
294
295/*!
296 * \fn DsoService::samplesRead
297 *
298 * This signal is emitted when the `Reading` characteristic has been notified.
299 *
300 * \see beginSampling
301 * \see stopSampling
302 */
303
304
305/*!
306 * \cond internal
307 * \class DsoServicePrivate
308 *
309 * The DsoServicePrivate class provides private implementation for DsoService.
310 */
311
312/*!
313 * \internal
314 * Constructs a new DsoServicePrivate object with public implementation \a q.
315 */
317 QLowEnergyController * controller, DsoService * const q)
318 : AbstractPokitServicePrivate(DsoService::serviceUuid, controller, q)
319{
320
321}
322
323/*!
324 * Returns \a settings in the format Pokit devices expect.
325 */
327{
328 static_assert(sizeof(settings.command) == 1, "Expected to be 1 byte.");
329 static_assert(sizeof(settings.triggerLevel) == 4, "Expected to be 2 bytes.");
330 static_assert(sizeof(settings.mode) == 1, "Expected to be 1 byte.");
331 static_assert(sizeof(settings.range) == 1, "Expected to be 1 byte.");
332 static_assert(sizeof(settings.samplingWindow) == 4, "Expected to be 4 bytes.");
333 static_assert(sizeof(settings.numberOfSamples) == 2, "Expected to be 2 bytes.");
334
335 QByteArray value;
336 QDataStream stream(&value, QIODevice::WriteOnly);
338 stream.setFloatingPointPrecision(QDataStream::SinglePrecision); // 32-bit floats, not 64-bit.
339 stream << (quint8)settings.command << settings.triggerLevel << (quint8)settings.mode
340 << settings.range << settings.samplingWindow << settings.numberOfSamples;
341
342 Q_ASSERT(value.size() == 13);
343 return value;
344}
345
346/*!
347 * Parses the `Metadata` \a value into a DsoService::Metatdata struct.
348 */
350{
351 DsoService::Metadata metadata{
352 DsoService::DsoStatus::Error, std::numeric_limits<float>::quiet_NaN(),
353 DsoService::Mode::Idle, 0, 0, 0, 0
354 };
355
356 if (!checkSize(QLatin1String("Metadata"), value, 17, 17)) {
357 return metadata;
358 }
359
360 metadata.status = static_cast<DsoService::DsoStatus>(value.at(0));
361 metadata.scale = qFromLittleEndian<float>(value.mid(1,4).constData());
362 metadata.mode = static_cast<DsoService::Mode>(value.at(5));
363 metadata.range = static_cast<quint8>(value.at(6));
364 metadata.samplingWindow = qFromLittleEndian<quint32>(value.mid(7,4).constData());
365 metadata.numberOfSamples = qFromLittleEndian<quint16>(value.mid(11,2).constData());
366 metadata.samplingRate = qFromLittleEndian<quint32>(value.mid(13,4).constData());
367 return metadata;
368}
369
370/*!
371 * Parses the `Reading` \a value into a DsoService::Samples vector.
372 */
374{
375 DsoService::Samples samples;
376 if ((value.size()%2) != 0) {
377 qCWarning(lc).noquote() << tr("Samples value has odd size %1 (should be even): %2")
378 .arg(value.size()).arg(toHexString(value));
379 return samples;
380 }
381 while ((samples.size()*2) < value.size()) {
382 samples.append(qFromLittleEndian<qint16>(value.mid(samples.size()*2,2).constData()));
383 }
384 qCDebug(lc).noquote() << tr("Read %n sample/s from %1-bytes.", nullptr, samples.size()).arg(value.size());
385 return samples;
386}
387
388/*!
389 * Implements AbstractPokitServicePrivate::characteristicRead to parse \a value, then emit a
390 * specialised signal, for each supported \a characteristic.
391 */
393 const QByteArray &value)
394{
396
397 if (characteristic.uuid() == DsoService::CharacteristicUuids::settings) {
398 qCWarning(lc).noquote() << tr("Settings characteristic is write-only, but somehow read")
399 << serviceUuid << characteristic.name() << characteristic.uuid();
400 return;
401 }
402
403 Q_Q(DsoService);
404 if (characteristic.uuid() == DsoService::CharacteristicUuids::metadata) {
405 Q_EMIT q->metadataRead(parseMetadata(value));
406 return;
407 }
408
409 if (characteristic.uuid() == DsoService::CharacteristicUuids::reading) {
410 qCWarning(lc).noquote() << tr("Reading characteristic is notify-only")
411 << serviceUuid << characteristic.name() << characteristic.uuid();
412 return;
413 }
414
415 qCWarning(lc).noquote() << tr("Unknown characteristic read for DSO service")
416 << serviceUuid << characteristic.name() << characteristic.uuid();
417}
418
419/*!
420 * Implements AbstractPokitServicePrivate::characteristicWritten to parse \a newValue, then emit a
421 * specialised signal, for each supported \a characteristic.
422 */
424 const QByteArray &newValue)
425{
427
428 Q_Q(DsoService);
429 if (characteristic.uuid() == DsoService::CharacteristicUuids::settings) {
430 Q_EMIT q->settingsWritten();
431 return;
432 }
433
434 if (characteristic.uuid() == DsoService::CharacteristicUuids::metadata) {
435 qCWarning(lc).noquote() << tr("Metadata characteristic is read/notify, but somehow written")
436 << serviceUuid << characteristic.name() << characteristic.uuid();
437 return;
438 }
439
440 if (characteristic.uuid() == DsoService::CharacteristicUuids::reading) {
441 qCWarning(lc).noquote() << tr("Reading characteristic is notify-only, but somehow written")
442 << serviceUuid << characteristic.name() << characteristic.uuid();
443 return;
444 }
445
446 qCWarning(lc).noquote() << tr("Unknown characteristic written for DSO service")
447 << serviceUuid << characteristic.name() << characteristic.uuid();
448}
449
450/*!
451 * Implements AbstractPokitServicePrivate::characteristicChanged to parse \a newValue, then emit a
452 * specialised signal, for each supported \a characteristic.
453 */
455 const QByteArray &newValue)
456{
458
459 Q_Q(DsoService);
460 if (characteristic.uuid() == DsoService::CharacteristicUuids::settings) {
461 qCWarning(lc).noquote() << tr("Settings characteristic is write-only, but somehow updated")
462 << serviceUuid << characteristic.name() << characteristic.uuid();
463 return;
464 }
465
466 if (characteristic.uuid() == DsoService::CharacteristicUuids::metadata) {
467 Q_EMIT q->metadataRead(parseMetadata(newValue));
468 return;
469 }
470
471 if (characteristic.uuid() == DsoService::CharacteristicUuids::reading) {
472 Q_EMIT q->samplesRead(parseSamples(newValue));
473 return;
474 }
475
476 qCWarning(lc).noquote() << tr("Unknown characteristic notified for DSO service")
477 << serviceUuid << characteristic.name() << characteristic.uuid();
478}
479
480/// \endcond
The AbstractPokitServicePrivate class provides private implementation for AbstractPokitService.
QBluetoothUuid serviceUuid
UUIDs for service.
virtual void characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue)
Handles QLowEnergyService::characteristicChanged events.
virtual void characteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &value)
Handles QLowEnergyService::characteristicRead events.
virtual void characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue)
Handles QLowEnergyService::characteristicWritten events.
static QString toHexString(const QByteArray &data, const int maxSize=20)
Returns up to maxSize bytes of data as a human readable hexadecimal string.
static bool checkSize(const QString &label, const QByteArray &data, const int minSize, const int maxSize=-1, const bool failOnMax=false)
Returns false if data is smaller than minSize, otherwise returns failOnMax if data is bigger than max...
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 DsoServicePrivate class provides private implementation for DsoService.
void characteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &value) override
Implements AbstractPokitServicePrivate::characteristicRead to parse value, then emit a specialised si...
static DsoService::Samples parseSamples(const QByteArray &value)
Parses the Reading value into a DsoService::Samples vector.
void characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) override
Implements AbstractPokitServicePrivate::characteristicChanged to parse newValue, then emit a speciali...
void characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) override
Implements AbstractPokitServicePrivate::characteristicWritten to parse newValue, then emit a speciali...
DsoServicePrivate(QLowEnergyController *controller, DsoService *const q)
static QByteArray encodeSettings(const DsoService::Settings &settings)
Returns settings in the format Pokit devices expect.
static DsoService::Metadata parseMetadata(const QByteArray &value)
Parses the Metadata value into a DsoService::Metatdata struct.
The DsoService class accesses the DSO (Digital Storage Oscilloscope) service of Pokit devices.
Definition dsoservice.h:24
DsoService(QLowEnergyController *const pokitDevice, QObject *parent=nullptr)
Constructs a new Pokit service with parent.
bool disableMetadataNotifications()
Disables client-side notifications of DSO metadata changes.
bool startDso(const Settings &settings)
Start the DSO with settings.
static QVariant maxValue(const PokitProduct product, const quint8 range, const Mode mode)
Returns the maximum value for range, or the string "Auto".
bool setSettings(const Settings &settings)
Configures the Pokit device's DSO mode.
bool fetchSamples()
Fetch DSO samples.
bool enableMetadataNotifications()
Enables client-side notifications of DSO metadata changes.
DsoStatus
Values supported by the Status attribute of the Metadata characteristic.
Definition dsoservice.h:77
@ Error
An error has occurred.
bool readCharacteristics() override
Read all characteristics.
bool enableReadingNotifications()
Enables client-side notifications of DSO readings.
static QString toString(const Mode &mode)
Returns mode as a user-friendly string.
bool readMetadataCharacteristic()
Reads the DSO service's Metadata characteristic.
Mode
Values supported by the Mode attribute of the Settings and Metadata characteristics.
Definition dsoservice.h:52
@ DcVoltage
Measure DC voltage.
@ AcCurrent
Measure AC current.
@ AcVoltage
Measure AC voltage.
@ Idle
Make device idle.
@ DcCurrent
Measure DC current.
@ ResendData
Resend the last acquired data.
bool disableReadingNotifications()
Disables client-side notifications of DSO readings.
Metadata metadata() const
Returns the most recent value of the DSO service's Metadata characteristic.
Declares the DsoService class.
Declares the DsoServicePrivate class.
QVariant maxValue(const PokitProduct product, const quint8 range)
Returns the maximum value for product's range in (integer) microamps, or the string "Auto".
QString toString(const PokitProduct product, const quint8 range)
Returns product's current range as a human-friendly string.
QString toString(const PokitProduct product, const quint8 range)
Returns product's current range as a human-friendly string.
QVariant maxValue(const PokitProduct product, const quint8 range)
Returns the maximum value for product's range in (integer) millivolts, or the string "Auto".
Declares the PokitMeter namespace.
Declares the PokitPro namespace.
PokitProduct
Pokit products known to, and supported by, the QtPokit library.
char at(int i) const const
const char * constData() const const
bool isNull() const const
QByteArray mid(int pos, int len) const const
int size() const const
void setByteOrder(QDataStream::ByteOrder bo)
void setFloatingPointPrecision(QDataStream::FloatingPointPrecision precision)
bool isValid() const const
QString name() const const
QBluetoothUuid uuid() const const
QByteArray value() const const
Q_EMITQ_EMIT
QString tr(const char *sourceText, const char *disambiguation, int n)
QString arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const const
void append(const T &value)
int size() const const
static const QBluetoothUuid metadata
UUID of the DSO service's Metadata characterstic.
Definition dsoservice.h:37
static const QBluetoothUuid reading
UUID of the DSO service's Reading characterstic.
Definition dsoservice.h:40
static const QBluetoothUuid settings
UUID of the DSO service's Settings characterstic.
Definition dsoservice.h:34
Attributes included in the Metadata characterstic.
Definition dsoservice.h:84
DsoStatus status
Current DSO status.
Definition dsoservice.h:85
Attributes included in the Settings characterstic.
Definition dsoservice.h:67
Mode mode
Desired operation mode.
Definition dsoservice.h:70
quint8 range
Desired range, eg settings.range = +PokitPro::CurrentRange::AutoRange;.
Definition dsoservice.h:71
Command command
Custom operation request.
Definition dsoservice.h:68
quint32 samplingWindow
Desired sampling window in microseconds.
Definition dsoservice.h:72
float triggerLevel
Trigger threshold level in Volts or Amps, depending on mode.
Definition dsoservice.h:69
quint16 numberOfSamples
Desired number of samples to acquire.
Definition dsoservice.h:73