T-vK / ESP32-BLE-Keyboard

Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)
2.4k stars 399 forks source link

setBatteryLevel() and USE_NIMBLE #210

Open alexz006 opened 1 year ago

alexz006 commented 1 year ago

If you set the battery level to setBatteryLevel() after bigin(), and if NIMBLE is not used, then everything works as it should and the battery level is updated in Windows 11.

If you use NIMBLE, the charge level is not updated in Windows 11.

02-02-2023 165759

/*
  Tests setBatteryLevel() if

  #define USE_NIMBLE
  and
  // #define USE_NIMBLE

  in BleKeyboard.h
*/

#include <BleKeyboard.h>

BleKeyboard bleKeyboard;

uint8_t BatteryLevel = 100;
unsigned long previousMillisBattery = 0; 

void setup() {
  Serial.begin(115200);

  bleKeyboard.setBatteryLevel(BatteryLevel);
  Serial.println("Battery Level before begin(): " + String(BatteryLevel));

  bleKeyboard.begin();

  while (!bleKeyboard.isConnected()) {
    Serial.print(".");
    delay(250);
  } Serial.println();

  delay(5000);

  BatteryLevel--;
  bleKeyboard.setBatteryLevel(BatteryLevel);
  Serial.println("Battery Level after begin(): " + String(BatteryLevel));
}

void loop() {
  while (!bleKeyboard.isConnected()) {
    Serial.print(".");
    delay(250);
  }

  // TEST setBatteryLevel()
  unsigned long currentMillis = millis();
  if(BatteryLevel>=4 && currentMillis - previousMillisBattery >= 3000) { // gradual discharge of the battery
    previousMillisBattery = currentMillis;
    BatteryLevel--;
    bleKeyboard.setBatteryLevel(BatteryLevel); // works only #if !defined(USE_NIMBLE)
    //bleKeyboard.begin();
    Serial.println("BatteryLevel in loop(): " + String(BatteryLevel));
  }

}
ekoslav commented 1 year ago

+1

alexz006 commented 1 year ago

https://github.com/h2zero/NimBLE-Arduino/pull/422

battosai30 commented 1 year ago

Same problem here :)

jojo-06 commented 6 months ago

adding m_batteryLevelCharacteristic->notify(); to the setBatteryLevel function of NimBLE-Arduino worked for me: (in file NimBLEHIDDevice.cpp)

void NimBLEHIDDevice::setBatteryLevel(uint8_t level) {
    m_batteryLevelCharacteristic->setValue(&level, 1);  
    m_batteryLevelCharacteristic->notify(); // new  
}

hope this helps

ignis32 commented 4 months ago

@jojo-06

Thanks a lot, that was useful and helped me with indication