送信先のアドレスと Characteristic UUID を与えて、String を送る方法です。
プログラム
send_data.py
#! /usr/bin/python
#
# send_data.py
#
# Oct/02/2024
# ------------------------------------------------------------------
import asyncio
from bleak import BleakClient
DEVICE_ADDRESS = "08:3A:F2:66:04:4A"
CHARACTERISTIC_UUID = "7DEF8317-7302-4EE6-8849-46FACE74CA2A"
# ------------------------------------------------------------------
async def send_data(address, char_uuid, data):
async with BleakClient(address) as client:
if client.is_connected:
print(f"Connected to {address}")
data_bytes = data.encode('utf-8')
await client.write_gatt_char(char_uuid, data_bytes)
print(f"Data '{data}' sent to characteristic {char_uuid}")
else:
print(f"Failed to connect to {address}")
#
# ------------------------------------------------------------------
if __name__ == "__main__":
data_to_send = "SU\r"
asyncio.run(send_data(DEVICE_ADDRESS, CHARACTERISTIC_UUID, data_to_send))
data_to_send = "ST\r"
asyncio.run(send_data(DEVICE_ADDRESS, CHARACTERISTIC_UUID, data_to_send))
data_to_send = "SV\r"
asyncio.run(send_data(DEVICE_ADDRESS, CHARACTERISTIC_UUID, data_to_send))
# ------------------------------------------------------------------
実行結果
$ ./send_data.py
Connected to 08:3A:F2:66:04:4A
' sent to characteristic 7DEF8317-7302-4EE6-8849-46FACE74CA2A
Connected to 08:3A:F2:66:04:4A
' sent to characteristic 7DEF8317-7302-4EE6-8849-46FACE74CA2A
Connected to 08:3A:F2:66:04:4A
' sent to characteristic 7DEF8317-7302-4EE6-8849-46FACE74CA2A