Skip to content

Instantly share code, notes, and snippets.

@jxmorris12
Created November 2, 2020 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jxmorris12/c58022bbcd8982f5779745e784dcc239 to your computer and use it in GitHub Desktop.
Save jxmorris12/c58022bbcd8982f5779745e784dcc239 to your computer and use it in GitHub Desktop.
automatically connect Mac to Bluetooth headphones
#!/usr/bin/env python
# jm8wx 11/2/20
import subprocess
import re
airpods_name = "Jack’s AirPods Pro"
def _color(s):
return "\033[94m" + s + "\033[0m"
def _run_cmd(cmd_str):
result = subprocess.check_output(cmd_str, shell=True)
return result.decode("utf-8").strip()
def main():
# blueutil documentation: https://github.com/toy/blueutil
# (1) search for named device (must be paired already)
paired_devices = _run_cmd("blueutil --paired")
airpods_re = f"^.+(?:{re.escape(airpods_name)}).+$"
airpods = re.search(airpods_re, paired_devices)
if not airpods:
print(f"Could not find headphones with name {airpods_name}. Found devices: {paired_devices}")
exit()
else:
# (2) get device ID
hex_re = r"(?:[A-Za-z0-9]{2}-?){6}" # get device ID, like 3c-4d-be-06-c4-09
airpods = airpods.group(0)
headphone_id = re.search(hex_re, airpods)
headphone_id = headphone_id.group(0)
# (3) connect to device
print(f"Connecting to {_color(airpods_name)}, device ID {_color(headphone_id)}")
pairing_output = _run_cmd(f"blueutil --connect {headphone_id}")
if __name__ == "__main__": main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment