2025年5月29日木曜日

BLE5 on raspicow receiver using aioble(わかりやすい)

 https://qiita.com/_53a/items/39d6bfd38c538d6a3c94 ble5でうごいた

このコードはaiobleをつかっているので直感的、普通につかうならこっちか。。。

import asyncio

import aioble

import bluetooth

# mimicking nRF41822 UART

SERVICE_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')

service = aioble.Service(SERVICE_UUID)

send_ch = aioble.Characteristic( #このchに送ると通信元にreadされた!

    service = service, # 下のuuidはSERVICE_UUIDではない!注意!

    uuid = bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'),

    read = True,

    notify = True,

)

recv_ch = aioble.Characteristic( # 通信元が、このchに送るとwrittenになる!

    service=service, # 下のuuidはSERVICE_UUIDではない!注意!

    uuid=bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'),

    write=True,

    write_no_response=True,

    capture=True

)


aioble.register_services(service)


async def advertise_task():

    while True:

        async with await aioble.advertise(

            interval_us=500_000,

            name="bt-test", # サービス名

            services=[SERVICE_UUID]

        ) as connection: # type: ignore

            print("connected: ", connection.device)

            await connection.disconnected(timeout_ms=None) #時間切れなし?


async def receive_task(): # 通信元からのメッセージを読んで送り返す

    while True:

        await recv_ch.written() # type: ignore

        data = recv_ch.read()

        print(f"received: {data}")

  # ここで一仕事できるはず

        send_ch.write(b'you said: ' + data, True)


async def main():

    tasks = [

        asyncio.create_task(receive_task()),

        asyncio.create_task(advertise_task())

    ]

    await asyncio.gather(*tasks)


asyncio.run(main())

0 件のコメント:

コメントを投稿