I'm coding Bluetooth on an ESP32 using Arduino IDE. Having a little trouble with const_cast const char *. Reading the paired device value has a '\n' line feed that I want to remove. So I cast it an editable char * then convert it back to a const char *, but somehow it isn't the same value.
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer *pServer = NULL;
BLEService *pService;
BLECharacteristic *pTxCharacteristic;
BLECharacteristic *pRxCharacteristic;
bool BLE_Paired = false;
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect( BLEServer* pServer ) {
BLE_Paired = true;
};
void onDisconnect( BLEServer* pServer ) {
BLE_Paired = false;
}
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite( BLECharacteristic *pCharacteristic ) {
std::string rxValue = pCharacteristic->getValue();
}
};
char* _name = "your nm";
const char* C_name = "Rick";
bool name_OK = false;
void setup() {
Serial.begin( 115200 );
BLEDevice::init( "bluetooth" );
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
pService = pServer->createService(SERVICE_UUID);
pTxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_TX,
BLECharacteristic::PROPERTY_NOTIFY );
pTxCharacteristic->addDescriptor( new BLE2902() );
pRxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_RX,
BLECharacteristic::PROPERTY_WRITE );
pRxCharacteristic->setCallbacks( new MyCallbacks() );
pService->start();
pServer->getAdvertising()->start();
}
void loop() {
while( BLE_Paired ) {
while( !name_OK ) {
// Receive the response from the Paired Device
pTxCharacteristic->setValue( "Name? " );
pTxCharacteristic->notify();
delay( 100 ); // bluetooth stack can get congested
// read it as const char *, but cast it as just a char *
_name = const_cast<char *>(pRxCharacteristic->getValue().c_str());
// the Paired Device adds a '\n' when the name is entered; remove it
for( int j=0; _name[j] != '\0'; j++ ) {
if( _name[j] == '\n' ) {
_name[j] = NULL; // NULL or '\0'
}
}
// cast name back to a const char *
const char* C_nm = const_cast<const char *>(_name);
Serial.print( "const _names: " );
Serial.print( C_name );
Serial.print( " =? " );
Serial.print( C_nm );
Serial.print( " : " );
Serial.println( strcmp( C_name, C_nm )); // result is -13, not 0
if( strcmp( C_name, C_nm ) == 0 )
name_OK = true;
}
}
}
So, I pair my BLE device, enter Rick, and the code replaces the '\n' with NULL, but the value isn't the same a const char * variable set to Rick. It's -13 instead of 0. Why? Many thanks.
I also removed '/r' with the '/n' and that shortened the string to match. Thanks to datafiddler.