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

 With "*": swith to long USB command mode that allows commands like 
 "G500" -> set generator to 500us period length
 These commands are sent only when <Enter> is pressed


# 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)

# version 0.1 29.11.2014
"""

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

import usb.core, time
import keypress_nonblocking as kp

# This is for keyboard rection, nonblocking
kb = kp.KBHit()
4

interface = 0

Quitflag = False

#--------------------------------------------------------------------
def usb_connect(Vendor_ID,Product_ID):
# connect to device

    dev = usb.core.find(idVendor = Vendor_ID,idProduct = Product_ID)
    if dev is None:
        print ("# Device not found")
    
    # if device present
    else:
        print ("# Found ASSERLOGGER on USB")
        # only linux: uncomment if device not free (error resource busy)   
        try:
            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)
        except:
            pass         
        
        # set configuration
        try:
            dev.set_configuration()
            print ("# Configuration set")
            return dev
        except:
            print ("# Configuration could not be set")
            return None    
            
#--------------------------------------------------------------------
def usb_read_and_print(dev):
    try:
        res = dev.read(0x81, 64)    # read 64 Byte from endpoint 1 (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) 
            return s[0] 
    except:
        print ("# Can not read from device! Is it disconnected?")
        return "READ_ERROR"                      
#--------------------------------------------------------------------

def keyboard_to_usb(dev, kb):
    # if keyboard input -> send command to device
    if kb.kbhit():
        c = kb.getch()
                            
        # "*" -> allow long input terminated by <Enter>
        if c=="*":
            kb.set_normal_term()    # for input, turn on normal terminal mode 
            t=raw_input("# Long USB command:")+chr(0)       # string terminator chr(0)
            
            n_bytes=dev.write(0x02, t)  
            
            kb.__init__()           # react to keypress again
             
            
        else:
            
            n_bytes = dev.write(0x02, c)      # write do device, endpoint 2
            
        return c    
#---------------------------------------------------------------------                    
# loop until connection is OK, quit with <ESC>
while True:
    
    dev=usb_connect(Vendor_ID,Product_ID)
    
    if dev != None:
                
        # communication loop
        while True:
            # read from device and print received message
            s = usb_read_and_print (dev)
            if s == "READ_ERROR":
                break 
            
            # check keyboard and send to usb        
            c = keyboard_to_usb(dev, kb)
     
            if c != None:
                ##print ord(c)
                if ord(c) == 27:
                    Quitflag=True
                    print ("# QUITTING")
                    break 

    else:
        print ("# Can not read from device! Is it disconnected?")
        time.sleep(0.2)   
        
    
    if Quitflag==True:
        break     
# end        
kb.set_normal_term()                    
print ("# END")
        
