Replace qDebug() by report_info() in bluetooth code

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2024-03-26 08:04:19 +01:00 committed by bstoeger
parent d83da05f8d
commit 4de109bbf1
3 changed files with 87 additions and 72 deletions

View file

@ -2,9 +2,9 @@
#include "btdiscovery.h" #include "btdiscovery.h"
#include "downloadfromdcthread.h" #include "downloadfromdcthread.h"
#include "core/libdivecomputer.h" #include "libdivecomputer.h"
#include "errorhelper.h"
#include <QTimer> #include <QTimer>
#include <QDebug>
#include <QLoggingCategory> #include <QLoggingCategory>
#include <QRegularExpression> #include <QRegularExpression>
#include <QElapsedTimer> #include <QElapsedTimer>
@ -177,7 +177,7 @@ BTDiscovery::BTDiscovery(QObject*) : m_btValid(false),
discoveryAgent(nullptr) discoveryAgent(nullptr)
{ {
if (m_instance) { if (m_instance) {
qDebug() << "trying to create an additional BTDiscovery object"; report_info("trying to create an additional BTDiscovery object");
return; return;
} }
m_instance = this; m_instance = this;
@ -195,11 +195,11 @@ void BTDiscovery::showNonDiveComputers(bool show)
void BTDiscovery::BTDiscoveryReDiscover() void BTDiscovery::BTDiscoveryReDiscover()
{ {
#if !defined(Q_OS_IOS) #if !defined(Q_OS_IOS)
qDebug() << "BTDiscoveryReDiscover: localBtDevice.isValid()" << localBtDevice.isValid(); report_info("BTDiscoveryReDiscover: localBtDevice.isValid() %d", localBtDevice.isValid());
if (localBtDevice.isValid() && if (localBtDevice.isValid() &&
localBtDevice.hostMode() != QBluetoothLocalDevice::HostPoweredOff) { localBtDevice.hostMode() != QBluetoothLocalDevice::HostPoweredOff) {
btPairedDevices.clear(); btPairedDevices.clear();
qDebug() << "BTDiscoveryReDiscover: localDevice " + localBtDevice.name() + " is powered on, starting discovery"; report_info("BTDiscoveryReDiscover: localDevice %s is powered on, starting discovery", qPrintable(localBtDevice.name()));
#else #else
// for iOS we can't use the localBtDevice as iOS is BLE only // for iOS we can't use the localBtDevice as iOS is BLE only
// we need to find some other way to test if Bluetooth is enabled, though // we need to find some other way to test if Bluetooth is enabled, though
@ -220,13 +220,13 @@ void BTDiscovery::BTDiscoveryReDiscover()
connect(discoveryAgent, QOverload<QBluetoothDeviceDiscoveryAgent::Error>::of(&QBluetoothDeviceDiscoveryAgent::error), connect(discoveryAgent, QOverload<QBluetoothDeviceDiscoveryAgent::Error>::of(&QBluetoothDeviceDiscoveryAgent::error),
#endif #endif
[this](QBluetoothDeviceDiscoveryAgent::Error error){ [this](QBluetoothDeviceDiscoveryAgent::Error error){
qDebug() << "device discovery received error" << discoveryAgent->errorString(); report_info("device discovery received error %s", qPrintable(discoveryAgent->errorString()));
}); });
qDebug() << "discovery methods" << (int)QBluetoothDeviceDiscoveryAgent::supportedDiscoveryMethods(); report_info("discovery methods %d", (int)QBluetoothDeviceDiscoveryAgent::supportedDiscoveryMethods());
} }
#if defined(Q_OS_ANDROID) #if defined(Q_OS_ANDROID)
// on Android, we cannot scan for classic devices - we just get the paired ones // on Android, we cannot scan for classic devices - we just get the paired ones
qDebug() << "starting BLE discovery"; report_info("starting BLE discovery");
discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod); discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
getBluetoothDevices(); getBluetoothDevices();
// and add the paired devices to the internal data // and add the paired devices to the internal data
@ -235,10 +235,10 @@ void BTDiscovery::BTDiscoveryReDiscover()
for (int i = 0; i < btPairedDevices.length(); i++) for (int i = 0; i < btPairedDevices.length(); i++)
btDeviceDiscoveredMain(btPairedDevices[i], true); btDeviceDiscoveredMain(btPairedDevices[i], true);
#else #else
qDebug() << "starting BT/BLE discovery"; report_info("starting BT/BLE discovery");
discoveryAgent->start(); discoveryAgent->start();
for (int i = 0; i < btPairedDevices.length(); i++) for (int i = 0; i < btPairedDevices.length(); i++)
qDebug() << "Paired =" << btPairedDevices[i].name << btPairedDevices[i].address; report_info("Paired = %s %s", qPrintable( btPairedDevices[i].name), qPrintable(btPairedDevices[i].address));
#endif #endif
#if defined(Q_OS_IOS) || (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) #if defined(Q_OS_IOS) || (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID))
@ -248,7 +248,7 @@ void BTDiscovery::BTDiscoveryReDiscover()
timer.start(3000); timer.start(3000);
#endif #endif
} else { } else {
qDebug() << "localBtDevice isn't valid or not connectable"; report_info("localBtDevice isn't valid or not connectable");
m_btValid = false; m_btValid = false;
} }
} }
@ -291,10 +291,10 @@ QString markBLEAddress(const QBluetoothDeviceInfo *device)
void BTDiscovery::btDeviceDiscoveryFinished() void BTDiscovery::btDeviceDiscoveryFinished()
{ {
qDebug() << "BT/BLE finished discovery"; report_info("BT/BLE finished discovery");
QList<QBluetoothDeviceInfo> devList = discoveryAgent->discoveredDevices(); QList<QBluetoothDeviceInfo> devList = discoveryAgent->discoveredDevices();
for (QBluetoothDeviceInfo device: devList) { for (QBluetoothDeviceInfo device: devList) {
qDebug() << device.name() << device.address().toString(); report_info("%s %s", qPrintable(device.name()), qPrintable(device.address().toString()));
} }
} }
@ -308,7 +308,7 @@ void BTDiscovery::btDeviceDiscovered(const QBluetoothDeviceInfo &device)
const auto serviceUuids = device.serviceUuids(); const auto serviceUuids = device.serviceUuids();
for (QBluetoothUuid id: serviceUuids) { for (QBluetoothUuid id: serviceUuids) {
addBtUuid(id); addBtUuid(id);
qDebug() << id.toByteArray(); report_info("%s", qPrintable(id.toByteArray()));
} }
#if defined(Q_OS_IOS) || defined(Q_OS_MACOS) || defined(Q_OS_WIN) #if defined(Q_OS_IOS) || defined(Q_OS_MACOS) || defined(Q_OS_WIN)
@ -337,7 +337,7 @@ void BTDiscovery::btDeviceDiscoveredMain(const btPairedDevice &device, bool from
msg = QString("%1 device: '%2' [%3]: ").arg(fromPaired ? "Paired" : "Discovered new").arg(newDevice).arg(device.address); msg = QString("%1 device: '%2' [%3]: ").arg(fromPaired ? "Paired" : "Discovered new").arg(newDevice).arg(device.address);
if (newDC) { if (newDC) {
QString vendor = dc_descriptor_get_vendor(newDC); QString vendor = dc_descriptor_get_vendor(newDC);
qDebug() << msg << "this could be a " + vendor; report_info("%s this could be a %s", qPrintable(msg), qPrintable(vendor));
btVP.btpdi = device; btVP.btpdi = device;
btVP.dcDescriptor = newDC; btVP.dcDescriptor = newDC;
btVP.vendorIdx = vendorList.indexOf(vendor); btVP.vendorIdx = vendorList.indexOf(vendor);
@ -352,7 +352,7 @@ void BTDiscovery::btDeviceDiscoveredMain(const btPairedDevice &device, bool from
newDevice += " "; newDevice += " ";
connectionListModel.addAddress(newDevice + device.address); connectionListModel.addAddress(newDevice + device.address);
} }
qDebug() << msg << "not recognized as dive computer"; report_info("%s not recognized as dive computer", qPrintable(msg));
} }
QList<BTDiscovery::btVendorProduct> BTDiscovery::getBtDcs() QList<BTDiscovery::btVendorProduct> BTDiscovery::getBtDcs()
@ -407,12 +407,12 @@ void BTDiscovery::getBluetoothDevices()
result.address = dev.callObjectMethod("getAddress","()Ljava/lang/String;").toString(); result.address = dev.callObjectMethod("getAddress","()Ljava/lang/String;").toString();
result.name = dev.callObjectMethod("getName", "()Ljava/lang/String;").toString(); result.name = dev.callObjectMethod("getName", "()Ljava/lang/String;").toString();
if (btType & 1) { // DEVICE_TYPE_CLASSIC if (btType & 1) { // DEVICE_TYPE_CLASSIC
qDebug() << "paired BT classic device type" << btType << "with address" << result.address; report_info("paired BT classic device type %d with address %s", btType, qPrintable(result.address));
btPairedDevices.append(result); btPairedDevices.append(result);
} }
if (btType & 2) { // DEVICE_TYPE_LE if (btType & 2) { // DEVICE_TYPE_LE
result.address = QString("LE:%1").arg(result.address); result.address = QString("LE:%1").arg(result.address);
qDebug() << "paired BLE device type" << btType << "with address" << result.address; report_info("paired BLE device type %d with address %s", btType, qPrintable(result.address));
btPairedDevices.append(result); btPairedDevices.append(result);
} }
} }
@ -451,7 +451,7 @@ void BTDiscovery::discoverAddress(QString address)
btAddress = extractBluetoothAddress(address); btAddress = extractBluetoothAddress(address);
if (!btDeviceInfo.keys().contains(address) && !discoveryAgent->isActive()) { if (!btDeviceInfo.keys().contains(address) && !discoveryAgent->isActive()) {
qDebug() << "restarting discovery agent"; report_info("restarting discovery agent");
discoveryAgent->start(); discoveryAgent->start();
} }
} }
@ -460,7 +460,7 @@ void BTDiscovery::stopAgent()
{ {
if (!discoveryAgent) if (!discoveryAgent)
return; return;
qDebug() << "---> stopping the discovery agent"; report_info("---> stopping the discovery agent");
discoveryAgent->stop(); discoveryAgent->stop();
} }
@ -491,7 +491,7 @@ QString extractBluetoothNameAddress(const QString &address, QString &name)
name = m.captured(1).trimmed(); name = m.captured(1).trimmed();
return extractedAddress; return extractedAddress;
} }
qDebug() << "can't parse address" << address; report_info("can't parse address %s", qPrintable(address));
return QString(); return QString();
} }
@ -507,7 +507,7 @@ QBluetoothDeviceInfo getBtDeviceInfo(const QString &devaddr)
return btDeviceInfo[devaddr]; return btDeviceInfo[devaddr];
} }
if(!btDeviceInfo.keys().contains(devaddr)) { if(!btDeviceInfo.keys().contains(devaddr)) {
qDebug() << "still looking scan is still running, we should just wait for a few moments"; report_info("still looking scan is still running, we should just wait for a few moments");
// wait for a maximum of 30 more seconds // wait for a maximum of 30 more seconds
// yes, that seems crazy, but on my Mac I see this take more than 20 seconds // yes, that seems crazy, but on my Mac I see this take more than 20 seconds
QElapsedTimer timer; QElapsedTimer timer;
@ -521,7 +521,7 @@ QBluetoothDeviceInfo getBtDeviceInfo(const QString &devaddr)
QThread::msleep(100); QThread::msleep(100);
} while (timer.elapsed() < 30000); } while (timer.elapsed() < 30000);
} }
qDebug() << "notify user that we can't find" << devaddr; report_info("notify user that we can't find %s", qPrintable(devaddr));
return QBluetoothDeviceInfo(); return QBluetoothDeviceInfo();
} }
#endif // BT_SUPPORT #endif // BT_SUPPORT

