ESPBLE.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import asyncio
  2. from bleak import BleakScanner
  3. from bleak import BleakClient
  4. target_name = "Long name works now"
  5. SERVICE_UUID= "d86aecf2-d87d-489f-b664-b02de82b2fc0"
  6. CHARACTERISTIC_UUID= "d86aecf2-d87d-489f-b664-b02de82b2fc0"
  7. async def connect():
  8. target_address = None
  9. devices = await BleakScanner.discover()
  10. for d in devices:
  11. print(d)
  12. if target_name == d.name:
  13. target_address = d.address
  14. print("found target {} bluetooth device with address {} ".format(target_name,target_address))
  15. break
  16. else:
  17. print("could not find device")
  18. return target_address
  19. async def main():
  20. target_address = await connect()
  21. if target_address is not None:
  22. async with BleakClient(target_address) as client:
  23. print(f"Connected: {client.is_connected}")
  24. while 1:
  25. #text = input()
  26. #if text == "quit":
  27. # break
  28. #await client.write_gatt_char(CHARACTERISTIC_UUID, bytes(text, 'UTF-8'), response=True)
  29. try:
  30. data = await client.read_gatt_char(CHARACTERISTIC_UUID)
  31. datastr = data.decode('utf-8') #convert byte to str
  32. print("data: {}".format(datastr))
  33. except Exception:
  34. print("failed to get data, restarting connection.")
  35. asyncio.run(main())