import subprocess

def run(cmd):
    ret = subprocess.run(["powershell.exe", cmd], stdout=subprocess.PIPE)
    s = ret.stdout
    return s.decode("utf-8")


def get_busid():
    info = run(r"usbipd list")
    begin = info.find("STM32 STLink") 
    busid = info[begin - 18: begin - 15]
    return busid


def attach_stlink():
    busid = get_busid()
    cmd = "usbipd bind -b " + busid
    run(cmd)
    cmd = "usbipd attach --wsl --busid " + busid
    run(cmd)


def deattach_stlink():
    busid = get_busid()
    cmd = "usbipd detach --busid " + busid
    run(cmd)

def get_id(name):
    info = run(r"usbipd list")
    begin = info.find(name)
    busid = info[begin - 18: begin - 15]
    return busid

def attach_dev(name):
    busid = get_id(name)
    cmd = "usbipd bind -b " + busid
    run(cmd)
    cmd = "usbipd attach -a --wsl --busid " + busid
    run(cmd)


def deattach_dev(name):
    busid = get_id(name)
    cmd = "usbipd detach --busid " + busid
    run(cmd)    

def get_list():
    info = run(r"usbipd list")
    print(info)

if __name__ == "__main__":
    # deattach_stlink()
    attach_stlink()
    #
    # attach_dev("Silicon Labs") 
    # deattach_dev("Silicon Labs") 
    # attach_dev("ATLink-USART")
    # attach_dev("Prolific")

    # deattach_dev("ATLink-USART")
    # get_list()

