dobluetooth.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import asyncio
  2. from bleak import BleakScanner
  3. from bleak import BleakClient
  4. import time
  5. target_name = "Long name works now"
  6. global target_address
  7. target_address = None
  8. SERVICE_UUID= "d86aecf2-d87d-489f-b664-b02de82b2fc0"
  9. CHARACTERISTIC_UUID= "d86aecf2-d87d-489f-b664-b02de82b2fc0"
  10. async def connect():
  11. devices = await BleakScanner.discover()
  12. for d in devices:
  13. print(d)
  14. if target_name == d.name:
  15. target_address = d.address
  16. print("found target {} bluetooth device with address {} ".format(target_name,target_address))
  17. return target_address
  18. break
  19. else:
  20. print("could not find device")
  21. async def getData():
  22. target_address = await connect()
  23. if target_address is not None:
  24. async with BleakClient(target_address) as client:
  25. print(f"Connected: {client.is_connected}")
  26. while 1:
  27. try:
  28. data = await client.read_gatt_char(CHARACTERISTIC_UUID)
  29. datastr = data.decode('utf-8') #convert byte to str
  30. dataarr = convertToNumbers(datastr)
  31. print("time: {} ||| numbers: {}".format(time.time(), dataarr))
  32. except Exception:
  33. print("failed to get data, restarting connection.")
  34. def convertToNumbers(stringlist):
  35. dlist = stringlist.split(",")
  36. dlist = dlist[0:-1]
  37. intlist = []
  38. for string in dlist:
  39. intlist.append(float(string))
  40. return intlist