我需要在 ctypes 回调函数内执行一系列读/写任务,但仍在负责提供此类读/写任务的异步任务内:
async def main(ble_address):
async with BleakClient(ble_address) as client:
def my_io_callback(...)
# await client.read_gatt_char(UUID) ???
# await client.write_gatt_char(UUID, ...) ???
my_c_function(to_c_function(my_io_callback))
asyncio.run(main(ble_address))
我无法在回调中移动整个异步块,因为它将被调用多次,并且我需要在整个交互过程中连接设备。
处理这种情况的正确方法是什么?到目前为止我看到的答案还没有完全涵盖这个特殊情况。
就像 Paul 在评论中所说的那样:从同步函数中,您可以创建一个任务 = 只需在一个通道中记下它,在该通道中,c 范围之外的代码可以等待它 -
或者您可以创建一个任务并使用
.add_done_callback
来获取要在任务解决时调用的同步函数。
...
all_tasks = set()
async def result_checker():
# continous loop fetching the results of the async
# tasks created inside the c-types callback
while True:
for next_task in asyncio.as_completed(all_tasks):
result = await next_task
...
async def main(ble_address):
result_checker_task = asyncio.create_task(result_checker())
async with BleakClient(ble_address) as client:
def my_io_callback(...)
t1 = asyncio.create_task(client.read_gatt_char(UUID))
# if you need the result of t1 inside this function:
def inner(t1_task):
result = t1_task.result()
...
t1.add_done_callback(inner)
# await client.write_gatt_char(UUID, ...) ???
my_c_function(to_c_function(my_io_callback))
...
# do things
# at end:
result_checker_task.cancel()
asyncio.run(main(ble_address))