# Communication with ASSERLOGGER using pyUSB
# works like a USB terminal
# data are received, key strokes are sent

# for pyusb: git clone https://github.com/walac/pyusb.git 
# cd pyusb
# sudo python setup.py
# Windows needs libusb! (http://sourceforge.net/projects/libusb-win32)

Vendor_ID = 0x3EB #(ATMEL)
Product_ID = 0x02 #usb_small_lib "hid")

import usb.core, time


# This is for keyboard reaction, nonblocking
import keypress_nonblocking as kp
kb = kp.KBHit()

interface = 0

dev = usb.core.find(idVendor = Vendor_ID,idProduct = Product_ID)

if dev is None:
    print ("device not found")

else:
    # only linux: uncomment if device not free (error resource busy)   
    if dev.is_kernel_driver_active(interface) is True:    
        dev.detach_kernel_driver(interface)        
        usb.util.claim_interface(dev, interface)        
        dev = usb.core.find(idVendor = Vendor_ID,idProduct = Product_ID)
    
    dev.set_configuration()
    
    
    # communication code
    while True:
        
        # receive
        res = dev.read(0x81, 64)    # read 64 Byte (ADC) from endpoint1 (0x81)
        if len(res):                # and print 
            s=res.tostring()
            s=s.split(chr(0))       # USB string is delimi1ted by chr(0)
            print( s[0] )           # print everything before chr(0) 
            
                
        # if keyboard input, send command
        if kb.kbhit():
            c = kb.getch()
            dev.write(0x02, c)      # write do device
            
                       
            # quit with <ESC>
            if ord(c) == 27:
                break
            
    # end        
    kb.set_normal_term()                    
    print ("# END")
