def init(self, flip_to_comms=True): self.is_kernel_driver_detached = False if flip_to_comms and self.dev.idProduct == HID_PRODUCT_ID: if self.dev.is_kernel_driver_active(0): logger.debug('Detaching kernel driver') self.dev.detach_kernel_driver(0) self.is_kernel_driver_detached = True self.flip_to_comms_mode() util.dispose_resources(self.dev) self.dev = None logger.info('Connecting to Neo in communication mode') while self.dev is None: sleep(0.1) self.dev = usb.core.find(idVendor=VENDOR_ID, idProduct=COM_PRODUCT_ID) if self.dev.idProduct == COM_PRODUCT_ID: cfg = self.dev[0] intf = cfg[(0, 0)] endpoints = intf.endpoints() def get_endpoint(direction): predicate = lambda ep: \ util.endpoint_type(ep.bmAttributes) == util.ENDPOINT_TYPE_BULK and \ util.endpoint_direction(ep.bEndpointAddress) == direction eps = list(filter(predicate, endpoints)) if len(eps) == 0: raise NeotoolsError( 'Cannot find endpoint with direction %s' % direction) return eps[0] self.in_endpoint = get_endpoint(util.ENDPOINT_IN) self.out_endpoint = get_endpoint(util.ENDPOINT_OUT)
def _close(self): dev = self._dev release_interface(dev, self._intNum) dispose_resources(dev) self._dev = None # release 'Endpoints' objects for prevent undeleted 'Device' resource self._epOut = self._epIn = None
def wrapper(self, *args, **kwargs): try: result = func(self, *args, **kwargs) except: raise finally: try: if self.autodispose: dispose_resources(self.device) except USBError: pass return result
def _close(self) -> None: print('USB CLOSE START') if self._loop is not None: if self._loop.is_alive(): self._loop.stop() self._loop.join() self._loop = None try: self._dev.reset() dispose_resources(self._dev) except: pass self._dev = self._epOut = self._epIn = None self._driver_open = False print('USB CLOSE END')
def release_all_devices(cls, devclass: Optional[Type] = None) -> int: """Release all open devices. :param devclass: optional class to only release devices of one type :return: the count of device that have been released. """ cls.Lock.acquire() try: remove_devs = set() for devkey in cls.Devices: if devclass: dev = cls._get_backend_device(cls.Devices[devkey][0]) if dev is None or not isinstance(dev, devclass): continue dispose_resources(cls.Devices[devkey][0]) remove_devs.add(devkey) for devkey in remove_devs: del cls.Devices[devkey] return len(remove_devs) finally: cls.Lock.release()
def disconnect(self): data=bytes([0,0]) print("STOP interface 2 FRAME..",end='') r = self.dev.ctrl_transfer( bmRequestType=1, bRequest=0x0B, wValue=0, wIndex=2, data_or_wLength=data, timeout=100) print(r) print("STOP interface 1 FILEIO..",end='') r = self.dev.ctrl_transfer( bmRequestType=1, bRequest=0x0B, wValue=0, wIndex=1, data_or_wLength=data, timeout=100) print(r) util.dispose_resources(self.dev)
def release_device(cls, usb_dev: UsbDevice): """Release a previously open device, if it not used anymore. :param usb_dev: a previously instanciated USB device instance """ # Lookup for ourselves in the class dictionary cls.Lock.acquire() try: for devkey in cls.Devices: dev, refcount = cls.Devices[devkey] if dev == usb_dev: # found if refcount > 1: # another interface is open, decrement cls.Devices[devkey][1] -= 1 else: # last interface in use, release dispose_resources(cls.Devices[devkey][0]) del cls.Devices[devkey] break finally: cls.Lock.release()
def _finalize_object(self): util.dispose_resources(self.dev) self.dev = None
def tearDown(self): uu.dispose_resources(self.dev)
def dispose(self): """ Release device resources so other applications can use it meanwhile. A disposed device gets auto claimed upon the next interaction. """ dispose_resources(self.device)
def disconnect(self): self._connected = False util.dispose_resources(self._usb_device) self._usb_device = None self._endpoint_in = None self._endpoint_out = None
def __del__(self): util.dispose_resources(self.dev) self.dev = None
def readScale(mode_weight_requested): # these are conversion factors ounces_per_gram = 0.035274 ounces_per_pound = 16 # These values are specific to the Dymo scale. They can be found using the device filter, e.g. libusb_win32 in # windows VENDOR_ID = 0x0922 PRODUCT_ID = 0x8003 try: # find the USB device device = core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID) # use the default configuration device.set_configuration() # first endpoint, this is again specific to the Dymo scale endpoint = device[0][(0, 0)][0] # read a data packet, it will try so 10 times before throwing the error to the function calling, in this case # accurate_reading() attempts = 10 data = None while data is None: try: data = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize) except core.USBError as e: data = None if e.args == ('Operation timed out',): continue attempts -= 1 if attempts < 0: print(e.args) print('Error in readscale') util.dispose_resources(device) return 'Error' # this releases the usb scale util.dispose_resources(device) except Exception as e: print(e) print('Error in readscale') return 'Not connected' # determine the weight units used by the scale, these can only be ounces or grams mode_weight = 'g' if data[2] == 11: mode_weight = 'oz' # determine the scaling factor, only relevant if the scale is set to ounces, 256 is scaling factor of 1, # 255 is 10^-1 etc scaling_factor = data[3] scaling_factor = scaling_factor - 256 scaling_factor = 10 ** scaling_factor # check whether the unit of mass is acceptable if mode_weight_requested.lower() not in ['g', 'kg', 'kgs', 'lb', 'lbs', 'pounds', 'oz']: return 'Unsupported UOM' # determine the current reading and convert, using formulas from # http://steventsnyder.com/reading-a-dymo-usb-scale-using-python/ if mode_weight == 'g': reading = (data[4] + (256 * data[5])) # convert if necessary to requested format if mode_weight_requested.lower() == 'oz': reading = reading * ounces_per_gram if mode_weight_requested.lower() == 'kg' or mode_weight_requested.lower() == 'kgs': reading = reading / 1000 if mode_weight_requested.lower() == 'lb' or mode_weight_requested.lower() == 'lbs' or mode_weight_requested.lower() == 'pounds': reading = reading * ounces_per_gram / ounces_per_pound # this means the scale is set to ounces else: reading = scaling_factor * (data[4] + (256 * data[5])) # convert if necessary if mode_weight_requested == 'g': reading = reading / ounces_per_gram if mode_weight_requested.lower() == 'kg' or mode_weight_requested.lower() == 'kgs': reading = reading / ounces_per_gram / 1000 if mode_weight_requested.lower() == 'lb' or mode_weight_requested.lower() == 'lbs' or mode_weight_requested.lower() == 'pounds': reading = reading / ounces_per_pound return reading
if __name__ == '__main__': path_serial, ids, path_fw, verbose = parse_option() if not path_serial or not ids[0] or not ids[1] or not path_fw: usage(3) logger_app.info(f'logging results into {path_log_results}') logger_app.info(f'using serial {path_serial}') logger_app.info(f'fuzzing device {ids[0]:x}:{ids[1]:x}') logger_app.info(f'using unpacked firmware from {path_fw}') s = serial.Serial(path_serial, 115200) # TODO: check is not already opened logger_app.info(f'opened serial successfully') logger_app.info('starting to fuzz') time.sleep(4) # allow to disconnect previous device from usb.util import dispose_resources for _ in tqdm.trange(0x10000): device_reset_to_adfu_mode(s) time.sleep(1) # race condition between reset and wait dev, e_read, e_write = wait_device(*ids) upload_fw(e_read, e_write, path_fw) fuzz(e_read, e_write, _) dispose_resources(dev) # free open files
def tearDown(self): self.dev.ctrl_transfer(uu.CTRL_OUT | uu.CTRL_RECIPIENT_INTERFACE | uu.CTRL_TYPE_VENDOR, SS_TRIGGER, 0, 0, [0]) uu.dispose_resources(self.dev)
def send(machine=None, zones=None, modes=None, speed=MAX_SPEED, save=False): """ Sends zone commands to the device for all modes. This is used by lsd, either talking directly to it when it has root access, or via the lsdaemon as intermediary. In any case this is the main entry point of the library, that you can use for your own applications. If mode is None is specified, then the commands are executed just for the current session, meaning that you will see the changes immediately. Arguments: + machine: a machine, as detected by get_machine. + zones: an iterable where each element is a size two iterable, where the first element is the zone uid and the latter is a list, where every item is a command to be sent to such zone with its arguments. + modes: a list of modes uids to apply current configuration to. + speed: theme speed for current configuration (range 0 to 65535). + save: when True, send a cmd_save request to make changes permantent. See ``protocol.send_for_mode`` for more details. Returns an integer intended to be the value returned by sys.exit. """ try: machine = get_machine() except EnvironmentError: return log_error_code(ERROR_DEVICE_NOT_FOUND) device = machine['device'] if modes is None: modes = [] modes.append(None) try: # Try to gain device control really hard. This should work in most # situations for most machines. connect(device) except USBError: return log_error_code(ERROR_DEVICE_CANNOT_TAKE_OVER) try: wait_ok(device) cmd_reset(device, RESET_ALL_LIGHTS_ON) wait_ok(device) except USBError: return log_error_code(ERROR_DEVICE_TIMEOUT) for mode in modes: code = send_for_mode(machine, zones, mode, speed) if code != SUCCESS: return code # Mark loop end try: if save: cmd_save(device) cmd_transmit_execute(device) except USBError: return log_error_code(ERROR_DEVICE_TIMEOUT) # Free the robots^C^Cdevice dispose_resources(device) return SUCCESS
def release(self): util.dispose_resources(self.__usb_device)