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