Python 中的低功耗蓝牙
我正在尝试使用蓝牙低能与其他设备进行通信。通过沟通,我的意思是发送将在我所在的区域中侦听的设备上显示的简短消息。我正在使用Bleak python库。 这是示例代码,我在堆栈上找到了此代码,它列出了蓝牙设备。
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))
问题是有时它并非所有可访问的设备显示。我想添加向其发送简短消息的功能,但是找不到任何适当的教程或代码示例。它应该像一个信标。
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经深入探索了您的问题,我认为Repo A已被Ołgaban组织弄清楚可能会有所帮助。
https://github.com/olgaban/ogwarning
这些伙计们使用EddiestOne Beaton来广告一条消息
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