import usb.core
import usb.util
import time

ID_VENDOR = 0x4242
ID_PRODUCT = 0x0001

ENDPOINT_IN = 0x81

def read_guitar_note(device):
    try:
        data = device.read(ENDPOINT_IN, 8, 1000)

        # Convert raw bytes to string, stop at first null byte
        note_str = bytes(data).split(b'\x00')[0].decode('ascii', errors='ignore')
        return note_str
    
    except usb.core.USBError:
        return None

if __name__ == "__main__":
    dev = usb.core.find(idVendor=ID_VENDOR, idProduct=ID_PRODUCT)
    assert dev is not None

    dev.set_configuration()
    usb.util.claim_interface(dev, 0)
    print("Ecoute en cours...")

    try:
        if dev.is_kernel_driver_active(0):
            dev.detach_kernel_driver(0)
    except (NotImplementedError, usb.core.USBError):
        pass

    while True:
        if dev is None:
            break
        
        note = read_guitar_note(dev)
        if note:
            print(f"Note: {note}")