-
Notifications
You must be signed in to change notification settings - Fork 319
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for multiple MCP2221 I2C buses (improved) #637
Closed
ezio-melotti
wants to merge
28
commits into
adafruit:main
from
ezio-melotti:multiple-mcp2221-improved
Closed
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
f86d610
draft: Add i2c bus_id support
fgervais b428f71
Cleanup
fgervais 32852ce
Add examples
fgervais 877aae7
Manage MCP instances so different modules can share them
fgervais 24a73e2
Remove prints
fgervais ce4032f
Remove examples/mcps_busio_i2c.py
fgervais ca9d6ec
Change single example to include multiple mcp2221s
fgervais a7b6441
Add get_instance() docstring
fgervais 1224623
Change if/else syntax for pylint no-else-return
fgervais 301fa1f
Allow access to protected member
fgervais 5104e5d
Allow pylint unexpected-keyword-arg
fgervais 9447b81
Reorder third-party import in mcp2221 multiple example
fgervais 6e98be4
Merge commit 'd04bc037c3498c442671d9578b3fecbb3fc4e950' into multiple…
ezio-melotti 1fe958f
Merge pull request #1 from ezio-melotti/multiple-mcp2221-updated
fgervais b2e6c67
Add license to examples
fgervais db91cce
Add copyright to examples
fgervais 6b89397
List mcp2221 examples in examples.rst
fgervais d739532
Improve multiple MCP2221 support.
ezio-melotti bb0ea63
Improve examples/mcp2221_multiple_busio_i2c.py.
ezio-melotti 3477c4f
Make `black` happy.
ezio-melotti eafe43f
Restore compatibility with Python 3.7.
ezio-melotti a584d04
Make `pylint` happy.
ezio-melotti 505be77
Make `pylint` happier.
ezio-melotti c8d9318
Restore import in pin.py.
ezio-melotti 4ea3997
Refactor the MCP2221 implementation.
ezio-melotti 86ac218
Silence Pylint warning.
ezio-melotti 041462e
Remove debug prints.
ezio-melotti 28ae3d3
Make pylint happy.
ezio-melotti File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# SPDX-FileCopyrightText: 2022, The Blinka Authors. | ||
# | ||
# SPDX-License-Identifier: MIT | ||
import busio | ||
|
||
|
||
# Usage: | ||
# $ python mcp2221_first_busio_i2c.py | ||
# I2C devices found: ['0x70'] | ||
|
||
|
||
i2c = busio.I2C() | ||
print("I2C devices found: ", [hex(i) for i in i2c.scan()]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# SPDX-FileCopyrightText: 2022, The Blinka Authors. | ||
# | ||
# SPDX-License-Identifier: MIT | ||
|
||
import busio | ||
|
||
from adafruit_blinka.microcontroller.mcp2221.mcp2221 import MCP2221 | ||
|
||
# Usage: | ||
# $ python mcp2221_multiple_busio_i2c.py | ||
# 2 MCP2221 found: [b'2-3.3:1.2', b'2-3.2:1.2'] | ||
# I2C devices found on 2-3.3:1.2: ['0x77'] | ||
# I2C devices found on 2-3.2:1.2: ['0x58', '0x61'] | ||
|
||
# # MCP2221.available_paths() is roughly equivalent to | ||
# import hid | ||
# MCP2221_VID = 0x04D8 | ||
# MCP2221_PID = 0x00DD | ||
# addresses = [mcp["path"] for mcp in hid.enumerate(MCP2221_VID, MCP2221_PID)] | ||
|
||
addresses = MCP2221.available_paths() | ||
print(f"{len(addresses)} MCP2221(s) found: {addresses}") | ||
|
||
i2c_busses = [] | ||
for address in addresses: | ||
i2c_busses.append(busio.I2C(bus_id=address)) | ||
|
||
for address, i2c in zip(addresses, i2c_busses): | ||
print(f"I2C devices found on {address.decode()}:", [hex(i) for i in i2c.scan()]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# SPDX-FileCopyrightText: 2022, The Blinka Authors. | ||
# | ||
# SPDX-License-Identifier: MIT | ||
import argparse | ||
import busio | ||
|
||
|
||
# Usage: | ||
# $ lsusb | grep Microchip | ||
# Bus 001 Device 082: ID 04d8:00dd Microchip Technology, Inc. | ||
# Bus 001 Device 083: ID 04d8:00dd Microchip Technology, Inc. | ||
# $ python mcp2221_single_busio_i2c.py -b 1 -d 83 | ||
# I2C devices found: ['0x70'] | ||
|
||
|
||
# Bus and Device number can be gathered from `lsusb` | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument( | ||
"-b", "--bus", type=int, required=True, help="USB bus number (base10)" | ||
) | ||
parser.add_argument( | ||
"-d", "--device", type=int, required=True, help="USB device number (base10)" | ||
) | ||
args = parser.parse_args() | ||
|
||
# Need to be bytes, always function 2 | ||
device_path = "{:04x}:{:04x}:02".format(args.bus, args.device).encode() | ||
i2c = busio.I2C(bus_id=device_path) | ||
print("I2C devices found: ", [hex(i) for i in i2c.scan()]) |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
import os | ||
import time | ||
import atexit | ||
import warnings | ||
|
||
import hid | ||
|
||
|
@@ -53,9 +54,46 @@ class MCP2221: | |
GP_ALT1 = 0b011 | ||
GP_ALT2 = 0b100 | ||
|
||
def __init__(self): | ||
# attempting to reopen the same hid device results in an error, | ||
# so we cache and return already opened devices | ||
instances = {} | ||
|
||
# pylint gets confused by the use of __new__, so disable no-member checks | ||
# pylint: disable=no-member | ||
def __new__(cls, bus_id=None): | ||
"""Return a (possibly cached) MCP2221 instance.""" | ||
# check for an existing cached instance and return it | ||
if bus_id in cls.instances: | ||
return cls.instances[bus_id] | ||
# if there is no cached instance, create a new one | ||
self = super().__new__(cls) | ||
self._hid = hid.device() | ||
self._hid.open(MCP2221.VID, MCP2221.PID) | ||
if bus_id is not None: | ||
# use the given bus_id | ||
self._hid.open_path(bus_id) | ||
self._bus_id = bus_id | ||
else: | ||
# find the first available MCP | ||
bus_ids = cls.available_paths(require_mcps=True) | ||
# loop through all the available MCPs | ||
# pylint: disable-next=redefined-argument-from-local | ||
for bus_id in bus_ids: | ||
try: | ||
# pylint: disable-next=protected-access | ||
self._hid.open_path(bus_id) | ||
self._bus_id = bus_id | ||
break # we found an MCP that is available | ||
except (OSError, RuntimeError): | ||
if len(bus_ids) == 1: | ||
raise # we failed to open the only MCP | ||
continue # try opening the next one | ||
else: | ||
raise RuntimeError( | ||
f"Can not open any of the {len(bus_ids)} connected MCP2221 devices." | ||
) | ||
# cache the new instance | ||
cls.instances[self._bus_id] = self | ||
|
||
# make sure the device gets closed before exit | ||
atexit.register(self.close) | ||
if MCP2221_RESET_DELAY >= 0: | ||
|
@@ -64,6 +102,19 @@ def __init__(self): | |
for pin in range(4): | ||
self.gp_set_mode(pin, self.GP_GPIO) # set to GPIO mode | ||
self.gpio_set_direction(pin, 1) # set to INPUT | ||
return self | ||
|
||
@staticmethod | ||
def available_paths(*, require_mcps=False): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For this method I considered a few different options:
Regarding the name:
|
||
"""Return a list of paths of the currently connected MCP2221s. | ||
|
||
Raises a RuntimeError if *require_mcps* is True and there | ||
are no MCP2221 connected. | ||
""" | ||
mcps = hid.enumerate(MCP2221.VID, MCP2221.PID) | ||
if require_mcps and not mcps: | ||
raise RuntimeError("No MCP2221 detected.") | ||
return [mcp["path"] for mcp in mcps] | ||
|
||
def close(self): | ||
"""Close the hid device. Does nothing if the device is not open.""" | ||
|
@@ -132,18 +183,27 @@ def _sram_dump(self): | |
self._pretty_report(b"\x61") | ||
|
||
def _reset(self): | ||
dev_list_before_reset = MCP2221.available_paths() | ||
# pylint: disable-next=access-member-before-definition | ||
dev_list_before_reset.remove(self._bus_id) | ||
self._hid_xfer(b"\x70\xAB\xCD\xEF", response=False) | ||
self._hid.close() | ||
time.sleep(MCP2221_RESET_DELAY) | ||
|
||
start = time.monotonic() | ||
while time.monotonic() - start < 5: | ||
try: | ||
self._hid.open(MCP2221.VID, MCP2221.PID) | ||
except OSError: | ||
# try again | ||
dev_list_after_reset = MCP2221.available_paths() | ||
# The new device is the one present after reset but not before | ||
device_new_path = set(dev_list_before_reset) ^ set(dev_list_after_reset) | ||
if not device_new_path: | ||
time.sleep(0.1) | ||
continue | ||
# The set should have only a single value, get it out of the set | ||
device_new_path = next(iter(device_new_path)) | ||
self._hid.open_path(device_new_path) | ||
self._bus_id = device_new_path | ||
return | ||
|
||
raise OSError("open failed") | ||
|
||
# ---------------------------------------------------------------- | ||
|
@@ -399,4 +459,10 @@ def dac_write(self, pin, value): | |
# pylint: enable=unused-argument | ||
|
||
|
||
mcp2221 = MCP2221() | ||
def __getattr__(name): | ||
if name == "mcp2221": | ||
# someone is trying to import the module-level instance | ||
msg = "Import the MCP2221 class and create a new instance instead." | ||
warnings.warn(msg, DeprecationWarning, stacklevel=2) | ||
return MCP2221(MCP2221.available_paths()[0]) | ||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This script doesn't work for me because of this line. The paths to my devices look like
2-3.3:1.2
, whereas this will produce something like0002:0003:02
. Perhaps the example could be updated to print a list of available addresses, and prompt the user to select one.