Ringinator/BLE-Communication/client.py
2024-06-11 13:03:22 +02:00

73 lines
2.4 KiB
Python

# import asyncio
# from bleak import BleakClient
# # Replace with your ESP32 address and characteristic UUIDs
# ESP32_ADDRESS = "80:7D:3A:B7:99:A2"
# SENSOR_CHARACTERISTIC_UUID = "19b10001-e8f2-537e-4f6c-d104768a1214"
# LED_CHARACTERISTIC_UUID = "19b10002-e8f2-537e-4f6c-d104768a1214"
# led_state = 0
# async def run(address, loop):
# global led_state
# try:
# async with BleakClient(address, loop=loop) as client:
# print(f"Connected to {address}")
# while True:
# # Read temperature
# data = await client.read_gatt_char(SENSOR_CHARACTERISTIC_UUID)
# temperature = float(data.decode('utf_8')) # Assuming temperature is the value
# print(temperature)
# # Write to LED characteristic
# await client.write_gatt_char(LED_CHARACTERISTIC_UUID, bytearray([led_state]))
# print(f"LED state set to {led_state}")
# # Toggle LED state
# led_state = 1 - led_state
# await asyncio.sleep(1) # Adjust the interval as needed
# except Exception as e:
# print(f"Error: {e}")
# loop = asyncio.get_event_loop()
# loop.run_until_complete(run(ESP32_ADDRESS, loop))
import asyncio
from bleak import BleakClient
# Replace with your ESP32 address and characteristic UUIDs
ESP32_ADDRESS = "F4:12:FA:9F:27:11"
SENSOR_CHARACTERISTIC_UUID = "19b10001-e8f2-537e-4f6c-d104768a1214"
LED_CHARACTERISTIC_UUID = "19b10002-e8f2-537e-4f6c-d104768a1214"
led_state = 0
async def run(address, loop):
global led_state
try:
async with BleakClient(address, loop=loop) as client:
print(f"Connected to {address}")
while True:
# Read temperature
data = await client.read_gatt_char(SENSOR_CHARACTERISTIC_UUID)
temperature = data.decode('utf_8') # Assuming temperature is the value
print(temperature)
# Write to LED characteristic
await client.write_gatt_char(LED_CHARACTERISTIC_UUID, bytearray([led_state]))
print(f"LED state set to {led_state}")
# Toggle LED state
led_state = 1 - led_state
await asyncio.sleep(0.01) # Adjust the interval as needed
except Exception as e:
print(f"Error: {e}")
loop = asyncio.get_event_loop()
loop.run_until_complete(run(ESP32_ADDRESS, loop))