def __init__(self, usb_context, write_queue, vendor_id=None, product_id=None): self.app_connected = False self._context = usb_context isconfigured, self._handle = self._find_handle(vendor_id, product_id) if isconfigured: print("Device is in accessory mode") # TODO: should I reset the device? # self._handle.claimInterface(0) # self._handle.resetDevice() # time.sleep(2) # isconfigured, self._handle = self._find_handle(vendor_id, product_id) # self._handle = self._configure_accessory_mode() else: self._handle = self._configure_accessory_mode() self._handle.claimInterface(0) # pause for one second so the android device can react to changes time.sleep(1) device = self._handle.getDevice() config = device[0] interface = config[0] self._in_endpoint, self._out_endpoint = self._get_endpoints( interface[0]) if self._in_endpoint is None or self._out_endpoint is None: self._handle.releaseInterface(0) raise usb1.USBError( 'Unable to retreive endpoints for accessory device') read_callback = usb1.USBTransferHelper() callback_obj = ReadCallback(self, write_queue) read_callback.setEventCallback( usb1.TRANSFER_COMPLETED, callback_obj, ) self._read_list = [] for _ in range(64): data_reader = self._handle.getTransfer() data_reader.setBulk( self._in_endpoint, 0x4000, callback=read_callback, ) data_reader.submit() self._read_list.append(data_reader) self._write_queue = write_queue self._is_running = True self._write_thread = threading.Thread(target=self._write_thread_proc) self._write_thread.start()
def read_data_thread(cnt, size): context = usb1.USBContext() #print('captured libusb devices:\n') #print(context.getDeviceList()) try: handle = context.openByVendorIDAndProductID(0x04b4, 0x00f1) print('success') except: print('device not found') exit(1) handle.claimInterface(0) th = usb1.USBTransferHelper() th.setEventCallback(usb1.TRANSFER_COMPLETED, read_cb) tranlist = [0, 1, 2, 3, 4, 5] for x in [0, 1]: tranlist[x] = handle.getTransfer() tranlist[x].setBulk(0x86, 2048, callback=read_cb) tranlist[x].submit() #trans.setBulk(0x86,2048,callback=read_cb) #print(trans.getStatus()) #trans.submit() #print(trans.isSubmitted()) print('submitted') #device = usb.core.find(idVendor=0x04b4) #print(device) #print(device.backend) ##print(device.manufacturer) ##print(device.product) #print('list of the device config:\n',device.configurations()) #print('will set this default config') #device.set_configuration() #print(device[0][0,0][0]) #print(device[0][0,0][1]) #data = array('B') #data.fromlist(list(range(0,256))) #data.fromlist(list(range(0,256))) #data.fromlist([0]*512) #data[510]=2 #data[508]=2 #data[506]=4 #data.fromlist(list(range(255,-1,-1))) #wlen = device.write(0x2,array('h',[1,2])) #wlen = device.write(0x2,data) #print(wlen,'Bs send.') #print(data) time.sleep(0.1) rdata = array('H') rdata.fromlist([0] * size) #rdata = device.read(0x86,4) #rdata = device.read(0x86,512) while 1: context.handleEvents()
def _start_si_receive(self) -> None: def usb_events_thread_func() -> None: while self._event_thread_run: try: self._usb_ctx.handleEvents() except usb.USBErrorInterrupted: pass helper = usb.USBTransferHelper() helper.setEventCallback(usb.TRANSFER_COMPLETED, self._process_si_receive) helper.setDefaultCallback(self._process_si_errors) transfer = self._usb_devh.getTransfer() transfer.setInterrupt(EP.SI, SI_BUF_LEN, callback=helper) self._usb_pthread = threading.Thread(target=usb_events_thread_func) self._usb_pthread.start() transfer.submit()
def main(): with usb1.USBContext() as context: context.setDebug(usb1.LOG_LEVEL_DEBUG) handle = context.openByVendorIDAndProductID( 0x1d6b, 0x0104, skip_on_error=True, ) if handle is None: print('Device not found') return device = handle.getDevice() assert len(device) == 1 configuration = device[0] assert len(configuration) == 1 interface = configuration[0] assert len(interface) == 1 alt_setting = interface[0] lang_id, = handle.getSupportedLanguageList() interface_name = handle.getStringDescriptor( alt_setting.getDescriptor(), lang_id) interface_name_ascii = handle.getASCIIStringDescriptor( alt_setting.getDescriptor()) assert interface_name == common.INTERFACE_NAME == interface_name_ascii, ( repr(interface_name), repr(interface_name_ascii)) try: handle.controlRead( usb1.TYPE_VENDOR | usb1.RECIPIENT_INTERFACE, common.REQUEST_STALL, 0, 0, 1, ) except usb1.USBErrorPipe: pass else: raise ValueError('Did not stall') try: handle.controlWrite( usb1.TYPE_VENDOR | usb1.RECIPIENT_INTERFACE, common.REQUEST_STALL, 0, 0, 'a', ) except usb1.USBErrorPipe: pass else: raise ValueError('Did not stall') echo_value = None for length in range(1, 65): echo_next_value = handle.controlRead( usb1.TYPE_VENDOR | usb1.RECIPIENT_INTERFACE, common.REQUEST_ECHO, 0, 0, length, ) if echo_next_value == echo_value: break print(repr(echo_next_value)) echo_value = echo_next_value handle.controlWrite( usb1.TYPE_VENDOR | usb1.RECIPIENT_INTERFACE, common.REQUEST_ECHO, 0, 0, 'foo bar baz', ) print( repr( handle.controlRead( usb1.TYPE_VENDOR | usb1.RECIPIENT_INTERFACE, common.REQUEST_ECHO, 0, 0, 64, ))) size = [0] def onTransfer(transfer): result = time() < deadline if result: size[0] += transfer.getActualLength() return result usb_file_data_reader = usb1.USBTransferHelper() usb_file_data_reader.setEventCallback( usb1.TRANSFER_COMPLETED, onTransfer, ) NUM_TRANSFER = 8 transfer_list = [handle.getTransfer() for _ in range(NUM_TRANSFER)] active_configuration = handle.getConfiguration() if active_configuration != 1: print('Unexpected active configuration:', active_configuration) handle.setConfiguration(1) active_configuration = handle.getConfiguration() assert active_configuration == 1, active_configuration handle.claimInterface(0) DURATION = .2 buf = bytearray(512) for ep_desc in alt_setting: ep = ep_desc.getAddress() if ep & 0xf0: buf[0] = 0 else: for offset, _ in enumerate(buf): buf[offset] = ep size[0] = 0 for transfer in transfer_list: transfer.setBulk( ep, buf, callback=usb_file_data_reader, timeout=int(DURATION * 1000), ) transfer.submit() begin = time() deadline = begin + DURATION while any(x.isSubmitted() for x in transfer_list): context.handleEvents() actual_duration = time() - begin print( '%i%s' % ( ep & 0x7f, 'IN' if ep & 0x80 else 'OUT', ), '\tbandwidth: %i B/s (%.2fs)' % (size[0] / actual_duration, actual_duration), hex(buf[0]))
def main(): with usb1.USBContext() as context: for device in context.getDeviceIterator(skip_on_error=True): try: handle = device.open() except usb1.USBErrorAccess: continue for interface in device[handle.getConfiguration() - 1]: if len(interface) != 1: continue interface_setting = interface[0] if (interface_setting.getNumEndpoints() == 2 and interface_setting.getClass() == usb1.CLASS_VENDOR_SPEC and handle.getStringDescriptor( interface_setting.getDescriptor(), 0x0409, ) == u'USBCat'): interface_number = interface_setting.getNumber() print('Device found at %03i:%03i interface %i' % ( device.getBusNumber(), device.getDeviceAddress(), interface_number, )) handle.claimInterface(interface_number) to_device, = [ x.getAddress() for x in interface_setting if x.getAddress() & usb1.ENDPOINT_DIR_MASK == usb1.ENDPOINT_OUT ] from_device, = [ x.getAddress() for x in interface_setting if x.getAddress() & usb1.ENDPOINT_DIR_MASK == usb1.ENDPOINT_IN ] break else: continue break else: print('Device not found') return fcntl.fcntl( sys.stdin, fcntl.F_SETFL, fcntl.fcntl(sys.stdin, fcntl.F_GETFL) | os.O_NONBLOCK, ) def sender(): buf = sys.stdin.read(BUF_SIZE) print('sending', len(buf), 'bytes', file=sys.stderr) handle.bulkWrite(to_device, buf) def onReceive(transfer): length = transfer.getActualLength() print('received', length, 'bytes', file=sys.stderr) sys.stdout.write(transfer.getBuffer()[:length]) return True transfer_helper = usb1.USBTransferHelper() transfer_helper.setEventCallback(usb1.TRANSFER_COMPLETED, onReceive) transfer_list = [] for _ in xrange(PENDING_READ_COUNT): transfer = handle.getTransfer() transfer.setBulk(from_device, BUF_SIZE, transfer_helper) transfer.submit() transfer_list.append(transfer) epoll = usb1.USBPoller(context, select.epoll()) event_dispatcher_dict = {} def register(file_object, handler): epoll.register(file_object, select.EPOLLIN) event_dispatcher_dict[file_object.fileno()] = handler register(sys.stdin, sender) try: while True: for fd, event in epoll.poll(10): print( 'epoll: fd %r got event %r' % (fd, event), file=sys.stderr, ) event_dispatcher_dict[fd]() except (KeyboardInterrupt, EOFError): pass
import usb1, libusb1 import time, struct ctx = usb1.LibUSBContext() dev = ctx.getByVendorIDAndProductID(0x1d50, 0x6018) if not dev: print 'Device not found.' exit(1) handle = dev.open() handle.claimInterface(5) def transfer_cb(t): print t.getBuffer()[:t.getActualLength()].encode('hex') return True th = usb1.USBTransferHelper() th.setEventCallback(libusb1.LIBUSB_TRANSFER_COMPLETED, transfer_cb) t = handle.getTransfer() t.setBulk(0x85, 64, th) t.submit() while 1: ctx.handleEvents()
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option( '-f', '--firmware', default='/lib/firmware/ITI1480A.rbf', help='Path to firmware file to upload', ) parser.add_option( '-d', '--device', help='USB device to use, in "bus.dev" format', ) parser.add_option( '-o', '--out', help='File to write dump data to. Default: stdout', ) parser.add_option( '-v', '--verbose', action='store_true', help='Print informative messages to stderr', ) (options, args) = parser.parse_args() if options.firmware is None: parser.print_help(sys.stderr) sys.exit(1) if options.device is None: usb_device = None else: usb_device = options.device.split('.') assert len(usb_device) == 2 usb_device = (int(usb_device[0]), int(usb_device[1])) if options.out is None: out_file = os.fdopen(sys.stdout.fileno(), 'w') else: out_file = open(options.out, 'wb', 0) verbose = options.verbose with usb1.USBContext() as context: handle = getDeviceHandle(context, VENDOR_ID, DEVICE_ID, usb_device) if handle is None: print('ITI1480A USB Analyzer not found', file=sys.stderr) sys.exit(1) handle.claimInterface(0) analyzer = USBAnalyzer(handle) analyzer.sendFirmware(open(options.firmware, 'rb')) # Call queue: process received signals synchronously. # Asynchronous processing is tricky because capture stop and pause need to # communicate with the analyzer, and complex tricks are needed when libusb # event handling happens "in parallel" (handleEvents + sighandler triggered # at the wrong time). call_queue = [] def exit(): if verbose: sys.stderr.write('\nExiting...\n') analyzer.stopCapture() def pause(): analyzer.pauseCapture() if verbose: sys.stderr.write('\nCapture paused') os.kill(os.getpid(), signal.SIGSTOP) analyzer.continueCapture() if verbose: sys.stderr.write('Capture resumed\n') # Install signal handlers for sig in (signal.SIGINT, signal.SIGTERM): signal.signal(sig, lambda sig, stack: call_queue.append(exit)) signal.signal(signal.SIGTSTP, lambda sig, stack: call_queue.append(pause)) usb_file_data_reader = usb1.USBTransferHelper() transfer_dump_callback = TransferDumpCallback(out_file, verbose=verbose) usb_file_data_reader.setEventCallback( usb1.TRANSFER_COMPLETED, transfer_dump_callback, ) reader_list = [] append = reader_list.append for _ in xrange(64): data_reader = handle.getTransfer() data_reader.setBulk( 0x82, 0x8000, callback=usb_file_data_reader, ) data_reader.submit() append(data_reader) if verbose: sys.stderr.write( 'Capture started\n' 'SIGTSTP (^Z) to pause capture (signals the pause to analyser)\n' 'SIGCONT (fg) to unpause\n' 'SIGINT (^C) / SIGTERM to gracefuly exit\n') try: while any(x.isSubmitted() for x in reader_list): try: context.handleEvents() except usb1.USBErrorInterrupted: pass while call_queue: call_queue.pop(0)() finally: handle.releaseInterface(0)