Я кодирую Bluetooth на ESP32, используя Arduino IDE. Возникли небольшие проблемы с const_cast const char *. Чтение значения парного устройства имеет перевод строки \ n, который я хочу удалить. Поэтому я приведу его к редактируемому символу *, а затем преобразовал его обратно в постоянный символ *, но почему-то это не то же самое значение.
#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;
}
}
}
Итак, я связываю свое устройство BLE, ввожу Rick, и код заменяет '\ n' на NULL, но значение не совпадает с переменной const char *, установленной в Rick. Это -13 вместо 0. Почему?
Большое спасибо.