0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python3: GATT で String データを送信

Last updated at Posted at 2024-10-02

送信先のアドレスと 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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?