From c8fec97695cc2f71b59f3d8979b4203aefc6e6db Mon Sep 17 00:00:00 2001 From: Dirk Hohndel Date: Thu, 27 Sep 2018 06:21:04 -0700 Subject: Bluetooth: add helper to separate BT name and address And restructure the existing "isBtAddress()" function in the process. Also add more tests. Signed-off-by: Dirk Hohndel --- core/btdiscovery.cpp | 29 ++++++++++++++++++++++++++++- core/btdiscovery.h | 2 ++ 2 files changed, 30 insertions(+), 1 deletion(-) (limited to 'core') diff --git a/core/btdiscovery.cpp b/core/btdiscovery.cpp index deef322e4..258f16e2c 100644 --- a/core/btdiscovery.cpp +++ b/core/btdiscovery.cpp @@ -305,6 +305,10 @@ bool BTDiscovery::checkException(const char* method, const QAndroidJniObject *ob void BTDiscovery::discoverAddress(QString address) { + // let's make sure there is no device name mixed in with the address + QString btAddress; + btAddress = extractBluetoothAddress(address); + #if defined(Q_OS_MACOS) // macOS appears to need a fresh scan if we want to switch devices static QString lastAddress; @@ -321,11 +325,34 @@ void BTDiscovery::discoverAddress(QString address) } bool isBluetoothAddress(const QString &address) +{ + return extractBluetoothAddress(address) != QString(); +} +QString extractBluetoothAddress(const QString &address) { QRegularExpression re("(LE:)*([0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}|{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}})", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatch m = re.match(address); - return m.hasMatch(); + return m.captured(0); +} + +QString extractBluetoothNameAddress(const QString &address, QString &name) +{ + // sometimes our device text is of the form "name (address)", sometimes it's just "address" + // let's simply return the address + name = QString(); + QString extractedAddress = extractBluetoothAddress(address); + if (extractedAddress == address.trimmed()) + return address; + + QRegularExpression re("^([^()]+)\\(([^)]*\\))$"); + QRegularExpressionMatch m = re.match(address); + if (m.hasMatch()) { + name = m.captured(1).trimmed(); + return extractedAddress; + } + qDebug() << "can't parse address" << address; + return QString(); } void saveBtDeviceInfo(const QString &devaddr, QBluetoothDeviceInfo deviceInfo) diff --git a/core/btdiscovery.h b/core/btdiscovery.h index 17790e30c..679e0cae6 100644 --- a/core/btdiscovery.h +++ b/core/btdiscovery.h @@ -18,6 +18,8 @@ void saveBtDeviceInfo(const QString &devaddr, QBluetoothDeviceInfo deviceInfo); bool isBluetoothAddress(const QString &address); +QString extractBluetoothAddress(const QString &address); +QString extractBluetoothNameAddress(const QString &address, QString &name); QBluetoothDeviceInfo getBtDeviceInfo(const QString &devaddr); class BTDiscovery : public QObject { -- cgit v1.2.3-70-g09d2