#!/usr/bin/env python3
import usb.core as core
import usb.util as util
from usb.core import USBError

from remotes import tv

# Use usb-devices to find the Arduino
dev = core.find(idVendor=0x2341, idProduct=0x0043)
detached = False

if dev is None:
    raise ValueError("Device Not Found!")


#if dev.is_kernel_driver_active(0):
#    try:
#        dev.detach_kernel_driver(0)
#        detached = True
#        print("Kernel detached")
#    except USBError as e:
#        exit("Failed detaching kernel driver!")
#else:
#    print("No Kernel Attached!")

#try:
#    util.claim_interface(dev, 0)
#    print("Claimed Device!")
#except:
#    endpoint = dev[0][(0,0)][0]
#    data = dev.read(endpoint.bEndpointAddress, 0x0040)
#    print(type(data))
#    print(data)

#if detached:
#    dev.attach_kernel_driver(0)
#    print("Kernel attached")

#exit()
#print(type(dev))
#print(dev)

# Setup the device
# https://github.com/pyusb/pyusb/issues/357
#dev.set_configuration()

# From https://stackoverflow.com/questions/29345325/raspberry-pyusb-gets-resource-busy
dev.reset()

# Get the config
cfg = dev.get_active_configuration()

#print(cfg)

# Index the config for interfaces
intf = cfg[(0, 0)]

print(intf)

# If you don't know the endpoint
# Obatains the endpoint out
ep = util.find_descriptor(
    intf,
    custom_match = \
    lambda e: \
        util.endpoint_direction(e.bEndpointAddress) == \
        util.ENDPOINT_IN)

assert ep is not None
# Now we timeout here. :(
ep.write(b'0x57E3E817,32,1\n')
