from subprocess import run
import sys
import time

def main():
    # make sure there is a default bluetooth controller
    while True:
        try:
            # listing might return okay when no device
            run(["/usr/bin/bluetoothctl", "list"], check=True)
            # show returns negatively when "No default controller available"
            run(["/usr/bin/bluetoothctl", "show"], check=True)
            print("bluetooth controller is available, terminating\n")
            break
        except:
            print("bluetooth controller not available, replugging USB ports [2..5]\n")
            # Rpi PPPS 1-1 is internal hub, port 2 is external ports [2..5], action 2 is cycle
            run(["/sbin/uhubctl", "--location=1-1", "--port=2", "--action=2"])
            time.sleep(15)
            continue
    return 0

if(__name__ == "__main__"):
    sys.exit(main())
