h2zero / esp-nimble-cpp

C++ library for the esp32 NimBLE stack based on and mostly compatible with @nkolban cpp_utils BLE library.
https://h2zero.github.io/esp-nimble-cpp/
Apache License 2.0
182 stars 62 forks source link

feat(NimBLEClient): allow connection id / established flag to be set via public API. #156

Closed finger563 closed 5 months ago

finger563 commented 7 months ago

This PR replaces #152

Main use case is to allow an easy mechanism for GATT Servers to read the name of connected clients by passing their connection info to the Client class.

Example (from espp::BleGattServer):

  std::string get_connected_device_name(NimBLEConnInfo &conn_info) {
    if (!server_) {
      logger_.error("Server not created");
      return {};
    }
    if (!client_) {
      logger_.error("Client not created");
      return {};
    }

    // since this connection is handled by the server, we won't manually
    // connect, and instead inform the client that we are already connected
    // using this conn handle
    client_->clearConnection(); // make sure any previous connection state is cleared
    client_->setConnection(conn_info);

    // could alternatively use:
    // client_->clearConnection();
    // client_->setConnection(conn_info.getConnHandle(), conn_info.getAddress());

    // refresh the services
    client_->getServices(true);
    // now get Generic Access Service
    auto gas = client_->getService(NimBLEUUID("1800"));
    if (!gas) {
      logger_.error("Failed to get Generic Access Service");
      return {};
    }
    // now get the Device Name characteristic
    auto name_char = gas->getCharacteristic(NimBLEUUID("2A00"));
    if (!name_char) {
      logger_.error("Failed to get Device Name characteristic");
      return {};
    }
    // make sure we can read it
    if (!name_char->canRead()) {
      logger_.error("Failed to read Device Name characteristic");
      return {};
    }
    // and read it
    return name_char->readValue();
  }
finger563 commented 5 months ago

Looks good, thanks! Have you tested this with the changes?

Yup, I've tested my changes locally in espp:

CleanShot 2024-06-04 at 10 41 19

With the output from espp/components/hid_service/example: CleanShot 2024-06-04 at 10 44 18

Showing that the code to get the remote device name using this code is good :)

CleanShot 2024-06-04 at 10 45 04