Jakeler / ble-serial

"RFCOMM for BLE" a UART over Bluetooth low energy (4+) bridge for Linux, Mac and Windows
https://blog.ja-ke.tech/tags/#bluetooth
MIT License
251 stars 37 forks source link

Standalone example somewhere? #63

Closed ThomasAtBBTF closed 1 year ago

ThomasAtBBTF commented 2 years ago

I would like to use your library without the com0com component. Just directly from a python application on windows.

Do you have any sample code which you could share?

I am working with an nRF52840 board with CircuitPython installed and would like to communicate over the Nordic UART characteristic to send and receive data. Looking at my device with an Bluetooth tool I see the characteristic UUID' which you just added.

Thanks Thomas

Jakeler commented 2 years ago

Yes, this is what I came up with:

import asyncio, logging
from ble_serial.bluetooth.ble_interface import BLE_interface

def receive_callback(value: bytes):
    print("Received:", value)

async def hello_sender(ble: BLE_interface):
    while True:
        await asyncio.sleep(3.0)
        print("Sending...")
        ble.queue_send(b"Hello world\n")

async def main():
    # None uses default/autodetection, insert values if needed
    ADAPTER = "hci0"
    SERVICE_UUID = None
    WRITE_UUID = None
    READ_UUID = None
    DEVICE = "20:91:48:4C:4C:54"

    ble = BLE_interface(ADAPTER, SERVICE_UUID)
    ble.set_receiver(receive_callback)

    try:
        await ble.connect(DEVICE, "public", 10.0)
        await ble.setup_chars(WRITE_UUID, READ_UUID, "rw")

        await asyncio.gather(ble.send_loop(), hello_sender(ble))
    finally:
        await ble.disconnect()

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

Does that help?

ThomasAtBBTF commented 2 years ago

Thank you for answering so quickly. I will give it a try tomorrow morning. But from what I see from the example, it looks understandable. The only thing that is kind of "obscure" to me is identifying the "partner" to connect with. Currently, I think the MAC-Address or Device-Address is problematic as it seems to me that the devices are changing this address "all the time". There seems to be something like the device name which the tools on Android I have can "figure out" somehow. I will let you know and will be happy to publish my results here.

ThomasAtBBTF commented 1 year ago

After a while I got your example working today. The problems, I had were more related to the device / service / characteristic identification than to the actual transfer of data. A part of my problem was/ is the advertisement of the services / characteristics as my BLE device is actually mainly a keyboard with a Nordic UART as a "side" feature. I am realizing that I have to modify my advertisement strategy to make the connection more seamless. But anyway, thank you again for providing the sample code.