{"id":20277418,"url":"https://github.com/ekspla/micropython_aioble_examples","last_synced_at":"2025-03-04T01:42:03.747Z","repository":{"id":203639424,"uuid":"710069030","full_name":"ekspla/micropython_aioble_examples","owner":"ekspla","description":"A few aioble (asyncio BLE) examples of micropython using esp32","archived":false,"fork":false,"pushed_at":"2024-05-22T06:14:44.000Z","size":24,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-05-23T00:22:26.304Z","etag":null,"topics":["aioble","asyncio","ble","bluetooth-low-energy","esp32","heart-rate","hioki","micropython","multimeter","python","voltmeter"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ekspla.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-26T00:41:23.000Z","updated_at":"2024-06-13T08:47:02.560Z","dependencies_parsed_at":null,"dependency_job_id":"4c27a708-a15e-48fd-aaaa-cd62b73849cb","html_url":"https://github.com/ekspla/micropython_aioble_examples","commit_stats":null,"previous_names":["ekspla/micropython_aioble_examples"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekspla%2Fmicropython_aioble_examples","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekspla%2Fmicropython_aioble_examples/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekspla%2Fmicropython_aioble_examples/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ekspla%2Fmicropython_aioble_examples/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ekspla","download_url":"https://codeload.github.com/ekspla/micropython_aioble_examples/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241768282,"owners_count":20017120,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aioble","asyncio","ble","bluetooth-low-energy","esp32","heart-rate","hioki","micropython","multimeter","python","voltmeter"],"created_at":"2024-11-14T13:18:23.817Z","updated_at":"2025-03-04T01:42:03.739Z","avatar_url":"https://github.com/ekspla.png","language":"Python","readme":"# micropython_aioble_examples\nA few aioble (asyncio bluetooth low energy) examples of MicroPython using ESP32\n\n(C) 2023-2025 [ekspla](https://github.com/ekspla/micropython_aioble_examples)\n\nThe following examples were tested with [MicroPython](https://micropython.org/) 1.21.0-1.23.0 and \n[aioble](https://github.com/micropython/micropython-lib/tree/master/micropython/bluetooth/aioble) on \n[ESP32-DevKitC-32E](https://www.espressif.com/en/products/devkits/esp32-devkitc).\n\n\n## Read measured values from a [HIOKI](https://www.hioki.com/) voltmeter via BLE\n```hioki_z3210.py```\n\nAn example to read measured values from HIOKI's voltmeter, DT4261, via \n[Z3210 BLE interface](https://www.hioki.com/global/products/specialized-solutions/connecting-instruments/id_6780).\nOther mesurement tools of HIOKI equipped with the BLE interface may also work (with/without a bit of modification).\nThough the ways (e.g. commands; [references](https://www.hioki.com/global/support/download/software/versionup/detail/id_235) \navailable from their website) to communicate with the tools are similar to those of \nUSB ([DT4900-01](https://www.hioki.com/global/support/download/software/versionup/detail/id_235)), RS232 and GPIB interfaces, \nI found this BLE interface very useful in probing hazardous high voltages/currents at a safe place because of the wireless nature.  \n\nI feel like using a home-built tiny display device equipped with an ESP32 is more convenient than using HIOKI's proprietary \nsoftware with a smartphone.\n\n```python\nMicroPython v1.21.0 on 2023-10-05; Generic ESP32 module with ESP32\nType \"help()\" for more information.\n\u003e\u003e\u003e\n\u003e\u003e\u003e import hioki_z3210\n\u003e\u003e\u003e hioki_z3210.start()\nDevice(ADDR_PUBLIC, a4:9e:69:xx:yy:zz)\nConnecting to Device(ADDR_PUBLIC, a4:9e:69:xx:yy:zz)\nConnected.\n(2023, 10, 26, 9, 37, 3, 3, 299)        +1.00000000E-04\n(2023, 10, 26, 9, 37, 3, 3, 299)        +1.00000000E-04\n(2023, 10, 26, 9, 37, 4, 3, 299)        +1.00000000E-04\n(2023, 10, 26, 9, 37, 4, 3, 299)        +1.00000000E-04\n\n ...\n \n```\n\n## Read heart rate values from a heart rate sensor via BLE\n```hr_read.py```\n\nAn example to read heart rate values (BPM) from \n[Magene's H64](https://support.magene.com/hc/en-us/categories/900000170623-H64-Heart-Rate-Sensor).  \nChange the device name ```_HR_SENSOR_NAME``` or the ```address``` to specify your device.  The code should work for most \nof the BLE heart-rate sensors because the service and the characteristics are common.\n\n```python\nMicroPython v1.21.0 on 2023-10-05; Generic ESP32 module with ESP32\nType \"help()\" for more information.\n\u003e\u003e\u003e\n\u003e\u003e\u003e import hr_read\n\u003e\u003e\u003e hr_read.start()\nConnecting to Device(ADDR_RANDOM, d8:75:ba:xx:yy:zz)\n(2000, 1, 1, 6, 27, 59, 5, 1)\t45\n(2000, 1, 1, 6, 28, 0, 5, 1)\t45\n(2000, 1, 1, 6, 28, 1, 5, 1)\t45\n(2000, 1, 1, 6, 28, 2, 5, 1)\t46\n\n ...\n\n```\n\n## Handling of connections to multiple peripherals and disconnect/reconnect\n```conn_multiple.py```\n\nBased on the codes of voltmeter and heart rate monitor, an example is shown.\n\nYou may want to change the maximum allowed number of connections in bluetooth stack.  \nESP32_GENERIC ([ESP-IDF](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/kconfig.html)) for example, \nchange ```CONFIG_BT_NIMBLE_MAX_CONNECTIONS``` and ```CONFIG_BTDM_CTRL_BLE_MAX_CONN``` in config file (default to 4 and 3, \nrespectively). I have changed these (to 5 and 4) and got successfull concurrent connections to 4 peripherals.\n\nIf you have to find peripheral devices, write and use a loop of scan/connect/service-discovery to list the target devices \nin the beginning.\n```\nConnecting to Device(ADDR_RANDOM, d8:75:ba:xx:yy:zz)             # Heart rate sensor, switched on.\nConnected. \u003cDeviceConnection object at 3ffedf70\u003e\nConnecting to Device(ADDR_PUBLIC, a4:9e:69:xx:yy:zz)             # Voltmeter DT4261, switched off.\n(2024, 5, 22, 7, 32, 27, 2, 143)        48 [bpm]\n(2024, 5, 22, 7, 32, 29, 2, 143)        48 [bpm]\n(2024, 5, 22, 7, 32, 30, 2, 143)        48 [bpm]\n(2024, 5, 22, 7, 32, 31, 2, 143)        48 [bpm]\nTimeout during connection\n(2024, 5, 22, 7, 32, 32, 2, 143)        48 [bpm]\n(2024, 5, 22, 7, 32, 34, 2, 143)        48 [bpm]\n(2024, 5, 22, 7, 32, 35, 2, 143)        48 [bpm]\nConnecting to Device(ADDR_PUBLIC, a4:9e:69:xx:yy:zz)             # Power on DT4261.\nConnected. \u003cDeviceConnection object at 3fff1240\u003e\n(2024, 5, 22, 7, 32, 37, 2, 143)        47 [bpm]\n(2024, 5, 22, 7, 32, 37, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 37, 2, 143)        47 [bpm]\n(2024, 5, 22, 7, 32, 38, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 38, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 39, 2, 143)        47 [bpm]\n(2024, 5, 22, 7, 32, 39, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 40, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 40, 2, 143)        47 [bpm]\n(2024, 5, 22, 7, 32, 40, 2, 143)        DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 32, 41, 2, 143)        DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 32, 41, 2, 143)        46 [bpm]\n(2024, 5, 22, 7, 32, 42, 2, 143)        DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 32, 42, 2, 143)        DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 32, 43, 2, 143)        46 [bpm]\nError!                                                           # Power off DT4261.\n(2024, 5, 22, 7, 32, 44, 2, 143)        45 [bpm]\n(2024, 5, 22, 7, 32, 45, 2, 143)        45 [bpm]\n(2024, 5, 22, 7, 32, 46, 2, 143)        46 [bpm]\nConnecting to Device(ADDR_PUBLIC, a4:9e:69:xx:yy:zz)\n(2024, 5, 22, 7, 32, 48, 2, 143)        46 [bpm]\n(2024, 5, 22, 7, 32, 49, 2, 143)        45 [bpm]\n(2024, 5, 22, 7, 32, 51, 2, 143)        46 [bpm]\n(2024, 5, 22, 7, 32, 52, 2, 143)        45 [bpm]\nTimeout during connection\n(2024, 5, 22, 7, 32, 53, 2, 143)        45 [bpm]\n(2024, 5, 22, 7, 32, 55, 2, 143)        45 [bpm]\n(2024, 5, 22, 7, 32, 55, 2, 143)        45 [bpm]\n(2024, 5, 22, 7, 32, 57, 2, 143)        45 [bpm]\nConnecting to Device(ADDR_PUBLIC, a4:9e:69:xx:yy:zz)             # Power on DT4261 again.\nConnected. \u003cDeviceConnection object at 3ffd3450\u003e\n(2024, 5, 22, 7, 32, 58, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 58, 2, 143)        46 [bpm]\n(2024, 5, 22, 7, 32, 59, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 32, 59, 2, 143)        DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 33, 0, 2, 143)         46 [bpm]\n(2024, 5, 22, 7, 33, 0, 2, 143)         DT4261;+0.00000000E+00\n(2024, 5, 22, 7, 33, 1, 2, 143)         DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 33, 1, 2, 143)         46 [bpm]\n(2024, 5, 22, 7, 33, 1, 2, 143)         DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 33, 2, 2, 143)         DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 33, 2, 2, 143)         45 [bpm]\n(2024, 5, 22, 7, 33, 3, 2, 143)         DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 33, 3, 2, 143)         45 [bpm]\n(2024, 5, 22, 7, 33, 3, 2, 143)         DT4261;-1.00000000E-04\n(2024, 5, 22, 7, 33, 4, 2, 143)         DT4261;-1.00000000E-04\nmain_hr closed                                                   # Stop the loop.\n(2024, 5, 22, 7, 33, 4, 2, 143)         DT4261;-1.00000000E-04\nmain_4261 closed\nEnd.\n\n```\n\n## How can we handle successive notified packets as a client using aioble?\n(A link to discussion of this topic can be found \n[here](https://github.com/orgs/micropython/discussions/15544).)\n\nIn the current version of ```aioble/client.py```, a data of a notified \npacket can be overwritten by those of the successive notified packets in \nthe queue to which the data are appended.  This is because the size of the \nqueue by default is 1:  ```self._notify_queue = deque((), 1)```\n\nSo *a ```while True:``` loop* with *a ```charateristic.notified()```* \nshown in the official examples, as well as ```hr_read.py``` shown above, are not \nnecessarily useful; **notified packets should be well separated in time from each other**.\n\nThough I do not know exactly what is the future plan of the core developers to \nsolve the issue, there is a comment in ```aioble/client.py``` as follows:\n```\n# Append the data. By default this is a deque with max-length==1, so it\n# replaces. But if capture is enabled then it will append.\n```\n\nAs a workaround for Nordic UART client used in [mpy_xoss_sync.py](https://github.com/ekspla/xoss_sync), \nI changed the size of the queue and retrieved the accumulated notified data from the queue as followings.\n``` python\nbuffer = bytearray()\nasync with connection:\n    service = await connection.service(_SERVICE_UUID) # A Nordic UART Service.\n    tx_characteristic = await service.characteristic(_TX_CHARACTERISTIC_UUID)\n    rx_characteristic = await service.characteristic(_RX_CHARACTERISTIC_UUID)\n    tx_characteristic._notify_queue = deque((), 7) # Change the size of the queue.\n    await self.tx_characteristic.subscribe(notify=True)\n\n    while True:\n         await request_transport(rx_characteristic) # Send command to request transport.\n         data = await tx_characteristic.notified()\n         await asyncio.sleep(1) # Wait until the queue is filled.\n         buffer.extend(data)\n         while len(queue := tx_characteristic._notify_queue) \u003e= 1:\n             buffer.extend(queue.popleft())\n         tx_characteristic._notify_event.clear() # Make sure to clear the flag.\n\n         # Do something with the buffer.\n```\n\nThe workaround is useful in this case because the server (peripheral) always waits for the response of the \nchunk of data from the client (micropython/aioble) before going to the next, and this waiting time can be used \nby the client to process (e.g. concatinate) the data in the queue.\n\n\nA pair of test codes, ```nus_modem_client.py``` and ```nus_modem_server.py```, were prepared as the complete \nset of working example.  In this case, a primitive YMODEM file transfer protocol was implemented on \n[Nordic UART service's](https://docs.nordicsemi.com/bundle/ncs-latest/page/nrf/libraries/bluetooth_services/services/nus.html) \nTX/RX channels.  Athough there are limitations as described below, it works well as expected and has been \nalready applied to [one of my projects](https://github.com/ekspla/xoss_sync).\n\nThe throughput measured was 27.7 kbps using 7.5 ms connection interval and tick rate of 1 ms (CONFIG_FREERTOS_HZ=1000) \nwith ESP32-S3-WROOM-1-N16R8 and micro-SD card, while the theoretical limit assuming 3 connection events/128-byte data block \nis 45.5 kbps.\n\nThe limitations are due mainly to the implementation of YMODEM in part as follows:\n- The script expects a transport with MTU of 23, 128-byte data per block, and CRC16/ARC (not CRC16/XMODEM).\nLarger MTU by DLE (Data Length Extension) and 1024-byte data in YMODEM (STX), that make throughput higher, are not \nsupported (not implemented yet).\n\n## ESP32 chip as a USB bluetooth dongle (HCI H4) for use with unix-port (Linux) of micropython and aioble\n\nA cheap USB bluetooth dongle was easily built by using an ESP32, a USB-UART chip ([CH340E](https://www.wch.cn/search?t=all\u0026q=CH340E)) \nand a 600-mA LDO ([RT9080](https://www.richtek.com/Products/Linear%20Regulator/Single%20Output%20Linear%20Regulator/RT9080?sc_lang=en)). \nAs shown in the figures below, I tried to reduce the lengths of the cables as short as possible to obtain the \nhighest reliable speed.  USB-UART/LDO built on frontside and ESP32 mounted on backside were sticked together to form the \nhome-made USB dongle. \n![PHOTO_FRONTSIDE_CH340_LDO](https://github.com/ekspla/micropython_aioble_examples/blob/main/figs/Frontside_CH340_LDO.jpg \"Frontside\")\n![PHOTO_BACKSIDE_ESP32](https://github.com/ekspla/micropython_aioble_examples/blob/main/figs/Backside_ESP32.jpg \"Backside\")\n\nThe firmware on the ESP32, which was written through the pin sockets shown in the photo above, was built on `controller_hci_uart_esp32`, \n[an example of Espressif's ESP-IDF](https://github.com/espressif/esp-idf/tree/master/examples/bluetooth/hci), with the following parameters.\n\nUART baudrate = 1 Mbps; \nhardware flow control; \nFreeRTOS tick rate = 1 ms; \nCPU frequency = 240 MHz; \nGPIO pins 5, 18, 23, 19 are used as TxD, RxD, CTS, RTS, respectively.\n\nI had to modify the codes as followings to set the parameters as above.\n\nModify `ESP-IDF/components/bt/controller/esp32/Kconfig.in`:\n``` Diff\n    config BTDM_CTRL_HCI_UART_BAUDRATE\n        int \"UART Baudrate for HCI\"\n        depends on BTDM_CTRL_HCI_MODE_UART_H4\n-       range 115200 921600\n-       default 921600\n+       range 115200 3000000\n+       default 1000000\n        help\n```\nModify `sdkconfig.defaults`:\n```\nCONFIG_BT_BLUEDROID_ENABLED=n\nCONFIG_BT_CONTROLLER_ONLY=y\nCONFIG_BTDM_CTRL_HCI_MODE_UART_H4=y\nCONFIG_BTDM_CTRL_HCI_UART_NO=1\nCONFIG_BTDM_CTRL_HCI_UART_BAUDRATE=1000000\nCONFIG_BTDM_CTRL_MODEM_SLEEP=n\n\n# Other config\nCONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y\nCONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240\nCONFIG_FREERTOS_HZ=1000\n```\nRun `idf.py menuconfig`, then `idf.py build`.\n\nTo use the other baudrate, you have to modify it also in `MPY/ports/unix/mpbthciport.c`, which defaults to 1 Mbps. \nBecause I could not obtain reliable connections at 1.5, 2 and 3 M bps, the baudrate was set to 1 Mbps in my case.\n\n[The MPY on Linux machine using NimBLE stack was built](https://github.com/orgs/micropython/discussions/10234) as \nfollows: \n``` Shell\nmake -C ports/unix MICROPY_PY_BLUETOOTH=1 MICROPY_BLUETOOTH_NIMBLE=1\n```\n\nBecause the built-in USB-UART kernel module did not work reliably at a very high speed, I had to compile the module \nusing the latest source code (V1.8 on 2024.08) of the manufacturer (WCH) obtained from \n[their website](http://www.wch.cn/download/CH341SER_LINUX_ZIP.html) \nor from [their github repository](https://github.com/WCHSoftGroup/ch341ser_linux). \nBefore start using it, set an appropriate permission of the USB-UART device you are using (e.g. `chomod 666` or `adduser` \nto the `dialout` group).\n\nYou have to specify the USB-UART device if it is not `/dev/ttyUSB0` as written in `MPY/ports/unix/mpbthciport.c`.\n\nIn my case `MICROPYBTUART=/dev/ttyCH341USB0`:\n``` Python\nMICROPYBTUART=/dev/ttyCH341USB0 micropython\nMicroPython v1.23.0 on 2024-11-18; linux [GCC 11.5.0] version\nUse Ctrl-D to exit, Ctrl-E for paste mode\n\u003e\u003e\u003e from bluetooth import BLE\n\u003e\u003e\u003e BLE().active(1)\nTrue\n\u003e\u003e\u003e import aioble\n\u003e\u003e\u003e \n```\n\nThis dongle/unix-port MPY combination was successfully used with my aioble test code, \n[nus_modem_client.py](https://github.com/ekspla/micropython_aioble_examples/blob/main/nus_modem_client.py), \nin this repository.\n\n- Additional notes: \nYou can also use this USB dongle from the other softwares such as [BlueZ](https://github.com/bluez/bluez), \n[BTstack](https://github.com/bluekitchen/btstack) and \n[Google Bumble](https://github.com/google/bumble) because the APIs of HCI H4 are common.\n","funding_links":[],"categories":["Libraries"],"sub_categories":["Communications"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fekspla%2Fmicropython_aioble_examples","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fekspla%2Fmicropython_aioble_examples","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fekspla%2Fmicropython_aioble_examples/lists"}