I am trying to learn the BLE of ESP32 and intend to implement the function of HID controller. I have added related Services and Characteristics, and can use gatts_write() and gatts_notify() to write and notify the value of Characteristics.
I encountered some problems when adding Descriptors to Characteristics, here is some fake code:
Code: Select all
import ubluetooth as bt
import struct
import time
from ble_advertising import advertising_payload
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1 << 0)
_IRQ_CENTRAL_DISCONNECT = const(1 << 1)
pack = struct.pack
class BatteryService(object):
UUID = bt.UUID(0x180F)
__CLIENT_CHARACTERISTIC_CONFIGURATION_DESC = ((bt.UUID(0x2902), bt.FLAG_READ),)
__BATTERY_LEVEL_CHAR = (bt.UUID(0x2A19), bt.FLAG_READ | bt.FLAG_NOTIFY, __CLIENT_CHARACTERISTIC_CONFIGURATION_DESC)
SERVICE = (UUID, (__BATTERY_LEVEL_CHAR,),)
class BLE_HID(object):
def __init__(self, ble, name="hid"):
self._ble = ble
self._conn_handle = None
self._write = self._ble.gatts_write
self._read = self._ble.gatts_read
self._notify = self._ble.gatts_notify
self._services = (BatteryService.SERVICE)
self._ble.active(True)
self._ble.irq(handler=self._irq)
(
# (
# self._device_name_handle,
# self._appearance_handle,
# ),
(
self._battery_level_handle,
self._battery_descriptor_handle
),
) = self._ble.gatts_register_services(self._services)
self._payload = advertising_payload(name=name, services=[BatteryService.UUID], appearance=961)
self._advertise()
def _irq(self, event, data):
if event == _IRQ_CENTRAL_CONNECT:
conn_handle, _, _, = data
self._conn_handle = conn_handle
time.sleep(0.5)
# self._setup_generic_access()
self._set_battery_level()
elif event == _IRQ_CENTRAL_DISCONNECT:
conn_handle, _, _, = data
self._conn_handle = None
self._advertise()
# def _setup_generic_access(self):
# self._write(self._device_name_handle, GenericAccess.Values.DEVICE_NAME)
# self._write(self._appearance_handle, GenericAccess.Values.APPEARANCE)
def _set_battery_level(self):
# self._write(self._battery_descriptor_handle, pack("h", 0x0100))
def _advertise(self, interval_us=500000):
self._ble.gap_advertise(interval_us, adv_data=self._payload)
def main():
ble = bt.BLE()
hid = BLE_HID(ble)
if __name__ == "__main__":
main()
Code: Select all
01-01
To be sure, I don’t know what “16bit” is. Secondly, I don’t know if gatts_write() can write values to Descriptors?
This is my first question.
A part of the code is commented out in the fake code. I intend to replace the Generic Access Service for changing the Device Name (default is ESP32) but it also fails. I don’t know if the Generic Access Service is immutable or there is something wrong with my method?
My ESP32 board firmware is v1.12-169 with idf 3.x