bluetoothctl.py 915 B

1234567891011121314151617181920212223242526
  1. import subprocess
  2. import time
  3. # [!] To get this to work bluetoothctl needs to connect to the device before using BLE_GATT.connect
  4. def ble_ctl(addr:str):
  5. """
  6. use bluetoothctl interactively: scan on, ... wait ..., scan off, connect CF:CD:27:79:55:6B, exit
  7. subprocess has a relevant bug in line-buffering, see issue 21471
  8. """
  9. ctl = subprocess.Popen(['bluetoothctl'], stdin = subprocess.PIPE)
  10. def writeHelper(proc, str, delay = 1):
  11. proc.stdin.write(str.encode('utf-8'))
  12. proc.stdin.flush()
  13. time.sleep(delay)
  14. # send bluetoothctl commands interactively
  15. writeHelper(ctl, "scan on\n", 4)
  16. writeHelper(ctl, "scan off\n")
  17. writeHelper(ctl, "connect " + addr + "\n", 3)
  18. writeHelper(ctl, "exit\n")
  19. # wait for child subprocess to terminate
  20. while True:
  21. if None != ctl.poll():
  22. break
  23. time.sleep(.1)
  24. ble_ctl('CF:CD:27:79:55:6B')