sharandac / My-TTGO-Watch

A GUI named hedge for smartwatch like devices based on ESP32. Currently support for T-Watch2020 (V1,V2,V3), T-Watch2021, M5Paper, M5Core2 and native Linux support for testing.
GNU General Public License v2.0
523 stars 247 forks source link

I am a beginner in C++,I have implemented the Bluetooth client function, but I often crash when connecting to the Bluetooth server and need assistance with code review #398

Closed Hans-Wu-cn closed 4 months ago

Hans-Wu-cn commented 1 year ago

I am a beginner in C++,I have implemented the Bluetooth client function, but I often crash when connecting to the Bluetooth server and need assistance with code review. Client Part Code:

uint32_t last_click_time = 0;
static NimBLEUUID SERVICE_UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static NimBLEUUID CHAR_UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");
//connect bluetooth 
bool connectToDevice(uint16_t index)
{
    if (found_devices.size() <= index)
    {
        return server != nullptr;
    }
    NimBLEAdvertisedDevice *&device = found_devices[index];
    if (device->isAdvertisingService(SERVICE_UUID))
    {
        log_i("Connecting device: %s -", device->haveName() ? device->getName().c_str() : "---");
        return server != nullptr;
    }
    pClient = NimBLEDevice::createClient();
    log_i("Connecting device: %s -", device->haveName() ? device->getName().c_str() : "---");
    bool conect = pClient->connect(device);
    log_i("1");
    if (!conect)
    {
        return false;
    }
    log_i("1");
    server = pClient->getService(SERVICE_UUID);
    log_i("1");
    if (server == nullptr)
    {
        log_i("Failed to find our service UUID: %s", SERVICE_UUID.toString().c_str());
        if (pClient != nullptr)
        {
            log_i("1");
            pClient->disconnect();
        }
        return false;
    }
    pRemoteCharacteristic = server->getCharacteristic(CHAR_UUID);
    if (pRemoteCharacteristic == nullptr)
    {
        log_i("Connected Failed to find our characteristic UUID :%s", CHAR_UUID.toString().c_str());
        if (pClient != nullptr)
        {
            pClient->disconnect();
            pClient = nullptr;
        }
        return false;
    }
    // Registration feature notification callback
    pRemoteCharacteristic->subscribe(true, notifyCallback, false);

    return server != nullptr;

}

// This is a double click event for a label, double click to connect to Bluetooth
static void smop_label_click_event_cb(lv_obj_t *obj, lv_event_t event)
{
    switch (event)
    {
    case (LV_EVENT_CLICKED):
    {
        // Simulate Double Click Event
        // Get the current time
        uint32_t current_time = lv_tick_get();

        // Calculate the time interval between last click
        uint32_t time_diff = current_time - last_click_time;
        // Update Last Click Time
        last_click_time = current_time;
        if (time_diff < 500)
        {
            const char *smop_label_value = lv_label_get_text(smop_label);
            modified_str = String(smop_label_value);
            int oindex = modified_str.indexOf('o');
            log_i("selected_row:%d", selected_row);
            if (oindex > -1)
            {
                bool is_connect = connectToDevice(selected_row - 1);
                if (is_connect)
                {
                    modified_str[oindex] = 'x';
                    log_i("oindex:%d", oindex);
                    lv_label_set_text(smop_label, modified_str.c_str());
                }
                return;
            }
        }
        break;
    }
    }
}

This is the server-side code:

#include <BLEDevice.h>
#include <BLEScan.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// Define the UUID of BLE features and services
static BLEUUID SERVICE_UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static BLEUUID CHARACTERISTIC_UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");
BLEService *pService;
BLEAdvertising *pAdvertising;
bool is_sleep=false;
Ticker timer;

BLECharacteristic *pCharacteristic; 
std::vector<BLEAdvertisedDevice*> foundDevices;
BLEScan *pBLEScan;
// Timer interrupt processing function
void timerInterruptHandler()
{
    is_sleep=true;
    Serial.println("Time");
    pAdvertising->start();
    is_sleep=false;
}

void setupTimer(){
  uint32_t interval = 150111; // 1秒

  // Set timer interrupt callback function
  timer.attach_ms(interval, timerInterruptHandler);
}

