pax_global_header00006660000000000000000000000064147124037250014517gustar00rootroot0000000000000052 comment=051f3816aea89623aaa24b6720e92442f03e2f76 usbsdmux-24.11.1/000077500000000000000000000000001471240372500135375ustar00rootroot00000000000000usbsdmux-24.11.1/.codespellrc000066400000000000000000000001251471240372500160350ustar00rootroot00000000000000[codespell] skip = ./.git,./*.egg-info,./.pybuild,./build,./env,./venv,./envs,./dist usbsdmux-24.11.1/.github/000077500000000000000000000000001471240372500150775ustar00rootroot00000000000000usbsdmux-24.11.1/.github/workflows/000077500000000000000000000000001471240372500171345ustar00rootroot00000000000000usbsdmux-24.11.1/.github/workflows/check-and-publish.yaml000066400000000000000000000040551471240372500233050ustar00rootroot00000000000000name: Check and Publish on: [push, pull_request] jobs: codespell: name: Codespell runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: make qa-codespell pytest: name: Python Test runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: make qa-pytest ruff: name: Python Format and Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: make qa-ruff build: name: Python Build runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: # include tags and full history for setuptools_scm fetch-depth: 0 - run: make build - uses: actions/upload-artifact@v4 with: name: dist path: dist publish-test: name: Publish to test.pypi.org if: ${{ github.event_name == 'push' && vars.PUBLISH_PYPI == 'true' && (startsWith(github.ref, 'refs/tags') || github.ref == 'refs/heads/master') }} runs-on: ubuntu-latest needs: - codespell - pytest - ruff - build permissions: id-token: write steps: - name: Download artifacts from build stage uses: actions/download-artifact@v4 with: name: dist path: dist/ - name: Publish distribution package to TestPyPI uses: pypa/gh-action-pypi-publish@release/v1 with: repository-url: https://test.pypi.org/legacy/ publish-production: name: Publish if: ${{ github.event_name == 'push' && vars.PUBLISH_PYPI == 'true' && startsWith(github.ref, 'refs/tags') }} runs-on: ubuntu-latest needs: - codespell - pytest - ruff - build - publish-test permissions: id-token: write steps: - name: Download artifacts from build stage uses: actions/download-artifact@v4 with: name: dist path: dist/ - name: Publish distribution package to PyPI uses: pypa/gh-action-pypi-publish@release/v1 with: attestations: false usbsdmux-24.11.1/.gitignore000066400000000000000000000001341471240372500155250ustar00rootroot00000000000000*.pyc __pycache__/ build/ dist/ *.egg-info *.venv .tox/ envs/ .idea venv/ #emacs *~ \#* .#*usbsdmux-24.11.1/COPYING000066400000000000000000000636421471240372500146050ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! usbsdmux-24.11.1/MANIFEST.in000066400000000000000000000001551471240372500152760ustar00rootroot00000000000000include COPYING graft contrib global-exclude .* global-exclude *~ global-exclude *.swp global-exclude *.pyc usbsdmux-24.11.1/Makefile000066400000000000000000000034341471240372500152030ustar00rootroot00000000000000PYTHON=python3 PYTHON_ENV_ROOT=envs PYTHON_PACKAGING_VENV=$(PYTHON_ENV_ROOT)/$(PYTHON)-packaging-env PYTHON_QA_ENV=$(PYTHON_ENV_ROOT)/$(PYTHON)-qa-env # packaging environment ####################################################### .PHONY: packaging-env build _release $(PYTHON_PACKAGING_VENV)/.created: rm -rf $(PYTHON_PACKAGING_VENV) && \ $(PYTHON) -m venv $(PYTHON_PACKAGING_VENV) && \ . $(PYTHON_PACKAGING_VENV)/bin/activate && \ $(PYTHON) -m pip install --upgrade pip && \ $(PYTHON) -m pip install build date > $(PYTHON_PACKAGING_VENV)/.created .PHONY: packaging-env build packaging-env: $(PYTHON_PACKAGING_VENV)/.created build: packaging-env . $(PYTHON_PACKAGING_VENV)/bin/activate && \ rm -rf dist *.egg-info && \ $(PYTHON) -m build # helper ###################################################################### .PHONY: clean envs clean: rm -rf $(PYTHON_ENV_ROOT) envs: packaging-env qa-env # testing ##################################################################### .PHONY: qa qa-env qa-codespell qa-pytest qa-ruff $(PYTHON_QA_ENV)/.created: rm -rf $(PYTHON_QA_ENV) && \ $(PYTHON) -m venv $(PYTHON_QA_ENV) && \ . $(PYTHON_QA_ENV)/bin/activate && \ $(PYTHON) -m pip install pip --upgrade && \ $(PYTHON) -m pip install codespell ruff pytest pytest-mock && \ date > $(PYTHON_QA_ENV)/.created qa-env: $(PYTHON_QA_ENV)/.created qa: qa-codespell qa-pytest qa-ruff qa-codespell: qa-env . $(PYTHON_QA_ENV)/bin/activate && \ codespell qa-codespell-fix: qa-env . $(PYTHON_QA_ENV)/bin/activate && \ codespell -w qa-pytest: qa-env . $(PYTHON_QA_ENV)/bin/activate && \ $(PYTHON) -m pytest -vv qa-ruff: qa-env . $(PYTHON_QA_ENV)/bin/activate && \ ruff format --check --diff && ruff check qa-ruff-fix: qa-env . $(PYTHON_QA_ENV)/bin/activate && \ ruff format && ruff check --fix usbsdmux-24.11.1/README.rst000066400000000000000000000265721471240372500152420ustar00rootroot00000000000000Welcome to usbsdmux =================== |license| |pypi| Purpose ------- This software is used to control a special piece of hardware called the `USB-SD-Mux `_. It can be used via the command line or as a Python library. The USB-SD-Mux is built around a `Microchip USB2642 `_ card reader. Thus most of this software deals with interfacing this device using Linux ioctls(). This software is aimed to be used with `Labgrid `_. But it can also be used stand-alone or in your own applications. Quickstart ---------- To get started with the ``usbsdmux`` tool you will first need to install the ``usbsdmux`` package. There are different methods to doing this: Installation from your Linux Distribution The easiest way to install the ``usbsdmux`` tool and stay somewhat up to date without having to deal with Python virtual environments. May not be available for your distribution and may be lacking in features because distributions ship older software versions. Installation via pipx from PyPi Another way to install the ``usbsdmux`` from a pre-packaged source. Always installs the latest ``usbsdmux`` release, but needs to be kept up to date manually. Also needs a re-install when your systems Python version is updated. This installation method uses ``pipx`` to automate the Python virtual environment management. Installation in a venv from PyPi This method is very similar to the ``pipx`` method, but manages the virtual environment manually instead of letting ``pipx`` manage it. Installation from Source The way to go if you can not wait to test out new features. Installation from Distribution Packages ``````````````````````````````````````` This tool is `packaged `_ in Debian 12 (aka *bookworm*) and later. The package ships the ``usbsdmux`` tool and the corresponding *udev* -rules. So you can simply ``apt install usbsdmux`` and skip all installation steps below. .. image:: https://repology.org/badge/vertical-allrepos/usbsdmux.svg :target: https://repology.org/project/usbsdmux/versions :alt: Packaging status :align: right Packages also exist for `some other distributions `_. Installation via pipx from PyPi Packages ```````````````````````````````````````` Install ``pipx`` via your Linux distributions package manager, e.g.: .. code-block:: bash $ sudo apt install pipx # For Debian based distributions $ sudo pacman -S python-pipx # For Arch Linux based distributions And follow the `pipx manual `_ on how to add ``pipx``-installed software to your ``PATH``, e.g. by using ``pipx ensurepath``. And finally install the ``usbsdmux`` package using ``pipx``: .. code-block:: bash $ pipx install usbsdmux Installation in a venv from PyPi Packages ````````````````````````````````````````` Create and activate a Python virtual environment for the ``usbsdmux`` package: .. code-block:: bash $ python3 -m venv venv $ source venv/bin/activate Install the ``usbsdmux`` package into the virtual environment: .. code-block:: bash $ python3 -m pip install usbsdmux Installation From Source ```````````````````````` To get the latest and greatest you can also install the ``usbsdmux`` package right from the git repository: .. code-block:: bash $ git clone https://github.com/linux-automation/usbsdmux.git $ cd usbsdmux $ python3 -m venv venv $ source venv/bin/activate $ python3 -m pip install . Usage ````` Once installed you can run ``usbsdmux`` command with the ``-h`` flag to get a list of possible command invocations: .. code-block:: text $ usbsdmux -h usage: usbsdmux [-h] [--config CONFIG] [--json] SG {get,dut,client,host,off,gpio,info} ... positional arguments: SG /dev/sg* to use {get,dut,client,host,off,gpio,info} Supply one of the following commands to interact with the device get Read the current state of the USB-SD-Mux dut Switch to the DUT client Switch to the DUT host Switch to the host off Disconnect from host and DUT gpio Manipulate a GPIO (open drain output only) info Show information about the SD card options: -h, --help show this help message and exit --config CONFIG Set config file location --json Format output as json. Useful for scripting. Using as root ------------- If you just want to try the USB-SD-Mux (or maybe if it is just ok for you) you can just use the ``usbsdmux`` command as root. If you have installed this tool inside a virtual environment you can just call the shell-wrapper along with the appropriate `/dev/sg*` device path: .. code-block:: bash $ sudo /path/to/venv/bin/usbsdmux /dev/sg0 dut $ sudo /path/to/venv/bin/usbsdmux /dev/sg0 host If you encounter any issues using the USB-SD-Mux at this point consider consulting the `Troubleshooting`_ section later in this README. Using as normal user / Reliable names ------------------------------------- The example udev-rule in ``contrib/udev/99-usbsdmux.rules`` serves two purposes: * Allow users currently logged into the system and users in the ``plugdev`` group [1]_ to access connected USB-SD-Muxes. * Create a reliable path in the filesystem to access specific USB-SD-Muxes based on their pre-programmed unique serial number. This is useful when multiple USB-SD-Muxes are connect to a system, as the enumeration-order, and thus the ``/dev/sg*`` numbering, may differ between reboots. The serial number is printed on a label attached to the device. Users of a Debian based distribution [1]_ can install the udev rule by cloning this repository and copying it to the appropriate location and reloading the active udev rules: .. code-block:: bash $ git clone "https://github.com/linux-automation/usbsdmux.git" $ sudo cp usbsdmux/contrib/udev/99-usbsdmux.rules /etc/udev/rules.d/ $ sudo udevadm control --reload-rules After reattaching the USB-SD-Mux you should get a list of connected USB-SD-Muxes, based on their unique serial numbers, by listing the contents of the ``/dev/usb-sd-mux/`` directory: .. code-block:: bash $ ls -l /dev/usb-sd-mux/ total 0 lrwxrwxrwx 1 root plugdev 6 Mar 31 11:21 id-000000000042 -> ../sg3 lrwxrwxrwx 1 root plugdev 6 Mar 27 00:33 id-000000000078 -> ../sg2 lrwxrwxrwx 1 root plugdev 6 Mar 24 09:51 id-000000000378 -> ../sg1 .. [1] The ``plugdev`` group is used in Debian and Debian based distributions (like Ubuntu and Linux Mint) to grant access to pluggable gadgets. Depending on your Linux distribution you may want to create/use another group for this purpose and adapt the ``udev`` rule accordingly. How it works ------------ High-Level Functions ```````````````````` The ``usbsdmux`` package provides the the following features: * Muxing the SD-Card to either the DUT, Host or disconnecting it altogether via the ``usbsdmux`` command. * Writing the Configuration-EEPROM of the USB2642 from the command line to customize the representation of the USB device via the ``usbsdmux-configure`` command. Low-Level Functions ``````````````````` Under the hood this tool provides interfaces to access the following features of the Microchip USB2642: * Accessing the auxiliary I2C bus with write and write-read transactions with up to 512 bytes of payload using a simple Python interface. * Writing an I2C Configuration-EEPROM on the configuration I2C. This is done using an undocumented command that was reverse-engineered from Microchip's freely available EOL-Tools. MQTT Statistics --------------- This tool can be configured to send certain statistics to a MQTT broker. To use this feature the `usbsdmux` util has to be installed with some additional dependencies: .. code-block:: bash $ python3 -m venv venv $ source venv/bin/activate $ python3 -m pip install "usbsdmux[mqtt]" To enable this feature create a config file at ``/etc/usbsdmux.config`` or use ``--config`` to specify a file location. See the example config file `usbsdmux.config `_ for available configuration options. Troubleshooting --------------- * Some single board computers, especially Raspberry Pi model 4s, do not work with new/fast micro SD cards, due to drive strength issues at high frequencies. Use old and slow micro SD cards with these devices. Another workaround is the replacement of resistors ``R101`` and ``R102`` with 0Ω parts. This modifications does however void the EMC compliance statement provided by the Linux Automation GmbH. * Some usecases, like hard to reach connectors or full-size SD cards, necessitate the use of adapters or extension cables, leading to the same drive strength issues and require the same workarounds as documented above. * In order for the ``/dev/sg*`` device to appear the ``sg`` kernel module needs to be loaded into the kernel. This is usually done automatically by ``udev`` once the USB-SD-Mux is connected. To manually load the kernel module run ``sudo modprobe sg``. .. |license| image:: https://img.shields.io/badge/license-LGPLv2.1-blue.svg :alt: LGPLv2.1 :target: https://raw.githubusercontent.com/linux-automation/usbsdmux/master/COPYING .. |pypi| image:: https://img.shields.io/pypi/v/usbsdmux.svg :alt: pypi.org :target: https://pypi.org/project/usbsdmux Contributing ------------ Thank you for considering a contribution to this project! Changes should be submitted via a `Github pull request `_. This project uses the `Developer's Certificate of Origin 1.1 `_ with the same `process `_ as used for the Linux kernel: Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. Then you just add a line (using ``git commit -s``) saying: Signed-off-by: Random J Developer using a known identity (sorry, no anonymous contributions). usbsdmux-24.11.1/contrib/000077500000000000000000000000001471240372500151775ustar00rootroot00000000000000usbsdmux-24.11.1/contrib/udev/000077500000000000000000000000001471240372500161425ustar00rootroot00000000000000usbsdmux-24.11.1/contrib/udev/99-usbsdmux.rules000066400000000000000000000006471471240372500213360ustar00rootroot00000000000000# USB-SD-Mux ACTION=="add", SUBSYSTEM=="scsi_generic", KERNEL=="sg[0-9]*", ATTRS{manufacturer}=="Pengutronix", ATTRS{product}=="usb-sd-mux*", SYMLINK="usb-sd-mux/id-$attr{serial}", TAG+="uaccess", GROUP="plugdev" ACTION=="add", SUBSYSTEM=="scsi_generic", KERNEL=="sg[0-9]*", ATTRS{manufacturer}=="Linux Automation GmbH", ATTRS{product}=="usb-sd-mux*", SYMLINK="usb-sd-mux/id-$attr{serial}", TAG+="uaccess", GROUP="plugdev" usbsdmux-24.11.1/contrib/usbsdmux.config000066400000000000000000000002231471240372500202350ustar00rootroot00000000000000# /etc/usbsdmux.config [mqtt] server = localhost port = 1883 topic = usbsdmux # username = fixme # password = fixme [send] host = True dut = Trueusbsdmux-24.11.1/pyproject.toml000066400000000000000000000023031471240372500164510ustar00rootroot00000000000000[build-system] requires = ["setuptools", "setuptools_scm[toml]"] build-backend = "setuptools.build_meta" [project] name = "usbsdmux" description = "Tool to control an USB-SD-Mux from the command line" authors = [ { name = "Chris Fiege", email = "python@pengutronix.de" }, ] readme = "README.rst" license = { "text" = "LGPL-2.1-or-later" } dependencies = [] classifiers = [ "Environment :: Console", "Natural Language :: English", "Operating System :: Unix", "Programming Language :: Python :: 3 :: Only", ] dynamic = ["version"] # via setuptools_scm [project.optional-dependencies] mqtt = ["paho-mqtt"] [project.urls] homepage="https://github.com/linux-automation/usbsdmux" documentation="https://www.linux-automation.com/usbsdmux-M01/" [project.scripts] usbsdmux = "usbsdmux.__main__:main" usbsdmux-configure = "usbsdmux.usb2642eeprom:main" [tool.setuptools] packages = [ "usbsdmux", ] include-package-data = true [tool.setuptools_scm] local_scheme = "no-local-version" [tool.ruff] line-length = 119 exclude = [ "__pycache__", "usbsdmux.egg-info", ".pybuild", "build", "debian", "env", "venv", "envs", "dist", ] [tool.ruff.lint] select = ["B", "E", "F", "I", "SIM", "UP"] usbsdmux-24.11.1/tests/000077500000000000000000000000001471240372500147015ustar00rootroot00000000000000usbsdmux-24.11.1/tests/reference/000077500000000000000000000000001471240372500166375ustar00rootroot00000000000000usbsdmux-24.11.1/tests/reference/02544d53413034471027b7748500bc00.json000066400000000000000000000200211471240372500232510ustar00rootroot00000000000000{ "scr": { "reg": "SCR", "raw": "0235800001000000", "fields": [ { "field": "SCR_STRUCTURE", "name": "SCR Structure", "raw": [ 0, 4 ], "enum": "1.0" }, { "field": "SD_SPEC", "name": "SD Memory Card - Spec. Version", "raw": [ 2, 4 ], "enum": "2.00 or 3.0X" }, { "field": "DATA_STAT_AFTER_ERASE", "name": "data status after erase", "raw": [ 0, 1 ], "value": "False" }, { "field": "SD_SECURITY", "name": "CPRM Security Support", "raw": [ 3, 3 ], "enum": "SDHC Card (Security Version 2.00)" }, { "field": "SD_BUS_WIDTHS", "name": "DAT Bus widths supported", "raw": [ 5, 4 ], "bits": [ "1 bit", "4 bit" ] }, { "field": "SD_SPEC3", "name": "Spec. Version 3.00 or higher", "raw": [ 1, 1 ] }, { "field": "EX_SECURITY", "name": "Extended Security Support", "raw": [ 0, 4 ] }, { "field": "RESERVED", "raw": [ 0, 9 ] }, { "field": "CMD_SUPPORT", "name": "Command Support bits", "raw": [ 0, 2 ], "bits": [] }, { "field": "RESERVED_MFG", "raw": [ 16777216, 32 ] } ], "computed": {} }, "cid": { "reg": "CID", "raw": "02544d53413034471027b7748500bc00", "fields": [ { "field": "MID", "name": "Manufacturer ID", "raw": [ 2, 8 ], "enum": "SanDisk" }, { "field": "OID", "name": "OEM/Application ID", "raw": [ 21581, 16 ], "value": "TM" }, { "field": "PNM", "name": "Product name", "raw": [ 357575963719, 40 ], "value": "SA04G" }, { "field": "PRV", "name": "Product revision", "raw": [ 16, 8 ], "value": "1.0" }, { "field": "PSN", "name": "Product serial number", "raw": [ 666334341, 32 ], "value": "666334341" }, { "field": "RESERVED", "raw": [ 0, 4 ] }, { "field": "MDT_Y", "name": "Manufacturing date (year)", "raw": [ 11, 8 ], "value": "2011" }, { "field": "MDT_M", "name": "Manufacturing date (month)", "raw": [ 12, 4 ], "value": "13" }, { "field": "CRC", "name": "CRC7 checksum", "raw": [ 0, 7 ] }, { "field": "NU1", "name": "not used, always 1", "raw": [ 0, 1 ] } ], "computed": {} }, "csd": { "reg": "CSD_20", "raw": "400e00325b5900001d177f800a400000", "fields": [ { "field": "CSD_STRUCTURE", "name": "CSD structure", "raw": [ 1, 2 ], "enum": "2.0" }, { "field": "TAAC", "name": "data read access-time-1", "raw": [ 14, 8 ], "decoded": [ 1.0, "1ms" ], "value": 1000000.0, "unit": "ns" }, { "field": "NSAC", "name": "data read access-time-2", "raw": [ 0, 8 ], "value": "0", "unit": "CLK cycles" }, { "field": "TRAN_SPEED", "name": "max. data transfer rate", "raw": [ 50, 8 ], "decoded": [ 2.5, "10Mbit/s" ], "value": 25000000.0, "unit": "bit/s" }, { "field": "CCC", "name": "card command classes", "raw": [ 1461, 12 ], "bits": [ "0", "2", "4", "5", "7", "8", "10" ] }, { "field": "READ_BL_LEN", "name": "max. read data block length", "raw": [ 9, 4 ], "value": "512", "unit": "bytes" }, { "field": "READ_BL_PARTIAL", "name": "partial blocks for read allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "WRITE_BLK_MISALIGN", "name": "write block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "READ_BLK_MISALIGN", "name": "read block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "DSR_IMP", "name": "driver stage register implemented", "raw": [ 0, 1 ], "value": "False" }, { "field": "C_SIZE", "name": "device size", "raw": [ 7447, 22 ], "value": "3904897024", "unit": "bytes" }, { "field": "ERASE_BLK_EN", "name": "erase single block enable", "raw": [ 1, 1 ], "value": "True" }, { "field": "SECTOR_SIZE", "name": "erase sector size", "raw": [ 127, 7 ], "value": "128", "unit": "write blocks" }, { "field": "WP_GRP_SIZE", "name": "write protect group size", "raw": [ 0, 7 ], "value": "1", "unit": "erase sectors" }, { "field": "WP_GRP_ENABLE", "name": "write protect group enable", "raw": [ 0, 1 ], "value": "False" }, { "field": "R2W_FACTOR", "name": "write speed factor", "raw": [ 2, 3 ], "value": "4", "unit": "multiples of read access time" }, { "field": "WRITE_BL_LEN", "name": "max. write data block length", "raw": [ 9, 4 ], "value": "512", "unit": "bytes" }, { "field": "WRITE_BL_PARTIAL", "name": "partial blocks for write allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT_GRP", "name": "file format group", "raw": [ 0, 1 ] }, { "field": "COPY", "name": "copy flag", "raw": [ 0, 1 ], "value": "False" }, { "field": "PERM_WRITE_PROTECT", "name": "permanent write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "TMP_WRITE_PROTECT", "name": "temporary write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT", "name": "file format", "raw": [ 0, 3 ], "enum": "Hard disk-like file system with partition table" }, { "field": "CRC", "raw": [ 0, 7 ] } ], "computed": { "sector_size_bytes": { "value": 65536, "unit": "bytes", "name": "sector size" }, "wp_grp_size_bytes": { "value": 65536, "unit": "bytes", "name": "write protect group size" } } } } usbsdmux-24.11.1/tests/reference/02544d53413034471027b7748500bc00.text000066400000000000000000000074711471240372500233020ustar00rootroot00000000000000CSD_20 Register Value: 400e00325b5900001d177f800a400000 CSD_STRUCTURE: CSD structure raw: 0b01 == 0x1 == 1 enum: 2.0 TAAC: data read access-time-1 raw: 0b00001110 == 0xe == 14 decoded: (1.0, '1ms') value: 1000000.0 ns NSAC: data read access-time-2 raw: 0b00000000 == 0x0 == 0 value: 0 CLK cycles TRAN_SPEED: max. data transfer rate raw: 0b00110010 == 0x32 == 50 decoded: (2.5, '10Mbit/s') value: 25000000.0 bit/s CCC: card command classes raw: 0b010110110101 == 0x5b5 == 1461 bits: 0, 2, 4, 5, 7, 8, 10 READ_BL_LEN: max. read data block length raw: 0b1001 == 0x9 == 9 value: 512 bytes READ_BL_PARTIAL: partial blocks for read allowed raw: 0b0 == 0x0 == 0 value: False WRITE_BLK_MISALIGN: write block misalignment allowed raw: 0b0 == 0x0 == 0 value: False READ_BLK_MISALIGN: read block misalignment allowed raw: 0b0 == 0x0 == 0 value: False DSR_IMP: driver stage register implemented raw: 0b0 == 0x0 == 0 value: False C_SIZE: device size raw: 0b0000000001110100010111 == 0x1d17 == 7447 value: 3904897024 bytes ERASE_BLK_EN: erase single block enable raw: 0b1 == 0x1 == 1 value: True SECTOR_SIZE: erase sector size raw: 0b1111111 == 0x7f == 127 value: 128 write blocks WP_GRP_SIZE: write protect group size raw: 0b0000000 == 0x0 == 0 value: 1 erase sectors WP_GRP_ENABLE: write protect group enable raw: 0b0 == 0x0 == 0 value: False R2W_FACTOR: write speed factor raw: 0b010 == 0x2 == 2 value: 4 multiples of read access time WRITE_BL_LEN: max. write data block length raw: 0b1001 == 0x9 == 9 value: 512 bytes WRITE_BL_PARTIAL: partial blocks for write allowed raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT_GRP: file format group raw: 0b0 == 0x0 == 0 COPY: copy flag raw: 0b0 == 0x0 == 0 value: False PERM_WRITE_PROTECT: permanent write protection raw: 0b0 == 0x0 == 0 value: False TMP_WRITE_PROTECT: temporary write protection raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT: file format raw: 0b000 == 0x0 == 0 enum: Hard disk-like file system with partition table CRC raw: 0b0000000 == 0x0 == 0 SCR Register Value: 0235800001000000 SCR_STRUCTURE: SCR Structure raw: 0b0000 == 0x0 == 0 enum: 1.0 SD_SPEC: SD Memory Card - Spec. Version raw: 0b0010 == 0x2 == 2 enum: 2.00 or 3.0X DATA_STAT_AFTER_ERASE: data status after erase raw: 0b0 == 0x0 == 0 value: False SD_SECURITY: CPRM Security Support raw: 0b011 == 0x3 == 3 enum: SDHC Card (Security Version 2.00) SD_BUS_WIDTHS: DAT Bus widths supported raw: 0b0101 == 0x5 == 5 bits: 1 bit, 4 bit SD_SPEC3: Spec. Version 3.00 or higher raw: 0b1 == 0x1 == 1 EX_SECURITY: Extended Security Support raw: 0b0000 == 0x0 == 0 RESERVED raw: 0b000000000 == 0x0 == 0 CMD_SUPPORT: Command Support bits raw: 0b00 == 0x0 == 0 bits: RESERVED_MFG raw: 0b00000001000000000000000000000000 == 0x1000000 == 16777216 CID Register Value: 02544d53413034471027b7748500bc00 MID: Manufacturer ID raw: 0b00000010 == 0x2 == 2 enum: SanDisk OID: OEM/Application ID raw: 0b0101010001001101 == 0x544d == 21581 value: TM PNM: Product name raw: 0b0101001101000001001100000011010001000111 == 0x5341303447 == 357575963719 value: SA04G PRV: Product revision raw: 0b00010000 == 0x10 == 16 value: 1.0 PSN: Product serial number raw: 0b00100111101101110111010010000101 == 0x27b77485 == 666334341 value: 666334341 RESERVED raw: 0b0000 == 0x0 == 0 MDT_Y: Manufacturing date (year) raw: 0b00001011 == 0xb == 11 value: 2011 MDT_M: Manufacturing date (month) raw: 0b1100 == 0xc == 12 value: 13 CRC: CRC7 checksum raw: 0b0000000 == 0x0 == 0 NU1: not used, always 1 raw: 0b0 == 0x0 == 0 usbsdmux-24.11.1/tests/reference/1b534d474638533530d8466363a16700.json000066400000000000000000000201611471240372500233060ustar00rootroot00000000000000{ "scr": { "reg": "SCR", "raw": "0205848700000000", "fields": [ { "field": "SCR_STRUCTURE", "name": "SCR Structure", "raw": [ 0, 4 ], "enum": "1.0" }, { "field": "SD_SPEC", "name": "SD Memory Card - Spec. Version", "raw": [ 2, 4 ], "enum": "2.00 or 3.0X" }, { "field": "DATA_STAT_AFTER_ERASE", "name": "data status after erase", "raw": [ 0, 1 ], "value": "False" }, { "field": "SD_SECURITY", "name": "CPRM Security Support", "raw": [ 0, 3 ], "enum": "No Security" }, { "field": "SD_BUS_WIDTHS", "name": "DAT Bus widths supported", "raw": [ 5, 4 ], "bits": [ "1 bit", "4 bit" ] }, { "field": "SD_SPEC3", "name": "Spec. Version 3.00 or higher", "raw": [ 1, 1 ] }, { "field": "EX_SECURITY", "name": "Extended Security Support", "raw": [ 0, 4 ] }, { "field": "RESERVED", "raw": [ 289, 9 ] }, { "field": "CMD_SUPPORT", "name": "Command Support bits", "raw": [ 3, 2 ], "bits": [ "Speed Class Control (CMD20)", "Set Block Count (CMD23)" ] }, { "field": "RESERVED_MFG", "raw": [ 0, 32 ] } ], "computed": {} }, "cid": { "reg": "CID", "raw": "1b534d474638533530d8466363a16700", "fields": [ { "field": "MID", "name": "Manufacturer ID", "raw": [ 27, 8 ], "enum": "Samsung" }, { "field": "OID", "name": "OEM/Application ID", "raw": [ 21325, 16 ], "value": "SM" }, { "field": "PNM", "name": "Product name", "raw": [ 306120774453, 40 ], "value": "GF8S5" }, { "field": "PRV", "name": "Product revision", "raw": [ 48, 8 ], "value": "3.0" }, { "field": "PSN", "name": "Product serial number", "raw": [ 3628491619, 32 ], "value": "3628491619" }, { "field": "RESERVED", "raw": [ 10, 4 ] }, { "field": "MDT_Y", "name": "Manufacturing date (year)", "raw": [ 22, 8 ], "value": "2022" }, { "field": "MDT_M", "name": "Manufacturing date (month)", "raw": [ 7, 4 ], "value": "8" }, { "field": "CRC", "name": "CRC7 checksum", "raw": [ 0, 7 ] }, { "field": "NU1", "name": "not used, always 1", "raw": [ 0, 1 ] } ], "computed": {} }, "csd": { "reg": "CSD_20", "raw": "400e0032db79000eebff7f800a400000", "fields": [ { "field": "CSD_STRUCTURE", "name": "CSD structure", "raw": [ 1, 2 ], "enum": "2.0" }, { "field": "TAAC", "name": "data read access-time-1", "raw": [ 14, 8 ], "decoded": [ 1.0, "1ms" ], "value": 1000000.0, "unit": "ns" }, { "field": "NSAC", "name": "data read access-time-2", "raw": [ 0, 8 ], "value": "0", "unit": "CLK cycles" }, { "field": "TRAN_SPEED", "name": "max. data transfer rate", "raw": [ 50, 8 ], "decoded": [ 2.5, "10Mbit/s" ], "value": 25000000.0, "unit": "bit/s" }, { "field": "CCC", "name": "card command classes", "raw": [ 3511, 12 ], "bits": [ "0", "1", "2", "4", "5", "7", "8", "10", "11" ] }, { "field": "READ_BL_LEN", "name": "max. read data block length", "raw": [ 9, 4 ], "value": "512", "unit": "bytes" }, { "field": "READ_BL_PARTIAL", "name": "partial blocks for read allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "WRITE_BLK_MISALIGN", "name": "write block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "READ_BLK_MISALIGN", "name": "read block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "DSR_IMP", "name": "driver stage register implemented", "raw": [ 0, 1 ], "value": "False" }, { "field": "C_SIZE", "name": "device size", "raw": [ 977919, 22 ], "value": "512711720960", "unit": "bytes" }, { "field": "ERASE_BLK_EN", "name": "erase single block enable", "raw": [ 1, 1 ], "value": "True" }, { "field": "SECTOR_SIZE", "name": "erase sector size", "raw": [ 127, 7 ], "value": "128", "unit": "write blocks" }, { "field": "WP_GRP_SIZE", "name": "write protect group size", "raw": [ 0, 7 ], "value": "1", "unit": "erase sectors" }, { "field": "WP_GRP_ENABLE", "name": "write protect group enable", "raw": [ 0, 1 ], "value": "False" }, { "field": "R2W_FACTOR", "name": "write speed factor", "raw": [ 2, 3 ], "value": "4", "unit": "multiples of read access time" }, { "field": "WRITE_BL_LEN", "name": "max. write data block length", "raw": [ 9, 4 ], "value": "512", "unit": "bytes" }, { "field": "WRITE_BL_PARTIAL", "name": "partial blocks for write allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT_GRP", "name": "file format group", "raw": [ 0, 1 ] }, { "field": "COPY", "name": "copy flag", "raw": [ 0, 1 ], "value": "False" }, { "field": "PERM_WRITE_PROTECT", "name": "permanent write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "TMP_WRITE_PROTECT", "name": "temporary write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT", "name": "file format", "raw": [ 0, 3 ], "enum": "Hard disk-like file system with partition table" }, { "field": "CRC", "raw": [ 0, 7 ] } ], "computed": { "sector_size_bytes": { "value": 65536, "unit": "bytes", "name": "sector size" }, "wp_grp_size_bytes": { "value": 65536, "unit": "bytes", "name": "write protect group size" } } } } usbsdmux-24.11.1/tests/reference/1b534d474638533530d8466363a16700.text000066400000000000000000000075361471240372500233340ustar00rootroot00000000000000CSD_20 Register Value: 400e0032db79000eebff7f800a400000 CSD_STRUCTURE: CSD structure raw: 0b01 == 0x1 == 1 enum: 2.0 TAAC: data read access-time-1 raw: 0b00001110 == 0xe == 14 decoded: (1.0, '1ms') value: 1000000.0 ns NSAC: data read access-time-2 raw: 0b00000000 == 0x0 == 0 value: 0 CLK cycles TRAN_SPEED: max. data transfer rate raw: 0b00110010 == 0x32 == 50 decoded: (2.5, '10Mbit/s') value: 25000000.0 bit/s CCC: card command classes raw: 0b110110110111 == 0xdb7 == 3511 bits: 0, 1, 2, 4, 5, 7, 8, 10, 11 READ_BL_LEN: max. read data block length raw: 0b1001 == 0x9 == 9 value: 512 bytes READ_BL_PARTIAL: partial blocks for read allowed raw: 0b0 == 0x0 == 0 value: False WRITE_BLK_MISALIGN: write block misalignment allowed raw: 0b0 == 0x0 == 0 value: False READ_BLK_MISALIGN: read block misalignment allowed raw: 0b0 == 0x0 == 0 value: False DSR_IMP: driver stage register implemented raw: 0b0 == 0x0 == 0 value: False C_SIZE: device size raw: 0b0011101110101111111111 == 0xeebff == 977919 value: 512711720960 bytes ERASE_BLK_EN: erase single block enable raw: 0b1 == 0x1 == 1 value: True SECTOR_SIZE: erase sector size raw: 0b1111111 == 0x7f == 127 value: 128 write blocks WP_GRP_SIZE: write protect group size raw: 0b0000000 == 0x0 == 0 value: 1 erase sectors WP_GRP_ENABLE: write protect group enable raw: 0b0 == 0x0 == 0 value: False R2W_FACTOR: write speed factor raw: 0b010 == 0x2 == 2 value: 4 multiples of read access time WRITE_BL_LEN: max. write data block length raw: 0b1001 == 0x9 == 9 value: 512 bytes WRITE_BL_PARTIAL: partial blocks for write allowed raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT_GRP: file format group raw: 0b0 == 0x0 == 0 COPY: copy flag raw: 0b0 == 0x0 == 0 value: False PERM_WRITE_PROTECT: permanent write protection raw: 0b0 == 0x0 == 0 value: False TMP_WRITE_PROTECT: temporary write protection raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT: file format raw: 0b000 == 0x0 == 0 enum: Hard disk-like file system with partition table CRC raw: 0b0000000 == 0x0 == 0 SCR Register Value: 0205848700000000 SCR_STRUCTURE: SCR Structure raw: 0b0000 == 0x0 == 0 enum: 1.0 SD_SPEC: SD Memory Card - Spec. Version raw: 0b0010 == 0x2 == 2 enum: 2.00 or 3.0X DATA_STAT_AFTER_ERASE: data status after erase raw: 0b0 == 0x0 == 0 value: False SD_SECURITY: CPRM Security Support raw: 0b000 == 0x0 == 0 enum: No Security SD_BUS_WIDTHS: DAT Bus widths supported raw: 0b0101 == 0x5 == 5 bits: 1 bit, 4 bit SD_SPEC3: Spec. Version 3.00 or higher raw: 0b1 == 0x1 == 1 EX_SECURITY: Extended Security Support raw: 0b0000 == 0x0 == 0 RESERVED raw: 0b100100001 == 0x121 == 289 CMD_SUPPORT: Command Support bits raw: 0b11 == 0x3 == 3 bits: Speed Class Control (CMD20), Set Block Count (CMD23) RESERVED_MFG raw: 0b00000000000000000000000000000000 == 0x0 == 0 CID Register Value: 1b534d474638533530d8466363a16700 MID: Manufacturer ID raw: 0b00011011 == 0x1b == 27 enum: Samsung OID: OEM/Application ID raw: 0b0101001101001101 == 0x534d == 21325 value: SM PNM: Product name raw: 0b0100011101000110001110000101001100110101 == 0x4746385335 == 306120774453 value: GF8S5 PRV: Product revision raw: 0b00110000 == 0x30 == 48 value: 3.0 PSN: Product serial number raw: 0b11011000010001100110001101100011 == 0xd8466363 == 3628491619 value: 3628491619 RESERVED raw: 0b1010 == 0xa == 10 MDT_Y: Manufacturing date (year) raw: 0b00010110 == 0x16 == 22 value: 2022 MDT_M: Manufacturing date (month) raw: 0b0111 == 0x7 == 7 value: 8 CRC: CRC7 checksum raw: 0b0000000 == 0x0 == 0 NU1: not used, always 1 raw: 0b0 == 0x0 == 0 usbsdmux-24.11.1/tests/reference/744a605553442020104182bbc7010600.json000066400000000000000000000220321471240372500232410ustar00rootroot00000000000000{ "scr": { "reg": "SCR", "raw": "0225800000000000", "fields": [ { "field": "SCR_STRUCTURE", "name": "SCR Structure", "raw": [ 0, 4 ], "enum": "1.0" }, { "field": "SD_SPEC", "name": "SD Memory Card - Spec. Version", "raw": [ 2, 4 ], "enum": "2.00 or 3.0X" }, { "field": "DATA_STAT_AFTER_ERASE", "name": "data status after erase", "raw": [ 0, 1 ], "value": "False" }, { "field": "SD_SECURITY", "name": "CPRM Security Support", "raw": [ 2, 3 ], "enum": "SDSC Card (Security Version 1.01)" }, { "field": "SD_BUS_WIDTHS", "name": "DAT Bus widths supported", "raw": [ 5, 4 ], "bits": [ "1 bit", "4 bit" ] }, { "field": "SD_SPEC3", "name": "Spec. Version 3.00 or higher", "raw": [ 1, 1 ] }, { "field": "EX_SECURITY", "name": "Extended Security Support", "raw": [ 0, 4 ] }, { "field": "RESERVED", "raw": [ 0, 9 ] }, { "field": "CMD_SUPPORT", "name": "Command Support bits", "raw": [ 0, 2 ], "bits": [] }, { "field": "RESERVED_MFG", "raw": [ 0, 32 ] } ], "computed": {} }, "cid": { "reg": "CID", "raw": "744a605553442020104182bbc7010600", "fields": [ { "field": "MID", "name": "Manufacturer ID", "raw": [ 116, 8 ], "enum": "Transcend" }, { "field": "OID", "name": "OEM/Application ID", "raw": [ 19040, 16 ], "value": "J`" }, { "field": "PNM", "name": "Product name", "raw": [ 366469193760, 40 ], "value": "USD " }, { "field": "PRV", "name": "Product revision", "raw": [ 16, 8 ], "value": "1.0" }, { "field": "PSN", "name": "Product serial number", "raw": [ 1099086791, 32 ], "value": "1099086791" }, { "field": "RESERVED", "raw": [ 0, 4 ] }, { "field": "MDT_Y", "name": "Manufacturing date (year)", "raw": [ 16, 8 ], "value": "2016" }, { "field": "MDT_M", "name": "Manufacturing date (month)", "raw": [ 6, 4 ], "value": "7" }, { "field": "CRC", "name": "CRC7 checksum", "raw": [ 0, 7 ] }, { "field": "NU1", "name": "not used, always 1", "raw": [ 0, 1 ] } ], "computed": {} }, "csd": { "reg": "CSD_10", "raw": "007f00325b5a83bd6db7ff800a800000", "fields": [ { "field": "CSD_STRUCTURE", "name": "CSD structure", "raw": [ 0, 2 ], "enum": "1.0" }, { "field": "TAAC", "name": "data read access-time-1", "raw": [ 127, 8 ], "decoded": [ 8.0, "10ms" ], "value": 80000000.0, "unit": "ns" }, { "field": "NSAC", "name": "data read access-time-2", "raw": [ 0, 8 ], "value": "0", "unit": "CLK cycles" }, { "field": "TRAN_SPEED", "name": "max. data transfer rate", "raw": [ 50, 8 ], "decoded": [ 2.5, "10Mbit/s" ], "value": 25000000.0, "unit": "bit/s" }, { "field": "CCC", "name": "card command classes", "raw": [ 1461, 12 ], "bits": [ "0", "2", "4", "5", "7", "8", "10" ] }, { "field": "READ_BL_LEN", "name": "max. read data block length", "raw": [ 10, 4 ], "value": "1024", "unit": "bytes" }, { "field": "READ_BL_PARTIAL", "name": "partial blocks for read allowed", "raw": [ 1, 1 ], "value": "True" }, { "field": "WRITE_BLK_MISALIGN", "name": "write block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "READ_BLK_MISALIGN", "name": "read block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "DSR_IMP", "name": "driver stage register implemented", "raw": [ 0, 1 ], "value": "False" }, { "field": "C_SIZE", "name": "device size", "raw": [ 3829, 12 ], "value": "3830" }, { "field": "VDD_R_CURR_MIN", "name": "max. read current @VDD min", "raw": [ 5, 3 ], "enum": 35, "unit": "mA" }, { "field": "VDD_R_CURR_MAX", "name": "max. read current @VDD max", "raw": [ 5, 3 ], "enum": 45, "unit": "mA" }, { "field": "VDD_W_CURR_MIN", "name": "max. write current @VDD min", "raw": [ 5, 3 ], "enum": 35, "unit": "mA" }, { "field": "VDD_W_CURR_MAX", "name": "max. write current @VDD max", "raw": [ 5, 3 ], "enum": 45, "unit": "mA" }, { "field": "C_SIZE_MULT", "name": "device size multiplier", "raw": [ 7, 3 ], "value": "512" }, { "field": "ERASE_BLK_EN", "name": "erase single block enable", "raw": [ 1, 1 ], "value": "True" }, { "field": "SECTOR_SIZE", "name": "erase sector size", "raw": [ 127, 7 ], "value": "128", "unit": "write blocks" }, { "field": "WP_GRP_SIZE", "name": "write protect group size", "raw": [ 0, 7 ], "value": "1", "unit": "erase sectors" }, { "field": "WP_GRP_ENABLE", "name": "write protect group enable", "raw": [ 0, 1 ], "value": "False" }, { "field": "R2W_FACTOR", "name": "write speed factor", "raw": [ 2, 3 ], "value": "4", "unit": "multiples of read access time" }, { "field": "WRITE_BL_LEN", "name": "max. write data block length", "raw": [ 10, 4 ], "value": "1024", "unit": "bytes" }, { "field": "WRITE_BL_PARTIAL", "name": "partial blocks for write allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT_GRP", "name": "file format group", "raw": [ 0, 1 ] }, { "field": "COPY", "name": "copy flag", "raw": [ 0, 1 ], "value": "False" }, { "field": "PERM_WRITE_PROTECT", "name": "permanent write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "TMP_WRITE_PROTECT", "name": "temporary write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT", "name": "file format", "raw": [ 0, 3 ], "enum": "Hard disk-like file system with partition table" }, { "field": "CRC", "raw": [ 0, 7 ] } ], "computed": { "sector_size_bytes": { "value": 131072, "unit": "bytes", "name": "sector size" }, "wp_grp_size_bytes": { "value": 131072, "unit": "bytes", "name": "write protect group size" }, "device_size_bytes": { "value": 2008023040, "unit": "bytes", "name": "device size" } } } } usbsdmux-24.11.1/tests/reference/744a605553442020104182bbc7010600.text000066400000000000000000000103221471240372500232530ustar00rootroot00000000000000CSD_10 Register Value: 007f00325b5a83bd6db7ff800a800000 CSD_STRUCTURE: CSD structure raw: 0b00 == 0x0 == 0 enum: 1.0 TAAC: data read access-time-1 raw: 0b01111111 == 0x7f == 127 decoded: (8.0, '10ms') value: 80000000.0 ns NSAC: data read access-time-2 raw: 0b00000000 == 0x0 == 0 value: 0 CLK cycles TRAN_SPEED: max. data transfer rate raw: 0b00110010 == 0x32 == 50 decoded: (2.5, '10Mbit/s') value: 25000000.0 bit/s CCC: card command classes raw: 0b010110110101 == 0x5b5 == 1461 bits: 0, 2, 4, 5, 7, 8, 10 READ_BL_LEN: max. read data block length raw: 0b1010 == 0xa == 10 value: 1024 bytes READ_BL_PARTIAL: partial blocks for read allowed raw: 0b1 == 0x1 == 1 value: True WRITE_BLK_MISALIGN: write block misalignment allowed raw: 0b0 == 0x0 == 0 value: False READ_BLK_MISALIGN: read block misalignment allowed raw: 0b0 == 0x0 == 0 value: False DSR_IMP: driver stage register implemented raw: 0b0 == 0x0 == 0 value: False C_SIZE: device size raw: 0b111011110101 == 0xef5 == 3829 value: 3830 VDD_R_CURR_MIN: max. read current @VDD min raw: 0b101 == 0x5 == 5 enum: 35 mA VDD_R_CURR_MAX: max. read current @VDD max raw: 0b101 == 0x5 == 5 enum: 45 mA VDD_W_CURR_MIN: max. write current @VDD min raw: 0b101 == 0x5 == 5 enum: 35 mA VDD_W_CURR_MAX: max. write current @VDD max raw: 0b101 == 0x5 == 5 enum: 45 mA C_SIZE_MULT: device size multiplier raw: 0b111 == 0x7 == 7 value: 512 ERASE_BLK_EN: erase single block enable raw: 0b1 == 0x1 == 1 value: True SECTOR_SIZE: erase sector size raw: 0b1111111 == 0x7f == 127 value: 128 write blocks WP_GRP_SIZE: write protect group size raw: 0b0000000 == 0x0 == 0 value: 1 erase sectors WP_GRP_ENABLE: write protect group enable raw: 0b0 == 0x0 == 0 value: False R2W_FACTOR: write speed factor raw: 0b010 == 0x2 == 2 value: 4 multiples of read access time WRITE_BL_LEN: max. write data block length raw: 0b1010 == 0xa == 10 value: 1024 bytes WRITE_BL_PARTIAL: partial blocks for write allowed raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT_GRP: file format group raw: 0b0 == 0x0 == 0 COPY: copy flag raw: 0b0 == 0x0 == 0 value: False PERM_WRITE_PROTECT: permanent write protection raw: 0b0 == 0x0 == 0 value: False TMP_WRITE_PROTECT: temporary write protection raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT: file format raw: 0b000 == 0x0 == 0 enum: Hard disk-like file system with partition table CRC raw: 0b0000000 == 0x0 == 0 SCR Register Value: 0225800000000000 SCR_STRUCTURE: SCR Structure raw: 0b0000 == 0x0 == 0 enum: 1.0 SD_SPEC: SD Memory Card - Spec. Version raw: 0b0010 == 0x2 == 2 enum: 2.00 or 3.0X DATA_STAT_AFTER_ERASE: data status after erase raw: 0b0 == 0x0 == 0 value: False SD_SECURITY: CPRM Security Support raw: 0b010 == 0x2 == 2 enum: SDSC Card (Security Version 1.01) SD_BUS_WIDTHS: DAT Bus widths supported raw: 0b0101 == 0x5 == 5 bits: 1 bit, 4 bit SD_SPEC3: Spec. Version 3.00 or higher raw: 0b1 == 0x1 == 1 EX_SECURITY: Extended Security Support raw: 0b0000 == 0x0 == 0 RESERVED raw: 0b000000000 == 0x0 == 0 CMD_SUPPORT: Command Support bits raw: 0b00 == 0x0 == 0 bits: RESERVED_MFG raw: 0b00000000000000000000000000000000 == 0x0 == 0 CID Register Value: 744a605553442020104182bbc7010600 MID: Manufacturer ID raw: 0b01110100 == 0x74 == 116 enum: Transcend OID: OEM/Application ID raw: 0b0100101001100000 == 0x4a60 == 19040 value: J` PNM: Product name raw: 0b0101010101010011010001000010000000100000 == 0x5553442020 == 366469193760 value: USD PRV: Product revision raw: 0b00010000 == 0x10 == 16 value: 1.0 PSN: Product serial number raw: 0b01000001100000101011101111000111 == 0x4182bbc7 == 1099086791 value: 1099086791 RESERVED raw: 0b0000 == 0x0 == 0 MDT_Y: Manufacturing date (year) raw: 0b00010000 == 0x10 == 16 value: 2016 MDT_M: Manufacturing date (month) raw: 0b0110 == 0x6 == 6 value: 7 CRC: CRC7 checksum raw: 0b0000000 == 0x0 == 0 NU1: not used, always 1 raw: 0b0 == 0x0 == 0 usbsdmux-24.11.1/tests/reference/9f5449303030303000a1114bb5011400.json000066400000000000000000000200741471240372500232270ustar00rootroot00000000000000{ "scr": { "reg": "SCR", "raw": "02b5800200000000", "fields": [ { "field": "SCR_STRUCTURE", "name": "SCR Structure", "raw": [ 0, 4 ], "enum": "1.0" }, { "field": "SD_SPEC", "name": "SD Memory Card - Spec. Version", "raw": [ 2, 4 ], "enum": "2.00 or 3.0X" }, { "field": "DATA_STAT_AFTER_ERASE", "name": "data status after erase", "raw": [ 1, 1 ], "value": "True" }, { "field": "SD_SECURITY", "name": "CPRM Security Support", "raw": [ 3, 3 ], "enum": "SDHC Card (Security Version 2.00)" }, { "field": "SD_BUS_WIDTHS", "name": "DAT Bus widths supported", "raw": [ 5, 4 ], "bits": [ "1 bit", "4 bit" ] }, { "field": "SD_SPEC3", "name": "Spec. Version 3.00 or higher", "raw": [ 1, 1 ] }, { "field": "EX_SECURITY", "name": "Extended Security Support", "raw": [ 0, 4 ] }, { "field": "RESERVED", "raw": [ 0, 9 ] }, { "field": "CMD_SUPPORT", "name": "Command Support bits", "raw": [ 2, 2 ], "bits": [ "Set Block Count (CMD23)" ] }, { "field": "RESERVED_MFG", "raw": [ 0, 32 ] } ], "computed": {} }, "cid": { "reg": "CID", "raw": "9f5449303030303000a1114bb5011400", "fields": [ { "field": "MID", "name": "Manufacturer ID", "raw": [ 159, 8 ], "enum": "Kingston SD" }, { "field": "OID", "name": "OEM/Application ID", "raw": [ 21577, 16 ], "value": "TI" }, { "field": "PNM", "name": "Product name", "raw": [ 206966894640, 40 ], "value": "00000" }, { "field": "PRV", "name": "Product revision", "raw": [ 0, 8 ], "value": "0.0" }, { "field": "PSN", "name": "Product serial number", "raw": [ 2702265269, 32 ], "value": "2702265269" }, { "field": "RESERVED", "raw": [ 0, 4 ] }, { "field": "MDT_Y", "name": "Manufacturing date (year)", "raw": [ 17, 8 ], "value": "2017" }, { "field": "MDT_M", "name": "Manufacturing date (month)", "raw": [ 4, 4 ], "value": "5" }, { "field": "CRC", "name": "CRC7 checksum", "raw": [ 0, 7 ] }, { "field": "NU1", "name": "not used, always 1", "raw": [ 0, 1 ] } ], "computed": {} }, "csd": { "reg": "CSD_20", "raw": "400e00325b5900003b877f800a400000", "fields": [ { "field": "CSD_STRUCTURE", "name": "CSD structure", "raw": [ 1, 2 ], "enum": "2.0" }, { "field": "TAAC", "name": "data read access-time-1", "raw": [ 14, 8 ], "decoded": [ 1.0, "1ms" ], "value": 1000000.0, "unit": "ns" }, { "field": "NSAC", "name": "data read access-time-2", "raw": [ 0, 8 ], "value": "0", "unit": "CLK cycles" }, { "field": "TRAN_SPEED", "name": "max. data transfer rate", "raw": [ 50, 8 ], "decoded": [ 2.5, "10Mbit/s" ], "value": 25000000.0, "unit": "bit/s" }, { "field": "CCC", "name": "card command classes", "raw": [ 1461, 12 ], "bits": [ "0", "2", "4", "5", "7", "8", "10" ] }, { "field": "READ_BL_LEN", "name": "max. read data block length", "raw": [ 9, 4 ], "value": "512", "unit": "bytes" }, { "field": "READ_BL_PARTIAL", "name": "partial blocks for read allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "WRITE_BLK_MISALIGN", "name": "write block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "READ_BLK_MISALIGN", "name": "read block misalignment allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "DSR_IMP", "name": "driver stage register implemented", "raw": [ 0, 1 ], "value": "False" }, { "field": "C_SIZE", "name": "device size", "raw": [ 15239, 22 ], "value": "7990149120", "unit": "bytes" }, { "field": "ERASE_BLK_EN", "name": "erase single block enable", "raw": [ 1, 1 ], "value": "True" }, { "field": "SECTOR_SIZE", "name": "erase sector size", "raw": [ 127, 7 ], "value": "128", "unit": "write blocks" }, { "field": "WP_GRP_SIZE", "name": "write protect group size", "raw": [ 0, 7 ], "value": "1", "unit": "erase sectors" }, { "field": "WP_GRP_ENABLE", "name": "write protect group enable", "raw": [ 0, 1 ], "value": "False" }, { "field": "R2W_FACTOR", "name": "write speed factor", "raw": [ 2, 3 ], "value": "4", "unit": "multiples of read access time" }, { "field": "WRITE_BL_LEN", "name": "max. write data block length", "raw": [ 9, 4 ], "value": "512", "unit": "bytes" }, { "field": "WRITE_BL_PARTIAL", "name": "partial blocks for write allowed", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT_GRP", "name": "file format group", "raw": [ 0, 1 ] }, { "field": "COPY", "name": "copy flag", "raw": [ 0, 1 ], "value": "False" }, { "field": "PERM_WRITE_PROTECT", "name": "permanent write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "TMP_WRITE_PROTECT", "name": "temporary write protection", "raw": [ 0, 1 ], "value": "False" }, { "field": "FILE_FORMAT", "name": "file format", "raw": [ 0, 3 ], "enum": "Hard disk-like file system with partition table" }, { "field": "CRC", "raw": [ 0, 7 ] } ], "computed": { "sector_size_bytes": { "value": 65536, "unit": "bytes", "name": "sector size" }, "wp_grp_size_bytes": { "value": 65536, "unit": "bytes", "name": "write protect group size" } } } } usbsdmux-24.11.1/tests/reference/9f5449303030303000a1114bb5011400.text000066400000000000000000000075111471240372500232430ustar00rootroot00000000000000CSD_20 Register Value: 400e00325b5900003b877f800a400000 CSD_STRUCTURE: CSD structure raw: 0b01 == 0x1 == 1 enum: 2.0 TAAC: data read access-time-1 raw: 0b00001110 == 0xe == 14 decoded: (1.0, '1ms') value: 1000000.0 ns NSAC: data read access-time-2 raw: 0b00000000 == 0x0 == 0 value: 0 CLK cycles TRAN_SPEED: max. data transfer rate raw: 0b00110010 == 0x32 == 50 decoded: (2.5, '10Mbit/s') value: 25000000.0 bit/s CCC: card command classes raw: 0b010110110101 == 0x5b5 == 1461 bits: 0, 2, 4, 5, 7, 8, 10 READ_BL_LEN: max. read data block length raw: 0b1001 == 0x9 == 9 value: 512 bytes READ_BL_PARTIAL: partial blocks for read allowed raw: 0b0 == 0x0 == 0 value: False WRITE_BLK_MISALIGN: write block misalignment allowed raw: 0b0 == 0x0 == 0 value: False READ_BLK_MISALIGN: read block misalignment allowed raw: 0b0 == 0x0 == 0 value: False DSR_IMP: driver stage register implemented raw: 0b0 == 0x0 == 0 value: False C_SIZE: device size raw: 0b0000000011101110000111 == 0x3b87 == 15239 value: 7990149120 bytes ERASE_BLK_EN: erase single block enable raw: 0b1 == 0x1 == 1 value: True SECTOR_SIZE: erase sector size raw: 0b1111111 == 0x7f == 127 value: 128 write blocks WP_GRP_SIZE: write protect group size raw: 0b0000000 == 0x0 == 0 value: 1 erase sectors WP_GRP_ENABLE: write protect group enable raw: 0b0 == 0x0 == 0 value: False R2W_FACTOR: write speed factor raw: 0b010 == 0x2 == 2 value: 4 multiples of read access time WRITE_BL_LEN: max. write data block length raw: 0b1001 == 0x9 == 9 value: 512 bytes WRITE_BL_PARTIAL: partial blocks for write allowed raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT_GRP: file format group raw: 0b0 == 0x0 == 0 COPY: copy flag raw: 0b0 == 0x0 == 0 value: False PERM_WRITE_PROTECT: permanent write protection raw: 0b0 == 0x0 == 0 value: False TMP_WRITE_PROTECT: temporary write protection raw: 0b0 == 0x0 == 0 value: False FILE_FORMAT: file format raw: 0b000 == 0x0 == 0 enum: Hard disk-like file system with partition table CRC raw: 0b0000000 == 0x0 == 0 SCR Register Value: 02b5800200000000 SCR_STRUCTURE: SCR Structure raw: 0b0000 == 0x0 == 0 enum: 1.0 SD_SPEC: SD Memory Card - Spec. Version raw: 0b0010 == 0x2 == 2 enum: 2.00 or 3.0X DATA_STAT_AFTER_ERASE: data status after erase raw: 0b1 == 0x1 == 1 value: True SD_SECURITY: CPRM Security Support raw: 0b011 == 0x3 == 3 enum: SDHC Card (Security Version 2.00) SD_BUS_WIDTHS: DAT Bus widths supported raw: 0b0101 == 0x5 == 5 bits: 1 bit, 4 bit SD_SPEC3: Spec. Version 3.00 or higher raw: 0b1 == 0x1 == 1 EX_SECURITY: Extended Security Support raw: 0b0000 == 0x0 == 0 RESERVED raw: 0b000000000 == 0x0 == 0 CMD_SUPPORT: Command Support bits raw: 0b10 == 0x2 == 2 bits: Set Block Count (CMD23) RESERVED_MFG raw: 0b00000000000000000000000000000000 == 0x0 == 0 CID Register Value: 9f5449303030303000a1114bb5011400 MID: Manufacturer ID raw: 0b10011111 == 0x9f == 159 enum: Kingston SD OID: OEM/Application ID raw: 0b0101010001001001 == 0x5449 == 21577 value: TI PNM: Product name raw: 0b0011000000110000001100000011000000110000 == 0x3030303030 == 206966894640 value: 00000 PRV: Product revision raw: 0b00000000 == 0x0 == 0 value: 0.0 PSN: Product serial number raw: 0b10100001000100010100101110110101 == 0xa1114bb5 == 2702265269 value: 2702265269 RESERVED raw: 0b0000 == 0x0 == 0 MDT_Y: Manufacturing date (year) raw: 0b00010001 == 0x11 == 17 value: 2017 MDT_M: Manufacturing date (month) raw: 0b0100 == 0x4 == 4 value: 5 CRC: CRC7 checksum raw: 0b0000000 == 0x0 == 0 NU1: not used, always 1 raw: 0b0 == 0x0 == 0 usbsdmux-24.11.1/tests/reference/regenerate.sh000077500000000000000000000005501471240372500213170ustar00rootroot00000000000000#!/bin/bash set -ex self="$(realpath "${0}")" && selfdir="$(dirname "${self}")" cd "${selfdir}" for json in *.json; do text="$(basename -s .json "${json}").text" ../../usbsdmux/sd_regs.py --json "${json}" > "${json}.tmp" ../../usbsdmux/sd_regs.py "${json}.tmp" > "${text}.tmp" mv "${json}.tmp" "${json}" mv "${text}.tmp" "${text}" done usbsdmux-24.11.1/tests/test_cli.py000066400000000000000000000034271471240372500170670ustar00rootroot00000000000000import os import pytest import usbsdmux.__main__ def test_usage(capsys, mocker): "test that the usage output include the command name" mocker.patch("sys.argv", ["usbsdmux"]) with pytest.raises(SystemExit): usbsdmux.__main__.main() captured = capsys.readouterr() assert captured.out == "" assert captured.err.startswith("usage: usbsdmux"), "Invalid help: does not start with 'usage: usbsdmux'" def test_help_in_readme(capsys, mocker): "test that the help output matches the readme" mocker.patch("sys.argv", ["usbsdmux", "-h"]) with pytest.raises(SystemExit): usbsdmux.__main__.main() captured = capsys.readouterr() assert captured.out.startswith("usage: usbsdmux"), "Invalid help: does not start with 'usage: usbsdmux'" assert captured.err == "", f"Execution of 'usbsdmux -h' failed: \n{captured.err}" readme_path = os.path.join(os.path.dirname(__file__), "../", "README.rst") readme_lines = None with open(readme_path) as readme: for line in readme.readlines(): line = line.rstrip() if line == " $ usbsdmux -h": readme_lines = [] elif readme_lines is not None: if line and not line.startswith(" "): break readme_lines.append(line) assert readme_lines is not None, "Bash command not found. Did you include ' $ usbsdmux -h'?" assert readme_lines, "No output lines found. Did you indent the output correctly?" # remove trailing empty lines while readme_lines and not readme_lines[-1]: readme_lines.pop() output_lines = [f" {line}".rstrip() for line in captured.out.splitlines()] assert output_lines == readme_lines, "Output of 'usbsdmux -h' does not match output in README.rst" usbsdmux-24.11.1/tests/test_sd_regs.py000066400000000000000000000026121471240372500177410ustar00rootroot00000000000000import json import os.path import pytest from usbsdmux.sd_regs import CID, SCR, decode_csd REFS = [ "02544d53413034471027b7748500bc00", "1b534d474638533530d8466363a16700", "744a605553442020104182bbc7010600", "9f5449303030303000a1114bb5011400", ] @pytest.mark.parametrize("cid", REFS) def test_decode(cid): ref_name = os.path.join(os.path.dirname(__file__), "reference", f"{cid}.json") with open(ref_name) as ref_file: ref = json.load(ref_file) res = {} res["scr"] = SCR(ref["scr"]["raw"]).decode() res["cid"] = CID(ref["cid"]["raw"]).decode() res["csd"] = decode_csd(ref["csd"]["raw"]).decode() # get rid of json differences, like [] -> () res = json.loads(json.dumps(res)) assert res == ref @pytest.mark.parametrize("cid", REFS) def test_to_text(cid): ref_name_json = os.path.join(os.path.dirname(__file__), "reference", f"{cid}.json") ref_name_text = os.path.join(os.path.dirname(__file__), "reference", f"{cid}.text") with open(ref_name_json) as ref_file_json: ref_json = json.load(ref_file_json) with open(ref_name_text) as ref_file_text: ref_text = ref_file_text.read().split("\n")[:-1] res = [] res += decode_csd(ref_json["csd"]["raw"]).get_text_report() res += SCR(ref_json["scr"]["raw"]).get_text_report() res += CID(ref_json["cid"]["raw"]).get_text_report() assert res == ref_text usbsdmux-24.11.1/usbsdmux/000077500000000000000000000000001471240372500154115ustar00rootroot00000000000000usbsdmux-24.11.1/usbsdmux/__init__.py000066400000000000000000000000001471240372500175100ustar00rootroot00000000000000usbsdmux-24.11.1/usbsdmux/__main__.py000077500000000000000000000123331471240372500175100ustar00rootroot00000000000000#! /usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2017 Pengutronix, Chris Fiege # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import argparse import errno import json import sys from .mqtthelper import Config, publish_info from .sd_regs import decoded_to_text from .usbsdmux import NotInHostModeException, UnknownUsbSdMuxRevisionException, autoselect_driver def main(): parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("sg", metavar="SG", help="/dev/sg* to use") parser.add_argument("--config", help="Set config file location", default=None) format_parser = parser.add_mutually_exclusive_group() format_parser.add_argument("--json", help="Format output as json. Useful for scripting.", action="store_true") subparsers = parser.add_subparsers(help="Supply one of the following commands to interact with the device") subparsers.required = True subparsers.dest = "mode" subparsers.add_parser("get", help="Read the current state of the USB-SD-Mux") subparsers.add_parser("dut", help="Switch to the DUT") subparsers.add_parser("client", help="Switch to the DUT") subparsers.add_parser("host", help="Switch to the host") subparsers.add_parser("off", help="Disconnect from host and DUT") parser_gpio = subparsers.add_parser("gpio", help="Manipulate a GPIO (open drain output only)") parser_gpio.add_argument("gpio", help="The GPIO to change", choices=[0, 1], type=int) parser_gpio.add_argument("action", help="What to do with the GPIO", choices=["low", "0", "high", "1", "get"]) subparsers.add_parser("info", help="Show information about the SD card") args = parser.parse_args() config = Config(args.config) try: ctl = autoselect_driver(args.sg) except UnknownUsbSdMuxRevisionException as e: error_msg = str(e) + "\n" + f"Does {args.sg} really point to a USB-SD-Mux?" if args.json: print(json.dumps({"error-message": error_msg})) else: print(error_msg, file=sys.stderr) sys.exit(1) mode = args.mode error_msg = None try: if mode == "off": ctl.mode_disconnect() if args.json: print(json.dumps({})) elif mode in ("dut", "client"): publish_info(ctl, config, args.sg, "client") ctl.mode_DUT() if args.json: print(json.dumps({})) elif mode == "host": ctl.mode_host() if args.json: print(json.dumps({})) publish_info(ctl, config, args.sg, "host") elif mode == "get": if args.json: print(json.dumps({"switch-state": ctl.get_mode()})) else: print(ctl.get_mode()) elif mode == "gpio": if args.action == "get": if args.json: print(json.dumps({"gpio-state": {"gpio": args.gpio, "state:": ctl.gpio_get(args.gpio)}})) else: print(ctl.gpio_get(args.gpio)) elif args.action in ["0", "low"]: ctl.gpio_set_low(args.gpio) if args.json: print(json.dumps({})) elif args.action in ["1", "high"]: ctl.gpio_set_high(args.gpio) if args.json: print(json.dumps({})) elif mode == "info": info = ctl.get_card_info() if args.json: print(json.dumps(info, indent=2)) else: print("\n".join(decoded_to_text(info["scr"]))) print("\n".join(decoded_to_text(info["cid"]))) print("\n".join(decoded_to_text(info["csd"]))) except FileNotFoundError as fnfe: error_msg = str(fnfe) except PermissionError as perr: error_msg = str(perr) except OSError as ose: if ose.errno == errno.ENOTTY: # ENOTTY is raised when an error occurred when calling an ioctl error_msg = ose + "\n" + f"Does '{args.sg}' really point to a USB-SD-Mux?" else: raise ose except NotInHostModeException: error_msg = "Card information is only available in host mode." except NotImplementedError: error_msg = "This USB-SD-Mux does not support GPIOs." if error_msg: if args.json: print(json.dumps({"error-message": error_msg})) else: print(error_msg, file=sys.stderr) sys.exit(1) if __name__ == "__main__": main() usbsdmux-24.11.1/usbsdmux/ctypehelper.py000066400000000000000000000103451471240372500203120ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2017 Pengutronix, Chris Fiege # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import ctypes import string """ This module contains functions related to packing data into ctype arrays in special ways as needed by the Microchip USB2642. """ def string_to_uint8_array(str, array_length, c_string=False, padding=0xFF, encoding="UTF-16"): """ Converts a python-string into a ctypes.c_uint8 array of a given length. The str will be encoded with the given encoding before converting. If c_string is True the string will be terminated with 0x00. str will be padded with padding if the buffer is longer than the str. str will be cropped if the buffer is shorter. Arguments: str -- python string array_length -- length of the resulting array in bytes. c_string -- Switch to treat a str as c-string. String will be terminated with 0x00 padding -- This value will be used to pad buffer to the given length. """ # Preparing output array byte_buf = (ctypes.c_uint8 * array_length)() for i in range(array_length): byte_buf[i] = padding # Determine number of bytes to copy nbytes = str.encode(encoding) length = array_length - 1 if c_string else array_length count = min(len(nbytes), length) # Do the actual copy for i in range(count): byte_buf[i] = int(nbytes[i]) # Make string a c-string if c_string: i += 1 byte_buf[i] = 0x00 return byte_buf def string_to_microchip_unicode_uint8_array(text, array_length, constant=0x03): """ Converts a String to a USB2642 UTF-16 string. The USB2642 requires the first two bytes of the string to be <0x03>. This function first creates a UTF-16 string and then replaces the byte-order mark with this information. Arguments: text -- Text to copy into the array constant -- The constant byte placed into the 2nd byte """ byte_buf = string_to_uint8_array(text, array_length) byte_buf[0] = len(text) * 2 + 2 byte_buf[1] = constant return byte_buf def list_to_uint8_array(numbers, array_length): """ Converts a list of numbers into a ctypes.c_uint8 array of a given length. If numbers is too short for array_length it will be padded with 0x00. If numbers is too long it will be cropped. Arguments: numbers -- iterable of numbers (int, bytes, float...) array_length -- length of the resulting array """ byte_buf = (ctypes.c_uint8 * array_length)() count = min(len(numbers), array_length) for i in range(count): byte_buf[i] = int(numbers[i]) return byte_buf def to_pretty_hex(buffer): """Takes a byte-buffer and creates a pretty-looking hex-string from it""" if isinstance(buffer, ctypes.Structure): out = ctypes.create_string_buffer(ctypes.sizeof(buffer)) ctypes.memmove(ctypes.addressof(out), ctypes.addressof(buffer), ctypes.sizeof(buffer)) temp_buf = [ord(x) for x in out] elif isinstance(buffer[0], int): temp_buf = [x for x in buffer] else: temp_buf = [ord(x) for x in buffer] res = "" offs = 0 while len(temp_buf) > 0: window = temp_buf[0:8] temp_buf = temp_buf[8:] res += "0x{:02X}\t{} {}\n".format( offs, " ".join([f"{x:02X}" for x in window]), " ".join([chr(x) if chr(x) in string.printable.split(" ")[0] else "." for x in window]), ) offs += 8 return res usbsdmux-24.11.1/usbsdmux/i2c_gpio.py000066400000000000000000000104151471240372500174570ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2017 Pengutronix, Chris Fiege # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA from .usb2642 import Usb2642 class I2cGpio: # Registers inside the supported GPIO expanders _register_inputPort = 0x00 _register_outputPort = 0x01 _register_polarity = 0x02 _register_configuration = 0x03 # Values for the configuration register _direction_output = 0 _direction_input = 1 def __init__(self, sg): """ Arguments: sg -- /dev/sg* to use. """ self._usb = Usb2642(sg) def get_usb(self): return self._usb def _write_register(self, register, value): """ Writes a register on the GPIO-expander with a given value. """ self._usb.write_to(self._I2cAddr, [register, value]) def _read_register(self, addr): """ Returns a register of the GPIO-expander. """ return self._usb.write_read_to(self._I2cAddr, [addr], 1)[0] def set_pin_to_output(self, pins): """ Sets the corresponding pins as outputs. Arguments: pins -- Combination of I2cGpio.gpio_* """ direction = self._read_register(self._register_configuration) direction = (direction & ~pins) & 0xFF self._write_register(self._register_configuration, direction) def set_pin_to_input(self, pins): """ Sets the corresponding pins as inputs. Arguments: pins -- Combination of I2cGpio.gpio_* """ direction = self._read_register(self._register_configuration) direction = direction | pins self._write_register(self._register_configuration, direction) def get_gpio_config(self): """ Returns the state of the configuration register. """ return self._read_register(self._register_configuration) def get_input_values(self): """ Reads the value currently present on the port from the input register. """ return self._read_register(self._register_inputPort) def output_values(self, values: int, bitmask: int = 0xFF): """ Writes the given values to the GPIO-expander. Pins configured as Inputs are not affected by this. Arguments: values -- Combination of I2cGpio.gpio_* bitmask -- Only update bits in the register that are '1' in the bitmask """ if bitmask == 0xFF: # trivial case: Let's just write the value self._write_register(self._register_outputPort, values) else: # complex case: Let's do a read-modify-write val = self._read_register(self._register_outputPort) val = (val & ~bitmask) & 0xFF # reset masked bits val = val | (values & bitmask) # set bits set in values and bitmask self._write_register(self._register_outputPort, val) class Pca9536(I2cGpio): """ Interface to control a Pca9536 that is connected to the auxiliary-I2C of a Microchip USB2642. """ # The PCA9536 I2C slave Address in 7-Bit Format _I2cAddr = 0b100_0001 gpio_0 = 0x01 gpio_1 = 0x02 gpio_2 = 0x04 gpio_3 = 0x08 class Tca6408(I2cGpio): """ Interface to control a TCA6408 that is connected to the auxiliary-I2C of a Microchip USB2642. """ # The TCA6408 I2C slave Address in 7-Bit Format _I2cAddr = 0b010_0000 gpio_0 = 0x01 gpio_1 = 0x02 gpio_2 = 0x04 gpio_3 = 0x08 gpio_4 = 0x10 gpio_5 = 0x20 gpio_6 = 0x40 gpio_7 = 0x80 usbsdmux-24.11.1/usbsdmux/mqtthelper.py000066400000000000000000000113711471240372500201530ustar00rootroot00000000000000import configparser import json import os import sys class Config: """ Reads the configuration file by default at /etc/usbsdmux.config """ def __init__(self, configfile): if configfile is not None: if not os.path.isfile(configfile): raise FileNotFoundError("Config file {configfile} not found") else: configfile = "/etc/usbsdmux.config" config = configparser.ConfigParser() config.read(configfile) if "mqtt" not in config or "send" not in config: self.mqtt_enabled = False return else: self.mqtt_enabled = True mqtt_section = config["mqtt"] for argument in ("server", "port", "topic"): if argument not in mqtt_section: raise ValueError(f"Config value mqtt/{argument} not found. Please check {configfile}") self.mqtt_server = mqtt_section["server"] self.mqtt_port = int(mqtt_section["port"]) self.mqtt_topic = mqtt_section["topic"] if "username" in mqtt_section and "password" in mqtt_section: self.mqtt_auth = {"username": mqtt_section["username"], "password": mqtt_section["password"]} else: self.mqtt_auth = None send_section = config["send"] self.send_on_host = send_section.get("host", False) self.send_on_dut = send_section.get("dut", False) def _read_file(filename): try: with open(filename) as f: return f.read() except FileNotFoundError: return None def _read_int(filename, base=10): try: return int(_read_file(filename).strip(), base) except TypeError: return None def _gather_data(ctl, sg, mode): import socket import pkg_resources base_sg = os.path.realpath(sg) sg_name = os.path.basename(base_sg) # only file in this directory is a hard link pointing to the block device sd_name = os.listdir(f"/sys/class/scsi_generic/{sg_name}/device/block/")[0] # using that name we can obtain further information stat_data = [int(part) for part in _read_file(f"/sys/class/block/{sd_name}/stat").split()] # https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-block stat_names = ( "reads_completed_successfully", "reads_merged", "sectors_read", "time_spent_reading", "writes_completed", "writes_merged", "sectors_written", "time_spent_writing", "IOs_currently_in_progress", "time_spent_doing_IOs", "weighted_time_spent_doing_IOs", "discards_completed", "discards_merged", "sectors_discarded", "time_spent_discarding", "flush_requests_completed", "time_spent_flushing", ) stat = dict(zip(stat_names, stat_data)) usb_path = os.path.realpath(f"/sys/class/scsi_generic/{sg_name}") max_depth = 10 while not os.path.isfile(os.path.join(usb_path, "serial")) and max_depth > 0: usb_path = os.path.dirname(usb_path) max_depth -= 1 card_info = ctl.get_card_info() if ctl.get_mode() == "host" or mode == "dut" else None data = { "command": " ".join(sys.argv), "mode": mode, "sg": sg_name, "sd": sd_name, "usb": usb_path, "username": os.getlogin(), "hostname": socket.gethostname(), "labgrid-place": os.environ.get("LG_PLACE"), "model": type(ctl).__name__, "serial": _read_file(os.path.join(usb_path, "serial")).strip(), "version": pkg_resources.get_distribution("usbsdmux").version, "diskseq": _read_int(f"/sys/class/block/{sd_name}/diskseq"), "size": _read_int(f"/sys/class/block/{sd_name}/size"), "ioerr_cnt": _read_int(f"/sys/class/scsi_generic/{sg_name}/device/ioerr_cnt", 16), "stat": stat, "card_info": card_info, } return data def publish_info(ctl, config, sg, mode): """ Publish info to mqtt server, if mqtt is enabled. This requires installing paho-mqtt. """ if not config.mqtt_enabled: return if (mode == "client" and not config.send_on_dut) or (mode == "host" and not config.send_on_host): return try: import paho.mqtt.publish as mqtt except ImportError: print( "Sending data to an mqtt server requires paho-mqtt", "Please install it, e.g. by installing usbsdmux via:", "", ' python3 -m pip install "usbsdmux[mqtt]"', sep="\n", file=sys.stderr, ) exit(1) data = _gather_data(ctl, sg, mode) mqtt.single( config.mqtt_topic, payload=json.dumps(data), hostname=config.mqtt_server, port=config.mqtt_port, auth=config.mqtt_auth, ) usbsdmux-24.11.1/usbsdmux/sd_regs.py000077500000000000000000000402311471240372500174140ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2023 Pengutronix, Jan Lübbe # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA def bitslice(val, upper, lower): "extract a contiguous slice of bits from a larger value" size = upper - lower + 1 mask = (1 << size) - 1 return (val >> lower) & mask def decoded_to_text(decoded): "convert the output of the decode() function to human-readable text" text = [] text.append(f"{decoded['reg']} Register Value: {decoded['raw']}") for f in decoded["fields"]: if "name" in f: text.append(f" {f['field']}: {f['name']}") else: text.append(f" {f['field']}") raw = f["raw"] text.append(f" raw: 0b{format(raw[0], '0%db' % raw[1])} == 0x{raw[0]:0x} == {int(raw[0])}") if "enum" in f: text.append(f" enum: {f['enum']} {f.get('unit', '')}".rstrip()) if "bits" in f: text.append(f" bits: {', '.join(f['bits'])}") if "decoded" in f: text.append(f" decoded: {f['decoded']}") if "value" in f: text.append(f" value: {f['value']} {f.get('unit', '')}".rstrip()) return text class RegisterDecoder: "decode a register based on a mostly declarative description of the contents." FIELDS = {} def __init__(self, raw_hex): self.raw_hex = raw_hex self.raw = int(raw_hex, 16) def _get_slice(self, field): field = self.FIELDS[field] return field["slice"] def _get_details(self, field): field = self.FIELDS[field] return field def _get_value(self, field): upper, lower = self._get_slice(field) width = upper - lower + 1 value = bitslice(self.raw, upper, lower) return (value, width) def __getattr__(self, field): v, _ = self._get_value(field) details = self._get_details(field) if "convert" in details: v = details["convert"](v) return v def decode_field(self, field): "decode a single field into a key-value format" result = {} value, width = self._get_value(field) details = self._get_details(field) result["field"] = field if "name" in details: result["name"] = details["name"] result["raw"] = (value, width) if "enum" in details: try: result["enum"] = details["enum"][value] except (IndexError, KeyError): result["enum"] = None if "bits" in details: bits = [details["bits"][x] for x in range(width) if (value & (1 << x))] result["bits"] = bits if "convert" in details: result["value"] = str(details["convert"](value)) if "unit" in details: result["unit"] = details["unit"] if "decode" in details: decoded = details["decode"](self) result.update(decoded) return result def get_computed(self): "compute additional values which need multiple fields as input" return {} def decode(self): "decode all fields into a format suitable for JSON encoding" result = {"reg": self.__class__.__name__, "raw": self.raw_hex, "fields": []} for field, _ in sorted(self.FIELDS.items(), key=lambda x: x[1]["slice"], reverse=True): result["fields"].append(self.decode_field(field)) result["computed"] = self.get_computed() return result def get_text_report(self): "decode all fields and format as human-readable text" decoded = self.decode() return decoded_to_text(decoded) class CSD_Common(RegisterDecoder): TIME_VALUE_ENUM = ["reserved", 1.0, 1.2, 1.3, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 8.0] def decode_TAAC(self): v = self._get_value("TAAC") TIME_UNIT_ENUM = ["1ns", "10ns", "100ns", "1us", "10us", "100us", "1ms", "10ms"] TIME_SCALE_ENUM = [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000] unit = TIME_UNIT_ENUM[bitslice(v[0], 2, 0)] scale = TIME_SCALE_ENUM[bitslice(v[0], 2, 0)] value = self.TIME_VALUE_ENUM[bitslice(v[0], 6, 3)] scaled_value = value * scale if isinstance(value, float) else None return { "decoded": (value, unit), "value": scaled_value, "unit": "ns", } def decode_TRAN_SPEED(self): v = self._get_value("TRAN_SPEED") RATE_UNIT_ENUM = ["100 Kbit/s", "1Mbit/s", "10Mbit/s", "100Mbit/s", "reserved"] RATE_SCALE_ENUM = [100_000, 1_000_000, 10_000_000, 10_000_000, "reserved"] unit = RATE_UNIT_ENUM[bitslice(v[0], 2, 0)] scale = RATE_SCALE_ENUM[bitslice(v[0], 2, 0)] value = self.TIME_VALUE_ENUM[bitslice(v[0], 6, 3)] scaled_value = None if isinstance(value, float) and isinstance(scale, int): scaled_value = value * scale return { "decoded": (value, unit), "value": scaled_value, "unit": "bit/s", } FIELDS = { "CSD_STRUCTURE": { "slice": (127, 126), "name": "CSD structure", "enum": ["1.0", "2.0"], }, "TAAC": { "slice": (119, 112), "name": "data read access-time-1", "decode": decode_TAAC, }, "NSAC": { "slice": (111, 104), "name": "data read access-time-2", "convert": lambda v: v * 100, "unit": "CLK cycles", }, "TRAN_SPEED": { "slice": (103, 96), "name": "max. data transfer rate", "decode": decode_TRAN_SPEED, }, "CCC": {"slice": (95, 84), "name": "card command classes", "bits": [str(x) for x in range(12)]}, "READ_BL_LEN": { "slice": (83, 80), "name": "max. read data block length", "convert": lambda v: 2**v, "unit": "bytes", }, "READ_BL_PARTIAL": { "slice": (79, 79), "name": "partial blocks for read allowed", "convert": bool, }, "WRITE_BLK_MISALIGN": { "slice": (78, 78), "name": "write block misalignment allowed", "convert": bool, }, "READ_BLK_MISALIGN": { "slice": (77, 77), "name": "read block misalignment allowed", "convert": bool, }, "DSR_IMP": { "slice": (76, 76), "name": "driver stage register implemented", "convert": bool, }, "ERASE_BLK_EN": { "slice": (46, 46), "name": "erase single block enable", "convert": bool, }, "SECTOR_SIZE": { "slice": (45, 39), "name": "erase sector size", "convert": lambda v: v + 1, "unit": "write blocks", }, "WP_GRP_SIZE": { "slice": (38, 32), "name": "write protect group size", "convert": lambda v: v + 1, "unit": "erase sectors", }, "WP_GRP_ENABLE": { "slice": (31, 31), "name": "write protect group enable", "convert": bool, }, "R2W_FACTOR": { "slice": (28, 26), "name": "write speed factor", "convert": lambda v: 2**v, "unit": "multiples of read access time", }, "WRITE_BL_LEN": { "slice": (25, 22), "name": "max. write data block length", "convert": lambda v: 2**v, "unit": "bytes", }, "WRITE_BL_PARTIAL": { "slice": (21, 21), "name": "partial blocks for write allowed", "convert": bool, }, "FILE_FORMAT_GRP": { "slice": (15, 15), "name": "file format group", }, "COPY": { "slice": (14, 14), "name": "copy flag", "convert": bool, }, "PERM_WRITE_PROTECT": { "slice": (13, 13), "name": "permanent write protection", "convert": bool, }, "TMP_WRITE_PROTECT": { "slice": (12, 12), "name": "temporary write protection", "convert": bool, }, "FILE_FORMAT": { "slice": (11, 9), "name": "file format", "enum": [ "Hard disk-like file system with partition table", "DOS FAT (floppy-like) with boot sector only (no partition table)", "Universal File Format", "Others/Unknown", ], }, "CRC": { "slice": (7, 1), }, } def get_computed(self): result = {} sector_size = self.SECTOR_SIZE * self.WRITE_BL_LEN wp_grp_size = self.WP_GRP_SIZE * sector_size result["sector_size_bytes"] = { "value": sector_size, "unit": "bytes", "name": "sector size", } result["wp_grp_size_bytes"] = { "value": wp_grp_size, "unit": "bytes", "name": "write protect group size", } return result class CSD_10(CSD_Common): VDD_MIN_CURR_MA_ENUM = [0.5, 1, 5, 10, 25, 35, 60, 100] VDD_MAX_CURR_MA_ENUM = [1, 5, 10, 25, 35, 45, 80, 200] FIELDS = CSD_Common.FIELDS.copy() FIELDS["C_SIZE"] = { "slice": (73, 62), "name": "device size", "convert": lambda v: (v + 1), } FIELDS["VDD_R_CURR_MIN"] = { "slice": (61, 59), "name": "max. read current @VDD min", "enum": VDD_MIN_CURR_MA_ENUM, "unit": "mA", } FIELDS["VDD_R_CURR_MAX"] = { "slice": (58, 56), "name": "max. read current @VDD max", "enum": VDD_MAX_CURR_MA_ENUM, "unit": "mA", } FIELDS["VDD_W_CURR_MIN"] = { "slice": (55, 53), "name": "max. write current @VDD min", "enum": VDD_MIN_CURR_MA_ENUM, "unit": "mA", } FIELDS["VDD_W_CURR_MAX"] = { "slice": (52, 50), "name": "max. write current @VDD max", "enum": VDD_MAX_CURR_MA_ENUM, "unit": "mA", } FIELDS["C_SIZE_MULT"] = {"slice": (49, 47), "name": "device size multiplier", "convert": lambda v: 2 ** (v + 2)} def get_computed(self): result = super().get_computed() device_size = self.C_SIZE * self.C_SIZE_MULT * self.READ_BL_LEN result["device_size_bytes"] = { "value": device_size, "unit": "bytes", "name": "device size", } return result class CSD_20(CSD_Common): FIELDS = CSD_Common.FIELDS.copy() FIELDS["C_SIZE"] = { "slice": (69, 48), "name": "device size", "convert": lambda v: (v + 1) * 512 * 1024, "unit": "bytes", } def decode_csd(raw_hex): raw = int(raw_hex, 16) val = bitslice(raw, 127, 126) if val == 0: return CSD_10(raw_hex) elif val == 1: return CSD_20(raw_hex) else: raise ValueError(f"unknown CSD version {val}") class CID(RegisterDecoder): @staticmethod def convert_printable(value, size): # The spec defines some fields as ASCII strings, but in practice, cards # contain many other values as well. Clean up non-printable characters, # newlines, etc. result = "" for i in reversed(range(size)): c = chr((value >> 8 * i) & 0x7F) result += c if c.isprintable() else "." return result FIELDS = { "MID": { "slice": (127, 120), "name": "Manufacturer ID", "enum": { 0x02: "SanDisk", 0x03: "SanDisk SD", 0x1B: "Samsung", 0x74: "Transcend", 0x9F: "Kingston SD", }, }, "OID": { "slice": (119, 104), "name": "OEM/Application ID", "convert": lambda v: CID.convert_printable(v, 2), }, "PNM": { "slice": (103, 64), "name": "Product name", "convert": lambda v: CID.convert_printable(v, 5), }, "PRV": { "slice": (63, 56), "name": "Product revision", "convert": lambda v: f"{int(v >> 4 & 15)}.{int(v & 15)}", }, "PSN": { "slice": (55, 24), "name": "Product serial number", "convert": int, }, "RESERVED": { "slice": (23, 20), }, # "MDT": { # combined layout for reference # "slice": (19, 8), # "name": "Manufacturing date", # }, "MDT_Y": { "slice": (19, 12), "name": "Manufacturing date (year)", "convert": lambda v: v + 2000, }, "MDT_M": { "slice": (11, 8), "name": "Manufacturing date (month)", "convert": lambda v: v + 1, }, "CRC": { "slice": (7, 1), "name": "CRC7 checksum", }, "NU1": { "slice": (0, 0), "name": "not used, always 1", }, } class SCR(RegisterDecoder): FIELDS = { "SCR_STRUCTURE": { "slice": (63, 60), "name": "SCR Structure", "enum": ["1.0"], }, "SD_SPEC": { "slice": (59, 56), "name": "SD Memory Card - Spec. Version", "enum": ["1.0 or 1.01", "1.10", "2.00 or 3.0X"], }, "DATA_STAT_AFTER_ERASE": { "slice": (55, 55), "name": "data status after erase", "convert": bool, }, "SD_SECURITY": { "slice": (54, 52), "name": "CPRM Security Support", "enum": [ "No Security", "Not Used", "SDSC Card (Security Version 1.01)", "SDHC Card (Security Version 2.00)", "SDXC Card (Security Version 3.xx)", ], }, "SD_BUS_WIDTHS": { "slice": (51, 48), "name": "DAT Bus widths supported", "bits": ["1 bit", None, "4 bit", None], }, "SD_SPEC3": { "slice": (47, 47), "name": "Spec. Version 3.00 or higher", }, "EX_SECURITY": { "slice": (46, 43), "name": "Extended Security Support", }, "RESERVED": { "slice": (42, 34), }, "CMD_SUPPORT": { "slice": (33, 32), "name": "Command Support bits", "bits": ["Speed Class Control (CMD20)", "Set Block Count (CMD23)"], }, "RESERVED_MFG": { "slice": (31, 0), }, } if __name__ == "__main__": import argparse import json parser = argparse.ArgumentParser() parser.add_argument("--json", action="store_true") parser.add_argument("input", help="input in JSON format", type=str) args = parser.parse_args() with open(args.input) as fd: data = json.loads(fd.read()) if args.json: res = {} res["scr"] = SCR(data["scr"]["raw"]).decode() res["cid"] = CID(data["cid"]["raw"]).decode() res["csd"] = decode_csd(data["csd"]["raw"]).decode() print(json.dumps(res, indent=2)) else: res = [] res += decode_csd(data["csd"]["raw"]).get_text_report() res += SCR(data["scr"]["raw"]).get_text_report() res += CID(data["cid"]["raw"]).get_text_report() print("\n".join(res)) usbsdmux-24.11.1/usbsdmux/usb2642.py000066400000000000000000000416131471240372500170770ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2017 Pengutronix, Chris Fiege # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import ctypes import fcntl from time import sleep from .ctypehelper import ( list_to_uint8_array, ) """ This modules provides an interface to use the auxiliary and configuration I2C-busses of the Microchip USB2642. """ class FrameLengthException(Exception): pass class IoctlFailed(Exception): pass class I2cTransactionFailed(Exception): pass class SDTransactionFailed(Exception): pass class Usb2642: """ This class provides an interface to interact with devices on a Microchip USB2642 auxiliary I2C Bus and to write configuration to an EEPROM on the configuration I2C Bus. To do so it uses vendor specific SCSI-commands on the mass-storage device provided by the USB2642. Documentation to this behavior can be found in this documents: * 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' (Can be found in the (Windows-) software example provided on the components webpage) * The USB2641 datasheet * see http://www.microchip.com/wwwproducts/en/USB2642 for both documents Some more interesting links: * USB Mass Storage Bulk Transfer Profile Specification: http://www.usb.org/developers/docs/devclass_docs/usbmassbulk_10.pdf * Linux SG_IO ioctl() control structure: http://www.tldp.org/HOWTO/SCSI-Generic-HOWTO/sg_io_hdr_t.html * Denton Gentry's blog post about how to use the sg ioctl() from python: http://codingrelic.geekhold.com/2012/02/ata-commands-in-python.html This article uses it to make ATA-passthrough - beware that we do not use ATA-passthrough here. This class uses the /dev/sg* -Interface to access the SCSI-device even if no media is present. Make sure you have rw-rights :) """ def __init__(self, sg): """ Create a new USB2642-Interface wrapper. Arguments: sg -- The sg-device to use. E.g. "/dev/sg1" """ self.sg = sg class _SgioHdrStruct(ctypes.Structure): """ Structure used to access the ioctl() to send arbitrary SCSI-commands. Reflects the Kernel-Struct from: sg_io_hdr_t. """ _fields_ = [ ("interface_id", ctypes.c_int), ("dxfer_direction", ctypes.c_int), ("cmd_len", ctypes.c_ubyte), ("mx_sb_len", ctypes.c_ubyte), ("iovec_count", ctypes.c_ushort), ("dxfer_len", ctypes.c_uint), ("dxferp", ctypes.c_void_p), ("cmdp", ctypes.c_void_p), ("sbp", ctypes.c_void_p), ("timeout", ctypes.c_uint), ("flags", ctypes.c_uint), ("pack_id", ctypes.c_int), ("usr_ptr", ctypes.c_void_p), ("status", ctypes.c_ubyte), ("masked_status", ctypes.c_ubyte), ("msg_status", ctypes.c_ubyte), ("sb_len_wr", ctypes.c_ubyte), ("host_status", ctypes.c_ushort), ("driver_status", ctypes.c_ushort), ("resid", ctypes.c_int), ("duration", ctypes.c_uint), ("info", ctypes.c_uint), ] # sg_io_hdr_t contains 9 ints, 3 short ints, 6 chars and 4 pointers. So its # size is 9 * 4 + 3 * 2 + 6 * 1 + 4 * 4 = 64 on 32 bit architectures. On 64 # bit architectures there are two holes in the struct: # - 4 bytes before *usr_ptr to make the pointer aligned # - 4 bytes at the end to make the size a multiple of 8. # So the size there is: 9 * 4 + 3 * 2 + 6 * 1 + 4 * 8 + 2 * 4 = 88. if ctypes.sizeof(ctypes.c_void_p) == 4: assert ctypes.sizeof(_SgioHdrStruct) == 64 else: assert ctypes.sizeof(ctypes.c_void_p) == 8 assert ctypes.sizeof(_SgioHdrStruct) == 88 """IOCTL for SG_IO""" _SG_IO = 0x2285 # """SgioHdr dxfer direction constant: No direction""" _SG_DXFER_NONE = -1 """SgioHdr dxfer direction constant: Host to device""" _SG_DXFER_TO_DEV = -2 """SgioHdr dxfer direction constant: Device to Host""" _SG_DXFER_FROM_DEV = -3 """ This Opcode represents a vendor specific SCSI command. According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ _USB2642SCSIOPCODE = 0xCF """ This Vendor Action marks an I2C Write Action According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ _USB2642I2CWRITESTREAM = 0x23 """ This Vendor Action marks an I2C Write-Read Action According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ _USB2642I2CWRITEREADSTREAM = 0x22 class _USB2642I2cWriteStruct(ctypes.Structure): """I2C-Write Data Structure for up to 512 Bytes of Data According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ _fields_ = [ ("ScsiVendorCommand", ctypes.c_uint8), ("ScsiVendorActionWriteI2C", ctypes.c_uint8), ("I2cSlaveAddress", ctypes.c_uint8), ("I2cUnused", ctypes.c_uint8), ("I2cDataPhaseLenHigh", ctypes.c_uint8), ("I2cDataPhaseLenLow", ctypes.c_uint8), ("I2cCommandPhaseLen", ctypes.c_uint8), ("I2cCommandPayload", ctypes.c_uint8 * 9), ] assert ctypes.sizeof(_USB2642I2cWriteStruct) == 16 class _USB2642I2cReadStruct(ctypes.Structure): """ I2C-Read Data Structure for up to 512 Bytes of Data. According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ _fields_ = [ ("ScsiVendorCommand", ctypes.c_uint8), ("ScsiVendorActionWriteReadI2C", ctypes.c_uint8), ("I2cWriteSlaveAddress", ctypes.c_uint8), ("I2cReadSlaveAddress", ctypes.c_uint8), ("I2cReadPhaseLenHigh", ctypes.c_uint8), ("I2cReadPhaseLenLow", ctypes.c_uint8), ("I2cWritePhaseLen", ctypes.c_uint8), ("I2cWritePayload", ctypes.c_uint8 * 9), ] assert ctypes.sizeof(_USB2642I2cReadStruct) == 16 def _get_SCSI_cmd_I2C_write(self, slaveAddr, data): """ Create an I2cWrite Command Structure to write up to 512 bytes to device slaveAddr. According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ MAXLEN = 512 count = min(len(data), MAXLEN) dataArray = (ctypes.c_uint8 * MAXLEN)() dataArray[:count] = data[:count] slaveWriteAddr = (slaveAddr * 2) & 0xFF cmd = self._USB2642I2cWriteStruct( ScsiVendorCommand=self._USB2642SCSIOPCODE, ScsiVendorActionWriteI2C=self._USB2642I2CWRITESTREAM, I2cSlaveAddress=slaveWriteAddr, I2cUnused=0x00, I2cDataPhaseLenHigh=(count >> 8) & 0xFF, I2cDataPhaseLenLow=count & 0xFF, I2cCommandPhaseLen=0x00, I2cCommandPayload=(ctypes.c_uint8 * 9)(), ) return cmd, dataArray def _get_SCSI_cmd_I2C_write_read(self, slaveAddr, writeData, readLength): """ Create an I2cWriteRead Command Structure to write up to 9 bytes to device slaveAddr and then read back up to 512 bytes of data. According to: 'Microchip: I2C_Over_USB_UserGuilde_50002283A.pdf' P.20 """ MAXLEN = 512 readCount = min(readLength, MAXLEN) readDataArray = (ctypes.c_uint8 * MAXLEN)() MAXLEN = 9 writeCount = min(len(writeData), MAXLEN) writeDataArray = (ctypes.c_uint8 * MAXLEN)() writeDataArray[:writeCount] = writeData[:writeCount] slaveWriteAddr = (slaveAddr * 2) & 0xFF slaveReadAddr = slaveWriteAddr + 1 cmd = self._USB2642I2cReadStruct( ScsiVendorCommand=self._USB2642SCSIOPCODE, ScsiVendorActionWriteReadI2C=self._USB2642I2CWRITEREADSTREAM, I2cWriteSlaveAddress=slaveWriteAddr, I2cReadSlaveAddress=slaveReadAddr, I2cReadPhaseLenHigh=(readCount >> 8) & 0xFF, I2cReadPhaseLenLow=readCount & 0xFF, I2cWritePhaseLen=writeCount, I2cWritePayload=writeDataArray, ) return cmd, readDataArray def _get_SGIO(self, command, Sg_Dxfer, databuffer): """Fill the SG_IO ioctl() -structure with sane defaults for the given command. The command will create a 64-byte sense-buffer for returned status. Arguments: command -- SCSI-Command to use. ctypes.c_uint8 Sg_Dxfer -- _SG_DXFER_* to set the direction of the SCSI transfer. databuffer -- 512 bytes buffer of the block to read or write. """ sense = ctypes.c_buffer(64) sgio = self._SgioHdrStruct( # "S" for SCSI interface_id=ord("S"), # SG_DXFER_* dxfer_direction=Sg_Dxfer, # length of whatever we put into cmd cmd_len=ctypes.sizeof(command), # length of sense buffer mx_sb_len=ctypes.sizeof(sense), iovec_count=0, # data transfer length dxfer_len=ctypes.sizeof(databuffer), # pointer to data transfer buffer dxferp=ctypes.cast(databuffer, ctypes.c_void_p), # command to perform cmdp=ctypes.cast(ctypes.addressof(command), ctypes.c_void_p), # sense buffer memory sbp=ctypes.cast(sense, ctypes.c_void_p), # a timeout for this command in ms timeout=3000, # SG_FLAG_*, normally 0 flags=0, # unused pack_id=0, # unused usr_ptr=None, # output: SCSI-status status=0, # output: shifted, maskes SCSI-stauts masked_status=0, # output: optional: message level data msg_status=0, # output: byte actually written to sbp sb_len_wr=0, # output: errors from host adapter host_status=0, # output: errors from software driver driver_status=0, # output: result_len: actually transferred data resid=0, # output: time for the command in ms duration=0, # output: auxiliary information (?) info=0, ) return sgio, sense def _call_IOCTL(self, command, sg_dxfer, databuffer): """ Call the ioctl() This function will create the struct to call the ioctl() and handle return codes. Arguments: command -- SCSI Command payload to send. 16-Byte buffer containing the SCSI command parameters. sg_dxfer -- _SG_DXFER_*: Direction of the SCSI transfer databuffer -- 512 byte long buffer to be written or read """ sgio, sense = self._get_SGIO(command, sg_dxfer, databuffer) # print("SGIO:") # print(self.to_pretty_hex(sgio)) with open(self.sg, "r+b", buffering=0) as fh: rc = fcntl.ioctl(fh, self._SG_IO, sgio) if rc != 0: raise IoctlFailed(f"SG_IO ioctl() failed with non-zero exit-code {rc}") return databuffer, sense, sgio def write_config(self, data): """ Writes the eeprom contents from data into the config EEPROM on the auxiliary I2C bus. This is done using reverse-engineered commands send by the Microchip Windows-Demo-Tool. Arguments: data -- EEPROM blob to write as ctype.buffer. Length 384 Bytes as described in the USB2642 Datasheet. """ # SCSI Command was found on the USB-Bus. # Since most of the bytes are unknown this is used as plain magic. scsiCommand = list_to_uint8_array( [0xCF, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 16 ) # Data in the captured USB-transfer was suffixed with some random data. # Experiments showed that 0x00 works fine too. # Since the buffer is zero-ed when initialized the suffix could be removed. data_suffix = list_to_uint8_array([0x00], 127) # Copying prefix, data and suffix to the SCSI command data-section payload = (ctypes.c_uint8 * 512)() payload[: ctypes.sizeof(data)] = data payload[ctypes.sizeof(data) : ctypes.sizeof(data) + ctypes.sizeof(data_suffix)] = data_suffix # noqa: E203 # Perform the actual SCSI transfer self._call_IOCTL(scsiCommand, self._SG_DXFER_TO_DEV, payload) def write_read_to(self, i2cAddr, writeData, readLength): """ Tries to write data to an I2C-Device and afterwards read data from that device. This function will perform am I2C-Transaction like the following: * I2C-Start * I2C-Slave address with R/W = W (0) * writeData[0] * writeData[1] * ... * I2C-Repeated Start * I2C-Slave address with R/W = R (1) * readData[0] * readData[1] * ... * I2C-Stop This transaction can (for example) be used to set the address-pointer inside an EEPROM and read data from it. Arguments: i2cAddr -- 7-Bit I2C Slave address (as used by Linux). Will be shifted 1 Bit to the left before adding the R/W-bit. writeData -- iterable of bytes to write in the first phase readLengh -- number of bytes (0..512) to read in the second phase """ scsiCommand, data = self._get_SCSI_cmd_I2C_write_read(i2cAddr, writeData, readLength) # TODO: Add error handling if length of read or write do not match # requirements # print("I2C-Command:") # print(self.to_pretty_hex(scsiCommand)) # print("I2C-Payload:") # print(self.to_pretty_hex(data)) data, sense, sgio = self._call_IOCTL(scsiCommand, self._SG_DXFER_FROM_DEV, data) if sgio.status != 0: raise I2cTransactionFailed( f"SCSI-Transaction ended with status {sgio.status}. I2C-Transaction has probably failed." ) return list(data[:readLength]) def write_to(self, i2cAddr, data): """ Tries to write data to an I2C-Device. This function will perform am I2C-Transaction like the following: * I2C-Start * I2C-Slave address with R/W = W (0) * data[0] * data[1] * ... * I2C-Stop Transactions like this can (for example) be used if configuration registers on a device have to be written. Arguments: i2cAddr -- 7-Bit I2C Slave address (as used by Linux). Will be shifted 1 Bit to the left before adding the R/W-bit. data -- iterateable of bytes to write.""" scsiCommand, data = self._get_SCSI_cmd_I2C_write(i2cAddr, data) # TODO: Add length checks # print("I2C-Command:") # print(self.to_pretty_hex(scsiCommand)) # print("I2C-Payload:") # print(self.to_pretty_hex(data)) data, sense, sgio = self._call_IOCTL(scsiCommand, self._SG_DXFER_TO_DEV, data) if sgio.status != 0: raise I2cTransactionFailed( f"SCSI-Transaction ended with status {sgio.status}. I2C-Transaction has probably failed." ) def _read_register(self, reg, size, retries=5): scsiCommand = list_to_uint8_array( [0xCF, reg, 0x00, 0x00, size, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], 16 ) while True: databuffer = ctypes.c_buffer(size) _, _, sgio = self._call_IOCTL(scsiCommand, self._SG_DXFER_FROM_DEV, databuffer) if retries and sgio.status == 2: sleep(0.5) retries -= 1 continue if sgio.status != 0: raise SDTransactionFailed( f"SCSI Transaction ended with status {sgio.status}. SD Transaction has probably failed." ) break return databuffer.raw def read_cid(self): return self._read_register(0x18, 16) def read_csd(self): return self._read_register(0x1A, 16) def read_scr(self): return self._read_register(0x1B, 8) usbsdmux-24.11.1/usbsdmux/usb2642eeprom.py000077500000000000000000000346151471240372500203160ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2017 Pengutronix, Chris Fiege # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import argparse import ctypes import time from .ctypehelper import ( list_to_uint8_array, string_to_microchip_unicode_uint8_array, string_to_uint8_array, ) from .usb2642 import Usb2642 """ This module provides the high-level interface needed to write the contents of the configuration-EEPROM of a USB2642 using the USB2642. """ class VerificationFailedException(Exception): pass class USB2642Eeprom: """ Provides an interface to write the configuration EEPROM of a USB2642. """ def __init__(self, sg, i2c_addr=0x50): """ Create a new USB2642Eeprom Instance. Arguments: sg -- /dev/sg* to use i2c_addr -- 7-Bit Address of the EEPROM to use. Defaults to 0x50 for the configuration-EEPROM. You probably do NOT want to override this. """ self.i2c = Usb2642(sg) self.addr = i2c_addr class _EepromStruct(ctypes.Structure): """ Struct that contains the Configuration of the Card Reader and USB Hub. """ _pack_ = 1 # forces the struct to be packed tight and overrides the default # 4-byte aligned packing. _fields_ = [ # Flash Media Controller Configuration ("USB_SER_NUM", ctypes.c_uint8 * (0x19 - 0x00 + 1)), # 0x00 .. 0x19 USB Serial Number ("USB_VID", ctypes.c_uint16), # 0x1A .. 0x1B USB Vendor ID ("USB_PID", ctypes.c_uint16), # 0x1C .. 0x1D USB Product ID ( "USB_LANG_ID", ctypes.c_uint8 * (0x21 - 0x1E + 1), ), # 0x1E .. 0x21 USB Language Identifier, see http://www.usb.org/developers/docs/USB_LANGIDs.pdf ("USB_MFR_STR", ctypes.c_uint8 * (0x5D - 0x22 + 1)), # 0x22 .. 0x5D USB Manufacturer String (Unicode) ("USB_PRD_STR", ctypes.c_uint8 * (0x99 - 0x5E + 1)), # 0x5E .. 0x99 USB Product String (Unicode) ( "USB_BM_ATT", ctypes.c_uint8, ), # 0x9A USB BmAttribute, see http://sdphca.ucsd.edu/lab_equip_manuals/usb_20.pdf, P.266 ( "USB_MAX_PWR", ctypes.c_uint8, ), # 0x9B USB Max Power, see http://sdphca.ucsd.edu/lab_equip_manuals/usb_20.pdf, P.266, 1 Digit = 2mA ("ATT_LB", ctypes.c_uint8), # 0x9C Attribute Lo byte ("ATT_HLB", ctypes.c_uint8), # 0x9D Attribute Hi Lo byte ("ATT_LHB", ctypes.c_uint8), # 0x9E Attribute Lo Hi byte ("ATT_HB", ctypes.c_uint8), # 0x9F Attribute Hi byte ("reserved0", ctypes.c_uint8 * (0xA4 - 0xA0)), # 0xA0 .. 0xA3 reserved ("LUN_PWR_LB", ctypes.c_uint8), # 0xA4 LUN Power Lo byte ("LUN_PWR_HB", ctypes.c_uint8), # 0xA5 LUN Power Hi byte ("reserved1", ctypes.c_uint8 * (0xBF - 0xA6)), # 0xA6 .. 0xBE reserved ("DEV3_ID_STR", ctypes.c_uint8 * (0xC6 - 0xBF)), # 0xBF .. 0xC5 Card Reader Identifier String ("INQ_VEN_STR", ctypes.c_uint8 * (0xCE - 0xC6)), # 0xC6 .. 0xCD Inquiry Vendor String ("INQ_PRD_STR", ctypes.c_uint8 * (0xD3 - 0xCE)), # 0xCE .. 0xD2 48QFN Inquiry Product String ("DYN_NUM_LUN", ctypes.c_uint8), # 0xD3 Dynamic Number of LUNs ("LUN_DEV_MAP", ctypes.c_uint8 * (0xD8 - 0xD4)), # 0xD4 .. 0xD7 LUN to Device Mapping ("reserved2", ctypes.c_uint8 * (0xDB - 0xD8)), # 0xD8 .. 0xDA reserved # HUB CONTROLLER CONFIGURATION ("SD_MMC_BUS_TIMING", ctypes.c_uint8 * (0xDE - 0xDB)), # 0xDB .. 0xDD SD/MMC Bus Timing Control ("VID", ctypes.c_uint16), # 0xDE .. 0xDF Hub Vendor ID ("PID", ctypes.c_uint16), # 0xE0 .. 0xE1 Hub Product ID ("DID", ctypes.c_uint16), # 0xE2 .. 0xE3 Hub Device ID ("CFG_DAT_BYTE1", ctypes.c_uint8), # 0xE4 Configuration Data Byte 1 ("CFG_DAT_BYTE2", ctypes.c_uint8), # 0xE5 Configuration Data Byte 2 ("CFG_DAT_BYTE3", ctypes.c_uint8), # 0xE6 Configuration Data Byte 3 ("NR_DEVICE", ctypes.c_uint8), # 0xE7 Non-Removeable Devices ("PORT_DIS_SP", ctypes.c_uint8), # 0xE8 Port Disable (Self) ("PORT_DIS_BP", ctypes.c_uint8), # 0xE9 Post Disable (Bus) ("MAX_PWR_SP", ctypes.c_uint8), # 0xEA Max Power (Self) ("MAX_PWR_BP", ctypes.c_uint8), # 0xEB Max Power (Bus) ("HC_MAX_C_SP", ctypes.c_uint8), # 0xEC Hub Controller Max Current (Self) ("HC_MAX_C_BP", ctypes.c_uint8), # 0xED Hub Controller Max Current (Bus) ("PWR_ON_TIME", ctypes.c_uint8), # 0xEE Power-on time ("BOOST_UP", ctypes.c_uint8), # 0xEF Boost_Up ("BOOST_32", ctypes.c_uint8), # 0xF0 Boost_3:2 ("PRT_SWP", ctypes.c_uint8), # 0xF1 Port Swap ("PRTM12", ctypes.c_uint8), # 0xF2 Port Map 12 ("PRTM3", ctypes.c_uint8), # 0xF3 Port Map 3 # OTHER CONFIGURATION ("SD_CLK_LIM", ctypes.c_uint8), # 0xF4 SD Clock Limit for the Flash Media Controller ("reserved3", ctypes.c_uint8), # 0xF5 reserved ("MEDIA_SETTINGS", ctypes.c_uint8), # 0xF6 SD1 Timeout Configuration ("reserved4", ctypes.c_uint8 * (0xFC - 0xF7)), # 0xF7 .. 0xFB reserved ("NVSTORE_SIG", ctypes.c_uint8 * (0xFF - 0xFC + 1)), # 0xFC .. 0xFF Non-Volatile Storage Signature # Non Volatile Storage 2 Contents ("CLUN0_ID_STR", ctypes.c_uint8 * (0x106 - 0x100 + 1)), # 0x100 .. 0x106 LUN 0 Identifier String ("CLUN1_ID_STR", ctypes.c_uint8 * (0x10D - 0x107 + 1)), # 0x107 .. 0x10D LUN 1 Identifier String ("CLUN2_ID_STR", ctypes.c_uint8 * (0x114 - 0x10E + 1)), # 0x10E .. 0x114 LUN 2 Identifier String ("CLUN3_ID_STR", ctypes.c_uint8 * (0x11B - 0x115 + 1)), # 0x115 .. 0x11B LUN 3 Identifier String ("CLUN4_ID_STR", ctypes.c_uint8 * (0x122 - 0x11C + 1)), # 0x11C .. 0x122 LUN 4 Identifier String ("reserved5", ctypes.c_uint8 * (0x145 - 0x123 + 1)), # 0x123 .. 0x145 reserved ("DYN_NUM_EXT_LUN", ctypes.c_uint8), # 0x146 Dynamic Number of Extended LUNs ("LUN_DEV_MAP2", ctypes.c_uint8 * (0x14B - 0x147 + 1)), # 0x147 .. 0x14B LUN to Device mapping ("reserved6", ctypes.c_uint8 * (0x17B - 0x14C + 1)), # 0x14C .. 0x17B reserved ("NVSTORE_SIG2", ctypes.c_uint8 * (0x17F - 0x17C + 1)), # 0x17C .. 0x17F Non-Volatile Storage 2 Signature ] def get_struct( reader_VID, reader_PID, reader_vendorString, reader_productString, reader_serial, scsi_mfg, scsi_product ): """ Returns a pre-filled EepromStruct. Parameters are taken from the Datasheets defaults if nothing else is mentioned. """ s = USB2642Eeprom._EepromStruct( USB_SER_NUM=string_to_microchip_unicode_uint8_array(reader_serial, 0x19 - 0x00 + 1), USB_VID=0x0424, USB_PID=0x4041, USB_LANG_ID=list_to_uint8_array( [0x04, 0x03, 0x09, 0x04], 0x21 - 0x1E + 1 ), # reverse engineered from actual EEPROM. Does NOT match the datasheet. USB_MFR_STR=string_to_microchip_unicode_uint8_array(reader_vendorString, 0x5D - 0x22 + 1), USB_PRD_STR=string_to_microchip_unicode_uint8_array(reader_productString, 0x99 - 0x5E + 1), USB_BM_ATT=0x80, # Bus Powered, without Remote wakeup USB_MAX_PWR=0x30, # 0x30 * 2mA = 96mA Power Consumption ATT_LB=0x50, # use INQ-strings, SD card is write protected when SW_nWP is high ATT_HLB=0x80, ATT_LHB=0x00, ATT_HB=0x00, LUN_PWR_LB=0x00, LUN_PWR_HB=0x0A, DEV3_ID_STR=string_to_uint8_array("SD/MMC", 0xC5 - 0xBF + 1, encoding="UTF-8", padding=0x00), INQ_VEN_STR=string_to_uint8_array(scsi_mfg, 0xCD - 0xC6 + 1, encoding="UTF-8", padding=0x00), INQ_PRD_STR=string_to_uint8_array(scsi_product, 0xD2 - 0xCE + 1, encoding="UTF-8", padding=0x00), DYN_NUM_LUN=0x01, LUN_DEV_MAP=list_to_uint8_array([0xFF, 0x00, 0x00, 0x00], 0xD7 - 0xD4 + 1), SD_MMC_BUS_TIMING=list_to_uint8_array([0x59, 0x56, 0x97], 0xDD - 0xDB + 1), VID=0x0424, PID=0x2640, DID=0x08A2, CFG_DAT_BYTE1=0x8B, CFG_DAT_BYTE2=0x28, CFG_DAT_BYTE3=0x00, NR_DEVICE=0x02, PORT_DIS_SP=0x0C, # Disable the unused Downstream-Ports of the hub PORT_DIS_BP=0x0C, # Disable the unused Downstream-Ports of the hub MAX_PWR_SP=0x01, MAX_PWR_BP=0x32, HC_MAX_C_SP=0x01, HC_MAX_C_BP=0x32, PWR_ON_TIME=0x32, BOOST_UP=0x00, BOOST_32=0x00, PORT_SWP=0x00, PRTM12=0x00, PRTM3=0x00, SD_CLK_LIM=0x00, MEDIA_SETTINGS=0x00, NVSTORE_SIG=string_to_uint8_array("ata2", 4, c_string=False, encoding="UTF-8"), # according to datasheet the signature is "ATA2". # But reverse engineering the configuration written with the microchip-tool shows # that it should be "ata" instead. CLUN0_ID_STR=string_to_uint8_array("COMBO", 0x106 - 0x100 + 1, encoding="UTF-8", padding=0x00), CLUN1_ID_STR=string_to_uint8_array("COMBO", 0x106 - 0x100 + 1, encoding="UTF-8", padding=0x00), CLUN2_ID_STR=string_to_uint8_array("COMBO", 0x106 - 0x100 + 1, encoding="UTF-8", padding=0x00), CLUN3_ID_STR=string_to_uint8_array("COMBO", 0x106 - 0x100 + 1, encoding="UTF-8", padding=0x00), CLUN4_ID_STR=string_to_uint8_array("COMBO", 0x106 - 0x100 + 1, encoding="UTF-8", padding=0x00), DYN_NUM_EXT_LUN=0x00, LUN_DEV_MAP2=list_to_uint8_array([0xFF, 0xFF, 0xFF, 0xFF], 0x14B - 0x147 + 1), NVSTORE_SIG2=string_to_uint8_array("ecf1", 0x17F - 0x17C + 1, encoding="UTF-8", padding=0x00), ) assert ctypes.sizeof(s) == 384 return s def _read_EEPROM(self, addr=0, len=256): """ Reads len bytes of data starting from addr from the given EEPROM. Attributes: addr -- Byte address from where to start reading len -- Number of bytes to read (0..256) """ return self.i2c.write_read_to(self.addr, [addr], len) def _write_EEPROM(self, addr, data): """ Writes data to the EEPROM starting at addr. Attributes: addr -- Address to begin write at data -- Iterable containing data to write """ offset = 0 while offset < len(data): # determine minimum and maximum address to write in this block lower = max((addr + offset) & 0xF0, addr) upper = min(((addr + offset) & 0xF0) | 0x0F, addr + len(data)) lowerOffset = lower - addr upperOffset = upper - addr self.i2c.write_to(self.addr, [lower] + data[lowerOffset : (upperOffset + 1)]) # noqa: E203 time.sleep(0.1) offset = upperOffset + 1 def write(self, VID, PID, product_string, vendor_string, serial, scsi_mfg, scsi_product): """ Writes a configuration to the EEPROM. Arguments: VID -- USB Vendor ID, uint_16 PID -- USB Product ID, uint_16 product_string -- Product Name as String vendor_string -- Vendor Name as String serial -- Serial Number, 12 Hex Digits """ s = USB2642Eeprom._EepromStruct.get_struct( reader_VID=VID, reader_PID=PID, reader_productString=product_string, reader_vendorString=vendor_string, reader_serial=serial, scsi_mfg=scsi_mfg, scsi_product=scsi_product, ) buffer = (ctypes.c_uint8 * ctypes.sizeof(s))() ctypes.memmove(ctypes.addressof(buffer), ctypes.addressof(s), ctypes.sizeof(s)) self.i2c.write_config(buffer) def main(): parser = argparse.ArgumentParser( description="This tool writes and verifies the configuration EEPROM of the usb-sd-mux " "with the information given on the command line." ) parser.add_argument("sg", help="The /dev/sg* which is used.") parser.add_argument( "--productString", help="Sets the product name that will be written.", default="usb-sd-mux_rev1" ) parser.add_argument( "--manufacturerString", help="Sets the manufacturerString that will be written.", default="Pengutronix" ) parser.add_argument("--VID", help="Sets the VID that will be written.", default="0x0424") parser.add_argument("--ScsiManufacturer", help="Sets the ScsiManufacturer that will be written.", default="PTX") parser.add_argument("--ScsiProduct", help="Sets the ScsiProduct that will be written.", default="sdmux") parser.add_argument("--PID", help="Sets the USB-PIC that will be written.", default="0x4041") parser.add_argument("serial", help="Sets the Serial Number that will be written.") args = parser.parse_args() c = USB2642Eeprom(args.sg) c.write( VID=int(args.VID, base=16), PID=int(args.PID, base=16), product_string=args.productString, vendor_string=args.manufacturerString, serial=args.serial, scsi_mfg=args.ScsiManufacturer, scsi_product=args.ScsiProduct, ) print("Write completed") if __name__ == "__main__": main() usbsdmux-24.11.1/usbsdmux/usbsdmux.py000066400000000000000000000236751471240372500176520ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2017 Pengutronix, Chris Fiege # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import os import time from . import sd_regs from .i2c_gpio import Pca9536, Tca6408 class UnknownUsbSdMuxRevisionException(Exception): pass class NotInHostModeException(Exception): pass def autoselect_driver(sg): """ Create a new UsbSdMux with the correct driver for the device at /dev/ Arguments: sg -- /dev/sg* to use """ base_sg = os.path.realpath(sg) sg_name = os.path.basename(base_sg) model_filename = f"/sys/class/scsi_generic/{sg_name}/device/model" try: with open(model_filename) as fh: model = fh.read().strip() if model == "sdmux HS-SD/MMC": return UsbSdMuxClassic(sg) elif model == "sdFST HS-SD/MMC": return UsbSdMuxFast(sg) else: raise UnknownUsbSdMuxRevisionException( f"Could not determine type of USB-SD-Mux. Found unknown SCSI model '{model}'." ) except FileNotFoundError as e: raise UnknownUsbSdMuxRevisionException( f"Could not determine type of USB-SD-Mux. Does {model_filename} exist?" ) from e class UsbSdMux: """ Class to provide an interface for the multiplexer on an usb-sd-mux. """ def __init__(self, sg): """ Create a new UsbSdMux. Arguments: sg -- /dev/sg* to use """ raise NotImplementedError() def get_mode(self): """ Returns currently selected mode as string """ raise NotImplementedError() def mode_disconnect(self, wait=True): """ Will disconnect the Micro-SD Card from both host and DUT. Arguments: wait -- Command will block for some time until the voltage-supply of the sd-card is known to be close to zero """ raise NotImplementedError() def mode_DUT(self, wait=True): """ Switches the MicroSD-Card to the DUT. This Command will issue a disconnect first to make sure the SD-card has been properly disconnected from both sides and its supply was off. """ raise NotImplementedError() def mode_host(self, wait=True): """ Switches the MicroSD-Card to the Host. This Command will issue a disconnect first to make sure the SD-card has been properly disconnected from both sides and its supply was off. """ raise NotImplementedError() def gpio_get(self, gpio): """ Reads the value of gpio and returns "high" or "low" """ raise NotImplementedError() def gpio_set_high(self, gpio): """ Sets a gpio high. """ raise NotImplementedError() def gpio_set_low(self, gpio): """ Sets a gpio low. """ raise NotImplementedError() def get_card_info(self): if self.get_mode() != "host": raise NotInHostModeException() result = {} scr = self._usb.read_scr() result["scr"] = sd_regs.SCR(scr.hex()).decode() cid = self._usb.read_cid() result["cid"] = sd_regs.CID(cid.hex()).decode() csd = self._usb.read_csd() result["csd"] = sd_regs.decode_csd(csd.hex()).decode() return result class UsbSdMuxClassic(UsbSdMux): _DAT_enable = 0x00 _DAT_disable = Pca9536.gpio_0 _PWR_enable = 0x00 _PWR_disable = Pca9536.gpio_1 _select_DUT = Pca9536.gpio_2 _select_HOST = 0x00 _card_inserted = 0x00 _card_removed = Pca9536.gpio_3 def __init__(self, sg): self._pca = Pca9536(sg) self._usb = self._pca.get_usb() def get_mode(self): val = self._pca.get_input_values() # If the SD-Card is disabled, we do not need to check for the selected mode. # PWR_disable and DAT_disable are always switched at the same time. # Let's assume it is sufficient to check one of both. if val & self._PWR_disable: return "off" if val & self._select_DUT: return "dut" return "host" def mode_disconnect(self, wait=True): # Set the output registers to known values and activate them afterward self._pca.output_values(self._DAT_disable | self._PWR_disable | self._select_HOST | self._card_removed) self._pca.set_pin_to_output(Pca9536.gpio_0 | Pca9536.gpio_1 | Pca9536.gpio_2 | Pca9536.gpio_3) if wait: time.sleep(1) def mode_DUT(self, wait=True): self.mode_disconnect(wait) # switch selection to DUT first to prevent glitches on power and # data-lines self._pca.output_values(self._DAT_disable | self._PWR_disable | self._select_DUT | self._card_removed) # now connect data and power self._pca.output_values(self._DAT_enable | self._PWR_enable | self._select_DUT | self._card_removed) def mode_host(self, wait=True): self.mode_disconnect(wait) # The disconnect-command has already switched the card to the host. # Thus, we don't need to worry about glitches anymore. # now connect data and power self._pca.output_values(self._DAT_enable | self._PWR_enable | self._select_HOST | self._card_inserted) class UsbSdMuxFast(UsbSdMux): _DAT_enable = 0x00 _DAT_disable = Tca6408.gpio_2 _PWR_enable = 0x00 _PWR_disable = Tca6408.gpio_1 _select_DUT = Tca6408.gpio_0 _select_HOST = 0x00 _card_inserted = 0x00 _card_removed = Tca6408.gpio_3 gpio0 = Tca6408.gpio_5 gpio1 = Tca6408.gpio_4 def __init__(self, sg): self._tca = Tca6408(sg) self._assure_default_state() self._usb = self._tca.get_usb() def _assure_default_state(self): # If the USB-SD-Mux has just been powered on, its default ("DUT") is defined by pull-resistors. # If we now do a "read-modify-write" without taking into account the external default, we will # lose this state. # So let's check if the GPIO-expander is in Power-On-Reset defaults. # If so, write the same state to the device - but with driven outputs. if self._tca.get_gpio_config() == 0xFF: # If all pins are still set to "input" we are in the default state. # Let's set an output value that matches this configuration and set the relevant pins to output. self._tca.output_values(self._DAT_enable | self._PWR_enable | self._select_DUT | self._card_removed) self._tca.set_pin_to_output( Tca6408.gpio_0 | Tca6408.gpio_1 | Tca6408.gpio_2 | Tca6408.gpio_3 | Tca6408.gpio_4 | Tca6408.gpio_5 ) def get_mode(self): val = self._tca.get_input_values() # If the SD-Card is disabled, we do not need to check for the selected mode. # PWR_disable and DAT_disable are always switched at the same time. # Let's assume it is sufficient to check one of both. if val & self._PWR_disable: return "off" if val & self._select_DUT: return "dut" return "host" def mode_disconnect(self, wait=True): self._tca.output_values( values=self._DAT_disable | self._PWR_disable | self._select_HOST | self._card_removed, bitmask=self._tca.gpio_0 | self._tca.gpio_1 | self._tca.gpio_2 | self._tca.gpio_3, ) if wait: time.sleep(1) def mode_DUT(self, wait=True): self.mode_disconnect(wait) # switch selection to DUT first to prevent glitches on power and # data-lines self._tca.output_values( values=self._DAT_disable | self._PWR_disable | self._select_DUT | self._card_removed, bitmask=self._tca.gpio_0 | self._tca.gpio_1 | self._tca.gpio_2 | self._tca.gpio_3, ) # now connect data and power self._tca.output_values( values=self._DAT_enable | self._PWR_enable | self._select_DUT | self._card_removed, bitmask=self._tca.gpio_0 | self._tca.gpio_1 | self._tca.gpio_2 | self._tca.gpio_3, ) def mode_host(self, wait=True): self.mode_disconnect(wait) # The disconnect-command has already switched the card to the host. # Thus, we don't need to worry about glitches anymore. # now connect data and power self._tca.output_values( values=self._DAT_enable | self._PWR_enable | self._select_HOST | self._card_inserted, bitmask=self._tca.gpio_0 | self._tca.gpio_1 | self._tca.gpio_2 | self._tca.gpio_3, ) @staticmethod def _map_gpio(gpio): if gpio == 0: return UsbSdMuxFast.gpio0 elif gpio == 1: return UsbSdMuxFast.gpio1 raise ValueError("Unknown GPIO") def gpio_get(self, gpio): """ Reads the value of gpio and returns "high" or "low" """ gpio = UsbSdMuxFast._map_gpio(gpio) val = self._tca.get_input_values() if val & gpio: return "low" return "high" def gpio_set_high(self, gpio): gpio = UsbSdMuxFast._map_gpio(gpio) self._tca.output_values(0x0, gpio) def gpio_set_low(self, gpio): gpio = UsbSdMuxFast._map_gpio(gpio) self._tca.output_values(gpio, gpio)