dobluetooth.py 2.8 KB

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