// Initialize Bluetooth scanning
void setupBLEScan(){
    pBLEScan = BLEDevice::getScan();
    pBLEScan->setAdvertisedDeviceCallbacks(new SmopBLEScanCallbacks());
    // Set scanning time and scanning interval
    pBLEScan->setActiveScan(true);
    pBLEScan->setInterval(100);
    pBLEScan->setWindow(99);
}

// Initialize BLE services and features
void setupBLEServer() {
  // BLEDevice::init("T-Wristband-Server");
  BLEServer *pServer = BLEDevice::createServer();
  pService = pServer->createService(SERVICE_UUID);
  pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE |
                                         BLECharacteristic::PROPERTY_NOTIFY
                                       );

  pCharacteristic->setCallbacks(new SmopServerCallback());
  pCharacteristic->setValue("Hello World");
  pService->addCharacteristic(pCharacteristic);
  pService->start();
  pAdvertising = pServer->getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  // Start broadcasting
  pAdvertising->setScanResponse(false);
  pAdvertising->setMinPreferred(0x06);
  pAdvertising->start();
  setupTimer();
  Serial.println("Waiting for a client connection to notify...");
}

// Initialize Bluetooth module
void setupSmopBLE() {
  // Setting the Blue Shoot Scan Callback Function
  BLEDevice::init("T-Wristband");
  //Initialize Bluetooth scanning module
  setupBLEScan();
  //Initialize Bluetooth server
  setupBLEServer();
}

log:

[I][bleclt.cpp:215] connectToDevice(): Connected Failed to find our characteristic UUID :beb5483e-36e1-4688-b7f5-ea07361b26a8
Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.
Core 0 register dump:
PC      : 0x401bbec3  PS      : 0x00060430  A0      : 0x801c1e94  A1      : 0x3ffdacc0  
A2      : 0x00000000  A3      : 0x3ffca320  A4      : 0x00000000  A5      : 0x3ffd4f00
A6      : 0x8015d139  A7      : 0x00000000  A8      : 0x3ffca320  A9      : 0xfffffff9
A10     : 0x00000001  A11     : 0x00000000  A12     : 0x00000000  A13     : 0x00000000  
A14     : 0x00000000  A15     : 0x00000000  SAR     : 0x00000010  EXCCAUSE: 0x0000001c
EXCVADDR: 0x8015d149  LBEG    : 0x4000c46c  LEND    : 0x4000c477  LCOUNT  : 0x00000000  

ELF file SHA256: 0000000000000000

Backtrace: 0x401bbec3:0x3ffdacc0 0x401c1e91:0x3ffdacf0 0x401c1ec5:0x3ffdad10 0x401c2ca5:0x3ffdad30 0x401c36fd:0x3ffdad60 0x401c1213:0x3ffdad80 0x401c1275:0x3ffdade0 0x401c5e8a:0x3ffdae40 0x401c60e9:0x3ffdae60 0x401c46e1:0x3ffdae80 0x4008155a:0x3ffdaea0 0x401baadb:0x3ffdaec0 0x400940ae:0x3ffdaee0
  #0  0x401bbec3:0x3ffdacc0 in NimBLERemoteService::characteristicDiscCB(unsigned short, ble_gatt_error const*, ble_gatt_chr const*, void*) at .pio/libdeps/twv3/NimBLE-Arduino/src/NimBLERemoteService.cpp:88
  #1  0x401c1e91:0x3ffdacf0 in ble_gattc_disc_chr_uuid_cb at .pio/libdeps/twv3/NimBLE-Arduino/src/nimble/nimble/host/src/ble_gattc.c:4783
  #2  0x401c1ec5:0x3ffdad10 in ble_gattc_disc_chr_uuid_err at .pio/libdeps/twv3/NimBLE-Arduino/src/nimble/nimble/host/src/ble_gattc.c:4783
  #3  0x401c2ca5:0x3ffdad30 in ble_gattc_fail_procs at .pio/libdeps/twv3/NimBLE-Arduino/src/nimble/nimble/host/src/ble_gattc.c:4783

The device type is 2020 v3