pax_global_header00006660000000000000000000000064140757554050014526gustar00rootroot0000000000000052 comment=e4f3eda61c0c2617dd92ebf49d3f4539a2d0cbd6 usbsdmux-0.2.1/000077500000000000000000000000001407575540500134005ustar00rootroot00000000000000usbsdmux-0.2.1/.gitignore000066400000000000000000000000761407575540500153730ustar00rootroot00000000000000*.pyc __pycache__/ build/ dist/ *.egg-info *.venv .tox/ envs/ usbsdmux-0.2.1/COPYING000066400000000000000000000636421407575540500144460ustar00rootroot00000000000000 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-0.2.1/MANIFEST.in000066400000000000000000000002101407575540500151270ustar00rootroot00000000000000include COPYING include fastentrypoints.py graft contrib global-exclude .* global-exclude *~ global-exclude *.swp global-exclude *.pyc usbsdmux-0.2.1/Makefile000066400000000000000000000016031407575540500150400ustar00rootroot00000000000000PYTHON=python3 PYTHON_ENV_ROOT=envs PYTHON_PACKAGING_VENV=$(PYTHON_ENV_ROOT)/$(PYTHON)-packaging-env .PHONY: clean # packaging environment ####################################################### $(PYTHON_PACKAGING_VENV)/.created: REQUIREMENTS.packaging.txt rm -rf $(PYTHON_PACKAGING_VENV) && \ $(PYTHON) -m venv $(PYTHON_PACKAGING_VENV) && \ . $(PYTHON_PACKAGING_VENV)/bin/activate && \ pip install --upgrade pip && \ pip install -r REQUIREMENTS.packaging.txt date > $(PYTHON_PACKAGING_VENV)/.created packaging-env: $(PYTHON_PACKAGING_VENV)/.created sdist: packaging-env . $(PYTHON_PACKAGING_VENV)/bin/activate && \ rm -rf dist *.egg-info && \ ./setup.py sdist _release: sdist . $(PYTHON_PACKAGING_VENV)/bin/activate && \ twine upload dist/* # helper ###################################################################### clean: rm -rf $(PYTHON_ENV_ROOT) envs: env packaging-env usbsdmux-0.2.1/README.rst000066400000000000000000000163461407575540500151010ustar00rootroot00000000000000Welcome to usbsdmux =================== |license| |pypi| Purpose ------- This software is used to control a special piece of hardware called usb-sd-mux from the command line or python. The usb-sd-mux is build 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. High-Level Functions -------------------- usbsdmux provides the following functions: * Multiplexing the SD-Card to either DUT, Host or disconnect with ``usbsdmux`` * Writing the Configuration-EEPROM of the USB2642 from the command line to customize the representation of the USB device: ``usbsdmux-configure`` 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. Quickstart ---------- Create and activate a virtualenv for usbsdmux: .. code-block:: bash $ virtualenv -p python3 venv $ source venv/bin/activate Install usbsdmux into the virtualenv: .. code-block:: bash $ pip install usbsdmux Now you can run ``usbsdmux -h`` to get a list of possible command invocations: .. code-block:: text $ usbsdmux -h usage: usbsdmux [-h] SG {get,dut,client,host,off} positional arguments: SG /dev/sg* to use {get,dut,client,host,off} Action: get - return selected mode dut - set to dut mode client - set to dut mode (alias for dut) host - set to host mode off - set to off mode optional arguments: -h, --help show this help message and exit 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 ``usbsdmux`` as root. If you have installed this tool inside a virtualenv you can just call the shell-wrapper along with the appropriate `/dev/sg*` device path: .. code-block:: bash sudo /path/to/virtualenv/bin/usbsdmux /dev/sg0 dut sudo /path/to/virtualenv/bin/usbsdmux /dev/sg0 host Using as normal user / Reliable names ------------------------------------- The example udev-rule in ``contib/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. 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 thinking about contributing 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 your real name (sorry, no pseudonyms or anonymous contributions). usbsdmux-0.2.1/REQUIREMENTS.packaging.txt000066400000000000000000000000311407575540500200010ustar00rootroot00000000000000setuptools>=36.5.0 twine usbsdmux-0.2.1/contrib/000077500000000000000000000000001407575540500150405ustar00rootroot00000000000000usbsdmux-0.2.1/contrib/udev/000077500000000000000000000000001407575540500160035ustar00rootroot00000000000000usbsdmux-0.2.1/contrib/udev/99-usbsdmux.rules000066400000000000000000000006451407575540500211750ustar00rootroot00000000000000# 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-0.2.1/fastentrypoints.py000066400000000000000000000073751407575540500172420ustar00rootroot00000000000000# Copyright (c) 2016, Aaron Christianson # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' Monkey patch setuptools to write faster console_scripts with this format: import sys from mymodule import entry_function sys.exit(entry_function()) This is better. (c) 2016, Aaron Christianson http://github.com/ninjaaron/fast-entry_points ''' from setuptools.command import easy_install import re TEMPLATE = '''\ # -*- coding: utf-8 -*- import re import sys from {0} import {1} if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit({2}())''' @classmethod def get_args(cls, dist, header=None): """ Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): # ensure_safe_name if re.search(r'[\\/]', name): raise ValueError("Path separators not allowed in script names") script_text = TEMPLATE.format( ep.module_name, ep.attrs[0], '.'.join(ep.attrs)) args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res easy_install.ScriptWriter.get_args = get_args def main(): import os import re import shutil import sys dests = sys.argv[1:] or ['.'] filename = re.sub('\.pyc$', '.py', __file__) for dst in dests: shutil.copy(filename, dst) manifest_path = os.path.join(dst, 'MANIFEST.in') setup_path = os.path.join(dst, 'setup.py') # Insert the include statement to MANIFEST.in if not present with open(manifest_path, 'a+') as manifest: manifest.seek(0) manifest_content = manifest.read() if not 'include fastentrypoints.py' in manifest_content: manifest.write(('\n' if manifest_content else '') + 'include fastentrypoints.py') # Insert the import statement to setup.py if not present with open(setup_path, 'a+') as setup: setup.seek(0) setup_content = setup.read() if not 'import fastentrypoints' in setup_content: setup.seek(0) setup.truncate() setup.write('import fastentrypoints\n' + setup_content) print(__name__) usbsdmux-0.2.1/setup.cfg000066400000000000000000000003051407575540500152170ustar00rootroot00000000000000[metadata] long_description = file: README.rst classifiers = Environment :: Console Natural Language :: English Operating System :: Unix Programming Language :: Python :: 3 :: Only usbsdmux-0.2.1/setup.py000077500000000000000000000013321407575540500151140ustar00rootroot00000000000000#!/usr/bin/env python3 from setuptools import setup import fastentrypoints setup( name="usbsdmux", version="0.2.1", author="Chris Fiege", author_email="python@pengutronix.de", license="LGPL-2.1-or-later", url="https://github.com/pengutronix/usbsdmux", description="Tool to control an usb-sd-mux from the command line", packages=['usbsdmux'], entry_points={ 'console_scripts': [ 'usbsdmux = usbsdmux.__main__:main', 'usbsdmux-configure = usbsdmux.usb2642eeprom:main', 'usbsdmux-service = usbsdmux.service:main', ], }, classifiers=[ "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)" ] ) usbsdmux-0.2.1/usbsdmux/000077500000000000000000000000001407575540500152525ustar00rootroot00000000000000usbsdmux-0.2.1/usbsdmux/__init__.py000066400000000000000000000000001407575540500173510ustar00rootroot00000000000000usbsdmux-0.2.1/usbsdmux/__main__.py000077500000000000000000000067151407575540500173600ustar00rootroot00000000000000#! /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 sys from .usbsdmux import UsbSdMux def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument("sg", metavar="SG", help="/dev/sg* to use") parser.add_argument( "mode", help="Action:\n" "get - return selected mode\n" "dut - set to dut mode\n" "client - set to dut mode (alias for dut)\n" "host - set to host mode\n" "off - set to off mode", choices=["get", "dut", "client", "host", "off"], type=str.lower) # These arguments were previously used for the client/service # based method to grant USB-SD-Mux access to non-root users. # The client/service model is no longer needed due to new udev # rules and a change to how the /dev/sg* devices are accessed. # Display a warning but do not fail when these are used so # existing scripts do not break and can be upgraded gracefully. parser.add_argument("-d", "--direct", help=argparse.SUPPRESS, action="store_true", default=None) parser.add_argument("-c", "--client", help=argparse.SUPPRESS, action="store_true", default=None) parser.add_argument("-s", "--socket", help=argparse.SUPPRESS, default=None) args = parser.parse_args() if any(arg is not None for arg in (args.direct, args.client, args.socket)): print("usbsdmux: usage of -s/-c/-d arguments is deprecated " "as the service/client split is no longer required. " "Please upgrade your scripts to not supply either of these arguments", file=sys.stderr) ctl = UsbSdMux(args.sg) mode = args.mode.lower() try: if mode == "off": ctl.mode_disconnect() elif mode in ("dut", "client"): ctl.mode_DUT() elif mode == "host": ctl.mode_host() elif mode == "get": print(ctl.get_mode()) except FileNotFoundError as fnfe: print(fnfe, file=sys.stderr) sys.exit(1) except PermissionError as perr: print(perr, file=sys.stderr) sys.exit(1) except OSError as ose: if ose.errno == errno.ENOTTY: # ENOTTY is raised when an error occured when calling an ioctl print(ose, file=sys.stderr) print( f"Does '{args.sg}' really point to an USB-SD-Mux?", file=sys.stderr, ) sys.exit(1) else: raise ose if __name__ == "__main__": main() usbsdmux-0.2.1/usbsdmux/ctypehelper.py000066400000000000000000000105411407575540500201510ustar00rootroot00000000000000#!/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) if c_string: count = min(len(nbytes), array_length - 1) else: count = min(len(nbytes), array_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( ["{:02X}".format(x) 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-0.2.1/usbsdmux/pca9536.py000066400000000000000000000055161407575540500167250ustar00rootroot00000000000000#!/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 .usb2642i2c import Usb2642I2C class Pca9536(object): """ 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 = 0x41 # Registers inside the PCA9536 _register_inputPort = 0x00 _register_outputPort = 0x01 _register_polarity = 0x02 _register_configuration = 0x03 gpio_0 = 0x01 gpio_1 = 0x02 gpio_2 = 0x04 gpio_3 = 0x08 _direction_output = 0 _direction_input = 1 def __init__(self, sg): """ Create a new Pca9536-controller. Arguments: sg -- /dev/sg* to use. """ self.sg = sg self._usb = Usb2642I2C(sg) # After POR all Pins are Inputs. This value will from now on mirror the # value of die _register_configuration self._directionMask = 0xFF def _write_register(self, register, value): """ Writes a register on the Pca9536 with a given value. """ self._usb.write_to(self._I2cAddr, [register, value]) def read_register(self, addr, len=1): """ Returns a register of the Pca9536. """ return self._usb.write_read_to(self._I2cAddr, [addr], len) def set_pin_to_output(self, pins): """ Sets the corresponding pins as outputs. Arguments: pins -- Combination of Pca9536.gpio_* """ self._directionMask = self._directionMask & (~pins) self._write_register(self._register_configuration, self._directionMask) def set_pin_to_input(self, pins): """ Sets the corresponding pins as inputs. Arguments: pins -- Combination of Pca9536.gpio_* """ self._directionMask = self._directionMask | pins self._write_register(self._register_configuration, self._directionMask) def output_values(self, values): """ Writes the given values to the GPIO-expander. Pins configured as Inputs are not affected by this. Arguments: values -- Combination of Pca9536.gpio_* """ self._write_register(self._register_outputPort, values) usbsdmux-0.2.1/usbsdmux/service.py000066400000000000000000000030761407575540500172720ustar00rootroot00000000000000#! /usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright (C) 2021 Pengutronix, Leonard Göhrs # # 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 """ This service was intended as systemd-socket-activated unit and provided an interface to the USB-SD-Mux without the need for root privileges. Usage of this service became obsolete in new releases that changed the way the /dev/sg* devices are accessed and that added new udev rules to directly grant device access to the users. This file is kept here to notify users that have set up a systemd service. """ import sys def main(): print("The usage of usbsdmux-service is deprecated.", file=sys.stderr) print("Access to USB-SD-Mux devices is now controlled by a new set of udev rules.", file=sys.stderr) print("Please delete/deactivate the service calling this command.", file=sys.stderr) exit(-1) usbsdmux-0.2.1/usbsdmux/usb2642eeprom.py000077500000000000000000000343701407575540500201550ustar00rootroot00000000000000#!/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 struct import sys import time from .usb2642i2c import Usb2642I2C from .ctypehelper import string_to_microchip_unicode_uint8_array,\ string_to_uint8_array, list_to_uint8_array, to_pretty_hex """ 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(object): """ 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 = Usb2642I2C(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 Identifyer 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)]) 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-0.2.1/usbsdmux/usb2642i2c.py000066400000000000000000000376401407575540500173430ustar00rootroot00000000000000#!/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 .ctypehelper import string_to_microchip_unicode_uint8_array,\ string_to_uint8_array, list_to_uint8_array, to_pretty_hex """ 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 Usb2642I2C(object): """ 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 USB2642I2C-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 = len(data) if len(data) <= MAXLEN else MAXLEN dataArray = (ctypes.c_uint8 * MAXLEN)() for i in range(count): dataArray[i] = data[i] 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 = readLength if readLength <= MAXLEN else MAXLEN readDataArray = (ctypes.c_uint8 * MAXLEN)() MAXLEN = 9 writeCount = len(writeData) if len(writeData) <= MAXLEN else MAXLEN writeDataArray = (ctypes.c_uint8 * MAXLEN)() for i in range(min(MAXLEN, len(writeData))): writeDataArray[i] = writeData[i] 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, I2cCommandPayload = 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 oder 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("SG_IO ioctl() failed with non-zero exit-code {}"\ .format(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) # First looked like the data block was prefixed with some magic. # But at a second look this was not the case. Setting the length of this # field to 0 bytes prevents any padding. data_prefix = list_to_uint8_array([], 0) # 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)() for i in range(ctypes.sizeof(data_prefix)): payload[i] = data_prefix[i] for i in range(ctypes.sizeof(data)): payload[i+ctypes.sizeof(data_prefix)] = data[i] for i in range(ctypes.sizeof(data_suffix)): payload[i+ctypes.sizeof(data_prefix)+ctypes.sizeof(data)] = data_suffix[i] # 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 wit 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(\ "SCSI-Transaction ended with status {}. I2C-Transaction has probably failed.".\ format(sgio.status)) ret = [] for i in range(min(len(data), readLength)): ret.append(data[i]) return ret 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(\ "SCSI-Transaction ended with status {}. I2C-Transaction has probably failed.".\ format(sgio.status)) usbsdmux-0.2.1/usbsdmux/usbsdmux.py000066400000000000000000000072111407575540500174770ustar00rootroot00000000000000#!/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 time from .pca9536 import Pca9536 class UsbSdMux(object): """ Class to provide an interface for the multiplexer on an usb-sd-mux. """ _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): """ Create a new UsbSdMux. Arguments: sg -- /dev/sg* to use """ self._pca = Pca9536(sg) def get_mode(self): """ Returns currently selected mode as string """ val = self._pca.read_register(1)[0] # 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): """ Will disconnect the Micro-SD Card from both host and DUT. Arugments: wait -- Command will block for some time until the voltage-supply of the sd-card is known to be close to zero """ # Set the output registers to known values and activate them afterwards 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): """ Switches the MicroSD-Card to the DUT. This Command will issue a disconnect first to make sure the the SD-card has been properly disconnected from both sides and it's supply was off. """ 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): """ Switches the MicroSD-Card to the Host. This Command will issue a disconnect first to make sure the the SD-card has been properly disconnected from both sides and it's supply was off. """ 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)