electronicayciencia / EasyMCP2221

The most complete Python library to interface with MCP2221(A).
https://easymcp2221.readthedocs.io/
MIT License
15 stars 3 forks source link

Distinguishing between multiple connected MCP2221s #8

Closed chrisjbillington closed 3 months ago

chrisjbillington commented 3 months ago

It looks like there isn't a reliable way to distinguish multiple connected MCP2221s without a bit of extra work. The devnum parameter allows one to connect to several MCP2221s, but is not guaranteed to be stable. I'm doing something like the below (which is a bit hacky) to distinguish MCP2221s by serial number, but identifying them by their USB address could also be good (that should be stable as long as the devices remain plugged into the same USB ports).

class MCP2221(EasyMCP2221.Device):
    """Subclass that allows finding device by serial number instead of the unstable
    `devnum`, which is just based on the order hidapi enumerates devices."""
    device_open_timeout = 0
    def __init__(self, serial_number=None):
        self.hidhandler = hid.device()
        devnum = None
        if serial_number is None:
            devnum = 0
        else:
            for i, dev in enumerate(hid.enumerate(self.VID, self.PID)):
                try:
                    self.hidhandler.open_path(dev["path"])
                except OSError:
                    # Probably already in use
                    pass
                else:
                    usb_serial = self.read_flash_info()['USB_SERIAL']
                    if usb_serial == serial_number:
                        devnum = i
                        self.hidhandler.close()
                        break
        if devnum is None:
            raise ValueError(f"No MCP2221 with serial number {serial_number} found")

        super().__init__(devnum=devnum)
electronicayciencia commented 3 months ago

I merged your code with the class init. I also released a simple example: select_by_serial. Could you check it, please?