int0x76

Teensy: usb_rawhid

May 30th, 2014
434
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.03 KB | None | 0 0
  1. #!/usr/bin/env python
  2. ##########################################################################################################
  3. #
  4. # Python implementation of the usb_rawhid host-side functions for the Teensy (and other raw HID devices).
  5. # Requires the libhid library.
  6. #
  7. # Craig Heffner
  8. # 21-July-2011
  9. # http://www.devttys0.com
  10. #
  11. ##########################################################################################################
  12.  
  13. import sys
  14. try:
  15.     from hid import *
  16. except Exception, e:
  17.     print e
  18.     print "Please install libhid: http://libhid.alioth.debian.org/"
  19.     sys.exit(1)
  20.  
  21. class RawHID:
  22.  
  23.     READ_ENDPOINT = 0x81
  24.     WRITE_ENDPOINT = 0x02
  25.     INTERFACE = 0
  26.  
  27.     PACKET_LEN = 64
  28.     TIMEOUT = 1000 # milliseconds
  29.     CONNECT_RETRIES = 3
  30.  
  31.     def __init__(self, verbose=False):
  32.         self.verbose = verbose
  33.         self.hid = None
  34.         return None
  35.  
  36.     # Initialize libhid and connect to USB device.
  37.     #
  38.     # @vid - Vendor ID of the USB device.
  39.     # @pid - Product ID of the USB device.
  40.     #
  41.     # Returns True on success.
  42.     # Returns False on failure.
  43.     def open(self, vid, pid):
  44.         retval = False
  45.  
  46.         hid_ret = hid_init()
  47.         if hid_ret == HID_RET_SUCCESS:
  48.             self.hid = hid_new_HIDInterface()
  49.             match = HIDInterfaceMatcher()
  50.             match.vendor_id = vid
  51.             match.product_id = pid
  52.        
  53.             hid_ret = hid_force_open(self.hid, self.INTERFACE, match, self.CONNECT_RETRIES)
  54.             if hid_ret == HID_RET_SUCCESS:
  55.                 retval = True
  56.                 if self.verbose:
  57.                     hid_write_identification(sys.stderr, self.hid)
  58.  
  59.             elif self.verbose:
  60.                 sys.stderr.write("hid_force_open() failed with error code: %d\n" % hid_ret);
  61.         elif self.verbose:
  62.             sys.stderr.write("hid_init() failed with error code: %d\n" % hid_ret)
  63.  
  64.         return retval
  65.  
  66.     # Close HID connection and clean up.
  67.     #
  68.     # Returns True on success.
  69.     # Returns False on failure.
  70.     def close(self):
  71.         retval = False
  72.  
  73.         if hid_close(self.hid) == HID_RET_SUCCESS:
  74.             retval = True
  75.  
  76.         hid_cleanup()
  77.  
  78.         return retval
  79.  
  80.     # Send a USB packet to the connected USB device.
  81.     #
  82.     # @packet  - Data, in string format, to send to the USB device.
  83.     # @timeout - Read timeout, in milliseconds. Defaults to TIMEOUT.
  84.     #
  85.     # Returns True on success.
  86.     # Returns False on failure.
  87.     def send(self, packet, timeout=TIMEOUT):
  88.         retval = False
  89.  
  90.         hid_ret = hid_interrupt_write(self.hid, self.WRITE_ENDPOINT, packet, timeout)
  91.  
  92.         if hid_ret == HID_RET_SUCCESS:
  93.             retval = True
  94.         elif self.verbose:
  95.             sys.stderr.write("hid_interrupt_write() failed with error code: %d\n" % hid_ret)
  96.  
  97.         return retval
  98.  
  99.     # Read data from the connected USB device.
  100.     #
  101.     # @len     - Number of bytes to read. Defaults to PACKET_LEN.
  102.     # @timeout - Read timeout, in milliseconds. Defaults to TIMEOUT.
  103.     #
  104.     # Returns the received bytes on success.
  105.     # Returns None on failure.
  106.     def recv(self, plen=PACKET_LEN, timeout=TIMEOUT):
  107.  
  108.         hid_ret, packet = hid_interrupt_read(self.hid, self.READ_ENDPOINT, plen, timeout)
  109.  
  110.         if hid_ret != HID_RET_SUCCESS:
  111.             packet = None
  112.         elif self.verbose:
  113.             sys.stderr.write("hid_interrupt_read() failed with error code: %d\n" % hid_ret)
  114.  
  115.         return packet
  116.  
  117.  
  118.  
  119. # Example code to interface with the Teensy Raw HID Example firmware
  120. if __name__ == "__main__":
  121.  
  122.     BYTES_PER_LINE = 16
  123.  
  124.     # Teensy vendor ID and product ID
  125.     vid = 0x16C0
  126.     pid = 0x0480
  127.  
  128.     hid = RawHID()
  129.    
  130.     # Open a connection to the Teensy
  131.     if hid.open(vid, pid):
  132.  
  133.         print "\nConnected to Teensy..."
  134.  
  135.         # Turn on the Teensy pins D0-D3
  136.         hid.send("\x0F")
  137.        
  138.         try:
  139.             # Infinite loop to read data from the Teensy
  140.             while True:
  141.                 data = hid.recv(timeout=50)
  142.                 if data is not None:
  143.                     size = len(data)
  144.                     print ""
  145.                     print "recv %d bytes:" % size
  146.                
  147.                     # Print out each hex byte, 16 bytes per line
  148.                     for i in range(0, (size / BYTES_PER_LINE)):
  149.                         for j in range(0, BYTES_PER_LINE):
  150.                             print "%.2X" % ord(data[(i*BYTES_PER_LINE)+j]),
  151.                         print ""
  152.         except KeyboardInterrupt:
  153.             pass
  154.  
  155.         # Close the Teensy connection
  156.         hid.close()
  157.  
  158.         print "\nDisconnected from Teensy.\n"
  159.     else:
  160.         print "Failed to open HID device %X:%X" % (vid, pid)
Advertisement
Add Comment
Please, Sign In to add comment