dobluetooth.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import asyncio
  2. from bleak import BleakScanner, BleakClient
  3. import time
  4. dataarr = [0.0] * 6
  5. lastval = [0.0] * 6
  6. target_name = "Long name works now"
  7. target_address = None
  8. gclient = None
  9. SERVICE_UUID = "d86aecf2-d87d-489f-b664-b02de82b2fc0"
  10. CHARACTERISTIC_UUID = "d86aecf2-d87d-489f-b664-b02de82b2fc0"
  11. def getDataArr() -> list[float]:
  12. global dataarr, lastval
  13. if isinstance(dataarr, list) and all(isinstance(i, float) for i in dataarr):
  14. lastval = dataarr
  15. return dataarr
  16. else:
  17. return lastval
  18. async def connect():
  19. global target_address
  20. print("Scanning for BLE devices...")
  21. while True:
  22. try:
  23. devices = await BleakScanner.discover()
  24. for d in devices:
  25. print("Found:", d.name or "Unnamed", d.address)
  26. if d.name == target_name:
  27. target_address = d.address
  28. print(f"✅ Found target device '{target_name}' at {target_address}")
  29. return target_address
  30. print("❌ Target device not found. Retrying in 3s...")
  31. await asyncio.sleep(3)
  32. except Exception as e:
  33. print("⚠ BLE scan error:", e)
  34. await asyncio.sleep(3)
  35. async def getData():
  36. global target_address, gclient
  37. while True:
  38. try:
  39. if target_address is None:
  40. await connect()
  41. print("🔌 Attempting to connect to BLE device...")
  42. async with BleakClient(target_address) as client:
  43. gclient = client
  44. if not client.is_connected:
  45. print("❌ Failed to connect. Retrying...")
  46. await asyncio.sleep(2)
  47. continue
  48. print(f"✅ Connected to {target_address}")
  49. while client.is_connected:
  50. try:
  51. data = await client.read_gatt_char(CHARACTERISTIC_UUID)
  52. datastr = data.decode('utf-8')
  53. global dataarr
  54. dataarr = convertToNumbers(datastr)
  55. print("📡 Data:", dataarr)
  56. await asyncio.sleep(0.05) # Optional: slow it down a bit
  57. except Exception as e:
  58. print("⚠ Read error:", e)
  59. break # Break loop and reconnect
  60. except Exception as e:
  61. print("⚠ Connection error:", e)
  62. print("🔁 Reconnecting in 3s...")
  63. await asyncio.sleep(3)
  64. def convertToNumbers(stringlist) -> list[float]:
  65. try:
  66. dlist = stringlist.strip().split(",")
  67. dlist = [float(val) for val in dlist if val != '']
  68. if len(dlist) >= 6:
  69. return dlist[0:6] # Already scaled: [gyroX, gyroY, gyroZ, accX, accY, accZ]
  70. else:
  71. return lastval
  72. except Exception as e:
  73. print("⚠️ Conversion error:", e)
  74. return lastval