81 lines
2.4 KiB
C++
81 lines
2.4 KiB
C++
|
#include "BluetoothLeUartServer.h"
|
||
|
|
||
|
BluetoothLeUartServer::BluetoothLeUartServer(String deviceName, const char uartServiceUUID[36], const char rxUUID[36], const char txUUID[36])
|
||
|
{
|
||
|
this->uartServiceUUID = uartServiceUUID;
|
||
|
this->rxUUID = rxUUID;
|
||
|
this->txUUID = txUUID;
|
||
|
|
||
|
this->callbacks = nullptr;
|
||
|
|
||
|
// Create the BLE Device
|
||
|
BLEDevice::init(deviceName.c_str()); // Give it a name
|
||
|
|
||
|
// Create the BLE Server
|
||
|
bleServer = BLEDevice::createServer();
|
||
|
bleServer->setCallbacks(this);
|
||
|
|
||
|
// Create the BLE Service
|
||
|
bleService = bleServer->createService(this->uartServiceUUID);
|
||
|
|
||
|
// Create a BLE Characteristic
|
||
|
txCharacteristic = bleService->createCharacteristic(
|
||
|
this->txUUID,
|
||
|
BLECharacteristic::PROPERTY_NOTIFY);
|
||
|
|
||
|
txCharacteristic->addDescriptor(new BLE2902());
|
||
|
|
||
|
rxCharacteristic = bleService->createCharacteristic(
|
||
|
this->rxUUID,
|
||
|
BLECharacteristic::PROPERTY_READ |
|
||
|
BLECharacteristic::PROPERTY_WRITE);
|
||
|
|
||
|
rxCharacteristic->setCallbacks(this);
|
||
|
|
||
|
// Start the service
|
||
|
bleService->start();
|
||
|
|
||
|
// Start advertising
|
||
|
bleServer->getAdvertising()->addServiceUUID(bleService->getUUID());
|
||
|
bleServer->getAdvertising()->setScanResponse(true);
|
||
|
bleServer->getAdvertising()->setMinPreferred(0x06); // functions that help with iPhone connections issue
|
||
|
bleServer->getAdvertising()->setMinPreferred(0x12);
|
||
|
bleServer->getAdvertising()->start();
|
||
|
}
|
||
|
|
||
|
void BluetoothLeUartServer::setCallbacks(BluetoothLeUartServerCallbacks *callbacks)
|
||
|
{
|
||
|
this->callbacks = callbacks;
|
||
|
}
|
||
|
|
||
|
void BluetoothLeUartServer::sendData(String data)
|
||
|
{
|
||
|
txCharacteristic->setValue(data.c_str());
|
||
|
txCharacteristic->notify();
|
||
|
}
|
||
|
|
||
|
void BluetoothLeUartServer::onConnect(BLEServer *pServer)
|
||
|
{
|
||
|
this->deviceConnected = true;
|
||
|
if (this->callbacks != nullptr) {
|
||
|
this->callbacks->onDeviceConnectedChanged(this->deviceConnected);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void BluetoothLeUartServer::onDisconnect(BLEServer *pServer)
|
||
|
{
|
||
|
this->deviceConnected = false;
|
||
|
if (this->callbacks != nullptr)
|
||
|
this->callbacks->onDeviceConnectedChanged(this->deviceConnected);
|
||
|
}
|
||
|
|
||
|
void BluetoothLeUartServer::onWrite(BLECharacteristic *rxCharacteristic)
|
||
|
{
|
||
|
if (this->callbacks != nullptr)
|
||
|
this->callbacks->onDataReceived(rxCharacteristic->getValue().c_str());
|
||
|
}
|
||
|
|
||
|
bool BluetoothLeUartServer::getDeviceConnected()
|
||
|
{
|
||
|
return this->deviceConnected;
|
||
|
}
|