View file

@ -10,7 +10,6 @@
#include <QThread> #include <QThread>
#include <QTimer> #include <QTimer>
#include <QTime> #include <QTime>
#include <QDebug>
#include <QLoggingCategory> #include <QLoggingCategory>
#include <libdivecomputer/version.h> #include <libdivecomputer/version.h>
@ -50,22 +49,33 @@ static int debugCounter;
} while (timer.elapsed() < (ms)); \ } while (timer.elapsed() < (ms)); \
} while (0) } while (0)
static std::string current_time()
{
return QTime::currentTime().toString().toStdString();
}
template<typename T>
static std::string to_str(const T &v)
{
return v.toString().toStdString();
}
extern "C" { extern "C" {
void BLEObject::serviceStateChanged(QLowEnergyService::ServiceState newState) void BLEObject::serviceStateChanged(QLowEnergyService::ServiceState newState)
{ {
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << "serviceStateChanged"; report_info("serviceStateChanged");
auto service = qobject_cast<QLowEnergyService*>(sender()); auto service = qobject_cast<QLowEnergyService*>(sender());
if (service) if (service)
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << service->serviceUuid() << newState; report_info("%s %d", to_str(service->serviceUuid()).c_str(), static_cast<int>(newState));
} }
void BLEObject::characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value) void BLEObject::characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value)
{ {
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << QTime::currentTime() << "packet RECV" << value.toHex(); report_info("%s packet RECV %s", current_time().c_str(), qPrintable(value.toHex()));
if (IS_HW(device)) { if (IS_HW(device)) {
if (c.uuid() == telit[TELIT_DATA_TX] || c.uuid() == ublox[UBLOX_DATA_TX]) { if (c.uuid() == telit[TELIT_DATA_TX] || c.uuid() == ublox[UBLOX_DATA_TX]) {
hw_credit--; hw_credit--;
@ -73,7 +83,7 @@ void BLEObject::characteristcStateChanged(const QLowEnergyCharacteristic &c, con
if (hw_credit == MINIMAL_HW_CREDIT) if (hw_credit == MINIMAL_HW_CREDIT)
setHwCredit(MAXIMAL_HW_CREDIT - MINIMAL_HW_CREDIT); setHwCredit(MAXIMAL_HW_CREDIT - MINIMAL_HW_CREDIT);
} else { } else {
qDebug() << "ignore packet from" << c.uuid() << value.toHex(); report_info("ignore packet from %s %s", to_str(c.uuid()).c_str(), qPrintable(value.toHex()));
} }
} else { } else {
receivedPackets.append(value); receivedPackets.append(value);
@ -90,14 +100,14 @@ void BLEObject::characteristicWritten(const QLowEnergyCharacteristic &c, const Q
} }
} else { } else {
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << "BLEObject::characteristicWritten"; report_info("BLEObject::characteristicWritten");
} }
} }
void BLEObject::writeCompleted(const QLowEnergyDescriptor&, const QByteArray&) void BLEObject::writeCompleted(const QLowEnergyDescriptor&, const QByteArray&)
{ {
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << "BLE write completed"; report_info("BLE write completed");
desc_written++; desc_written++;
} }
@ -174,7 +184,7 @@ void BLEObject::addService(const QBluetoothUuid &newService)
{ {
const char *details; const char *details;
qDebug() << "Found service" << newService; report_info("Found service %s", to_str(newService).c_str());
// //
// Known bad service that we should ignore? // Known bad service that we should ignore?
@ -182,7 +192,7 @@ void BLEObject::addService(const QBluetoothUuid &newService)
// //
details = is_known_bad_service(newService); details = is_known_bad_service(newService);
if (details) { if (details) {
qDebug () << " .. ignoring service" << details; report_info(" .. ignoring service %s", details);
return; return;
} }
@ -204,14 +214,14 @@ void BLEObject::addService(const QBluetoothUuid &newService)
// //
details = is_known_serial_service(newService); details = is_known_serial_service(newService);
if (details) { if (details) {
qDebug () << " .. recognized service" << details; report_info(" .. recognized service %s", details);
services.clear(); services.clear();
} else { } else {
bool isStandardUuid = false; bool isStandardUuid = false;
newService.toUInt16(&isStandardUuid); newService.toUInt16(&isStandardUuid);
if (isStandardUuid) { if (isStandardUuid) {
qDebug () << " .. ignoring standard service"; report_info(" .. ignoring standard service");
return; return;
} }
} }
@ -220,7 +230,7 @@ void BLEObject::addService(const QBluetoothUuid &newService)
if (service) { if (service) {
// provide some visibility into what's happening in the log // provide some visibility into what's happening in the log
service->connect(service, &QLowEnergyService::stateChanged,[=](QLowEnergyService::ServiceState newState) { service->connect(service, &QLowEnergyService::stateChanged,[=](QLowEnergyService::ServiceState newState) {
qDebug() << " .. service state changed to" << newState; report_info(" .. service state changed to %d", static_cast<int>(newState));
}); });
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
service->connect(service, &QLowEnergyService::errorOccurred, service->connect(service, &QLowEnergyService::errorOccurred,
@ -228,10 +238,10 @@ void BLEObject::addService(const QBluetoothUuid &newService)
service->connect(service, QOverload<QLowEnergyService::ServiceError>::of(&QLowEnergyService::error), service->connect(service, QOverload<QLowEnergyService::ServiceError>::of(&QLowEnergyService::error),
#endif #endif
[=](QLowEnergyService::ServiceError newError) { [=](QLowEnergyService::ServiceError newError) {
qDebug() << "error discovering service details" << newError; report_info("error discovering service details %d", static_cast<int>(newError));
}); });
services.append(service); services.append(service);
qDebug() << "starting service characteristics discovery"; report_info("starting service characteristics discovery");
service->discoverDetails(); service->discoverDetails();
} }
} }
@ -247,7 +257,7 @@ BLEObject::BLEObject(QLowEnergyController *c, device_data_t *d)
BLEObject::~BLEObject() BLEObject::~BLEObject()
{ {
qDebug() << "Deleting BLE object"; report_info("Deleting BLE object");
qDeleteAll(services); qDeleteAll(services);
@ -302,7 +312,7 @@ dc_status_t BLEObject::write(const void *data, size_t size, size_t *actual)
if (actual) *actual = 0; if (actual) *actual = 0;
if (!receivedPackets.isEmpty()) { if (!receivedPackets.isEmpty()) {
qDebug() << ".. write HIT with still incoming packets in queue"; report_info(".. write HIT with still incoming packets in queue");
do { do {
receivedPackets.takeFirst(); receivedPackets.takeFirst();
} while (!receivedPackets.isEmpty()); } while (!receivedPackets.isEmpty());
@ -314,7 +324,7 @@ dc_status_t BLEObject::write(const void *data, size_t size, size_t *actual)
QByteArray bytes((const char *)data, (int) size); QByteArray bytes((const char *)data, (int) size);
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << QTime::currentTime() << "packet SEND" << bytes.toHex(); report_info("%s packet SEND %s", current_time().c_str(), qPrintable(bytes.toHex()));
QLowEnergyService::WriteMode mode; QLowEnergyService::WriteMode mode;
mode = (c.properties() & QLowEnergyCharacteristic::WriteNoResponse) ? mode = (c.properties() & QLowEnergyCharacteristic::WriteNoResponse) ?
@ -337,7 +347,7 @@ dc_status_t BLEObject::poll(int timeout)
return DC_STATUS_IO; return DC_STATUS_IO;
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << QTime::currentTime() << "packet WAIT"; report_info("%s packet WAIT", current_time().c_str());
WAITFOR(!receivedPackets.isEmpty(), timeout); WAITFOR(!receivedPackets.isEmpty(), timeout);
if (receivedPackets.isEmpty()) if (receivedPackets.isEmpty())
@ -376,7 +386,7 @@ dc_status_t BLEObject::read(void *data, size_t size, size_t *actual)
*actual += packet.size(); *actual += packet.size();
if (verbose > 2 || debugCounter < DEBUG_THRESHOLD) if (verbose > 2 || debugCounter < DEBUG_THRESHOLD)
qDebug() << QTime::currentTime() << "packet READ" << packet.toHex(); report_info("%s packet READ %s", current_time().c_str(), qPrintable(packet.toHex()));
return DC_STATUS_SUCCESS; return DC_STATUS_SUCCESS;
} }
@ -406,18 +416,18 @@ dc_status_t BLEObject::select_preferred_service(void)
WAITFOR(s->state() != QLowEnergyService::DiscoveringServices, BLE_TIMEOUT); WAITFOR(s->state() != QLowEnergyService::DiscoveringServices, BLE_TIMEOUT);
if (s->state() == QLowEnergyService::DiscoveringServices) if (s->state() == QLowEnergyService::DiscoveringServices)
#endif #endif
qDebug() << " .. service " << s->serviceUuid() << "still hasn't completed discovery - trouble ahead"; report_info(" .. service %s still hasn't completed discovery - trouble ahead", to_str(s->serviceUuid()).c_str());
} }
// Print out the services for debugging // Print out the services for debugging
for (const QLowEnergyService *s: services) { for (const QLowEnergyService *s: services) {
qDebug() << "Found service" << s->serviceUuid() << s->serviceName(); report_info("Found service %s %s", to_str(s->serviceUuid()).c_str(), qPrintable(s->serviceName()));
for (const QLowEnergyCharacteristic &c: s->characteristics()) { for (const QLowEnergyCharacteristic &c: s->characteristics()) {
qDebug() << " c:" << c.uuid(); report_info(" c: %s", to_str(c.uuid()).c_str());
for (const QLowEnergyDescriptor &d: c.descriptors()) for (const QLowEnergyDescriptor &d: c.descriptors())
qDebug() << " d:" << d.uuid(); report_info(" d: %s", to_str(d.uuid()).c_str());
} }
} }
@ -440,23 +450,23 @@ dc_status_t BLEObject::select_preferred_service(void)
} }
if (!hasread) { if (!hasread) {
qDebug () << " .. ignoring service without read characteristic" << uuid; report_info(" .. ignoring service without read characteristic %s", to_str(uuid).c_str());
continue; continue;
} }
if (!haswrite) { if (!haswrite) {
qDebug () << " .. ignoring service without write characteristic" << uuid; report_info(" .. ignoring service without write characteristic %s", to_str(uuid).c_str());
continue; continue;
} }
// We now know that the service has both read and write characteristics // We now know that the service has both read and write characteristics
preferred = s; preferred = s;
qDebug() << "Using service" << s->serviceUuid() << "as preferred service"; report_info("Using service %s as preferred service", to_str(s->serviceUuid()).c_str());
break; break;
} }
if (!preferred) { if (!preferred) {
qDebug() << "failed to find suitable service"; report_info("failed to find suitable service");
report_error("Failed to find suitable BLE GATT service"); report_error("Failed to find suitable BLE GATT service");
return DC_STATUS_IO; return DC_STATUS_IO;
} }
@ -508,7 +518,7 @@ dc_status_t BLEObject::setupHwTerminalIo(const QList<QLowEnergyCharacteristic> &
*/ */
if (allC.length() != 4 && allC.length() != 2) { if (allC.length() != 4 && allC.length() != 2) {
qDebug() << "This should not happen. HW/OSTC BT/BLE device without 2(UBLOX) or 4(TELIT) Characteristics"; report_info("This should not happen. HW/OSTC BT/BLE device without 2(UBLOX) or 4(TELIT) Characteristics");
return DC_STATUS_IO; return DC_STATUS_IO;
} }
@ -574,7 +584,7 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
QBluetoothAddress remoteDeviceAddress(devaddr); QBluetoothAddress remoteDeviceAddress(devaddr);
QLowEnergyController *controller = new QLowEnergyController(remoteDeviceAddress); QLowEnergyController *controller = new QLowEnergyController(remoteDeviceAddress);
#endif #endif
qDebug() << "qt_ble_open(" << devaddr << ")"; report_info("qt_ble_open(%s)", devaddr);
#if !defined(Q_OS_WIN) #if !defined(Q_OS_WIN)
if (use_random_address(user_device)) if (use_random_address(user_device))
@ -589,15 +599,15 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
switch (controller->state()) { switch (controller->state()) {
case QLowEnergyController::ConnectedState: case QLowEnergyController::ConnectedState:
qDebug() << "connected to the controller for device" << devaddr; report_info("connected to the controller for device %s", devaddr);
break; break;
case QLowEnergyController::ConnectingState: case QLowEnergyController::ConnectingState:
qDebug() << "timeout while trying to connect to the controller " << devaddr; report_info("timeout while trying to connect to the controller %s", devaddr);
report_error("Timeout while trying to connect to %s", devaddr); report_error("Timeout while trying to connect to %s", devaddr);
delete controller; delete controller;
return DC_STATUS_IO; return DC_STATUS_IO;
default: default:
qDebug() << "failed to connect to the controller " << devaddr << "with error" << controller->errorString(); report_info("failed to connect to the controller %s with error %s", devaddr, qPrintable(controller->errorString()));
report_error("Failed to connect to %s: '%s'", devaddr, qPrintable(controller->errorString())); report_error("Failed to connect to %s: '%s'", devaddr, qPrintable(controller->errorString()));
delete controller; delete controller;
return DC_STATUS_IO; return DC_STATUS_IO;
@ -614,7 +624,7 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
// the underlying issue still seems worth addressing. // the underlying issue still seems worth addressing.
// Finish discovering the services, then add all those services and discover their characteristics. // Finish discovering the services, then add all those services and discover their characteristics.
ble->connect(controller, &QLowEnergyController::discoveryFinished, [=] { ble->connect(controller, &QLowEnergyController::discoveryFinished, [=] {
qDebug() << "finished service discovery, start discovering characteristics"; report_info("finished service discovery, start discovering characteristics");
for (QBluetoothUuid s: controller->services()) for (QBluetoothUuid s: controller->services())
ble->addService(s); ble->addService(s);
}); });
@ -623,27 +633,27 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
#else #else
ble->connect(controller, QOverload<QLowEnergyController::Error>::of(&QLowEnergyController::error), [=](QLowEnergyController::Error newError) { ble->connect(controller, QOverload<QLowEnergyController::Error>::of(&QLowEnergyController::error), [=](QLowEnergyController::Error newError) {
#endif #endif
qDebug() << "controler discovery error" << controller->errorString() << newError; report_info("controler discovery error %s %d", qPrintable(controller->errorString()), static_cast<int>(newError));
}); });
controller->discoverServices(); controller->discoverServices();
WAITFOR(controller->state() != QLowEnergyController::DiscoveringState, BLE_TIMEOUT); WAITFOR(controller->state() != QLowEnergyController::DiscoveringState, BLE_TIMEOUT);
if (controller->state() == QLowEnergyController::DiscoveringState) if (controller->state() == QLowEnergyController::DiscoveringState)
qDebug() << " .. even after waiting for the full BLE timeout, controller is still in discovering state"; report_info(" .. even after waiting for the full BLE timeout, controller is still in discovering state");
qDebug() << " .. done discovering services"; report_info(" .. done discovering services");
dc_status_t error = ble->select_preferred_service(); dc_status_t error = ble->select_preferred_service();
if (error != DC_STATUS_SUCCESS) { if (error != DC_STATUS_SUCCESS) {
qDebug() << "failed to find suitable service on" << devaddr; report_info("Failed to find suitable service on '%s'", devaddr);
report_error("Failed to find suitable service on '%s'", devaddr); report_error("Failed to find suitable service on '%s'", devaddr);
delete ble; delete ble;
return error; return error;
} }
qDebug() << " .. enabling notifications"; report_info(" .. enabling notifications");
/* Enable notifications */ /* Enable notifications */
QList<QLowEnergyCharacteristic> list = ble->preferredService()->characteristics(); QList<QLowEnergyCharacteristic> list = ble->preferredService()->characteristics();
@ -658,7 +668,7 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
if (!is_read_characteristic(c)) if (!is_read_characteristic(c))
continue; continue;
qDebug() << "Using read characteristic" << c.uuid(); report_info("Using read characteristic %s", to_str(c.uuid()).c_str());
const QList<QLowEnergyDescriptor> l = c.descriptors(); const QList<QLowEnergyDescriptor> l = c.descriptors();
QLowEnergyDescriptor d = l.first(); QLowEnergyDescriptor d = l.first();
@ -670,12 +680,12 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
} }
} }
qDebug() << "now writing \"0x0100\" to the descriptor" << d.uuid().toString(); report_info("now writing \"0x0100\" to the descriptor %s", to_str(d.uuid()).c_str());
ble->preferredService()->writeDescriptor(d, QByteArray::fromHex("0100")); ble->preferredService()->writeDescriptor(d, QByteArray::fromHex("0100"));
WAITFOR(ble->descriptorWritten(), 1000); WAITFOR(ble->descriptorWritten(), 1000);
if (!ble->descriptorWritten()) { if (!ble->descriptorWritten()) {
qDebug() << "Bluetooth: Failed to enable notifications for characteristic" << c.uuid(); report_info("Bluetooth: Failed to enable notifications for characteristic %s", to_str(c.uuid()).c_str());
report_error("Bluetooth: Failed to enable notifications."); report_error("Bluetooth: Failed to enable notifications.");
delete ble; delete ble;
return DC_STATUS_TIMEOUT; return DC_STATUS_TIMEOUT;
@ -701,7 +711,7 @@ static void checkThreshold()
{ {
if (++debugCounter == DEBUG_THRESHOLD) { if (++debugCounter == DEBUG_THRESHOLD) {
QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = false")); QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = false"));
qDebug() << "turning off further BT debug output"; report_info("turning off further BT debug output");
} }
} }
@ -749,5 +759,4 @@ dc_status_t qt_ble_ioctl(void *io, unsigned int request, void *data, size_t size
} }
} }
} /* extern "C" */ } /* extern "C" */

