def choose_device(): all_devices = lsusb().split('\n') count = 0 for dev in all_devices: if not dev: continue print '[{}] {}'.format(count,dev) count += 1 try: choice = raw_input('Please enter an ID between 0 and {}: '.format(count-1)) choice = int(choice) except: exit(0) if not choice >= 1 and not choice <= count: error('Invalid choice: {}'.format(choice)) exit(0) vendor,device = all_devices[choice].split(' ')[5].split(':') return vendor,device
def IsConnected(self): logging.debug("def IsConnected(self):") ret = sh.lsusb() logging.debug(ret.stdout) expr = r'Bus (\d+) Device (\d+)\: ID (\w{4}.\w{4}) Dallas Semiconductor (DS\w+) .* 1-Wire adapter' device_data = re.findall(expr,ret.stdout) if len(device_data) > 0: logging.info("Found 1 wire adapter bus: %s, device: %s" % (device_data[0][0],device_data[0][1]) ) self.usb_bus_num = device_data[0][0] self.usb_dev_num = device_data[0][1] self._connected = True else: logging.error('Did not find any devices matching: "%s"' % expr) self.usb_bus_num = 0 self.usb_dev_num = 0 self._connected = False return self._connected
def IsConnected(self): logging.debug("def IsConnected(self):") ret = sh.lsusb() logging.debug(ret.stdout) expr = r'Bus (\d+) Device (\d+)\: ID (\w{4}.\w{4}) Dallas Semiconductor (DS\w+) .* 1-Wire adapter' device_data = re.findall(expr, ret.stdout) if len(device_data) > 0: logging.info("Found 1 wire adapter bus: %s, device: %s" % (device_data[0][0], device_data[0][1])) self.usb_bus_num = device_data[0][0] self.usb_dev_num = device_data[0][1] self._connected = True else: logging.error('Did not find any devices matching: "%s"' % expr) self.usb_bus_num = 0 self.usb_dev_num = 0 self._connected = False return self._connected
def main(resolution: int, color: str, duplex: bool, deskew: bool, trim: bool, batch: bool): result = str(lsusb('-d', '04f9:')) device: str bus: str (_, bus, _, device) = result.partition(':')[0].split(' ') sane_model = 'BrotherADS2700' sane_device = f'{sane_model}:libusb:{bus}:{device}' working_dir = tempfile.mkdtemp() mode_map = { 'monochrome': 'Black & White', 'grayscale': 'Gray', 'truecolor': '24 bit Color' } option_mode = mode_map[color] scan_line = 'Scanned document ' final_images = [] batch_number = 0 batch_complete = False while not batch_complete: scanner_output = os.path.join(working_dir, f'scanned-{batch_number}-%d.pnm') option_source = 'Automatic Document Feeder(left aligned,Duplex)' if duplex \ else 'Automatic Document Feeder(left aligned)' scan_iter: Iterable[str] = scanadf('--device-name', sane_device, '--mode', option_mode, '--resolution', resolution, '--output-file', scanner_output, '--source', option_source, _iter='err') with yaspin(text='Scanning...') as spin: for line in scan_iter: line = line.rstrip() if line.startswith(scan_line): file_name = line[len(scan_line):] out_file_name = file_name.replace('scanned', 'cleaned').replace( '.pnm', '.png') convert_args = [file_name, '-fuzz', '20%'] if trim: convert_args.append('-trim') if deskew: convert_args.extend(('-deskew', '30%')) convert_args.extend(('+repage', out_file_name)) pool.acquire() process = convert(*convert_args, _bg=True, _done=done) processes_lock.acquire() processes.append(process) processing_count = len(processes) processes_lock.release() final_images.append(out_file_name) spin.text = f'Scanning... {len(final_images)} scanned.' if processing_count > 0: spin.text += f' Processing {processing_count}...' spin.text = 'Scanning complete.' spin.green.ok('✔') processes_lock.acquire() processes_remaining = list(processes) processes_lock.release() with yaspin(text='Processing...') as spin: if len(processes_remaining) > 0: i = 0 for process in processes_remaining: spin.text = f'Processing {len(processes_remaining) - i}...' process.wait() i += 1 spin.text = 'Processing complete.' spin.green.ok('✔') processes.clear() if not batch: batch_complete = True else: batch_number += 1 while True: value = click.prompt('Next batch (Single/Duplex/Finished):', type=click.Choice(('s', 'd', 'F'), case_sensitive=False), default='F').lower() if value == 'f': batch_complete = True elif value == 'd': duplex = True elif value == 's': duplex = False else: continue break input_pdf = os.path.join(working_dir, 'cleaned.pdf') with yaspin(text='Creating PDF...') as spin: img2pdf(*final_images, '-o', input_pdf) spin.text = 'PDF complete.' spin.green.ok('✔') with yaspin(text='Waiting for PDF arrangement...', spinner=Spinners.clock) as spin: pdfarranger(input_pdf) spin.text = 'PDF arranger closed.' spin.green.ok('✔') if click.confirm(f'Remove temporary files ({working_dir})?', default=True, show_default=True): with yaspin(text='Cleaning up...') as spin: shutil.rmtree(working_dir) spin.text = 'Clean up complete.' spin.green.ok('✔')
def device_info(vendor,device): return lsusb('-v','-d','{}:{}'.format(vendor,device))
elif 'device exists' in r.text: return 2 else: raise Exception('Error: {}'.format(r.text)) except Exception as e: debug(str(e)) return False if __name__ == '__main__': if not getuid() is 0: error('This script should be run as root for more comprehensive output!') exit(0) parse_cl() usb_devices = [] if args.all: for entry in lsusb().split('\n'): if not entry: continue usb_devices.append(entry.split(' ')[5].split(':')) elif not args.dev: usb_devices.append(choose_device()) else: vendor,device = args.dev.split(':') try: int(vendor,16) int(device,16) if len(vendor) != 4 or len(device) != 4: raise ValueError except ValueError: error('Invalid vendor or device ID') exit(0) usb_devices.append([vendor,device])
def ui_command_lsusb(self): """ lsusb - list USB devices. """ print sh.lsusb()