#include "bluetoothserverclass.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qlist.h>
#include <QtCore/qloggingcategory.h>
#include <QtCore/qscopedpointer.h>
#include <QtCore/qtimer.h>
#include <qlowenergyservice.h>
#include <QDebug>
#include "classes/Application.h"
#include "models/DevicesListModelEx.h"
BluetoothServer::BluetoothServer(QObject *parent) : QObject(parent)
{
}
void BluetoothServer::startActivity()
{
if(isStarted)
return;
isStarted = true;
//! [Advertising Data]
advertisingData.setDiscoverability(QLowEnergyAdvertisingData::DiscoverabilityGeneral);
advertisingData.setIncludePowerLevel(true);
advertisingData.setLocalName("BTLE Server");
scanResponseData.setServices(QList<QBluetoothUuid>() << serviceUuid);
#ifndef ANDROID
advertisingData.setServices(QList<QBluetoothUuid>() << serviceUuid);
#endif
//! [Advertising Data]
//! [Service Data]
charModemIn.setUuid(modemInUuid);
charModemIn.setValue("");
charModemIn.setProperties(QLowEnergyCharacteristic::Write | QLowEnergyCharacteristic::WriteNoResponse);
const QLowEnergyDescriptorData clientConfigModemIn(QBluetoothUuid::ClientCharacteristicConfiguration, QByteArray(2, 0));
charModemIn.addDescriptor(clientConfigModemIn);
charModemOut.setUuid(modemOutUuid);
charModemOut.setValue(QByteArray(2, 0));
charModemOut.setProperties(QLowEnergyCharacteristic::Notify);
const QLowEnergyDescriptorData clientConfigModemOut(QBluetoothUuid::ClientCharacteristicConfiguration, QByteArray(2, 0));
charModemOut.addDescriptor(clientConfigModemOut);
charRx.setUuid(rxUuid);
charRx.setValue(QByteArray(2, 0));
charRx.setProperties(QLowEnergyCharacteristic::Write | QLowEnergyCharacteristic::WriteNoResponse);
const QLowEnergyDescriptorData clientConfigRx(QBluetoothUuid::ClientCharacteristicConfiguration, QByteArray(2, 0));
charRx.addDescriptor(clientConfigRx);
charTx.setUuid(txUuid);
charTx.setValue(QByteArray(2, 0));
charTx.setProperties(QLowEnergyCharacteristic::Notify);
const QLowEnergyDescriptorData clientConfigTx(QBluetoothUuid::ClientCharacteristicConfiguration, QByteArray(2, 0));
charTx.addDescriptor(clientConfigTx);
serviceData.setType(QLowEnergyServiceData::ServiceTypePrimary);
serviceData.setUuid(serviceUuid);
serviceData.addCharacteristic(charModemIn);
serviceData.addCharacteristic(charModemOut);
serviceData.addCharacteristic(charTx);
serviceData.addCharacteristic(charRx);
//! [Service Data]
//! [Start Advertising]
leController = QSharedPointer<QLowEnergyController>(QLowEnergyController::createPeripheral());
service = QSharedPointer<QLowEnergyService>(leController->addService(serviceData));
leController->startAdvertising(QLowEnergyAdvertisingParameters(), advertisingData, scanResponseData);
//! [Start Advertising]
QObject::connect(leController.data(), &QLowEnergyController::connected, this, [this]()
{
isInConnecting = true;
});
QObject::connect(leController.data(), &QLowEnergyController::disconnected, this, [this]()
{
isInConnecting = false;
qDebug() << "Is disconnected";
_application->setSelectedDeviceAddress(QString());
_application->isBTServerConnected = false;
emit _application->isBTServerConnectedChanged();
isConnected = false;
emit isConnectedChanged();
});
QObject::connect(service.data(), &QLowEnergyService::stateChanged, this, &BluetoothServer::onStateChanged);
QObject::connect(service.data(), &QLowEnergyService::characteristicChanged, this, &BluetoothServer::onCharacteristicChanged);
QObject::connect(service.data(), &QLowEnergyService::characteristicRead, this, &BluetoothServer::onCharacteristicRead);
QObject::connect(service.data(), &QLowEnergyService::characteristicWritten, this, &BluetoothServer::onCharacteristicWritten);
QObject::connect(service.data(), QOverload<QLowEnergyService::ServiceError>::of(&QLowEnergyService::error), this, &BluetoothServer::onError);
auto reconnect = [ = ]()
{
qDebug() << "Reconnect";
service.reset(leController->addService(serviceData));
QObject::connect(service.data(), &QLowEnergyService::stateChanged, this, &BluetoothServer::onStateChanged);
QObject::connect(service.data(), &QLowEnergyService::characteristicChanged, this, &BluetoothServer::onCharacteristicChanged);
QObject::connect(service.data(), &QLowEnergyService::characteristicRead, this, &BluetoothServer::onCharacteristicRead);
QObject::connect(service.data(), &QLowEnergyService::characteristicWritten, this, &BluetoothServer::onCharacteristicWritten);
QObject::connect(service.data(), QOverload<QLowEnergyService::ServiceError>::of(&QLowEnergyService::error), this, &BluetoothServer::onError);
if (!service.isNull())
leController->startAdvertising(QLowEnergyAdvertisingParameters(), advertisingData, scanResponseData);
};
QObject::connect(leController.data(), &QLowEnergyController::disconnected, reconnect);
}
void BluetoothServer::write(const QString &text)
{
qDebug() << "BluetoothServer::write " << text;
if(text.isEmpty() == false)
{
auto array = text.toLocal8Bit();
//Se inizia per 0x allora converte il comando
if(text.startsWith("0x") && text.length() >= 4)
{
bool ok;
int hex = text.mid(2, 2).toInt(&ok, 16);
if(ok == false)
return;
array.remove(0, 4);
array.insert(0, char(hex));
}
else
array.insert(0, '\x19');
if(array.back() != char(0x0A))
{
array.append('\x0D');
array.append('\x0A');
}
QLowEnergyCharacteristic characteristic = service->characteristic(txUuid);
service->writeCharacteristic(characteristic, text.toLocal8Bit());
}
}
void BluetoothServer::onStateChanged(QLowEnergyService::ServiceState s)
{
qDebug() << "serviceStateChanged, state: " << s;
}
void BluetoothServer::onCharacteristicChanged(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
qDebug() << c.uuid().toString();
qDebug() << c.name();
if(isInConnecting && c.uuid() == modemInUuid && value.startsWith(1))
{
_application->devicesListModel->clear();
qDebug() << "Is connected";
_application->isBTServerConnected = true;
emit _application->isBTServerConnectedChanged();
isConnected = true;
emit isConnectedChanged();
}
else
{
isInConnecting = false;
qDebug() << "Characteristic Changed: " << value;
emit dataReceived(value);
}
}
void BluetoothServer::onCharacteristicRead(const QLowEnergyCharacteristic &info, const QByteArray &value)
{
Q_UNUSED(info)
qDebug() << "Characteristic Read: " << value;
}
void BluetoothServer::onCharacteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
Q_UNUSED(c)
qDebug() << "Characteristic Written: " << value;
}
void BluetoothServer::onError(QLowEnergyService::ServiceError e)
{
Q_UNUSED(e)
emit error("Service error:");
}
#ifndef BLUETOOTHSERVERCLASS_H
#define BLUETOOTHSERVERCLASS_H
#include <QObject>
#include <QtBluetooth/qlowenergyadvertisingdata.h>
#include <QtBluetooth/qlowenergyadvertisingparameters.h>
#include <QtBluetooth/qlowenergycharacteristic.h>
#include <QtBluetooth/qlowenergycharacteristicdata.h>
#include <QtBluetooth/qlowenergydescriptordata.h>
#include <QtBluetooth/qlowenergycontroller.h>
#include <QtBluetooth/qlowenergyservice.h>
#include <QtBluetooth/qlowenergyservicedata.h>
class BluetoothServer : public QObject
{
Q_OBJECT
Q_PROPERTY(bool isConnected MEMBER isConnected NOTIFY isConnectedChanged)
public:
explicit BluetoothServer(QObject *parent = nullptr);
Q_INVOKABLE void write(const QString &text);
void startActivity();
signals:
void dataReceived(const QByteArray &buffer);
void error(const QString &error);
void isConnectedChanged();
void connected();
void disconnected();
private:
bool isStarted = false;
QLowEnergyAdvertisingData advertisingData;
QLowEnergyServiceData serviceData;
QLowEnergyAdvertisingData scanResponseData;
QBluetoothUuid serviceUuid = QBluetoothUuid(QStringLiteral("569a1101-b87f-490c-92cb-11ba5ea5167c"));
QBluetoothUuid modemInUuid = QBluetoothUuid(QStringLiteral("569a2003-b87f-490c-92cb-11ba5ea5167c"));
QBluetoothUuid modemOutUuid = QBluetoothUuid(QStringLiteral("569a2002-b87f-490c-92cb-11ba5ea5167c"));
QBluetoothUuid txUuid = QBluetoothUuid(QStringLiteral("569a2000-b87f-490c-92cb-11ba5ea5167c"));
QBluetoothUuid rxUuid = QBluetoothUuid(QStringLiteral("569a2001-b87f-490c-92cb-11ba5ea5167c"));
QLowEnergyCharacteristicData charModemIn;
QLowEnergyCharacteristicData charModemOut;
QLowEnergyCharacteristicData charRx;
QLowEnergyCharacteristicData charTx;
QSharedPointer<QLowEnergyController> leController;
QSharedPointer<QLowEnergyService> service;
bool isConnected = false;
bool isInConnecting = false;
public slots:
void onStateChanged(QLowEnergyService::ServiceState s);
void onCharacteristicChanged(const QLowEnergyCharacteristic &c, const QByteArray &value);
void onCharacteristicRead(const QLowEnergyCharacteristic &info, const QByteArray &value);
void onCharacteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value);
void onError(QLowEnergyService::ServiceError e);
};
#endif // BLUETOOTHSERVERCLASS_H