View file

@ -6,7 +6,6 @@
#include <QBluetoothLocalDevice> #include <QBluetoothLocalDevice>
#include <QEventLoop> #include <QEventLoop>
#include <QTimer> #include <QTimer>
#include <QDebug>
#include <QThread> #include <QThread>
#include <libdivecomputer/version.h> #include <libdivecomputer/version.h>
@ -17,6 +16,7 @@
#ifdef BLE_SUPPORT #ifdef BLE_SUPPORT
# include "qt-ble.h" # include "qt-ble.h"
#endif #endif
#include "errorhelper.h"
QList<QBluetoothUuid> registeredUuids; QList<QBluetoothUuid> registeredUuids;
@ -25,6 +25,12 @@ void addBtUuid(QBluetoothUuid uuid)
registeredUuids << uuid; registeredUuids << uuid;
} }
template<typename T>
static std::string to_str(const T &v)
{
return v.toString().toStdString();
}
extern "C" { extern "C" {
typedef struct qt_serial_t { typedef struct qt_serial_t {
/* /*
@ -34,7 +40,7 @@ typedef struct qt_serial_t {
long timeout; long timeout;
} qt_serial_t; } qt_serial_t;
static dc_status_t qt_serial_open(qt_serial_t **io, dc_context_t*, const char* devaddr) static dc_status_t qt_serial_open(qt_serial_t **io, dc_context_t*, const char *devaddr)
{ {
// Allocate memory. // Allocate memory.
qt_serial_t *serial_port = (qt_serial_t *) malloc (sizeof (qt_serial_t)); qt_serial_t *serial_port = (qt_serial_t *) malloc (sizeof (qt_serial_t));
@ -62,13 +68,13 @@ static dc_status_t qt_serial_open(qt_serial_t **io, dc_context_t*, const char* d
QBluetoothAddress remoteDeviceAddress(devaddr); QBluetoothAddress remoteDeviceAddress(devaddr);
#if defined(Q_OS_ANDROID) #if defined(Q_OS_ANDROID)
QBluetoothUuid uuid = QBluetoothUuid(QUuid("{00001101-0000-1000-8000-00805f9b34fb}")); QBluetoothUuid uuid = QBluetoothUuid(QUuid("{00001101-0000-1000-8000-00805f9b34fb}"));
qDebug() << "connecting to Uuid" << uuid; report_info("connecting to Uuid %s", to_str(uuid).c_str());
serial_port->socket->setPreferredSecurityFlags(QBluetooth::Security::NoSecurity); serial_port->socket->setPreferredSecurityFlags(QBluetooth::Security::NoSecurity);
serial_port->socket->connectToService(remoteDeviceAddress, uuid, QIODevice::ReadWrite | QIODevice::Unbuffered); serial_port->socket->connectToService(remoteDeviceAddress, uuid, QIODevice::ReadWrite | QIODevice::Unbuffered);
#else #else
QBluetoothLocalDevice dev; QBluetoothLocalDevice dev;
QBluetoothUuid uuid = QBluetoothUuid(QUuid("{00001101-0000-1000-8000-00805f9b34fb}")); QBluetoothUuid uuid = QBluetoothUuid(QUuid("{00001101-0000-1000-8000-00805f9b34fb}"));
qDebug() << "Linux Bluez connecting to Uuid" << uuid; report_info("Linux Bluez connecting to Uuid %s", to_str(uuid).c_str());
serial_port->socket->connectToService(remoteDeviceAddress, uuid, QIODevice::ReadWrite | QIODevice::Unbuffered); serial_port->socket->connectToService(remoteDeviceAddress, uuid, QIODevice::ReadWrite | QIODevice::Unbuffered);
#endif #endif
timer.start(msec); timer.start(msec);
@ -77,7 +83,7 @@ static dc_status_t qt_serial_open(qt_serial_t **io, dc_context_t*, const char* d
if (serial_port->socket->state() == QBluetoothSocket::SocketState::ConnectingState || if (serial_port->socket->state() == QBluetoothSocket::SocketState::ConnectingState ||
serial_port->socket->state() == QBluetoothSocket::SocketState::ServiceLookupState) { serial_port->socket->state() == QBluetoothSocket::SocketState::ServiceLookupState) {
// It seems that the connection step took more than expected. Wait another 20 seconds. // It seems that the connection step took more than expected. Wait another 20 seconds.
qDebug() << "The connection step took more than expected. Wait another 20 seconds"; report_info("The connection step took more than expected. Wait another 20 seconds");
timer.start(4 * msec); timer.start(4 * msec);
loop.exec(); loop.exec();
} }
@ -86,7 +92,7 @@ static dc_status_t qt_serial_open(qt_serial_t **io, dc_context_t*, const char* d
// Get the latest error and try to match it with one from libdivecomputer // Get the latest error and try to match it with one from libdivecomputer
QBluetoothSocket::SocketError err = serial_port->socket->error(); QBluetoothSocket::SocketError err = serial_port->socket->error();
qDebug() << "Failed to connect to device " << devaddr << ". Device state " << serial_port->socket->state() << ". Error: " << err; report_info("Failed to connect to device %s. Device state %d. Error: %d", devaddr, static_cast<int>(serial_port->socket->state()), static_cast<int>(err));
free (serial_port); free (serial_port);
switch(err) { switch(err) {