device.cpp Example File
lowenergyscanner/device.cpp
#include "device.h"
#include <qbluetoothaddress.h>
#include <qbluetoothdevicediscoveryagent.h>
#include <qbluetoothlocaldevice.h>
#include <qbluetoothdeviceinfo.h>
#include <qbluetoothservicediscoveryagent.h>
#include <QDebug>
#include <QList>
#include <QMetaEnum>
#include <QTimer>
Device::Device():
connected(false), controller(0), m_deviceScanState(false), randomAddress(false)
{
discoveryAgent = new QBluetoothDeviceDiscoveryAgent();
discoveryAgent->setLowEnergyDiscoveryTimeout(5000);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,
this, &Device::addDevice);
connect(discoveryAgent, QOverload<QBluetoothDeviceDiscoveryAgent::Error>::of(&QBluetoothDeviceDiscoveryAgent::error),
this, &Device::deviceScanError);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &Device::deviceScanFinished);
setUpdate("Search");
}
Device::~Device()
{
delete discoveryAgent;
delete controller;
qDeleteAll(devices);
qDeleteAll(m_services);
qDeleteAll(m_characteristics);
devices.clear();
m_services.clear();
m_characteristics.clear();
}
void Device::startDeviceDiscovery()
{
qDeleteAll(devices);
devices.clear();
emit devicesUpdated();
setUpdate("Scanning for devices ...");
discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
if (discoveryAgent->isActive()) {
m_deviceScanState = true;
Q_EMIT stateChanged();
}
}
void Device::addDevice(const QBluetoothDeviceInfo &info)
{
if (info.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
DeviceInfo *d = new DeviceInfo(info);
devices.append(d);
setUpdate("Last device added: " + d->getName());
}
}
void Device::deviceScanFinished()
{
emit devicesUpdated();
m_deviceScanState = false;
emit stateChanged();
if (devices.isEmpty())
setUpdate("No Low Energy devices found...");
else
setUpdate("Done! Scan Again!");
}
QVariant Device::getDevices()
{
return QVariant::fromValue(devices);
}
QVariant Device::getServices()
{
return QVariant::fromValue(m_services);
}
QVariant Device::getCharacteristics()
{
return QVariant::fromValue(m_characteristics);
}
QString Device::getUpdate()
{
return m_message;
}
void Device::scanServices(const QString &address)
{
for (int i = 0; i < devices.size(); i++) {
if (((DeviceInfo*)devices.at(i))->getAddress() == address )
currentDevice.setDevice(((DeviceInfo*)devices.at(i))->getDevice());
}
if (!currentDevice.getDevice().isValid()) {
qWarning() << "Not a valid device";
return;
}
qDeleteAll(m_characteristics);
m_characteristics.clear();
emit characteristicsUpdated();
qDeleteAll(m_services);
m_services.clear();
emit servicesUpdated();
setUpdate("Back\n(Connecting to device...)");
if (controller && m_previousAddress != currentDevice.getAddress()) {
controller->disconnectFromDevice();
delete controller;
controller = 0;
}
if (!controller) {
controller = new QLowEnergyController(currentDevice.getDevice());
connect(controller, &QLowEnergyController::connected,
this, &Device::deviceConnected);
connect(controller, QOverload<QLowEnergyController::Error>::of(&QLowEnergyController::error),
this, &Device::errorReceived);
connect(controller, &QLowEnergyController::disconnected,
this, &Device::deviceDisconnected);
connect(controller, &QLowEnergyController::serviceDiscovered,
this, &Device::addLowEnergyService);
connect(controller, &QLowEnergyController::discoveryFinished,
this, &Device::serviceScanDone);
}
if (isRandomAddress())
controller->setRemoteAddressType(QLowEnergyController::RandomAddress);
else
controller->setRemoteAddressType(QLowEnergyController::PublicAddress);
controller->connectToDevice();
m_previousAddress = currentDevice.getAddress();
}
void Device::addLowEnergyService(const QBluetoothUuid &serviceUuid)
{
QLowEnergyService *service = controller->createServiceObject(serviceUuid);
if (!service) {
qWarning() << "Cannot create service for uuid";
return;
}
ServiceInfo *serv = new ServiceInfo(service);
m_services.append(serv);
emit servicesUpdated();
}
void Device::serviceScanDone()
{
setUpdate("Back\n(Service scan done!)");
if (m_services.isEmpty())
emit servicesUpdated();
}
void Device::connectToService(const QString &uuid)
{
QLowEnergyService *service = 0;
for (int i = 0; i < m_services.size(); i++) {
ServiceInfo *serviceInfo = (ServiceInfo*)m_services.at(i);
if (serviceInfo->getUuid() == uuid) {
service = serviceInfo->service();
break;
}
}
if (!service)
return;
qDeleteAll(m_characteristics);
m_characteristics.clear();
emit characteristicsUpdated();
if (service->state() == QLowEnergyService::DiscoveryRequired) {
connect(service, &QLowEnergyService::stateChanged,
this, &Device::serviceDetailsDiscovered);
service->discoverDetails();
setUpdate("Back\n(Discovering details...)");
return;
}
const QList<QLowEnergyCharacteristic> chars = service->characteristics();
foreach (const QLowEnergyCharacteristic &ch, chars) {
CharacteristicInfo *cInfo = new CharacteristicInfo(ch);
m_characteristics.append(cInfo);
}
QTimer::singleShot(0, this, &Device::characteristicsUpdated);
}
void Device::deviceConnected()
{
setUpdate("Back\n(Discovering services...)");
connected = true;
controller->discoverServices();
}
void Device::errorReceived(QLowEnergyController::Error )
{
qWarning() << "Error: " << controller->errorString();
setUpdate(QString("Back\n(%1)").arg(controller->errorString()));
}
void Device::setUpdate(QString message)
{
m_message = message;
emit updateChanged();
}
void Device::disconnectFromDevice()
{
if (controller->state() != QLowEnergyController::UnconnectedState)
controller->disconnectFromDevice();
else
deviceDisconnected();
}
void Device::deviceDisconnected()
{
qWarning() << "Disconnect from device";
emit disconnected();
}
void Device::serviceDetailsDiscovered(QLowEnergyService::ServiceState newState)
{
if (newState != QLowEnergyService::ServiceDiscovered) {
if (newState != QLowEnergyService::DiscoveringServices) {
QMetaObject::invokeMethod(this, "characteristicsUpdated",
Qt::QueuedConnection);
}
return;
}
QLowEnergyService *service = qobject_cast<QLowEnergyService *>(sender());
if (!service)
return;
const QList<QLowEnergyCharacteristic> chars = service->characteristics();
foreach (const QLowEnergyCharacteristic &ch, chars) {
CharacteristicInfo *cInfo = new CharacteristicInfo(ch);
m_characteristics.append(cInfo);
}
emit characteristicsUpdated();
}
void Device::deviceScanError(QBluetoothDeviceDiscoveryAgent::Error error)
{
if (error == QBluetoothDeviceDiscoveryAgent::PoweredOffError)
setUpdate("The Bluetooth adaptor is powered off, power it on before doing discovery.");
else if (error == QBluetoothDeviceDiscoveryAgent::InputOutputError)
setUpdate("Writing or reading from the device resulted in an error.");
else {
static QMetaEnum qme = discoveryAgent->metaObject()->enumerator(
discoveryAgent->metaObject()->indexOfEnumerator("Error"));
setUpdate("Error: " + QLatin1String(qme.valueToKey(error)));
}
m_deviceScanState = false;
emit devicesUpdated();
emit stateChanged();
}
bool Device::state()
{
return m_deviceScanState;
}
bool Device::hasControllerError() const
{
if (controller && controller->error() != QLowEnergyController::NoError)
return true;
return false;
}
bool Device::isRandomAddress() const
{
return randomAddress;
}
void Device::setRandomAddress(bool newValue)
{
randomAddress = newValue;
emit randomAddressChanged();
}