-1

I'm trying to communicate with other devices using Bluetooth low energy. By communicate i mean sending short messages that will be displayed on that devices that are listening in the area I am in. I'm using Bleak Python library. Here is the example code, i found this code on stack and it lists Bluetooth devices.

import asyncio
import logging

from bleak import discover
from bleak import BleakClient

devices_dict = {}
devices_list = []
receive_data = []


# To discover BLE devices nearby
async def scan():
    dev = await discover()
    for i in range(0, len(dev)):
        # Print the devices discovered
        print("[" + str(i) + "]" + dev[i].address, dev[i].name, dev[i].metadata["uuids"])
        # Put devices information into list
        devices_dict[dev[i].address] = []
        devices_dict[dev[i].address].append(dev[i].name)
        devices_dict[dev[i].address].append(dev[i].metadata["uuids"])

        devices_list.append(dev[i].address)


def notification_handler(sender, data):
    print(', '.join('{:02x}'.format(x) for x in data))


async def run(address, debug=False):
    log = logging.getLogger(__name__)
    if debug:
        import sys

        log.setLevel(logging.DEBUG)
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(logging.DEBUG)
        log.addHandler(h)

    async with BleakClient(address) as client:
        x = await client.is_connected()
        log.info("Connected: {0}".format(x))

        for service in client.services:
            log.info("[Service] {0}: {1}".format(service.uuid, service.description))
            for char in service.characteristics:
                if "read" in char.properties:
                    try:
                        value = bytes(await client.read_gatt_char(char.uuid))
                    except Exception as e:
                        value = str(e).encode()
                else:
                    value = None
                log.info(
                    "\t[Characteristic] {0}: (Handle: {1}) ({2}) | Name: {3}, Value: {4} ".format(
                        char.uuid,
                        char.handle,
                        ",".join(char.properties),
                        char.description,
                        value,
                    )
                )
                for descriptor in char.descriptors:
                    value = await client.read_gatt_descriptor(descriptor.handle)
                    log.info(
                        "\t\t[Descriptor] {0}: (Handle: {1}) | Value: {2} ".format(
                            descriptor.uuid, descriptor.handle, bytes(value)
                        )
                    )

                CHARACTERISTIC_UUID = "put your characteristic uuid"

                await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
                await asyncio.sleep(5.0)
                await client.stop_notify(CHARACTERISTIC_UUID)


async def foo(address):
    async with BleakClient(address) as client:
        client.start_notify(address, callback)


if __name__ == "__main__":
    print("Scanning for peripherals...")

    loop = asyncio.get_event_loop()
    loop.run_until_complete(scan())

    # let user chose the device
    index = input('please select device from 0 to ' + str(len(devices_list)) + ":")
    index = int(index)
    address = devices_list[index]
    print("Address is " + address)

    # Run notify event
    loop = asyncio.get_event_loop()


    def callback(sender: int, data: bytearray):
        print(f"{sender}: {data}")


    loop.run_until_complete(foo(address))

The problem is that sometimes it displays not all of the accessible devices. I would like to add feature that sends a short message to it, but I can't find any proper tutorial or code example. It should act like a Beacon.If it is not possible in Python, can you suggest any other language that has such features and will solve this problem?

Szymon Budziak
  • 81
  • 1
  • 11
  • Are you saying this does work sometimes and sometimes not? Do certain devices appear sometimes and not appear sometimes? If you are having some success, I'm not sure tutorial will help. You will have to pay more attention to status and error codes, and that would be in the docs (and discovered through experimentation). – RufusVS Apr 02 '22 at 18:02
  • BLE defines multiple roles that devices can play. 1) The Broadcaster (beacon) is a transmitter only application. 2) The Observer (scanner) is for receiver only applications. 3) Devices acting in the Peripheral role can receive connections. 4) Devices acting in the Central role can connect to Peripheral devices. Bleak only supports the Central role. Is that what you are looking to do? It would also be good if you could clarify what hardware you are running on. – ukBaz Apr 02 '22 at 20:50

1 Answers1

0

I have deeply explorated your problem, and i think the repo a have found, crated by Ołgaban organization might be helpful.

https://github.com/Olgaban/OGWARning

These fellas use EddieStone Beacon to advertise a message

Kacper
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 04 '22 at 19:19