import usb.core
import usb.util



USB_IF      = 0 # Interface
USB_TIMEOUT = 5 # Timeout in ms
USB_VENDOR  = 0xffff # Vendor-ID:
USB_PRODUCT = 0x0035 # Product-ID


class UsbCardReader:
    def __init__(self, callback):
        #fn called on found card
        self.callback = callback
        # Find the HID device by vendor/product ID
        self.dev = usb.core.find(idVendor=USB_VENDOR, idProduct=USB_PRODUCT)
        # Get and store the endpoint
        self.endpoint = self.dev[0][(0,0)][0]
        if self.dev.is_kernel_driver_active(USB_IF) is True:
            self.dev.detach_kernel_driver(USB_IF)
        # Claim the device
        usb.util.claim_interface(self.dev, USB_IF)
        self.receivedNumber = 0

        cardread=threading.Thread(target=self.read)
        cardread.start()

    def read(self):
        receivedNumber = 0

        while True:
            control = None
            try:
                control = self.dev.read(self.endpoint.bEndpointAddress, self.endpoint.wMaxPacketSize, USB_TIMEOUT)
                if (control[2] != 40) & (control[2] != 0):
                    receivedDigit = control[2] - 29
                    if receivedDigit == 10:
                        receivedDigit = 0
                    receivedNumber = 10 * receivedNumber + receivedDigit

                if (( control[0] == 0 )) & (( control[2] == 40 )) & (( not receivedNumber == 0 )):
                    self.callback(receivedNumber)
                    receivedNumber = 0

            except KeyboardInterrupt:
                exit()
            except:
                pass

            time.sleep(0.001)