diff --git a/pom.xml b/pom.xml index 2cbe474..3f60a2b 100644 --- a/pom.xml +++ b/pom.xml @@ -173,103 +173,23 @@ - + org.apache.maven.plugins maven-jar-plugin 2.4 - - - - org.usb4java.Main - org.usb4java - true - - - - - - usb4java - jar - package - - usb4java - - org/libusb4java/** - - - - - libusb - jar - package - - libusb - - org/usb4java/** - - - - - libusb-no-natives - jar - package - - libusb-no-natives - - org/usb4java/** - org/libusb4java/*-*/** - - - - - libusb-natives - jar - package - - libusb-natives - - org/libusb4java/*-*/** - - - - - - org.codehaus.plexus plexus-archiver - 2.1.1 + 2.4.4 - - - maven-assembly-plugin - 2.4 - - false - - src/main/assembly/tarball.xml - src/main/assembly/zip.xml - - - - - package-assembly - package - - attached - - - - - @@ -348,18 +268,14 @@ junit 4.11 test - + - org.mockito - mockito-core - 1.9.5 + org.usb4java + libusb4java + linux-x86_64 + 1.2.0-SNAPSHOT test - - - javax.usb - usb-api - 1.0.2 - + org.apache.commons commons-lang3 diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 6ffddfb..e4d2690 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -8,7 +8,11 @@ Klaus Reimer - + + + Split project into usb4java (Main library), usb4java-javax + (javax.usb extension) and libusb4java (Native code). + Add hotplug support to low-level API. diff --git a/src/firmware/c/LICENSE.txt b/src/firmware/c/LICENSE.txt deleted file mode 100644 index 94a9ed0..0000000 --- a/src/firmware/c/LICENSE.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, 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 -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If 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 convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU 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 -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state 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 program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/src/firmware/c/Makefile b/src/firmware/c/Makefile deleted file mode 100644 index 175c8cf..0000000 --- a/src/firmware/c/Makefile +++ /dev/null @@ -1,106 +0,0 @@ -# ======================================================================== -# $Id$ -# Copyright (C) 2010 microblinks UG (Haftungsbeschraenkt) -# See LICENSE.txt for licensing information -# ======================================================================== - -# Project information -NAME = usb4java-test-firmware -MAJOR_VERSION = 1 -MINOR_VERSION = 0 -VERSION = $(MAJOR_VERSION).$(MINOR_VERSION) - -# Programmer information -PROGRAMMER = avrispmkII -PORT = usb:30 - -# Device information -DEVICE = atmega88 -F_CPU = 12000000 - -# Paths and filenames -SRC = . -TARGET = ../../../target/firmware -ELFFILE = $(TARGET)/$(NAME)-$(VERSION).elf -BINFILE = $(TARGET)/$(NAME)-$(VERSION).bin -HEXFILE = $(TARGET)/$(NAME)-$(VERSION).hex - -# Objects to compile -OBJECTS = \ - $(TARGET)/usbdrv/usbdrv.o \ - $(TARGET)/usbdrv/usbdrvasm.o \ - $(TARGET)/pwm/pwm.o \ - $(TARGET)/main.o - -# Include files -INCLUDES = \ - $(SRC)/descriptor.h \ - $(SRC)/usbconfig.h \ - $(SRC)/pwm/pwm.h \ - $(SRC)/pwm/pwmconfig.h - -# Compiler configuration -CC = avr-gcc -OBJCOPY = avr-objcopy -SIZE = avr-size -INCLUDEDIRS = -I$(SRC) -I$(SRC)/usbdrv -CFLAGS = -Wall -Werror -Os $(INCLUDEDIRS) -mmcu=$(DEVICE) \ - -DF_CPU=$(F_CPU) -DDEBUG_LEVEL=0 -DVERSION=$(VERSION) \ - -DMAJOR_VERSION=$(MAJOR_VERSION) -DMINOR_VERSION=$(MINOR_VERSION) -LDFLAGS = - -# AVR Dude configuration -AVRDUDE = avrdude -AVRDUDE_FLAGS = -c $(PROGRAMMER) -P $(PORT) -p $(DEVICE) - -# Default target -all: $(HEXFILE) $(BINFILE) - -# Builds the HEX file -$(HEXFILE): $(ELFFILE) - @echo "Building $(HEXFILE)" - @$(OBJCOPY) -j .text -j .data -O ihex $(ELFFILE) $(HEXFILE) - -# Builds the RAW file -$(BINFILE): $(ELFFILE) - @echo "Building $(BINFILE)" - @$(OBJCOPY) -j .text -j .data -O binary $(ELFFILE) $(BINFILE) - -# Builds the BIN file -$(ELFFILE): $(OBJECTS) - @echo "Building $(ELFFILE)" - @$(CC) $(CFLAGS) $(LDFLAGS) -o $(ELFFILE) $(OBJECTS) - @$(SIZE) $(ELFFILE) - -# Removes all build files from the source -clean: - @echo "Cleaning source" - @$(RM) -rf $(TARGET) - -# Create source distribution archive -dist: - mkdir .$(NAME)-$(VERSION) - cp -raf * .$(NAME)-$(VERSION) - find .$(NAME)-$(VERSION) -name "*.svn" | xargs rm -rf - rm -rf .$(NAME)-$(VERSION)/$(TARGET) - mv .$(NAME)-$(VERSION) $(NAME)-$(VERSION) - mkdir -p $(TARGET) - tar cvfj $(TARGET)/$(NAME)-$(VERSION).tar.bz2 $(NAME)-$(VERSION) - rm -rf $(NAME)-$(VERSION) - -# Flashes the firmware -flash: $(HEXFILE) - @echo "Flashing firmware" - @$(AVRDUDE) $(AVRDUDE_FLAGS) -U flash:w:$(HEXFILE):i - -# Generic target for compiling C files -$(TARGET)/%.o: $(SRC)/%.c $(INCLUDES) - @echo "Compiling $< to $@" - @mkdir -p "$(@D)" - @$(CC) $(CFLAGS) -c "$<" -o "$@" - -# Generic target for compiling assembler files -$(TARGET)/%.o: $(SRC)/%.S $(INCLUDES) - @echo "Assembling $< to $@" - @mkdir -p "$(@D)" - @$(CC) $(CFLAGS) -x assembler-with-cpp -c "$<" -o "$@" diff --git a/src/firmware/c/README.txt b/src/firmware/c/README.txt deleted file mode 100644 index d61b2ea..0000000 --- a/src/firmware/c/README.txt +++ /dev/null @@ -1,23 +0,0 @@ -The usb4java test firmware for the microblinks.de L controller. - -Makefile targets: - -all: Compiles the firmware. HEX file is then located in target directory. -clean: Removes all build artifacts from the source directory. -dist: Creates source distribution archive -flash: Builds the firmware and flashes it to the device - -To compile you need the packages gcc-avr and avr-libc. To flash you need -the package avrdude - -The programmer and the port for avrdude can be specified with the -variables PROGRAMMER and PORT. See avrdude manual for details. - -Example: - -make flash PROGRAMMER=avrispmkII PORT=usb:30 - - -This software includes V-USB (http://www.obdev.at/products/vusb/) from -Objective Development (http://www.obdev.at/). The source code together with -its license is located in the usbdrv folder. diff --git a/src/firmware/c/descriptor.h b/src/firmware/c/descriptor.h deleted file mode 100644 index 80cb09c..0000000 --- a/src/firmware/c/descriptor.h +++ /dev/null @@ -1,109 +0,0 @@ -#if USB_CFG_DESCR_PROPS_CONFIGURATION != 0 - -char usbDescriptorConfiguration[] = { /* USB configuration descriptor */ - 9, /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */ - USBDESCR_CONFIG, /* descriptor type */ - 18 + 12 * 7, 0, - /* total length of data returned (including inlined descriptors) */ - 1, /* number of interfaces in this configuration */ - 1, /* index of this configuration */ - 0, /* configuration name string index */ - (1 << 7) | (1 << 5), /* attributes */ - USB_CFG_MAX_BUS_POWER/2, /* max USB current in 2mA units */ - - 9, /* sizeof(usbDescrInterface): length of descriptor in bytes */ - USBDESCR_INTERFACE, /* descriptor type */ - 0, /* index of this interface */ - 0, /* alternate setting for this interface */ - 12, /* endpoints excl 0: number of endpoint descriptors to follow */ - USB_CFG_INTERFACE_CLASS, - USB_CFG_INTERFACE_SUBCLASS, - USB_CFG_INTERFACE_PROTOCOL, - 0, /* string index for interface */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x81, /* IN endpoint number 1 */ - 0x03, /* attrib: Interrupt endpoint */ - 64, 0, /* maximum packet size */ - USB_CFG_INTR_POLL_INTERVAL, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x01, /* OUT endpoint number 2 */ - 0x03, /* attrib: Interrupt endpoint */ - 64, 0, /* maximum packet size */ - USB_CFG_INTR_POLL_INTERVAL, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x82, /* IN endpoint number 1 */ - 0x03, /* attrib: Interrupt endpoint */ - 8, 0, /* maximum packet size */ - USB_CFG_INTR_POLL_INTERVAL, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x02, /* OUT endpoint number 2 */ - 0x03, /* attrib: Interrupt endpoint */ - 8, 0, /* maximum packet size */ - USB_CFG_INTR_POLL_INTERVAL, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x83, /* IN endpoint number 1 */ - 0x02, /* attrib: Bulk endpoint */ - 64, 0, /* maximum packet size */ - 0, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x03, /* OUT endpoint number 2 */ - 0x02, /* attrib: Bulk endpoint */ - 64, 0, /* maximum packet size */ - 0, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x84, /* IN endpoint number 1 */ - 0x02, /* attrib: Bulk endpoint */ - 8, 0, /* maximum packet size */ - 0, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x04, /* OUT endpoint number 2 */ - 0x02, /* attrib: Bulk endpoint */ - 8, 0, /* maximum packet size */ - 0, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x88, /* IN endpoint number 1 */ - 0x01, /* attrib: Isochronous endpoint */ - 8, 0, /* maximum packet size */ - 1, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x08, /* OUT endpoint number 2 */ - 0x01, /* attrib: Isochronous endpoint */ - 8, 0, /* maximum packet size */ - 1, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x09, /* OUT endpoint number 2 */ - 0x00, /* attrib: Control endpoint */ - 8, 0, /* maximum packet size */ - 0, /* in ms */ - - 7, /* sizeof(usbDescrEndpoint) */ - USBDESCR_ENDPOINT, /* descriptor type = endpoint */ - (char)0x89, /* OUT endpoint number 2 */ - 0x00, /* attrib: Control endpoint */ - 8, 0, /* maximum packet size */ - 0, /* in ms */ -}; - -#endif diff --git a/src/firmware/c/main.c b/src/firmware/c/main.c deleted file mode 100644 index 5f87f5a..0000000 --- a/src/firmware/c/main.c +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md file for licensing information. - */ - -#include -#include -#include -#include -#include -#include "pwm/pwm.h" -#include "usbdrv/usbdrv.h" -#include "descriptor.h" - -/** Map output channels to port pins */ -#define CHANNEL0 PIN_PB1 -#define CHANNEL1 PIN_PB2 -#define CHANNEL2 PIN_PD6 -#define CHANNEL3 PIN_PD5 -#define CHANNEL4 PIN_PB3 -#define CHANNEL5 PIN_PD3 - -/** Blinks memory size */ -#define MEM_SIZE 16 - -/** The flash checksum constant (1010 0101) */ -#define FLASH_CHECKSUM 0xa5 - -/** Data transfer write index */ -static unsigned usbWriteIndex; - -/** Data transfer write length */ -static unsigned usbWriteLength; - -/** The blinks memory */ -static unsigned char memory[MEM_SIZE]; - -/** The flash checksum flag in EEPROM */ -static uint8_t flashChecksum = 0; - -static unsigned char buffer[512]; - -static int buffer_size; - -static int buffer_read_index = 0; - -static int buffer_write_index = 0; - -static int dropper_index = 0; - -static int to_read = 0; - -static int to_write = 0; - -static unsigned char buffer_transform; - -static uint16_t restart; - -/** - * Reads the flash checksum into RAM. - */ -static void readFlashChecksum() -{ - eeprom_busy_wait(); - flashChecksum = eeprom_read_byte((uint8_t *) 0); -} - -/** - * Writes the flash checksum to EEPROM. - */ -static void writeFlashChecksum() -{ - eeprom_busy_wait(); - eeprom_write_byte((uint8_t *) 0, flashChecksum); -} - - -static void reenumerate(uint16_t delay) -{ - usbDeviceDisconnect(); - do - { - _delay_ms(1); - } - while(--delay); - usbDeviceConnect(); - - pwmSet(CHANNEL0, 0, 0); - pwmSet(CHANNEL1, 0, 0); - pwmSet(CHANNEL2, 255, 0); -} - - -/** - * Called when a larger data block is received by the device. It writes - * the data to the blinks memory. - * - * @param data * The data block - * @param len - * The length of the data block. - * @return 1 when no more data is expected, 0 if more data is expected, 0xff - * on error. - */ -uchar usbFunctionWrite(uchar *data, uchar len) -{ - while (len && usbWriteLength) - { - buffer[usbWriteIndex] = data[0]; - usbWriteIndex++; - data++; - len--; - usbWriteLength--; - } - return usbWriteLength ? 0 : 1; -} - -uchar usbFunctionRead(uchar *data, uchar len) -{ - pwmSet(CHANNEL2, 0, 0); - pwmSet(CHANNEL1, 0, 0); - pwmSet(CHANNEL0, 0, 0); - return 1; -} - -/** - * Called to setup a USB request. In most cases this also handles the whole - * USB request. Only when a larger data block is to written to the memory - * then it passes the control to the usbFunctionWrite function. - */ -usbMsgLen_t usbFunctionSetup(uchar setupData[8]) -{ - #define usbData ((usbRequest_t *) setupData) - - switch (usbData->bRequest) - { - case 0x14: - return 0xff; - - /* Go into flash mode */ - case 0x2: - restart--; - memory[0] &= 0xbf; - break; - - case 0x1: - case 0xb0: - if (usbData->bmRequestType & USBRQ_DIR_DEVICE_TO_HOST) - { - /* Read mode */ - usbMsgPtr = &buffer[usbData->wIndex.word]; - return usbData->wLength.word > buffer_size ? buffer_size : usbData->wLength.word; - } - else - { - /* Write mode */ - usbWriteIndex = usbData->wIndex.word; - usbWriteLength = usbData->wLength.word; - buffer_size = usbData->wLength.word; - return USB_NO_MSG; - } - break; - - case 0xa8: - if (!(usbData->bmRequestType & USBRQ_DIR_DEVICE_TO_HOST)) - { - pwmSet(CHANNEL0, 255, 0); - pwmSet(CHANNEL1, 255, 0); - pwmSet(CHANNEL2, 255, 0); - restart--; - return 0; - } - break; - - default: - break; - - - } - - return 0; -} - -void usbFunctionWriteOut(uchar *data, uchar len) -{ - int i; - - // Check if this is a new data block - if (!to_write) - { - buffer_transform = data[0]; - to_write = (((int) data[1]) << 8) | data[2]; - dropper_index = 0; - } - - // Copy and transform data - for (i = 0; i < len; i++) - { - switch (buffer_transform) - { - case 1: - buffer[buffer_write_index] = data[i]; - to_write--; - buffer_write_index++; - break; - - case 2: - buffer[buffer_write_index] = data[i] ^ 0xff; - to_write--; - buffer_write_index++; - break; - - case 3: - buffer[buffer_write_index] = data[i] ^ 0x55; - to_write--; - buffer_write_index++; - break; - - case 4: - if (dropper_index != 2) - { - buffer[buffer_write_index] = data[i] ^ 0x55; - buffer_write_index++; - dropper_index++; - } else dropper_index = 0; - to_write--; - break; - - default: - pwmSet(CHANNEL0, 255, 0); - pwmSet(CHANNEL1, 0, 0); - pwmSet(CHANNEL2, 0, 0); - } - } - - // When write is complete then start reading - if (!to_write) - { - to_read = buffer_write_index; - } -} - -/** - * Initializes USB. - */ -static void initUSB(void) -{ - usbInit(); - reenumerate(250); - sei(); -} - -/** - * Enters the boot loader. - */ -static void enterBootloader() -{ - /* Invalidate the checksum in flash */ - flashChecksum = FLASH_CHECKSUM ^ 0xff; - writeFlashChecksum(); - - /* Enable the watchdog and enter an endless loop. This will reboot - the device */ - cli(); - wdt_enable(WDTO_500MS); - while (1); -} - -/** - * Main program. - */ -int main() -{ - uchar i; - - /* Disable the watchdog */ - MCUSR = 0; - wdt_disable(); - - /* Read the flash checksum from EEPROM */ - readFlashChecksum(); - - /* Initialize USB and enable global interrupts */ - initUSB(); - - /* First initialize the PWM so all LEDs are off. */ - pwmInit(0); - pwmSet(CHANNEL0, 0, 0); - pwmSet(CHANNEL1, 0, 0); - pwmSet(CHANNEL2, 255, 0); - pwmSet(CHANNEL3, 0, 0); - pwmSet(CHANNEL4, 0, 0); - pwmSet(CHANNEL5, 0, 0); - - /* Initialize the blinks memory from eeprom */ - eeprom_busy_wait(); - eeprom_read_block(memory, (uint8_t*) 1, MEM_SIZE); - - /* Make sure bits 7 is cleared and bit 6 is set */ - memory[0] &= 0x7f; - memory[0] |= 0x40; - - /* Infinite program loop */ - i = 0; - while (memory[0] & 0x40) - { - restart = 50; - while (restart) - { - /* Process USB events */ - usbPoll(); - - int len = buffer_write_index - buffer_read_index; - if (len > 0 && usbInterruptIsReady()) - { - if (len > 8) len = 8; - usbSetInterrupt(&buffer[buffer_read_index], len); - buffer_read_index += len; - to_read -= len; - if (!to_read) - { - buffer_read_index = 0; - buffer_write_index = 0; - } - } - - if (restart < 50) restart--; - - /* When this loop has been executed for 100 times then - mark the flash as OK */ - if ((flashChecksum != FLASH_CHECKSUM) && (i < 100)) - { - i++; - if (i == 100) - { - flashChecksum = FLASH_CHECKSUM; - writeFlashChecksum(); - } - } - } - reenumerate(500); - } - - enterBootloader(); - - return 0; -} diff --git a/src/firmware/c/pwm/pwm.c b/src/firmware/c/pwm/pwm.c deleted file mode 100644 index 65cb9cd..0000000 --- a/src/firmware/c/pwm/pwm.c +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md file for licensing information. - */ - -#include -#include -#include -#include -#include "pwm.h" - -static int TCCR0CS[] = { - ((0 << CS02) | (0 << CS01) | (1 << CS00)), // 1 - ((0 << CS02) | (1 << CS01) | (0 << CS00)), // 8 - ((0 << CS02) | (1 << CS01) | (1 << CS00)), // 64 - ((1 << CS02) | (0 << CS01) | (0 << CS00)), // 256 - ((1 << CS02) | (0 << CS01) | (1 << CS00)) // 1024 -}; - -static int TCCR1CS[] = { - ((0 << CS12) | (0 << CS11) | (1 << CS10)), // 1 - ((0 << CS12) | (1 << CS11) | (0 << CS10)), // 8 - ((0 << CS12) | (1 << CS11) | (1 << CS10)), // 64 - ((1 << CS12) | (0 << CS11) | (0 << CS10)), // 256 - ((1 << CS12) | (0 << CS11) | (1 << CS10)) // 1024 -}; - -static int TCCR2CS[] = { - ((0 << CS22) | (0 << CS21) | (1 << CS20)), // 1 - ((0 << CS22) | (1 << CS21) | (0 << CS20)), // 8 - ((1 << CS22) | (0 << CS21) | (0 << CS20)), // 64 - ((1 << CS22) | (1 << CS21) | (0 << CS20)), // 256 - ((1 << CS22) | (1 << CS21) | (1 << CS20)) // 1024 -}; - -// Set the compare output mode bit masks for the three timers -#define TCCR0COM ((1 << COM0A1) | (1 << COM0A0) | (1 << COM0B1) | (1 << COM0B0)) -#define TCCR1COM ((1 << COM1A1) | (1 << COM1A0) | (1 << COM1B1) | (1 << COM1B0)) -#define TCCR2COM ((1 << COM2A1) | (1 << COM2A0) | (1 << COM2B1) | (1 << COM2B0)) - -/** - * Initializes the three timers and the six PWM channels. - * - * @param prescaling - * The prescaling index (0-4) - * - * Abbreviations: - * - * TCCR = Timer/Counter Control Register - * PWM = Pulse Width Modulation - * WGM = Waveform Generation Mode - * COM = Compare Output Mode - * OC = Output Compare pin - * CS = Clock Select - * DDR = Data Direction Register - * OCR = Output Compare Register - */ -void pwmInit(unsigned char prescaling) -{ - // ==================================================================== - // Configure the 16 Bit Timer (TCCR1) for doing PWM on PB1 and PB2 - // ==================================================================== - - TCCR1A = - // PWM Mode: Fast PWM 8 Bit (Part 1) - (1 << WGM10) - | (0 << WGM11) - - // The configured compare output mode - | TCCR1COM - ; - - - TCCR1B = - // PWM Mode: Fast PWM 8 Bit (Part 2) - (1 << WGM12) - | (0 << WGM13) - - // The configured clock selection (Prescaling) - | TCCR1CS[prescaling] - ; - - // Enable OC1A PWM Port - #ifdef USE_PB1 - DDRB |= (1 << PB1); - #endif - - // Enable OC1B PWM Port - #ifdef USE_PB2 - DDRB |= (1 << PB2); - #endif - - - // ==================================================================== - // Configure the first 8 Bit Timer (TCCR0) for doing PWM on PD6/PD5 - // ==================================================================== - - TCCR0A = - // PWM Mode: Fast PWM (Part 1) - (1 << WGM00) - | (1 << WGM01) - - // The configured compare output mode - | TCCR0COM - ; - - TCCR0B = - // PWM Mode: Fast PWM (Part 2) - (0 << WGM02) - - // The configured clock selection (Prescaling) - | TCCR0CS[prescaling] - ; - - // Enable OC0A PWM Port - #ifdef USE_PD6 - DDRD |= (1 << PD6); - #endif - - // Enable OC0B PWM Port - #ifdef USE_PD5 - DDRD |= (1 << PD5); - #endif - - - - // ==================================================================== - // Configure the second 8 Bit Timer (TCCR2) for doing PWM on PB3/PD3 - // ==================================================================== - - TCCR2A = - // PWM Mode: Fast PWM (Part 1) - (1 << WGM20) - | (1 << WGM21) - - // The configured compare output mode - | TCCR2COM - ; - - TCCR2B = - // PWM Mode: Fast PWM (Part 2) - (0 << WGM22) - - // The configured clock selection (Prescaling) - | TCCR2CS[prescaling] - ; - - // Enable OC2A PWM Port - #ifdef USE_PB3 - DDRB |= (1 << PB3); - #endif - - // Enable OC2B PWM Port - #ifdef USE_PD3 - DDRD |= (1 << PD3); - #endif -} diff --git a/src/firmware/c/pwm/pwm.h b/src/firmware/c/pwm/pwm.h deleted file mode 100644 index 38fe1a7..0000000 --- a/src/firmware/c/pwm/pwm.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See COPYING.txt file for licensing information. - */ - -#ifndef PWM_H -#define PWM_H - -#include "pwmconfig.h" - -// Define some understandable aliases for the PWM channels -#define PIN_PD6 OCR0A -#define PIN_PD5 OCR0B -#define PIN_PB1 OCR1AL -#define PIN_PB2 OCR1BL -#define PIN_PB3 OCR2A -#define PIN_PD3 OCR2B - -// Defines the pwmSet function to set a pin value -#define pwmSet(pin, value, invert) pin = (unsigned char) (invert ? value : ~value) - -extern void pwmInit(unsigned char prescaling); - -#endif diff --git a/src/firmware/c/pwm/pwmconfig.h b/src/firmware/c/pwm/pwmconfig.h deleted file mode 100644 index c7d94a5..0000000 --- a/src/firmware/c/pwm/pwmconfig.h +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See COPYING.txt file for licensing information. - */ - -#ifndef PWM_CONFIG_H -#define PWM_CONFIG_H - -/* Define which output pins are in use */ -#define USE_PD6 -#define USE_PD5 -#define USE_PB1 -#define USE_PB2 -#define USE_PB3 -#define USE_PD3 - -/* Defines the prescaling (1, 8, 64, 256 or 1024) */ -#define PRESCALING 1 - -#endif diff --git a/src/firmware/c/usbconfig.h b/src/firmware/c/usbconfig.h deleted file mode 100644 index 64bbb91..0000000 --- a/src/firmware/c/usbconfig.h +++ /dev/null @@ -1,386 +0,0 @@ -/* Name: usbconfig.h - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Christian Starkjohann - * Creation Date: 2005-04-01 - * Tabsize: 4 - * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -#ifndef __usbconfig_h_included__ -#define __usbconfig_h_included__ - -/* -General Description: -This file is an example configuration (with inline documentation) for the USB -driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is -also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may -wire the lines to any other port, as long as D+ is also wired to INT0 (or any -other hardware interrupt, as long as it is the highest level interrupt, see -section at the end of this file). -+ To create your own usbconfig.h file, copy this file to your project's -+ firmware source directory) and rename it to "usbconfig.h". -+ Then edit it accordingly. -*/ - -/* ---------------------------- Hardware Config ---------------------------- */ - -#define USB_CFG_IOPORTNAME D -/* This is the port where the USB bus is connected. When you configure it to - * "B", the registers PORTB, PINB and DDRB will be used. - */ -#define USB_CFG_DMINUS_BIT 1 -/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected. - * This may be any bit in the port. - */ -#define USB_CFG_DPLUS_BIT 2 -/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected. - * This may be any bit in the port. Please note that D+ must also be connected - * to interrupt pin INT0! [You can also use other interrupts, see section - * "Optional MCU Description" below, or you can connect D- to the interrupt, as - * it is required if you use the USB_COUNT_SOF feature. If you use D- for the - * interrupt, the USB interrupt will also be triggered at Start-Of-Frame - * markers every millisecond.] - */ -#define USB_CFG_CLOCK_KHZ (F_CPU/1000) -/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000, - * 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code - * require no crystal, they tolerate +/- 1% deviation from the nominal - * frequency. All other rates require a precision of 2000 ppm and thus a - * crystal! - * Since F_CPU should be defined to your actual clock rate anyway, you should - * not need to modify this setting. - */ -#define USB_CFG_CHECK_CRC 0 -/* Define this to 1 if you want that the driver checks integrity of incoming - * data packets (CRC checks). CRC checks cost quite a bit of code size and are - * currently only available for 18 MHz crystal clock. You must choose - * USB_CFG_CLOCK_KHZ = 18000 if you enable this option. - */ - -/* ----------------------- Optional Hardware Config ------------------------ */ - - #define USB_CFG_PULLUP_IOPORTNAME D -/* If you connect the 1.5k pullup resistor from D- to a port pin instead of - * V+, you can connect and disconnect the device from firmware by calling - * the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h). - * This constant defines the port on which the pullup resistor is connected. - */ -#define USB_CFG_PULLUP_BIT 0 -/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined - * above) where the 1.5k pullup resistor is connected. See description - * above for details. - */ - -/* --------------------------- Functional Range ---------------------------- */ - -#define USB_CFG_HAVE_INTRIN_ENDPOINT 1 -/* Define this to 1 if you want to compile a version with two endpoints: The - * default control endpoint 0 and an interrupt-in endpoint (any other endpoint - * number). - */ -#define USB_CFG_HAVE_INTRIN_ENDPOINT3 1 -/* Define this to 1 if you want to compile a version with three endpoints: The - * default control endpoint 0, an interrupt-in endpoint 3 (or the number - * configured below) and a catch-all default interrupt-in endpoint as above. - * You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature. - */ -#define USB_CFG_EP3_NUMBER 3 -/* If the so-called endpoint 3 is used, it can now be configured to any other - * endpoint number (except 0) with this macro. Default if undefined is 3. - */ -/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */ -/* The above macro defines the startup condition for data toggling on the - * interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1. - * Since the token is toggled BEFORE sending any data, the first packet is - * sent with the oposite value of this configuration! - */ -#define USB_CFG_IMPLEMENT_HALT 1 -/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature - * for endpoint 1 (interrupt endpoint). Although you may not need this feature, - * it is required by the standard. We have made it a config option because it - * bloats the code considerably. - */ -#define USB_CFG_SUPPRESS_INTR_CODE 0 -/* Define this to 1 if you want to declare interrupt-in endpoints, but don't - * want to send any data over them. If this macro is defined to 1, functions - * usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if - * you need the interrupt-in endpoints in order to comply to an interface - * (e.g. HID), but never want to send any data. This option saves a couple - * of bytes in flash memory and the transmit buffers in RAM. - */ -#define USB_CFG_INTR_POLL_INTERVAL 10 -/* If you compile a version with endpoint 1 (interrupt-in), this is the poll - * interval. The value is in milliseconds and must not be less than 10 ms for - * low speed devices. - */ -#define USB_CFG_IS_SELF_POWERED 0 -/* Define this to 1 if the device has its own power supply. Set it to 0 if the - * device is powered from the USB bus. - */ -#define USB_CFG_MAX_BUS_POWER 100 -/* Set this variable to the maximum USB bus power consumption of your device. - * The value is in milliamperes. [It will be divided by two since USB - * communicates power requirements in units of 2 mA.] - */ -#define USB_CFG_IMPLEMENT_FN_WRITE 1 -/* Set this to 1 if you want usbFunctionWrite() to be called for control-out - * transfers. Set it to 0 if you don't need it and want to save a couple of - * bytes. - */ -#define USB_CFG_IMPLEMENT_FN_READ 1 -/* Set this to 1 if you need to send control replies which are generated - * "on the fly" when usbFunctionRead() is called. If you only want to send - * data from a static buffer, set it to 0 and return the data from - * usbFunctionSetup(). This saves a couple of bytes. - */ -#define USB_CFG_IMPLEMENT_FN_WRITEOUT 1 -/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints. - * You must implement the function usbFunctionWriteOut() which receives all - * interrupt/bulk data sent to any endpoint other than 0. The endpoint number - * can be found in 'usbRxToken'. - */ -#define USB_CFG_HAVE_FLOWCONTROL 0 -/* Define this to 1 if you want flowcontrol over USB data. See the definition - * of the macros usbDisableAllRequests() and usbEnableAllRequests() in - * usbdrv.h. - */ -#define USB_CFG_DRIVER_FLASH_PAGE 0 -/* If the device has more than 64 kBytes of flash, define this to the 64 k page - * where the driver's constants (descriptors) are located. Or in other words: - * Define this to 1 for boot loaders on the ATMega128. - */ -#define USB_CFG_LONG_TRANSFERS 1 -/* Define this to 1 if you want to send/receive blocks of more than 254 bytes - * in a single control-in or control-out transfer. Note that the capability - * for long transfers increases the driver size. - */ -/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */ -/* This macro is a hook if you want to do unconventional things. If it is - * defined, it's inserted at the beginning of received message processing. - * If you eat the received message and don't want default processing to - * proceed, do a return after doing your things. One possible application - * (besides debugging) is to flash a status LED on each packet. - */ -/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */ -/* This macro is a hook if you need to know when an USB RESET occurs. It has - * one parameter which distinguishes between the start of RESET state and its - * end. - */ -/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */ -/* This macro (if defined) is executed when a USB SET_ADDRESS request was - * received. - */ -#define USB_COUNT_SOF 1 -/* define this macro to 1 if you need the global variable "usbSofCount" which - * counts SOF packets. This feature requires that the hardware interrupt is - * connected to D- instead of D+. - */ -/* #ifdef __ASSEMBLER__ - * macro myAssemblerMacro - * in YL, TCNT0 - * sts timer0Snapshot, YL - * endm - * #endif - * #define USB_SOF_HOOK myAssemblerMacro - * This macro (if defined) is executed in the assembler module when a - * Start Of Frame condition is detected. It is recommended to define it to - * the name of an assembler macro which is defined here as well so that more - * than one assembler instruction can be used. The macro may use the register - * YL and modify SREG. If it lasts longer than a couple of cycles, USB messages - * immediately after an SOF pulse may be lost and must be retried by the host. - * What can you do with this hook? Since the SOF signal occurs exactly every - * 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in - * designs running on the internal RC oscillator. - * Please note that Start Of Frame detection works only if D- is wired to the - * interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES! - */ -#define USB_CFG_CHECK_DATA_TOGGLING 0 -/* define this macro to 1 if you want to filter out duplicate data packets - * sent by the host. Duplicates occur only as a consequence of communication - * errors, when the host does not receive an ACK. Please note that you need to - * implement the filtering yourself in usbFunctionWriteOut() and - * usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable - * for each control- and out-endpoint to check for duplicate packets. - */ -#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0 -/* define this macro to 1 if you want the function usbMeasureFrameLength() - * compiled in. This function can be used to calibrate the AVR's RC oscillator. - */ -#define USB_USE_FAST_CRC 0 -/* The assembler module has two implementations for the CRC algorithm. One is - * faster, the other is smaller. This CRC routine is only used for transmitted - * messages where timing is not critical. The faster routine needs 31 cycles - * per byte while the smaller one needs 61 to 69 cycles. The faster routine - * may be worth the 32 bytes bigger code size if you transmit lots of data and - * run the AVR close to its limit. - */ - -/* -------------------------- Device Description --------------------------- */ - -#define USB_CFG_VENDOR_ID 0x47, 0x05 /* = 0x16c0 = 5824 = voti.nl */ -//#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */ -/* USB vendor ID for the device, low byte first. If you have registered your - * own Vendor ID, define it here. Otherwise you may use one of obdev's free - * shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules! - * *** IMPORTANT NOTE *** - * This template uses obdev's shared VID/PID pair for Vendor Class devices - * with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand - * the implications! - */ -#define USB_CFG_DEVICE_ID 0x02, 0x10 /* = 0x05dc = 1500 */ -//#define USB_CFG_DEVICE_ID 0xdc, 0x05 /* = 0x05dc = 1500 */ -/* This is the ID of the product, low byte first. It is interpreted in the - * scope of the vendor ID. If you have registered your own VID with usb.org - * or if you have licensed a PID from somebody else, define it here. Otherwise - * you may use one of obdev's free shared VID/PID pairs. See the file - * USB-IDs-for-free.txt for details! - * *** IMPORTANT NOTE *** - * This template uses obdev's shared VID/PID pair for Vendor Class devices - * with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand - * the implications! - */ -#define USB_CFG_DEVICE_VERSION 0x00, 0x01 -/* Version number of the device: Minor number first, then major number. - */ -#define USB_CFG_VENDOR_NAME 'M', 'a', 'n', 'u', 'f', 'a', 'c', 't', 'u', 'r', 'e', 'r' -#define USB_CFG_VENDOR_NAME_LEN 12 -/* These two values define the vendor name returned by the USB device. The name - * must be given as a list of characters under single quotes. The characters - * are interpreted as Unicode (UTF-16) entities. - * If you don't want a vendor name string, undefine these macros. - * ALWAYS define a vendor name containing your Internet domain name if you use - * obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for - * details. - */ -#define USB_CFG_DEVICE_NAME 'J', 'S', 'R', '8', '0', ' ', 'T', 'C', 'K', ' ', 'D', 'e', 'v', 'i', 'c', 'e' -#define USB_CFG_DEVICE_NAME_LEN 16 -/* Same as above for the device name. If you don't want a device name, undefine - * the macros. See the file USB-IDs-for-free.txt before you assign a name if - * you use a shared VID/PID. - */ -#define USB_CFG_SERIAL_NUMBER 'S', 'N', '1', '2', '3', '4', '5', '6' -#define USB_CFG_SERIAL_NUMBER_LEN 8 -/* Same as above for the serial number. If you don't want a serial number, - * undefine the macros. - * It may be useful to provide the serial number through other means than at - * compile time. See the section about descriptor properties below for how - * to fine tune control over USB descriptors such as the string descriptor - * for the serial number. - */ -#define USB_CFG_DEVICE_CLASS 0 /* set to 0 if deferred to interface */ -#define USB_CFG_DEVICE_SUBCLASS 0 -/* See USB specification if you want to conform to an existing device class. - * Class 0xff is "vendor specific". - */ -#define USB_CFG_INTERFACE_CLASS 0xff /* define class here if not at device level */ -#define USB_CFG_INTERFACE_SUBCLASS 0 -#define USB_CFG_INTERFACE_PROTOCOL 0 -/* See USB specification if you want to conform to an existing device class or - * protocol. The following classes must be set at interface level: - * HID class is 3, no subclass and protocol required (but may be useful!) - * CDC class is 2, use subclass 2 and protocol 1 for ACM - */ -/* #define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 42 */ -/* Define this to the length of the HID report descriptor, if you implement - * an HID device. Otherwise don't define it or define it to 0. - * If you use this define, you must add a PROGMEM character array named - * "usbHidReportDescriptor" to your code which contains the report descriptor. - * Don't forget to keep the array and this define in sync! - */ - -/* #define USB_PUBLIC static */ -/* Use the define above if you #include usbdrv.c instead of linking against it. - * This technique saves a couple of bytes in flash memory. - */ - -/* ------------------- Fine Control over USB Descriptors ------------------- */ -/* If you don't want to use the driver's default USB descriptors, you can - * provide our own. These can be provided as (1) fixed length static data in - * flash memory, (2) fixed length static data in RAM or (3) dynamically at - * runtime in the function usbFunctionDescriptor(). See usbdrv.h for more - * information about this function. - * Descriptor handling is configured through the descriptor's properties. If - * no properties are defined or if they are 0, the default descriptor is used. - * Possible properties are: - * + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched - * at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is - * used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if - * you want RAM pointers. - * + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found - * in static memory is in RAM, not in flash memory. - * + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash), - * the driver must know the descriptor's length. The descriptor itself is - * found at the address of a well known identifier (see below). - * List of static descriptor names (must be declared PROGMEM if in flash): - * char usbDescriptorDevice[]; - * char usbDescriptorConfiguration[]; - * char usbDescriptorHidReport[]; - * char usbDescriptorString0[]; - * int usbDescriptorStringVendor[]; - * int usbDescriptorStringDevice[]; - * int usbDescriptorStringSerialNumber[]; - * Other descriptors can't be provided statically, they must be provided - * dynamically at runtime. - * - * Descriptor properties are or-ed or added together, e.g.: - * #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18)) - * - * The following descriptors are defined: - * USB_CFG_DESCR_PROPS_DEVICE - * USB_CFG_DESCR_PROPS_CONFIGURATION - * USB_CFG_DESCR_PROPS_STRINGS - * USB_CFG_DESCR_PROPS_STRING_0 - * USB_CFG_DESCR_PROPS_STRING_VENDOR - * USB_CFG_DESCR_PROPS_STRING_PRODUCT - * USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER - * USB_CFG_DESCR_PROPS_HID - * USB_CFG_DESCR_PROPS_HID_REPORT - * USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver) - * - * Note about string descriptors: String descriptors are not just strings, they - * are Unicode strings prefixed with a 2 byte header. Example: - * int serialNumberDescriptor[] = { - * USB_STRING_DESCRIPTOR_HEADER(6), - * 'S', 'e', 'r', 'i', 'a', 'l' - * }; - */ - -#define USB_CFG_DESCR_PROPS_DEVICE 0 -#define USB_CFG_DESCR_PROPS_CONFIGURATION (USB_PROP_IS_RAM | USB_PROP_LENGTH(18 + 12 * 7)) -#define USB_CFG_DESCR_PROPS_STRINGS 0 -#define USB_CFG_DESCR_PROPS_STRING_0 0 -#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0 -#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0 -#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0 -#define USB_CFG_DESCR_PROPS_HID 0 -#define USB_CFG_DESCR_PROPS_HID_REPORT 0 -#define USB_CFG_DESCR_PROPS_UNKNOWN 0 - - -//#define usbMsgPtr_t unsigned short -/* If usbMsgPtr_t is not defined, it defaults to 'uchar *'. We define it to - * a scalar type here because gcc generates slightly shorter code for scalar - * arithmetics than for pointer arithmetics. Remove this define for backward - * type compatibility or define it to an 8 bit type if you use data in RAM only - * and all RAM is below 256 bytes (tiny memory model in IAR CC). - */ - -/* ----------------------- Optional MCU Description ------------------------ */ - -/* The following configurations have working defaults in usbdrv.h. You - * usually don't need to set them explicitly. Only if you want to run - * the driver on a device which is not yet supported or with a compiler - * which is not fully supported (such as IAR C) or if you use a differnt - * interrupt than INT0, you may have to define some of these. - */ -/* #define USB_INTR_CFG MCUCR */ -/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */ -/* #define USB_INTR_CFG_CLR 0 */ -/* #define USB_INTR_ENABLE GIMSK */ -/* #define USB_INTR_ENABLE_BIT INT0 */ -/* #define USB_INTR_PENDING GIFR */ -/* #define USB_INTR_PENDING_BIT INTF0 */ -/* #define USB_INTR_VECTOR INT0_vect */ - -#endif /* __usbconfig_h_included__ */ diff --git a/src/firmware/c/usbdrv/Changelog.txt b/src/firmware/c/usbdrv/Changelog.txt deleted file mode 100644 index 3da56f2..0000000 --- a/src/firmware/c/usbdrv/Changelog.txt +++ /dev/null @@ -1,329 +0,0 @@ -This file documents changes in the firmware-only USB driver for atmel's AVR -microcontrollers. New entries are always appended to the end of the file. -Scroll down to the bottom to see the most recent changes. - -2005-04-01: - - Implemented endpoint 1 as interrupt-in endpoint. - - Moved all configuration options to usbconfig.h which is not part of the - driver. - - Changed interface for usbVendorSetup(). - - Fixed compatibility with ATMega8 device. - - Various minor optimizations. - -2005-04-11: - - Changed interface to application: Use usbFunctionSetup(), usbFunctionRead() - and usbFunctionWrite() now. Added configuration options to choose which - of these functions to compile in. - - Assembler module delivers receive data non-inverted now. - - Made register and bit names compatible with more AVR devices. - -2005-05-03: - - Allow address of usbRxBuf on any memory page as long as the buffer does - not cross 256 byte page boundaries. - - Better device compatibility: works with Mega88 now. - - Code optimization in debugging module. - - Documentation updates. - -2006-01-02: - - Added (free) default Vendor- and Product-IDs bought from voti.nl. - - Added USBID-LICENSE.md file which defines the rules for using the free - shared VID/PID pair. - - Added Readme.txt to the usbdrv directory which clarifies administrative - issues. - -2006-01-25: - - Added "configured state" to become more standards compliant. - - Added "HALT" state for interrupt endpoint. - - Driver passes the "USB Command Verifier" test from usb.org now. - - Made "serial number" a configuration option. - - Minor optimizations, we now recommend compiler option "-Os" for best - results. - - Added a version number to usbdrv.h - -2006-02-03: - - New configuration variable USB_BUFFER_SECTION for the memory section where - the USB rx buffer will go. This defaults to ".bss" if not defined. Since - this buffer MUST NOT cross 256 byte pages (not even touch a page at the - end), the user may want to pass a linker option similar to - "-Wl,--section-start=.mybuffer=0x800060". - - Provide structure for usbRequest_t. - - New defines for USB constants. - - Prepared for HID implementations. - - Increased data size limit for interrupt transfers to 8 bytes. - - New macro usbInterruptIsReady() to query interrupt buffer state. - -2006-02-18: - - Ensure that the data token which is sent as an ack to an OUT transfer is - always zero sized. This fixes a bug where the host reports an error after - sending an out transfer to the device, although all data arrived at the - device. - - Updated docs in usbdrv.h to reflect changed API in usbFunctionWrite(). - -* Release 2006-02-20 - - - Give a compiler warning when compiling with debugging turned on. - - Added Oleg Semyonov's changes for IAR-cc compatibility. - - Added new (optional) functions usbDeviceConnect() and usbDeviceDisconnect() - (also thanks to Oleg!). - - Rearranged tests in usbPoll() to save a couple of instructions in the most - likely case that no actions are pending. - - We need a delay between the SET ADDRESS request until the new address - becomes active. This delay was handled in usbPoll() until now. Since the - spec says that the delay must not exceed 2ms, previous versions required - aggressive polling during the enumeration phase. We have now moved the - handling of the delay into the interrupt routine. - - We must not reply with NAK to a SETUP transaction. We can only achieve this - by making sure that the rx buffer is empty when SETUP tokens are expected. - We therefore don't pass zero sized data packets from the status phase of - a transfer to usbPoll(). This change MAY cause troubles if you rely on - receiving a less than 8 bytes long packet in usbFunctionWrite() to - identify the end of a transfer. usbFunctionWrite() will NEVER be called - with a zero length. - -* Release 2006-03-14 - - - Improved IAR C support: tiny memory model, more devices - - Added template usbconfig.h file under the name usbconfig-prototype.h - -* Release 2006-03-26 - - - Added provision for one more interrupt-in endpoint (endpoint 3). - - Added provision for one interrupt-out endpoint (endpoint 1). - - Added flowcontrol macros for USB. - - Added provision for custom configuration descriptor. - - Allow ANY two port bits for D+ and D-. - - Merged (optional) receive endpoint number into global usbRxToken variable. - - Use USB_CFG_IOPORTNAME instead of USB_CFG_IOPORT. We now construct the - variable name from the single port letter instead of computing the address - of related ports from the output-port address. - -* Release 2006-06-26 - - - Updated documentation in usbdrv.h and usbconfig-prototype.h to reflect the - new features. - - Removed "#warning" directives because IAR does not understand them. Use - unused static variables instead to generate a warning. - - Do not include when compiling with IAR. - - Introduced USB_CFG_DESCR_PROPS_* in usbconfig.h to configure how each - USB descriptor should be handled. It is now possible to provide descriptor - data in Flash, RAM or dynamically at runtime. - - STALL is now a status in usbTxLen* instead of a message. We can now conform - to the spec and leave the stall status pending until it is cleared. - - Made usbTxPacketCnt1 and usbTxPacketCnt3 public. This allows the - application code to reset data toggling on interrupt pipes. - -* Release 2006-07-18 - - - Added an #if !defined __ASSEMBLER__ to the warning in usbdrv.h. This fixes - an assembler error. - - usbDeviceDisconnect() takes pull-up resistor to high impedance now. - -* Release 2007-02-01 - - - Merged in some code size improvements from usbtiny (thanks to Dick - Streefland for these optimizations!) - - Special alignment requirement for usbRxBuf not required any more. Thanks - again to Dick Streefland for this hint! - - Reverted to "#warning" instead of unused static variables -- new versions - of IAR CC should handle this directive. - - Changed Open Source license to GNU GPL v2 in order to make linking against - other free libraries easier. We no longer require publication of the - circuit diagrams, but we STRONGLY encourage it. If you improve the driver - itself, PLEASE grant us a royalty free license to your changes for our - commercial license. - -* Release 2007-03-29 - - - New configuration option "USB_PUBLIC" in usbconfig.h. - - Set USB version number to 1.10 instead of 1.01. - - Code used USB_CFG_DESCR_PROPS_STRING_DEVICE and - USB_CFG_DESCR_PROPS_STRING_PRODUCT inconsistently. Changed all occurrences - to USB_CFG_DESCR_PROPS_STRING_PRODUCT. - - New assembler module for 16.5 MHz RC oscillator clock with PLL in receiver - code. - - New assembler module for 16 MHz crystal. - - usbdrvasm.S contains common code only, clock-specific parts have been moved - to usbdrvasm12.S, usbdrvasm16.S and usbdrvasm165.S respectively. - -* Release 2007-06-25 - - - 16 MHz module: Do SE0 check in stuffed bits as well. - -* Release 2007-07-07 - - - Define hi8(x) for IAR compiler to limit result to 8 bits. This is necessary - for negative values. - - Added 15 MHz module contributed by V. Bosch. - - Interrupt vector name can now be configured. This is useful if somebody - wants to use a different hardware interrupt than INT0. - -* Release 2007-08-07 - - - Moved handleIn3 routine in usbdrvasm16.S so that relative jump range is - not exceeded. - - More config options: USB_RX_USER_HOOK(), USB_INITIAL_DATATOKEN, - USB_COUNT_SOF - - USB_INTR_PENDING can now be a memory address, not just I/O - -* Release 2007-09-19 - - - Split out common parts of assembler modules into separate include file - - Made endpoint numbers configurable so that given interface definitions - can be matched. See USB_CFG_EP3_NUMBER in usbconfig-prototype.h. - - Store endpoint number for interrupt/bulk-out so that usbFunctionWriteOut() - can handle any number of endpoints. - - Define usbDeviceConnect() and usbDeviceDisconnect() even if no - USB_CFG_PULLUP_IOPORTNAME is defined. Directly set D+ and D- to 0 in this - case. - -* Release 2007-12-01 - - - Optimize usbDeviceConnect() and usbDeviceDisconnect() for less code size - when USB_CFG_PULLUP_IOPORTNAME is not defined. - -* Release 2007-12-13 - - - Renamed all include-only assembler modules from *.S to *.inc so that - people don't add them to their project sources. - - Distribute leap bits in tx loop more evenly for 16 MHz module. - - Use "macro" and "endm" instead of ".macro" and ".endm" for IAR - - Avoid compiler warnings for constant expr range by casting some values in - USB descriptors. - -* Release 2008-01-21 - - - Fixed bug in 15 and 16 MHz module where the new address set with - SET_ADDRESS was already accepted at the next NAK or ACK we send, not at - the next data packet we send. This caused problems when the host polled - too fast. Thanks to Alexander Neumann for his help and patience debugging - this issue! - -* Release 2008-02-05 - - - Fixed bug in 16.5 MHz module where a register was used in the interrupt - handler before it was pushed. This bug was introduced with version - 2007-09-19 when common parts were moved to a separate file. - - Optimized CRC routine (thanks to Reimar Doeffinger). - -* Release 2008-02-16 - - - Removed outdated IAR compatibility stuff (code sections). - - Added hook macros for USB_RESET_HOOK() and USB_SET_ADDRESS_HOOK(). - - Added optional routine usbMeasureFrameLength() for calibration of the - internal RC oscillator. - -* Release 2008-02-28 - - - USB_INITIAL_DATATOKEN defaults to USBPID_DATA1 now, which means that we - start with sending USBPID_DATA0. - - Changed defaults in usbconfig-prototype.h - - Added free USB VID/PID pair for MIDI class devices - - Restructured AVR-USB as separate package, not part of PowerSwitch any more. - -* Release 2008-04-18 - - - Restructured usbdrv.c so that it is easier to read and understand. - - Better code optimization with gcc 4. - - If a second interrupt in endpoint is enabled, also add it to config - descriptor. - - Added config option for long transfers (above 254 bytes), see - USB_CFG_LONG_TRANSFERS in usbconfig.h. - - Added 20 MHz module contributed by Jeroen Benschop. - -* Release 2008-05-13 - - - Fixed bug in libs-host/hiddata.c function usbhidGetReport(): length - was not incremented, pointer to length was incremented instead. - - Added code to command line tool(s) which claims an interface. This code - is disabled by default, but may be necessary on newer Linux kernels. - - Added usbconfig.h option "USB_CFG_CHECK_DATA_TOGGLING". - - New header "usbportability.h" prepares ports to other development - environments. - - Long transfers (above 254 bytes) did not work when usbFunctionRead() was - used to supply the data. Fixed this bug. [Thanks to Alexander Neumann!] - - In hiddata.c (example code for sending/receiving data over HID), use - USB_RECIP_DEVICE instead of USB_RECIP_INTERFACE for control transfers so - that we need not claim the interface. - - in usbPoll() loop 20 times polling for RESET state instead of 10 times. - This accounts for the higher clock rates we now support. - - Added a module for 12.8 MHz RC oscillator with PLL in receiver loop. - - Added hook to SOF code so that oscillator can be tuned to USB frame clock. - - Added timeout to waitForJ loop. Helps preventing unexpected hangs. - - Added example code for oscillator tuning to libs-device (thanks to - Henrik Haftmann for the idea to this routine). - - Implemented option USB_CFG_SUPPRESS_INTR_CODE. - -* Release 2008-10-22 - - - Fixed libs-device/osctune.h: OSCCAL is memory address on ATMega88 and - similar, not offset of 0x20 needs to be added. - - Allow distribution under GPLv3 for those who have to link against other - code distributed under GPLv3. - -* Release 2008-11-26 - - - Removed libusb-win32 dependency for hid-data example in Makefile.windows. - It was never required and confused many people. - - Added extern uchar usbRxToken to usbdrv.h. - - Integrated a module with CRC checks at 18 MHz by Lukas Schrittwieser. - -* Release 2009-03-23 - - - Hid-mouse example used settings from hid-data example, fixed that. - - Renamed project to V-USB due to a trademark issue with Atmel(r). - - Changed CommercialLICENSE.md and USBID-LICENSE.md to make the - background of USB ID registration clearer. - -* Release 2009-04-15 - - - Changed CommercialLICENSE.md to reflect the new range of PIDs from - Jason Kotzin. - - Removed USBID-LICENSE.md in favor of USB-IDs-for-free.txt and - USB-ID-FAQ.txt - - Fixed a bug in the 12.8 MHz module: End Of Packet decection was made in - the center between bit 0 and 1 of each byte. This is where the data lines - are expected to change and the sampled data may therefore be nonsense. - We therefore check EOP ONLY if bits 0 AND 1 have both been read as 0 on D-. - - Fixed a bitstuffing problem in the 16 MHz module: If bit 6 was stuffed, - the unstuffing code in the receiver routine was 1 cycle too long. If - multiple bytes had the unstuffing in bit 6, the error summed up until the - receiver was out of sync. - - Included option for faster CRC routine. - Thanks to Slawomir Fras (BoskiDialer) for this code! - - Updated bits in Configuration Descriptor's bmAttributes according to - USB 1.1 (in particular bit 7, it is a must-be-set bit now). - -* Release 2009-08-22 - - - Moved first DBG1() after odDebugInit() in all examples. - - Use vector INT0_vect instead of SIG_INTERRUPT0 if defined. This makes - V-USB compatible with the new "p" suffix devices (e.g. ATMega328p). - - USB_CFG_CLOCK_KHZ setting is now required in usbconfig.h (no default any - more). - - New option USB_CFG_DRIVER_FLASH_PAGE allows boot loaders on devices with - more than 64 kB flash. - - Built-in configuration descriptor allows custom definition for second - endpoint now. - -* Release 2010-07-15 - - - Fixed bug in usbDriverSetup() which prevented descriptor sizes above 255 - bytes. - - Avoid a compiler warning for unused parameter in usbHandleResetHook() when - compiler option -Wextra is enabled. - - Fixed wrong hex value for some IDs in USB-IDs-for-free.txt. - - Keep a define for USBATTR_BUSPOWER, although the flag does not exist - in USB 1.1 any more. Set it to 0. This is for backward compatibility. - -* Release 2012-01-09 - - - Define a separate (defined) type for usbMsgPtr so that projects using a - tiny memory model can define it to an 8 bit type in usbconfig.h. This - change also saves a couple of bytes when using a scalar 16 bit type. - - Inserted "const" keyword for all PROGMEM declarations because new GCC - requires it. - - Fixed problem with dependence of usbportability.h on usbconfig.h. This - problem occurred with IAR CC only. - - Prepared repository for github.com. - -* Release 2012-12-06 \ No newline at end of file diff --git a/src/firmware/c/usbdrv/CommercialLicense.txt b/src/firmware/c/usbdrv/CommercialLicense.txt deleted file mode 100644 index de1a2b0..0000000 --- a/src/firmware/c/usbdrv/CommercialLicense.txt +++ /dev/null @@ -1,166 +0,0 @@ -V-USB Driver Software License Agreement -Version 2012-07-09 - -THIS LICENSE AGREEMENT GRANTS YOU CERTAIN RIGHTS IN A SOFTWARE. YOU CAN -ENTER INTO THIS AGREEMENT AND ACQUIRE THE RIGHTS OUTLINED BELOW BY PAYING -THE AMOUNT ACCORDING TO SECTION 4 ("PAYMENT") TO OBJECTIVE DEVELOPMENT. - - -1 DEFINITIONS - -1.1 "OBJECTIVE DEVELOPMENT" shall mean OBJECTIVE DEVELOPMENT Software GmbH, -Grosse Schiffgasse 1A/7, 1020 Wien, AUSTRIA. - -1.2 "You" shall mean the Licensee. - -1.3 "V-USB" shall mean all files included in the package distributed under -the name "vusb" by OBJECTIVE DEVELOPMENT (http://www.obdev.at/vusb/) -unless otherwise noted. This includes the firmware-only USB device -implementation for Atmel AVR microcontrollers, some simple device examples -and host side software examples and libraries. - - -2 LICENSE GRANTS - -2.1 Source Code. OBJECTIVE DEVELOPMENT shall furnish you with the source -code of V-USB. - -2.2 Distribution and Use. OBJECTIVE DEVELOPMENT grants you the -non-exclusive right to use, copy and distribute V-USB with your hardware -product(s), restricted by the limitations in section 3 below. - -2.3 Modifications. OBJECTIVE DEVELOPMENT grants you the right to modify -the source code and your copy of V-USB according to your needs. - -2.4 USB IDs. OBJECTIVE DEVELOPMENT furnishes you with one or two USB -Product ID(s), sent to you in e-mail. These Product IDs are reserved -exclusively for you. OBJECTIVE DEVELOPMENT has obtained USB Product ID -ranges under the Vendor ID 5824 from Wouter van Ooijen (Van Ooijen -Technische Informatica, www.voti.nl) and under the Vendor ID 8352 from -Jason Kotzin (now flirc.tv, Inc.). Both owners of the Vendor IDs have -obtained these IDs from the USB Implementers Forum, Inc. (www.usb.org). -OBJECTIVE DEVELOPMENT disclaims all liability which might arise from the -assignment of USB IDs. - -2.5 USB Certification. Although not part of this agreement, we want to make -it clear that you cannot become USB certified when you use V-USB or a USB -Product ID assigned by OBJECTIVE DEVELOPMENT. AVR microcontrollers don't -meet the electrical specifications required by the USB specification and -the USB Implementers Forum certifies only members who bought a Vendor ID of -their own. - - -3 LICENSE RESTRICTIONS - -3.1 Number of Units. Only one of the following three definitions is -applicable. Which one is determined by the amount you pay to OBJECTIVE -DEVELOPMENT, see section 4 ("Payment") below. - -Hobby License: You may use V-USB according to section 2 above in no more -than 5 hardware units. These units must not be sold for profit. - -Entry Level License: You may use V-USB according to section 2 above in no -more than 150 hardware units. - -Professional License: You may use V-USB according to section 2 above in -any number of hardware units, except for large scale production ("unlimited -fair use"). Quantities below 10,000 units are not considered large scale -production. If your reach quantities which are obviously large scale -production, you must pay a license fee of 0.10 EUR per unit for all units -above 10,000. - -3.2 Rental. You may not rent, lease, or lend V-USB or otherwise encumber -any copy of V-USB, or any of the rights granted herein. - -3.3 Transfer. You may not transfer your rights under this Agreement to -another party without OBJECTIVE DEVELOPMENT's prior written consent. If -such consent is obtained, you may permanently transfer this License to -another party. The recipient of such transfer must agree to all terms and -conditions of this Agreement. - -3.4 Reservation of Rights. OBJECTIVE DEVELOPMENT retains all rights not -expressly granted. - -3.5 Non-Exclusive Rights. Your license rights under this Agreement are -non-exclusive. - -3.6 Third Party Rights. This Agreement cannot grant you rights controlled -by third parties. In particular, you are not allowed to use the USB logo or -other trademarks owned by the USB Implementers Forum, Inc. without their -consent. Since such consent depends on USB certification, it should be -noted that V-USB will not pass certification because it does not -implement checksum verification and the microcontroller ports do not meet -the electrical specifications. - - -4 PAYMENT - -The payment amount depends on the variation of this agreement (according to -section 3.1) into which you want to enter. Concrete prices are listed on -OBJECTIVE DEVELOPMENT's web site, usually at -http://www.obdev.at/vusb/license.html. You agree to pay the amount listed -there to OBJECTIVE DEVELOPMENT or OBJECTIVE DEVELOPMENT's payment processor -or reseller. - - -5 COPYRIGHT AND OWNERSHIP - -V-USB is protected by copyright laws and international copyright -treaties, as well as other intellectual property laws and treaties. V-USB -is licensed, not sold. - - -6 TERM AND TERMINATION - -6.1 Term. This Agreement shall continue indefinitely. However, OBJECTIVE -DEVELOPMENT may terminate this Agreement and revoke the granted license and -USB-IDs if you fail to comply with any of its terms and conditions. - -6.2 Survival of Terms. All provisions regarding secrecy, confidentiality -and limitation of liability shall survive termination of this agreement. - - -7 DISCLAIMER OF WARRANTY AND LIABILITY - -LIMITED WARRANTY. V-USB IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY -KIND. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OBJECTIVE -DEVELOPMENT AND ITS SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES, EITHER -EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND -NON-INFRINGEMENT, WITH REGARD TO V-USB, AND THE PROVISION OF OR FAILURE -TO PROVIDE SUPPORT SERVICES. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL -RIGHTS. YOU MAY HAVE OTHERS, WHICH VARY FROM STATE/JURISDICTION TO -STATE/JURISDICTION. - -LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, -IN NO EVENT SHALL OBJECTIVE DEVELOPMENT OR ITS SUPPLIERS BE LIABLE FOR ANY -SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER -(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, -BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY -LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE V-USB OR THE -PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF OBJECTIVE -DEVELOPMENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY -CASE, OBJECTIVE DEVELOPMENT'S ENTIRE LIABILITY UNDER ANY PROVISION OF THIS -AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR V-USB. - - -8 MISCELLANEOUS TERMS - -8.1 Marketing. OBJECTIVE DEVELOPMENT has the right to mention for marketing -purposes that you entered into this agreement. - -8.2 Entire Agreement. This document represents the entire agreement between -OBJECTIVE DEVELOPMENT and you. It may only be modified in writing signed by -an authorized representative of both, OBJECTIVE DEVELOPMENT and you. - -8.3 Severability. In case a provision of these terms and conditions should -be or become partly or entirely invalid, ineffective, or not executable, -the validity of all other provisions shall not be affected. - -8.4 Applicable Law. This agreement is governed by the laws of the Republic -of Austria. - -8.5 Responsible Courts. The responsible courts in Vienna/Austria will have -exclusive jurisdiction regarding all disputes in connection with this -agreement. - diff --git a/src/firmware/c/usbdrv/License.txt b/src/firmware/c/usbdrv/License.txt deleted file mode 100644 index 4460cfb..0000000 --- a/src/firmware/c/usbdrv/License.txt +++ /dev/null @@ -1,361 +0,0 @@ -OBJECTIVE DEVELOPMENT GmbH's V-USB driver software is distributed under the -terms and conditions of the GNU GPL version 2 or the GNU GPL version 3. It is -your choice whether you apply the terms of version 2 or version 3. The full -text of GPLv2 is included below. In addition to the requirements in the GPL, -we STRONGLY ENCOURAGE you to do the following: - -(1) Publish your entire project on a web site and drop us a note with the URL. -Use the form at http://www.obdev.at/vusb/feedback.html for your submission. - -(2) Adhere to minimum publication standards. Please include AT LEAST: - - a circuit diagram in PDF, PNG or GIF format - - full source code for the host software - - a Readme.txt file in ASCII format which describes the purpose of the - project and what can be found in which directories and which files - - a reference to http://www.obdev.at/vusb/ - -(3) If you improve the driver firmware itself, please give us a free license -to your modifications for our commercial license offerings. - - - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, 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 or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -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 give any other recipients of the Program a copy of this License -along with the Program. - -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 Program or any portion -of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -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 Program, 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 Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) 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; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, 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 executable. However, as a -special exception, the source code 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. - -If distribution of executable or 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 counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program 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. - - 5. 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 Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program 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 to -this License. - - 7. 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 Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program 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 Program. - -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. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program 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. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 Program -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 Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, 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 - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), 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 Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. 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 program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/src/firmware/c/usbdrv/Readme.txt b/src/firmware/c/usbdrv/Readme.txt deleted file mode 100644 index f6f5d13..0000000 --- a/src/firmware/c/usbdrv/Readme.txt +++ /dev/null @@ -1,172 +0,0 @@ -This is the Readme file to Objective Development's firmware-only USB driver -for Atmel AVR microcontrollers. For more information please visit -http://www.obdev.at/vusb/ - -This directory contains the USB firmware only. Copy it as-is to your own -project and add all .c and .S files to your project (these files are marked -with an asterisk in the list below). Then copy usbconfig-prototype.h as -usbconfig.h to your project and edit it according to your configuration. - - -TECHNICAL DOCUMENTATION -======================= -The technical documentation (API) for the firmware driver is contained in the -file "usbdrv.h". Please read all of it carefully! Configuration options are -documented in "usbconfig-prototype.h". - -The driver consists of the following files: - Readme.txt ............. The file you are currently reading. - Changelog.txt .......... Release notes for all versions of the driver. - usbdrv.h ............... Driver interface definitions and technical docs. -* usbdrv.c ............... High level language part of the driver. Link this - module to your code! -* usbdrvasm.S ............ Assembler part of the driver. This module is mostly - a stub and includes one of the usbdrvasm*.S files - depending on processor clock. Link this module to - your code! - usbdrvasm*.inc ......... Assembler routines for particular clock frequencies. - Included by usbdrvasm.S, don't link it directly! - asmcommon.inc .......... Common assembler routines. Included by - usbdrvasm*.inc, don't link it directly! - usbconfig-prototype.h .. Prototype for your own usbdrv.h file. -* oddebug.c .............. Debug functions. Only used when DEBUG_LEVEL is - defined to a value greater than 0. Link this module - to your code! - oddebug.h .............. Interface definitions of the debug module. - usbportability.h ....... Header with compiler-dependent stuff. - usbdrvasm.asm .......... Compatibility stub for IAR-C-compiler. Use this - module instead of usbdrvasm.S when you assembler - with IAR's tools. - LICENSE.md ............ Open Source license for this driver. - CommercialLICENSE.md .. Optional commercial license for this driver. - USB-ID-FAQ.txt ......... General infos about USB Product- and Vendor-IDs. - USB-IDs-for-free.txt ... List and terms of use for free shared PIDs. - -(*) ... These files should be linked to your project. - - -CPU CORE CLOCK FREQUENCY -======================== -We supply assembler modules for clock frequencies of 12 MHz, 12.8 MHz, 15 MHz, -16 MHz, 16.5 MHz 18 MHz and 20 MHz. Other clock rates are not supported. The -actual clock rate must be configured in usbconfig.h. - -12 MHz Clock -This is the traditional clock rate of V-USB because it's the lowest clock -rate where the timing constraints of the USB spec can be met. - -15 MHz Clock -Similar to 12 MHz, but some NOPs inserted. On the other hand, the higher clock -rate allows for some loops which make the resulting code size somewhat smaller -than the 12 MHz version. - -16 MHz Clock -This clock rate has been added for users of the Arduino board and other -ready-made boards which come with a fixed 16 MHz crystal. It's also an option -if you need the slightly higher clock rate for performance reasons. Since -16 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code -is somewhat tricky and has to insert a leap cycle every third byte. - -12.8 MHz and 16.5 MHz Clock -The assembler modules for these clock rates differ from the other modules -because they have been built for an RC oscillator with only 1% precision. The -receiver code inserts leap cycles to compensate for clock deviations. 1% is -also the precision which can be achieved by calibrating the internal RC -oscillator of the AVR. Please note that only AVRs with internal 64 MHz PLL -oscillator can reach 16.5 MHz with the RC oscillator. This includes the very -popular ATTiny25, ATTiny45, ATTiny85 series as well as the ATTiny26. Almost -all AVRs can reach 12.8 MHz, although this is outside the specified range. - -See the EasyLogger example at http://www.obdev.at/vusb/easylogger.html for -code which calibrates the RC oscillator based on the USB frame clock. - -18 MHz Clock -This module is closer to the USB specification because it performs an on the -fly CRC check for incoming packets. Packets with invalid checksum are -discarded as required by the spec. If you also implement checks for data -PID toggling on application level (see option USB_CFG_CHECK_DATA_TOGGLING -in usbconfig.h for more info), this ensures data integrity. Due to the CRC -tables and alignment requirements, this code is bigger than modules for other -clock rates. To activate this module, you must define USB_CFG_CHECK_CRC to 1 -and USB_CFG_CLOCK_KHZ to 18000 in usbconfig.h. - -20 MHz Clock -This module is for people who won't do it with less than the maximum. Since -20 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code -uses similar tricks as the 16 MHz module to insert leap cycles. - - -USB IDENTIFIERS -=============== -Every USB device needs a vendor- and a product-identifier (VID and PID). VIDs -are obtained from usb.org for a price of 1,500 USD. Once you have a VID, you -can assign PIDs at will. - -Since an entry level cost of 1,500 USD is too high for most small companies -and hobbyists, we provide some VID/PID pairs for free. See the file -USB-IDs-for-free.txt for details. - -Objective Development also has some license offerings which include product -IDs. See http://www.obdev.at/vusb/ for details. - - -DEVELOPMENT SYSTEM -================== -This driver has been developed and optimized for the GNU compiler version 3 -and 4. We recommend that you use the GNU compiler suite because it is freely -available. V-USB has also been ported to the IAR compiler and assembler. It -has been tested with IAR 4.10B/W32 and 4.12A/W32 on an ATmega8 with the -"small" and "tiny" memory model. Not every release is tested with IAR CC and -the driver may therefore fail to compile with IAR. Please note that gcc is -more efficient for usbdrv.c because this module has been deliberately -optimized for gcc. - -Gcc version 3 produces smaller code than version 4 due to new optimizing -capabilities which don't always improve things on 8 bit CPUs. The code size -generated by gcc 4 can be reduced with the compiler options --fno-move-loop-invariants, -fno-tree-scev-cprop and --fno-inline-small-functions in addition to -Os. On devices with more than -8k of flash memory, we also recommend the linker option --relax (written as --Wl,--relax for gcc) to convert absolute calls into relative where possible. - -For more information about optimizing options see: - - http://www.tty1.net/blog/2008-04-29-avr-gcc-optimisations_en.html - -These optimizations are good for gcc 4.x. Version 3.x of gcc does not support -most of these options and produces good code anyway. - - -USING V-USB FOR FREE -==================== -The AVR firmware driver is published under the GNU General Public License -Version 2 (GPL2) and the GNU General Public License Version 3 (GPL3). It is -your choice whether you apply the terms of version 2 or version 3. - -If you decide for the free GPL2 or GPL3, we STRONGLY ENCOURAGE you to do the -following things IN ADDITION to the obligations from the GPL: - -(1) Publish your entire project on a web site and drop us a note with the URL. -Use the form at http://www.obdev.at/vusb/feedback.html for your submission. -If you don't have a web site, you can publish the project in obdev's -documentation wiki at -http://www.obdev.at/goto.php?t=vusb-wiki&p=hosted-projects. - -(2) Adhere to minimum publication standards. Please include AT LEAST: - - a circuit diagram in PDF, PNG or GIF format - - full source code for the host software - - a Readme.txt file in ASCII format which describes the purpose of the - project and what can be found in which directories and which files - - a reference to http://www.obdev.at/vusb/ - -(3) If you improve the driver firmware itself, please give us a free license -to your modifications for our commercial license offerings. - - -COMMERCIAL LICENSES FOR V-USB -============================= -If you don't want to publish your source code under the terms of the GPL, -you can simply pay money for V-USB. As an additional benefit you get -USB PIDs for free, reserved exclusively to you. See the file -"CommercialLICENSE.md" for details. - diff --git a/src/firmware/c/usbdrv/USB-ID-FAQ.txt b/src/firmware/c/usbdrv/USB-ID-FAQ.txt deleted file mode 100644 index a4a6bd6..0000000 --- a/src/firmware/c/usbdrv/USB-ID-FAQ.txt +++ /dev/null @@ -1,149 +0,0 @@ -Version 2012-07-09 - -========================== -WHY DO WE NEED THESE IDs? -========================== - -USB is more than a low level protocol for data transport. It also defines a -common set of requests which must be understood by all devices. And as part -of these common requests, the specification defines data structures, the -USB Descriptors, which are used to describe the properties of the device. - -From the perspective of an operating system, it is therefore possible to find -out basic properties of a device (such as e.g. the manufacturer and the name -of the device) without a device-specific driver. This is essential because -the operating system can choose a driver to load based on this information -(Plug-And-Play). - -Among the most important properties in the Device Descriptor are the USB -Vendor- and Product-ID. Both are 16 bit integers. The most simple form of -driver matching is based on these IDs. The driver announces the Vendor- and -Product-IDs of the devices it can handle and the operating system loads the -appropriate driver when the device is connected. - -It is obvious that this technique only works if the pair Vendor- plus -Product-ID is unique: Only devices which require the same driver can have the -same pair of IDs. - - -===================================================== -HOW DOES THE USB STANDARD ENSURE THAT IDs ARE UNIQUE? -===================================================== - -Since it is so important that USB IDs are unique, the USB Implementers Forum, -Inc. (usb.org) needs a way to enforce this legally. It is not forbidden by -law to build a device and assign it any random numbers as IDs. Usb.org -therefore needs an agreement to regulate the use of USB IDs. The agreement -binds only parties who agreed to it, of course. Everybody else is free to use -any numbers for their IDs. - -So how can usb.org ensure that every manufacturer of USB devices enters into -an agreement with them? They do it via trademark licensing. Usb.org has -registered the trademark "USB", all associated logos and related terms. If -you want to put an USB logo on your product or claim that it is USB -compliant, you must license these trademarks from usb.org. And this is where -you enter into an agreement. See the "USB-IF Trademark License Agreement and -Usage Guidelines for the USB-IF Logo" at -http://www.usb.org/developers/logo_license/. - -Licensing the USB trademarks requires that you buy a USB Vendor-ID from -usb.org (one-time fee of ca. 2,000 USD), that you become a member of usb.org -(yearly fee of ca. 4,000 USD) and that you meet all the technical -specifications from the USB spec. - -This means that most hobbyists and small companies will never be able to -become USB compliant, just because membership is so expensive. And you can't -be compliant with a driver based on V-USB anyway, because the AVR's port pins -don't meet the electrical specifications for USB. So, in principle, all -hobbyists and small companies are free to choose any random numbers for their -IDs. They have nothing to lose... - -There is one exception worth noting, though: If you use a sub-component which -implements USB, the vendor of the sub-components may guarantee USB -compliance. This might apply to some or all of FTDI's solutions. - - -======================================================================= -WHY SHOULD YOU OBTAIN USB IDs EVEN IF YOU DON'T LICENSE USB TRADEMARKS? -======================================================================= - -You have learned in the previous section that you are free to choose any -numbers for your IDs anyway. So why not do exactly this? There is still the -technical issue. If you choose IDs which are already in use by somebody else, -operating systems will load the wrong drivers and your device won't work. -Even if you choose IDs which are not currently in use, they may be in use in -the next version of the operating system or even after an automatic update. - -So what you need is a pair of Vendor- and Product-IDs for which you have the -guarantee that no USB compliant product uses them. This implies that no -operating system will ever ship with drivers responsible for these IDs. - - -============================================== -HOW DOES OBJECTIVE DEVELOPMENT HANDLE USB IDs? -============================================== - -Objective Development gives away pairs of USB-IDs with their V-USB licenses. -In order to ensure that these IDs are unique, Objective Development has an -agreement with the company/person who has bought the USB Vendor-ID from -usb.org. This agreement ensures that a range of USB Product-IDs is reserved -for assignment by Objective Development and that the owner of the Vendor-ID -won't give it to anybody else. - -This means that you have to trust three parties to ensure uniqueness of -your IDs: - - - Objective Development, that they don't give the same PID to more than - one person. - - The owner of the Vendor-ID that they don't assign PIDs from the range - assigned to Objective Development to anybody else. - - Usb.org that they don't assign the same Vendor-ID a second time. - - -================================== -WHO IS THE OWNER OF THE VENDOR-ID? -================================== - -Objective Development has obtained ranges of USB Product-IDs under two -Vendor-IDs: Under Vendor-ID 5824 from Wouter van Ooijen (Van Ooijen -Technische Informatica, www.voti.nl) and under Vendor-ID 8352 from Jason -Kotzin (now flirc.tv, Inc.). Both VID owners have received their Vendor-ID -directly from usb.org. - - -========================================================================= -CAN I USE USB-IDs FROM OBJECTIVE DEVELOPMENT WITH OTHER DRIVERS/HARDWARE? -========================================================================= - -The short answer is: Yes. All you get is a guarantee that the IDs are never -assigned to anybody else. What more do you need? - - -============================ -WHAT ABOUT SHARED ID PAIRS? -============================ - -Objective Development has reserved some PID/VID pairs for shared use. You -have no guarantee of uniqueness for them, except that no USB compliant device -uses them. In order to avoid technical problems, we must ensure that all -devices with the same pair of IDs use the same driver on kernel level. For -details, see the file USB-IDs-for-free.txt. - - -====================================================== -I HAVE HEARD THAT SUB-LICENSING OF USB-IDs IS ILLEGAL? -====================================================== - -A 16 bit integer number cannot be protected by copyright laws. It is not -sufficiently complex. And since none of the parties involved entered into the -USB-IF Trademark License Agreement, we are not bound by this agreement. So -there is no reason why it should be illegal to sub-license USB-IDs. - - -============================================= -WHO IS LIABLE IF THERE ARE INCOMPATIBILITIES? -============================================= - -Objective Development disclaims all liabilities which might arise from the -assignment of IDs. If you guarantee product features to your customers -without proper disclaimer, YOU are liable for that. diff --git a/src/firmware/c/usbdrv/USB-IDs-for-free.txt b/src/firmware/c/usbdrv/USB-IDs-for-free.txt deleted file mode 100644 index d46517d..0000000 --- a/src/firmware/c/usbdrv/USB-IDs-for-free.txt +++ /dev/null @@ -1,154 +0,0 @@ -Version 2009-08-22 - -=========================== -FREE USB-IDs FOR SHARED USE -=========================== - -Objective Development has reserved a set of USB Product-IDs for use according -to the guidelines outlined below. For more information about the concept of -USB IDs please see the file USB-ID-FAQ.txt. Objective Development guarantees -that the IDs listed below are not used by any USB compliant devices. - - -==================== -MECHANISM OF SHARING -==================== - -From a technical point of view, two different devices can share the same USB -Vendor- and Product-ID if they require the same driver on operating system -level. We make use of this fact by assigning separate IDs for various device -classes. On application layer, devices must be distinguished by their textual -name or serial number. We offer separate sets of IDs for discrimination by -textual name and for serial number. - -Examples for shared use of USB IDs are included with V-USB in the "examples" -subdirectory. - - -====================================== -IDs FOR DISCRIMINATION BY TEXTUAL NAME -====================================== - -If you use one of the IDs listed below, your device and host-side software -must conform to these rules: - -(1) The USB device MUST provide a textual representation of the manufacturer -and product identification. The manufacturer identification MUST be available -at least in USB language 0x0409 (English/US). - -(2) The textual manufacturer identification MUST contain either an Internet -domain name (e.g. "mycompany.com") registered and owned by you, or an e-mail -address under your control (e.g. "myname@gmx.net"). You can embed the domain -name or e-mail address in any string you like, e.g. "Objective Development -http://www.obdev.at/vusb/". - -(3) You are responsible for retaining ownership of the domain or e-mail -address for as long as any of your products are in use. - -(4) You may choose any string for the textual product identification, as long -as this string is unique within the scope of your textual manufacturer -identification. - -(5) Application side device look-up MUST be based on the textual manufacturer -and product identification in addition to VID/PID matching. The driver -matching MUST be a comparison of the entire strings, NOT a sub-string match. - -(6) For devices which implement a particular USB device class (e.g. HID), the -operating system's default class driver MUST be used. If an operating system -driver for Vendor Class devices is needed, this driver must be libusb or -libusb-win32 (see http://libusb.org/ and -http://libusb-win32.sourceforge.net/). - -Table if IDs for discrimination by textual name: - -PID dec (hex) | VID dec (hex) | Description of use -==============+===============+============================================ -1500 (0x05dc) | 5824 (0x16c0) | For Vendor Class devices with libusb ---------------+---------------+-------------------------------------------- -1503 (0x05df) | 5824 (0x16c0) | For generic HID class devices (which are - | | NOT mice, keyboards or joysticks) ---------------+---------------+-------------------------------------------- -1505 (0x05e1) | 5824 (0x16c0) | For CDC-ACM class devices (modems) ---------------+---------------+-------------------------------------------- -1508 (0x05e4) | 5824 (0x16c0) | For MIDI class devices ---------------+---------------+-------------------------------------------- - -Note that Windows caches the textual product- and vendor-description for -mice, keyboards and joysticks. Name-bsed discrimination is therefore not -recommended for these device classes. - - -======================================= -IDs FOR DISCRIMINATION BY SERIAL NUMBER -======================================= - -If you use one of the IDs listed below, your device and host-side software -must conform to these rules: - -(1) The USB device MUST provide a textual representation of the serial -number, unless ONLY the operating system's default class driver is used. -The serial number string MUST be available at least in USB language 0x0409 -(English/US). - -(2) The serial number MUST start with either an Internet domain name (e.g. -"mycompany.com") registered and owned by you, or an e-mail address under your -control (e.g. "myname@gmx.net"), both terminated with a colon (":") character. -You MAY append any string you like for further discrimination of your devices. - -(3) You are responsible for retaining ownership of the domain or e-mail -address for as long as any of your products are in use. - -(5) Application side device look-up MUST be based on the serial number string -in addition to VID/PID matching. The matching must start at the first -character of the serial number string and include the colon character -terminating your domain or e-mail address. It MAY stop anywhere after that. - -(6) For devices which implement a particular USB device class (e.g. HID), the -operating system's default class driver MUST be used. If an operating system -driver for Vendor Class devices is needed, this driver must be libusb or -libusb-win32 (see http://libusb.org/ and -http://libusb-win32.sourceforge.net/). - -(7) If ONLY the operating system's default class driver is used, e.g. for -mice, keyboards, joysticks, CDC or MIDI devices and no discrimination by an -application is needed, the serial number may be omitted. - - -Table if IDs for discrimination by serial number string: - -PID dec (hex) | VID dec (hex) | Description of use -===============+===============+=========================================== -10200 (0x27d8) | 5824 (0x16c0) | For Vendor Class devices with libusb ----------------+---------------+------------------------------------------- -10201 (0x27d9) | 5824 (0x16c0) | For generic HID class devices (which are - | | NOT mice, keyboards or joysticks) ----------------+---------------+------------------------------------------- -10202 (0x27da) | 5824 (0x16c0) | For USB Mice ----------------+---------------+------------------------------------------- -10203 (0x27db) | 5824 (0x16c0) | For USB Keyboards ----------------+---------------+------------------------------------------- -10204 (0x27dc) | 5824 (0x16c0) | For USB Joysticks ----------------+---------------+------------------------------------------- -10205 (0x27dd) | 5824 (0x16c0) | For CDC-ACM class devices (modems) ----------------+---------------+------------------------------------------- -10206 (0x27de) | 5824 (0x16c0) | For MIDI class devices ----------------+---------------+------------------------------------------- - - -================= -ORIGIN OF USB-IDs -================= - -OBJECTIVE DEVELOPMENT Software GmbH has obtained all VID/PID pairs listed -here from Wouter van Ooijen (see www.voti.nl) for exclusive disposition. -Wouter van Ooijen has obtained the VID from the USB Implementers Forum, Inc. -(see www.usb.org). The VID is registered for the company name "Van Ooijen -Technische Informatica". - - -========== -DISCLAIMER -========== - -OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any -problems which are caused by the shared use of these VID/PID pairs. diff --git a/src/firmware/c/usbdrv/asmcommon.inc b/src/firmware/c/usbdrv/asmcommon.inc deleted file mode 100644 index f80959d..0000000 --- a/src/firmware/c/usbdrv/asmcommon.inc +++ /dev/null @@ -1,187 +0,0 @@ -/* Name: asmcommon.inc - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Christian Starkjohann - * Creation Date: 2007-11-05 - * Tabsize: 4 - * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -/* Do not link this file! Link usbdrvasm.S instead, which includes the - * appropriate implementation! - */ - -/* -General Description: -This file contains assembler code which is shared among the USB driver -implementations for different CPU cocks. Since the code must be inserted -in the middle of the module, it's split out into this file and #included. - -Jump destinations called from outside: - sofError: Called when no start sequence was found. - se0: Called when a package has been successfully received. - overflow: Called when receive buffer overflows. - doReturn: Called after sending data. - -Outside jump destinations used by this module: - waitForJ: Called to receive an already arriving packet. - sendAckAndReti: - sendNakAndReti: - sendCntAndReti: - usbSendAndReti: - -The following macros must be defined before this file is included: - .macro POP_STANDARD - .endm - .macro POP_RETI - .endm -*/ - -#define token x1 - -overflow: - ldi x2, 1< 0 - -#warning "Never compile production devices with debugging enabled" - -static void uartPutc(char c) -{ - while(!(ODDBG_USR & (1 << ODDBG_UDRE))); /* wait for data register empty */ - ODDBG_UDR = c; -} - -static uchar hexAscii(uchar h) -{ - h &= 0xf; - if(h >= 10) - h += 'a' - (uchar)10 - '0'; - h += '0'; - return h; -} - -static void printHex(uchar c) -{ - uartPutc(hexAscii(c >> 4)); - uartPutc(hexAscii(c)); -} - -void odDebug(uchar prefix, uchar *data, uchar len) -{ - printHex(prefix); - uartPutc(':'); - while(len--){ - uartPutc(' '); - printHex(*data++); - } - uartPutc('\r'); - uartPutc('\n'); -} - -#endif diff --git a/src/firmware/c/usbdrv/oddebug.h b/src/firmware/c/usbdrv/oddebug.h deleted file mode 100644 index 33376bc..0000000 --- a/src/firmware/c/usbdrv/oddebug.h +++ /dev/null @@ -1,122 +0,0 @@ -/* Name: oddebug.h - * Project: AVR library - * Author: Christian Starkjohann - * Creation Date: 2005-01-16 - * Tabsize: 4 - * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -#ifndef __oddebug_h_included__ -#define __oddebug_h_included__ - -/* -General Description: -This module implements a function for debug logs on the serial line of the -AVR microcontroller. Debugging can be configured with the define -'DEBUG_LEVEL'. If this macro is not defined or defined to 0, all debugging -calls are no-ops. If it is 1, DBG1 logs will appear, but not DBG2. If it is -2, DBG1 and DBG2 logs will be printed. - -A debug log consists of a label ('prefix') to indicate which debug log created -the output and a memory block to dump in hex ('data' and 'len'). -*/ - - -#ifndef F_CPU -# define F_CPU 12000000 /* 12 MHz */ -#endif - -/* make sure we have the UART defines: */ -#include "usbportability.h" - -#ifndef uchar -# define uchar unsigned char -#endif - -#if DEBUG_LEVEL > 0 && !(defined TXEN || defined TXEN0) /* no UART in device */ -# warning "Debugging disabled because device has no UART" -# undef DEBUG_LEVEL -#endif - -#ifndef DEBUG_LEVEL -# define DEBUG_LEVEL 0 -#endif - -/* ------------------------------------------------------------------------- */ - -#if DEBUG_LEVEL > 0 -# define DBG1(prefix, data, len) odDebug(prefix, data, len) -#else -# define DBG1(prefix, data, len) -#endif - -#if DEBUG_LEVEL > 1 -# define DBG2(prefix, data, len) odDebug(prefix, data, len) -#else -# define DBG2(prefix, data, len) -#endif - -/* ------------------------------------------------------------------------- */ - -#if DEBUG_LEVEL > 0 -extern void odDebug(uchar prefix, uchar *data, uchar len); - -/* Try to find our control registers; ATMEL likes to rename these */ - -#if defined UBRR -# define ODDBG_UBRR UBRR -#elif defined UBRRL -# define ODDBG_UBRR UBRRL -#elif defined UBRR0 -# define ODDBG_UBRR UBRR0 -#elif defined UBRR0L -# define ODDBG_UBRR UBRR0L -#endif - -#if defined UCR -# define ODDBG_UCR UCR -#elif defined UCSRB -# define ODDBG_UCR UCSRB -#elif defined UCSR0B -# define ODDBG_UCR UCSR0B -#endif - -#if defined TXEN -# define ODDBG_TXEN TXEN -#else -# define ODDBG_TXEN TXEN0 -#endif - -#if defined USR -# define ODDBG_USR USR -#elif defined UCSRA -# define ODDBG_USR UCSRA -#elif defined UCSR0A -# define ODDBG_USR UCSR0A -#endif - -#if defined UDRE -# define ODDBG_UDRE UDRE -#else -# define ODDBG_UDRE UDRE0 -#endif - -#if defined UDR -# define ODDBG_UDR UDR -#elif defined UDR0 -# define ODDBG_UDR UDR0 -#endif - -static inline void odDebugInit(void) -{ - ODDBG_UCR |= (1<len & 0x10){ /* packet buffer was empty */ - txStatus->buffer[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */ - }else{ - txStatus->len = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */ - } - p = txStatus->buffer + 1; - i = len; - do{ /* if len == 0, we still copy 1 byte, but that's no problem */ - *p++ = *data++; - }while(--i > 0); /* loop control at the end is 2 bytes shorter than at beginning */ - usbCrc16Append(&txStatus->buffer[1], len); - txStatus->len = len + 4; /* len must be given including sync byte */ - DBG2(0x21 + (((int)txStatus >> 3) & 3), txStatus->buffer, len + 3); -} - -USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len) -{ - usbGenericSetInterrupt(data, len, &usbTxStatus1); -} -#endif - -#if USB_CFG_HAVE_INTRIN_ENDPOINT3 -USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len) -{ - usbGenericSetInterrupt(data, len, &usbTxStatus3); -} -#endif -#endif /* USB_CFG_SUPPRESS_INTR_CODE */ - -/* ------------------ utilities for code following below ------------------- */ - -/* Use defines for the switch statement so that we can choose between an - * if()else if() and a switch/case based implementation. switch() is more - * efficient for a LARGE set of sequential choices, if() is better in all other - * cases. - */ -#if USB_CFG_USE_SWITCH_STATEMENT -# define SWITCH_START(cmd) switch(cmd){{ -# define SWITCH_CASE(value) }break; case (value):{ -# define SWITCH_CASE2(v1,v2) }break; case (v1): case(v2):{ -# define SWITCH_CASE3(v1,v2,v3) }break; case (v1): case(v2): case(v3):{ -# define SWITCH_DEFAULT }break; default:{ -# define SWITCH_END }} -#else -# define SWITCH_START(cmd) {uchar _cmd = cmd; if(0){ -# define SWITCH_CASE(value) }else if(_cmd == (value)){ -# define SWITCH_CASE2(v1,v2) }else if(_cmd == (v1) || _cmd == (v2)){ -# define SWITCH_CASE3(v1,v2,v3) }else if(_cmd == (v1) || _cmd == (v2) || (_cmd == v3)){ -# define SWITCH_DEFAULT }else{ -# define SWITCH_END }} -#endif - -#ifndef USB_RX_USER_HOOK -#define USB_RX_USER_HOOK(data, len) -#endif -#ifndef USB_SET_ADDRESS_HOOK -#define USB_SET_ADDRESS_HOOK() -#endif - -/* ------------------------------------------------------------------------- */ - -/* We use if() instead of #if in the macro below because #if can't be used - * in macros and the compiler optimizes constant conditions anyway. - * This may cause problems with undefined symbols if compiled without - * optimizing! - */ -#define GET_DESCRIPTOR(cfgProp, staticName) \ - if(cfgProp){ \ - if((cfgProp) & USB_PROP_IS_RAM) \ - flags = 0; \ - if((cfgProp) & USB_PROP_IS_DYNAMIC){ \ - len = usbFunctionDescriptor(rq); \ - }else{ \ - len = USB_PROP_LENGTH(cfgProp); \ - usbMsgPtr = (usbMsgPtr_t)(staticName); \ - } \ - } - -/* usbDriverDescriptor() is similar to usbFunctionDescriptor(), but used - * internally for all types of descriptors. - */ -static inline usbMsgLen_t usbDriverDescriptor(usbRequest_t *rq) -{ -usbMsgLen_t len = 0; -uchar flags = USB_FLG_MSGPTR_IS_ROM; - - SWITCH_START(rq->wValue.bytes[1]) - SWITCH_CASE(USBDESCR_DEVICE) /* 1 */ - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice) - SWITCH_CASE(USBDESCR_CONFIG) /* 2 */ - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration) - SWITCH_CASE(USBDESCR_STRING) /* 3 */ -#if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC - if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM) - flags = 0; - len = usbFunctionDescriptor(rq); -#else /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */ - SWITCH_START(rq->wValue.bytes[0]) - SWITCH_CASE(0) - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0) - SWITCH_CASE(1) - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor) - SWITCH_CASE(2) - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice) - SWITCH_CASE(3) - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber) - SWITCH_DEFAULT - if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){ - len = usbFunctionDescriptor(rq); - } - SWITCH_END -#endif /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */ -#if USB_CFG_DESCR_PROPS_HID_REPORT /* only support HID descriptors if enabled */ - SWITCH_CASE(USBDESCR_HID) /* 0x21 */ - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18) - SWITCH_CASE(USBDESCR_HID_REPORT)/* 0x22 */ - GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport) -#endif - SWITCH_DEFAULT - if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){ - len = usbFunctionDescriptor(rq); - } - SWITCH_END - usbMsgFlags = flags; - return len; -} - -/* ------------------------------------------------------------------------- */ - -/* usbDriverSetup() is similar to usbFunctionSetup(), but it's used for - * standard requests instead of class and custom requests. - */ -static inline usbMsgLen_t usbDriverSetup(usbRequest_t *rq) -{ -usbMsgLen_t len = 0; -uchar *dataPtr = usbTxBuf + 9; /* there are 2 bytes free space at the end of the buffer */ -uchar value = rq->wValue.bytes[0]; -#if USB_CFG_IMPLEMENT_HALT -uchar index = rq->wIndex.bytes[0]; -#endif - - dataPtr[0] = 0; /* default reply common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */ - SWITCH_START(rq->bRequest) - SWITCH_CASE(USBRQ_GET_STATUS) /* 0 */ - uchar recipient = rq->bmRequestType & USBRQ_RCPT_MASK; /* assign arith ops to variables to enforce byte size */ - if(USB_CFG_IS_SELF_POWERED && recipient == USBRQ_RCPT_DEVICE) - dataPtr[0] = USB_CFG_IS_SELF_POWERED; -#if USB_CFG_IMPLEMENT_HALT - if(recipient == USBRQ_RCPT_ENDPOINT && index == 0x81) /* request status for endpoint 1 */ - dataPtr[0] = usbTxLen1 == USBPID_STALL; -#endif - dataPtr[1] = 0; - len = 2; -#if USB_CFG_IMPLEMENT_HALT - SWITCH_CASE2(USBRQ_CLEAR_FEATURE, USBRQ_SET_FEATURE) /* 1, 3 */ - if(value == 0 && index == 0x81){ /* feature 0 == HALT for endpoint == 1 */ - usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL; - usbResetDataToggling(); - } -#endif - SWITCH_CASE(USBRQ_SET_ADDRESS) /* 5 */ - usbNewDeviceAddr = value; - USB_SET_ADDRESS_HOOK(); - SWITCH_CASE(USBRQ_GET_DESCRIPTOR) /* 6 */ - len = usbDriverDescriptor(rq); - goto skipMsgPtrAssignment; - SWITCH_CASE(USBRQ_GET_CONFIGURATION) /* 8 */ - dataPtr = &usbConfiguration; /* send current configuration value */ - len = 1; - SWITCH_CASE(USBRQ_SET_CONFIGURATION) /* 9 */ - usbConfiguration = value; - usbResetStall(); - SWITCH_CASE(USBRQ_GET_INTERFACE) /* 10 */ - len = 1; -#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE - SWITCH_CASE(USBRQ_SET_INTERFACE) /* 11 */ - usbResetDataToggling(); - usbResetStall(); -#endif - SWITCH_DEFAULT /* 7=SET_DESCRIPTOR, 12=SYNC_FRAME */ - /* Should we add an optional hook here? */ - SWITCH_END - usbMsgPtr = (usbMsgPtr_t)dataPtr; -skipMsgPtrAssignment: - return len; -} - -/* ------------------------------------------------------------------------- */ - -/* usbProcessRx() is called for every message received by the interrupt - * routine. It distinguishes between SETUP and DATA packets and processes - * them accordingly. - */ -static inline void usbProcessRx(uchar *data, uchar len) -{ -usbRequest_t *rq = (void *)data; - -/* usbRxToken can be: - * 0x2d 00101101 (USBPID_SETUP for setup data) - * 0xe1 11100001 (USBPID_OUT: data phase of setup transfer) - * 0...0x0f for OUT on endpoint X - */ - DBG2(0x10 + (usbRxToken & 0xf), data, len + 2); /* SETUP=1d, SETUP-DATA=11, OUTx=1x */ - USB_RX_USER_HOOK(data, len) -#if USB_CFG_IMPLEMENT_FN_WRITEOUT - if(usbRxToken < 0x10){ /* OUT to endpoint != 0: endpoint number in usbRxToken */ - usbFunctionWriteOut(data, len); - return; - } -#endif - if(usbRxToken == (uchar)USBPID_SETUP){ - if(len != 8) /* Setup size must be always 8 bytes. Ignore otherwise. */ - return; - usbMsgLen_t replyLen; - usbTxBuf[0] = USBPID_DATA0; /* initialize data toggling */ - usbTxLen = USBPID_NAK; /* abort pending transmit */ - usbMsgFlags = 0; - uchar type = rq->bmRequestType & USBRQ_TYPE_MASK; - if(type != USBRQ_TYPE_STANDARD){ /* standard requests are handled by driver */ - replyLen = usbFunctionSetup(data); - }else{ - replyLen = usbDriverSetup(rq); - } -#if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE - if(replyLen == USB_NO_MSG){ /* use user-supplied read/write function */ - /* do some conditioning on replyLen, but on IN transfers only */ - if((rq->bmRequestType & USBRQ_DIR_MASK) != USBRQ_DIR_HOST_TO_DEVICE){ - if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */ - replyLen = rq->wLength.bytes[0]; - }else{ - replyLen = rq->wLength.word; - } - } - usbMsgFlags = USB_FLG_USE_USER_RW; - }else /* The 'else' prevents that we limit a replyLen of USB_NO_MSG to the maximum transfer len. */ -#endif - if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */ - if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0]) /* limit length to max */ - replyLen = rq->wLength.bytes[0]; - }else{ - if(replyLen > rq->wLength.word) /* limit length to max */ - replyLen = rq->wLength.word; - } - usbMsgLen = replyLen; - }else{ /* usbRxToken must be USBPID_OUT, which means data phase of setup (control-out) */ -#if USB_CFG_IMPLEMENT_FN_WRITE - if(usbMsgFlags & USB_FLG_USE_USER_RW){ - uchar rval = usbFunctionWrite(data, len); - if(rval == 0xff){ /* an error occurred */ - usbTxLen = USBPID_STALL; - }else if(rval != 0){ /* This was the final package */ - usbMsgLen = 0; /* answer with a zero-sized data packet */ - } - } -#endif - } -} - -/* ------------------------------------------------------------------------- */ - -/* This function is similar to usbFunctionRead(), but it's also called for - * data handled automatically by the driver (e.g. descriptor reads). - */ -static uchar usbDeviceRead(uchar *data, uchar len) -{ - if(len > 0){ /* don't bother app with 0 sized reads */ -#if USB_CFG_IMPLEMENT_FN_READ - if(usbMsgFlags & USB_FLG_USE_USER_RW){ - len = usbFunctionRead(data, len); - }else -#endif - { - uchar i = len; - usbMsgPtr_t r = usbMsgPtr; - if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){ /* ROM data */ - do{ - uchar c = USB_READ_FLASH(r); /* assign to char size variable to enforce byte ops */ - *data++ = c; - r++; - }while(--i); - }else{ /* RAM data */ - do{ - *data++ = *((uchar *)r); - r++; - }while(--i); - } - usbMsgPtr = r; - } - } - return len; -} - -/* ------------------------------------------------------------------------- */ - -/* usbBuildTxBlock() is called when we have data to transmit and the - * interrupt routine's transmit buffer is empty. - */ -static inline void usbBuildTxBlock(void) -{ -usbMsgLen_t wantLen; -uchar len; - - wantLen = usbMsgLen; - if(wantLen > 8) - wantLen = 8; - usbMsgLen -= wantLen; - usbTxBuf[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* DATA toggling */ - len = usbDeviceRead(usbTxBuf + 1, wantLen); - if(len <= 8){ /* valid data packet */ - usbCrc16Append(&usbTxBuf[1], len); - len += 4; /* length including sync byte */ - if(len < 12) /* a partial package identifies end of message */ - usbMsgLen = USB_NO_MSG; - }else{ - len = USBPID_STALL; /* stall the endpoint */ - usbMsgLen = USB_NO_MSG; - } - usbTxLen = len; - DBG2(0x20, usbTxBuf, len-1); -} - -/* ------------------------------------------------------------------------- */ - -static inline void usbHandleResetHook(uchar notResetState) -{ -#ifdef USB_RESET_HOOK -static uchar wasReset; -uchar isReset = !notResetState; - - if(wasReset != isReset){ - USB_RESET_HOOK(isReset); - wasReset = isReset; - } -#else - notResetState = notResetState; // avoid compiler warning -#endif -} - -/* ------------------------------------------------------------------------- */ - -USB_PUBLIC void usbPoll(void) -{ -schar len; -uchar i; - - len = usbRxLen - 3; - if(len >= 0){ -/* We could check CRC16 here -- but ACK has already been sent anyway. If you - * need data integrity checks with this driver, check the CRC in your app - * code and report errors back to the host. Since the ACK was already sent, - * retries must be handled on application level. - * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3); - */ - usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len); -#if USB_CFG_HAVE_FLOWCONTROL - if(usbRxLen > 0) /* only mark as available if not inactivated */ - usbRxLen = 0; -#else - usbRxLen = 0; /* mark rx buffer as available */ -#endif - } - if(usbTxLen & 0x10){ /* transmit system idle */ - if(usbMsgLen != USB_NO_MSG){ /* transmit data pending? */ - usbBuildTxBlock(); - } - } - for(i = 20; i > 0; i--){ - uchar usbLineStatus = USBIN & USBMASK; - if(usbLineStatus != 0) /* SE0 has ended */ - goto isNotReset; - } - /* RESET condition, called multiple times during reset */ - usbNewDeviceAddr = 0; - usbDeviceAddr = 0; - usbResetStall(); - DBG1(0xff, 0, 0); -isNotReset: - usbHandleResetHook(i); -} - -/* ------------------------------------------------------------------------- */ - -USB_PUBLIC void usbInit(void) -{ -#if USB_INTR_CFG_SET != 0 - USB_INTR_CFG |= USB_INTR_CFG_SET; -#endif -#if USB_INTR_CFG_CLR != 0 - USB_INTR_CFG &= ~(USB_INTR_CFG_CLR); -#endif - USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT); - usbResetDataToggling(); -#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE - usbTxLen1 = USBPID_NAK; -#if USB_CFG_HAVE_INTRIN_ENDPOINT3 - usbTxLen3 = USBPID_NAK; -#endif -#endif -} - -/* ------------------------------------------------------------------------- */ diff --git a/src/firmware/c/usbdrv/usbdrv.h b/src/firmware/c/usbdrv/usbdrv.h deleted file mode 100644 index 66f9184..0000000 --- a/src/firmware/c/usbdrv/usbdrv.h +++ /dev/null @@ -1,746 +0,0 @@ -/* Name: usbdrv.h - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Christian Starkjohann - * Creation Date: 2004-12-29 - * Tabsize: 4 - * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -#ifndef __usbdrv_h_included__ -#define __usbdrv_h_included__ -#include "usbconfig.h" -#include "usbportability.h" - -/* -Hardware Prerequisites: -======================= -USB lines D+ and D- MUST be wired to the same I/O port. We recommend that D+ -triggers the interrupt (best achieved by using INT0 for D+), but it is also -possible to trigger the interrupt from D-. If D- is used, interrupts are also -triggered by SOF packets. D- requires a pull-up of 1.5k to +3.5V (and the -device must be powered at 3.5V) to identify as low-speed USB device. A -pull-down or pull-up of 1M SHOULD be connected from D+ to +3.5V to prevent -interference when no USB master is connected. If you use Zener diodes to limit -the voltage on D+ and D-, you MUST use a pull-down resistor, not a pull-up. -We use D+ as interrupt source and not D- because it does not trigger on -keep-alive and RESET states. If you want to count keep-alive events with -USB_COUNT_SOF, you MUST use D- as an interrupt source. - -As a compile time option, the 1.5k pull-up resistor on D- can be made -switchable to allow the device to disconnect at will. See the definition of -usbDeviceConnect() and usbDeviceDisconnect() further down in this file. - -Please adapt the values in usbconfig.h according to your hardware! - -The device MUST be clocked at exactly 12 MHz, 15 MHz, 16 MHz or 20 MHz -or at 12.8 MHz resp. 16.5 MHz +/- 1%. See usbconfig-prototype.h for details. - - -Limitations: -============ -Robustness with respect to communication errors: -The driver assumes error-free communication. It DOES check for errors in -the PID, but does NOT check bit stuffing errors, SE0 in middle of a byte, -token CRC (5 bit) and data CRC (16 bit). CRC checks can not be performed due -to timing constraints: We must start sending a reply within 7 bit times. -Bit stuffing and misplaced SE0 would have to be checked in real-time, but CPU -performance does not permit that. The driver does not check Data0/Data1 -toggling, but application software can implement the check. - -Input characteristics: -Since no differential receiver circuit is used, electrical interference -robustness may suffer. The driver samples only one of the data lines with -an ordinary I/O pin's input characteristics. However, since this is only a -low speed USB implementation and the specification allows for 8 times the -bit rate over the same hardware, we should be on the safe side. Even the spec -requires detection of asymmetric states at high bit rate for SE0 detection. - -Number of endpoints: -The driver supports the following endpoints: - -- Endpoint 0, the default control endpoint. -- Any number of interrupt- or bulk-out endpoints. The data is sent to - usbFunctionWriteOut() and USB_CFG_IMPLEMENT_FN_WRITEOUT must be defined - to 1 to activate this feature. The endpoint number can be found in the - global variable 'usbRxToken'. -- One default interrupt- or bulk-in endpoint. This endpoint is used for - interrupt- or bulk-in transfers which are not handled by any other endpoint. - You must define USB_CFG_HAVE_INTRIN_ENDPOINT in order to activate this - feature and call usbSetInterrupt() to send interrupt/bulk data. -- One additional interrupt- or bulk-in endpoint. This was endpoint 3 in - previous versions of this driver but can now be configured to any endpoint - number. You must define USB_CFG_HAVE_INTRIN_ENDPOINT3 in order to activate - this feature and call usbSetInterrupt3() to send interrupt/bulk data. The - endpoint number can be set with USB_CFG_EP3_NUMBER. - -Please note that the USB standard forbids bulk endpoints for low speed devices! -Most operating systems allow them anyway, but the AVR will spend 90% of the CPU -time in the USB interrupt polling for bulk data. - -Maximum data payload: -Data payload of control in and out transfers may be up to 254 bytes. In order -to accept payload data of out transfers, you need to implement -'usbFunctionWrite()'. - -USB Suspend Mode supply current: -The USB standard limits power consumption to 500uA when the bus is in suspend -mode. This is not a problem for self-powered devices since they don't need -bus power anyway. Bus-powered devices can achieve this only by putting the -CPU in sleep mode. The driver does not implement suspend handling by itself. -However, the application may implement activity monitoring and wakeup from -sleep. The host sends regular SE0 states on the bus to keep it active. These -SE0 states can be detected by using D- as the interrupt source. Define -USB_COUNT_SOF to 1 and use the global variable usbSofCount to check for bus -activity. - -Operation without an USB master: -The driver behaves neutral without connection to an USB master if D- reads -as 1. To avoid spurious interrupts, we recommend a high impedance (e.g. 1M) -pull-down or pull-up resistor on D+ (interrupt). If Zener diodes are used, -use a pull-down. If D- becomes statically 0, the driver may block in the -interrupt routine. - -Interrupt latency: -The application must ensure that the USB interrupt is not disabled for more -than 25 cycles (this is for 12 MHz, faster clocks allow longer latency). -This implies that all interrupt routines must either have the "ISR_NOBLOCK" -attribute set (see "avr/interrupt.h") or be written in assembler with "sei" -as the first instruction. - -Maximum interrupt duration / CPU cycle consumption: -The driver handles all USB communication during the interrupt service -routine. The routine will not return before an entire USB message is received -and the reply is sent. This may be up to ca. 1200 cycles @ 12 MHz (= 100us) if -the host conforms to the standard. The driver will consume CPU cycles for all -USB messages, even if they address another (low-speed) device on the same bus. - -*/ - -/* ------------------------------------------------------------------------- */ -/* --------------------------- Module Interface ---------------------------- */ -/* ------------------------------------------------------------------------- */ - -#define USBDRV_VERSION 20121206 -/* This define uniquely identifies a driver version. It is a decimal number - * constructed from the driver's release date in the form YYYYMMDD. If the - * driver's behavior or interface changes, you can use this constant to - * distinguish versions. If it is not defined, the driver's release date is - * older than 2006-01-25. - */ - - -#ifndef USB_PUBLIC -#define USB_PUBLIC -#endif -/* USB_PUBLIC is used as declaration attribute for all functions exported by - * the USB driver. The default is no attribute (see above). You may define it - * to static either in usbconfig.h or from the command line if you include - * usbdrv.c instead of linking against it. Including the C module of the driver - * directly in your code saves a couple of bytes in flash memory. - */ - -#ifndef __ASSEMBLER__ -#ifndef uchar -#define uchar unsigned char -#endif -#ifndef schar -#define schar signed char -#endif -/* shortcuts for well defined 8 bit integer types */ - -#if USB_CFG_LONG_TRANSFERS /* if more than 254 bytes transfer size required */ -# define usbMsgLen_t unsigned -#else -# define usbMsgLen_t uchar -#endif -/* usbMsgLen_t is the data type used for transfer lengths. By default, it is - * defined to uchar, allowing a maximum of 254 bytes (255 is reserved for - * USB_NO_MSG below). If the usbconfig.h defines USB_CFG_LONG_TRANSFERS to 1, - * a 16 bit data type is used, allowing up to 16384 bytes (the rest is used - * for flags in the descriptor configuration). - */ -#define USB_NO_MSG ((usbMsgLen_t)-1) /* constant meaning "no message" */ - -#ifndef usbMsgPtr_t -#define usbMsgPtr_t uchar * -#endif -/* Making usbMsgPtr_t a define allows the user of this library to define it to - * an 8 bit type on tiny devices. This reduces code size, especially if the - * compiler supports a tiny memory model. - * The type can be a pointer or scalar type, casts are made where necessary. - * Although it's paradoxical, Gcc 4 generates slightly better code for scalar - * types than for pointers. - */ - -struct usbRequest; /* forward declaration */ - -USB_PUBLIC void usbInit(void); -/* This function must be called before interrupts are enabled and the main - * loop is entered. We exepct that the PORT and DDR bits for D+ and D- have - * not been changed from their default status (which is 0). If you have changed - * them, set both back to 0 (configure them as input with no internal pull-up). - */ -USB_PUBLIC void usbPoll(void); -/* This function must be called at regular intervals from the main loop. - * Maximum delay between calls is somewhat less than 50ms (USB timeout for - * accepting a Setup message). Otherwise the device will not be recognized. - * Please note that debug outputs through the UART take ~ 0.5ms per byte - * at 19200 bps. - */ -extern usbMsgPtr_t usbMsgPtr; -/* This variable may be used to pass transmit data to the driver from the - * implementation of usbFunctionWrite(). It is also used internally by the - * driver for standard control requests. - */ -USB_PUBLIC usbMsgLen_t usbFunctionSetup(uchar data[8]); -/* This function is called when the driver receives a SETUP transaction from - * the host which is not answered by the driver itself (in practice: class and - * vendor requests). All control transfers start with a SETUP transaction where - * the host communicates the parameters of the following (optional) data - * transfer. The SETUP data is available in the 'data' parameter which can - * (and should) be casted to 'usbRequest_t *' for a more user-friendly access - * to parameters. - * - * If the SETUP indicates a control-in transfer, you should provide the - * requested data to the driver. There are two ways to transfer this data: - * (1) Set the global pointer 'usbMsgPtr' to the base of the static RAM data - * block and return the length of the data in 'usbFunctionSetup()'. The driver - * will handle the rest. Or (2) return USB_NO_MSG in 'usbFunctionSetup()'. The - * driver will then call 'usbFunctionRead()' when data is needed. See the - * documentation for usbFunctionRead() for details. - * - * If the SETUP indicates a control-out transfer, the only way to receive the - * data from the host is through the 'usbFunctionWrite()' call. If you - * implement this function, you must return USB_NO_MSG in 'usbFunctionSetup()' - * to indicate that 'usbFunctionWrite()' should be used. See the documentation - * of this function for more information. If you just want to ignore the data - * sent by the host, return 0 in 'usbFunctionSetup()'. - * - * Note that calls to the functions usbFunctionRead() and usbFunctionWrite() - * are only done if enabled by the configuration in usbconfig.h. - */ -USB_PUBLIC usbMsgLen_t usbFunctionDescriptor(struct usbRequest *rq); -/* You need to implement this function ONLY if you provide USB descriptors at - * runtime (which is an expert feature). It is very similar to - * usbFunctionSetup() above, but it is called only to request USB descriptor - * data. See the documentation of usbFunctionSetup() above for more info. - */ -#if USB_CFG_HAVE_INTRIN_ENDPOINT -USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len); -/* This function sets the message which will be sent during the next interrupt - * IN transfer. The message is copied to an internal buffer and must not exceed - * a length of 8 bytes. The message may be 0 bytes long just to indicate the - * interrupt status to the host. - * If you need to transfer more bytes, use a control read after the interrupt. - */ -#define usbInterruptIsReady() (usbTxLen1 & 0x10) -/* This macro indicates whether the last interrupt message has already been - * sent. If you set a new interrupt message before the old was sent, the - * message already buffered will be lost. - */ -#if USB_CFG_HAVE_INTRIN_ENDPOINT3 -USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len); -#define usbInterruptIsReady3() (usbTxLen3 & 0x10) -/* Same as above for endpoint 3 */ -#endif -#endif /* USB_CFG_HAVE_INTRIN_ENDPOINT */ -#if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH /* simplified interface for backward compatibility */ -#define usbHidReportDescriptor usbDescriptorHidReport -/* should be declared as: PROGMEM char usbHidReportDescriptor[]; */ -/* If you implement an HID device, you need to provide a report descriptor. - * The HID report descriptor syntax is a bit complex. If you understand how - * report descriptors are constructed, we recommend that you use the HID - * Descriptor Tool from usb.org, see http://www.usb.org/developers/hidpage/. - * Otherwise you should probably start with a working example. - */ -#endif /* USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH */ -#if USB_CFG_IMPLEMENT_FN_WRITE -USB_PUBLIC uchar usbFunctionWrite(uchar *data, uchar len); -/* This function is called by the driver to provide a control transfer's - * payload data (control-out). It is called in chunks of up to 8 bytes. The - * total count provided in the current control transfer can be obtained from - * the 'length' property in the setup data. If an error occurred during - * processing, return 0xff (== -1). The driver will answer the entire transfer - * with a STALL token in this case. If you have received the entire payload - * successfully, return 1. If you expect more data, return 0. If you don't - * know whether the host will send more data (you should know, the total is - * provided in the usbFunctionSetup() call!), return 1. - * NOTE: If you return 0xff for STALL, 'usbFunctionWrite()' may still be called - * for the remaining data. You must continue to return 0xff for STALL in these - * calls. - * In order to get usbFunctionWrite() called, define USB_CFG_IMPLEMENT_FN_WRITE - * to 1 in usbconfig.h and return 0xff in usbFunctionSetup().. - */ -#endif /* USB_CFG_IMPLEMENT_FN_WRITE */ -#if USB_CFG_IMPLEMENT_FN_READ -USB_PUBLIC uchar usbFunctionRead(uchar *data, uchar len); -/* This function is called by the driver to ask the application for a control - * transfer's payload data (control-in). It is called in chunks of up to 8 - * bytes each. You should copy the data to the location given by 'data' and - * return the actual number of bytes copied. If you return less than requested, - * the control-in transfer is terminated. If you return 0xff, the driver aborts - * the transfer with a STALL token. - * In order to get usbFunctionRead() called, define USB_CFG_IMPLEMENT_FN_READ - * to 1 in usbconfig.h and return 0xff in usbFunctionSetup().. - */ -#endif /* USB_CFG_IMPLEMENT_FN_READ */ - -extern uchar usbRxToken; /* may be used in usbFunctionWriteOut() below */ -#if USB_CFG_IMPLEMENT_FN_WRITEOUT -USB_PUBLIC void usbFunctionWriteOut(uchar *data, uchar len); -/* This function is called by the driver when data is received on an interrupt- - * or bulk-out endpoint. The endpoint number can be found in the global - * variable usbRxToken. You must define USB_CFG_IMPLEMENT_FN_WRITEOUT to 1 in - * usbconfig.h to get this function called. - */ -#endif /* USB_CFG_IMPLEMENT_FN_WRITEOUT */ -#ifdef USB_CFG_PULLUP_IOPORTNAME -#define usbDeviceConnect() ((USB_PULLUP_DDR |= (1<device, 1=device->host - * t ..... type: 0=standard, 1=class, 2=vendor, 3=reserved - * r ..... recipient: 0=device, 1=interface, 2=endpoint, 3=other - */ - -/* USB setup recipient values */ -#define USBRQ_RCPT_MASK 0x1f -#define USBRQ_RCPT_DEVICE 0 -#define USBRQ_RCPT_INTERFACE 1 -#define USBRQ_RCPT_ENDPOINT 2 - -/* USB request type values */ -#define USBRQ_TYPE_MASK 0x60 -#define USBRQ_TYPE_STANDARD (0<<5) -#define USBRQ_TYPE_CLASS (1<<5) -#define USBRQ_TYPE_VENDOR (2<<5) - -/* USB direction values: */ -#define USBRQ_DIR_MASK 0x80 -#define USBRQ_DIR_HOST_TO_DEVICE (0<<7) -#define USBRQ_DIR_DEVICE_TO_HOST (1<<7) - -/* USB Standard Requests */ -#define USBRQ_GET_STATUS 0 -#define USBRQ_CLEAR_FEATURE 1 -#define USBRQ_SET_FEATURE 3 -#define USBRQ_SET_ADDRESS 5 -#define USBRQ_GET_DESCRIPTOR 6 -#define USBRQ_SET_DESCRIPTOR 7 -#define USBRQ_GET_CONFIGURATION 8 -#define USBRQ_SET_CONFIGURATION 9 -#define USBRQ_GET_INTERFACE 10 -#define USBRQ_SET_INTERFACE 11 -#define USBRQ_SYNCH_FRAME 12 - -/* USB descriptor constants */ -#define USBDESCR_DEVICE 1 -#define USBDESCR_CONFIG 2 -#define USBDESCR_STRING 3 -#define USBDESCR_INTERFACE 4 -#define USBDESCR_ENDPOINT 5 -#define USBDESCR_HID 0x21 -#define USBDESCR_HID_REPORT 0x22 -#define USBDESCR_HID_PHYS 0x23 - -//#define USBATTR_BUSPOWER 0x80 // USB 1.1 does not define this value any more -#define USBATTR_BUSPOWER 0 -#define USBATTR_SELFPOWER 0x40 -#define USBATTR_REMOTEWAKE 0x20 - -/* USB HID Requests */ -#define USBRQ_HID_GET_REPORT 0x01 -#define USBRQ_HID_GET_IDLE 0x02 -#define USBRQ_HID_GET_PROTOCOL 0x03 -#define USBRQ_HID_SET_REPORT 0x09 -#define USBRQ_HID_SET_IDLE 0x0a -#define USBRQ_HID_SET_PROTOCOL 0x0b - -/* ------------------------------------------------------------------------- */ - -#endif /* __usbdrv_h_included__ */ diff --git a/src/firmware/c/usbdrv/usbdrvasm.S b/src/firmware/c/usbdrv/usbdrvasm.S deleted file mode 100644 index 141534f..0000000 --- a/src/firmware/c/usbdrv/usbdrvasm.S +++ /dev/null @@ -1,392 +0,0 @@ -/* Name: usbdrvasm.S - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Christian Starkjohann - * Creation Date: 2007-06-13 - * Tabsize: 4 - * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -/* -General Description: -This module is the assembler part of the USB driver. This file contains -general code (preprocessor acrobatics and CRC computation) and then includes -the file appropriate for the given clock rate. -*/ - -#define __SFR_OFFSET 0 /* used by avr-libc's register definitions */ -#include "usbportability.h" -#include "usbdrv.h" /* for common defs */ - -/* register names */ -#define x1 r16 -#define x2 r17 -#define shift r18 -#define cnt r19 -#define x3 r20 -#define x4 r21 -#define x5 r22 -#define bitcnt x5 -#define phase x4 -#define leap x4 - -/* Some assembler dependent definitions and declarations: */ - -#ifdef __IAR_SYSTEMS_ASM__ - extern usbRxBuf, usbDeviceAddr, usbNewDeviceAddr, usbInputBufOffset - extern usbCurrentTok, usbRxLen, usbRxToken, usbTxLen - extern usbTxBuf, usbTxStatus1, usbTxStatus3 -# if USB_COUNT_SOF - extern usbSofCount -# endif - public usbCrc16 - public usbCrc16Append - - COMMON INTVEC -# ifndef USB_INTR_VECTOR - ORG INT0_vect -# else /* USB_INTR_VECTOR */ - ORG USB_INTR_VECTOR -# undef USB_INTR_VECTOR -# endif /* USB_INTR_VECTOR */ -# define USB_INTR_VECTOR usbInterruptHandler - rjmp USB_INTR_VECTOR - RSEG CODE - -#else /* __IAR_SYSTEMS_ASM__ */ - -# ifndef USB_INTR_VECTOR /* default to hardware interrupt INT0 */ -# ifdef INT0_vect -# define USB_INTR_VECTOR INT0_vect // this is the "new" define for the vector -# else -# define USB_INTR_VECTOR SIG_INTERRUPT0 // this is the "old" vector -# endif -# endif - .text - .global USB_INTR_VECTOR - .type USB_INTR_VECTOR, @function - .global usbCrc16 - .global usbCrc16Append -#endif /* __IAR_SYSTEMS_ASM__ */ - - -#if USB_INTR_PENDING < 0x40 /* This is an I/O address, use in and out */ -# define USB_LOAD_PENDING(reg) in reg, USB_INTR_PENDING -# define USB_STORE_PENDING(reg) out USB_INTR_PENDING, reg -#else /* It's a memory address, use lds and sts */ -# define USB_LOAD_PENDING(reg) lds reg, USB_INTR_PENDING -# define USB_STORE_PENDING(reg) sts USB_INTR_PENDING, reg -#endif - -#define usbTxLen1 usbTxStatus1 -#define usbTxBuf1 (usbTxStatus1 + 1) -#define usbTxLen3 usbTxStatus3 -#define usbTxBuf3 (usbTxStatus3 + 1) - - -;---------------------------------------------------------------------------- -; Utility functions -;---------------------------------------------------------------------------- - -#ifdef __IAR_SYSTEMS_ASM__ -/* Register assignments for usbCrc16 on IAR cc */ -/* Calling conventions on IAR: - * First parameter passed in r16/r17, second in r18/r19 and so on. - * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer) - * Result is passed in r16/r17 - * In case of the "tiny" memory model, pointers are only 8 bit with no - * padding. We therefore pass argument 1 as "16 bit unsigned". - */ -RTMODEL "__rt_version", "3" -/* The line above will generate an error if cc calling conventions change. - * The value "3" above is valid for IAR 4.10B/W32 - */ -# define argLen r18 /* argument 2 */ -# define argPtrL r16 /* argument 1 */ -# define argPtrH r17 /* argument 1 */ - -# define resCrcL r16 /* result */ -# define resCrcH r17 /* result */ - -# define ptrL ZL -# define ptrH ZH -# define ptr Z -# define byte r22 -# define bitCnt r19 -# define polyL r20 -# define polyH r21 -# define scratch r23 - -#else /* __IAR_SYSTEMS_ASM__ */ -/* Register assignments for usbCrc16 on gcc */ -/* Calling conventions on gcc: - * First parameter passed in r24/r25, second in r22/23 and so on. - * Callee must preserve r1-r17, r28/r29 - * Result is passed in r24/r25 - */ -# define argLen r22 /* argument 2 */ -# define argPtrL r24 /* argument 1 */ -# define argPtrH r25 /* argument 1 */ - -# define resCrcL r24 /* result */ -# define resCrcH r25 /* result */ - -# define ptrL XL -# define ptrH XH -# define ptr x -# define byte r18 -# define bitCnt r19 -# define polyL r20 -# define polyH r21 -# define scratch r23 - -#endif - -#if USB_USE_FAST_CRC - -; This implementation is faster, but has bigger code size -; Thanks to Slawomir Fras (BoskiDialer) for this code! -; It implements the following C pseudo-code: -; unsigned table(unsigned char x) -; { -; unsigned value; -; -; value = (unsigned)x << 6; -; value ^= (unsigned)x << 7; -; if(parity(x)) -; value ^= 0xc001; -; return value; -; } -; unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen) -; { -; unsigned crc = 0xffff; -; -; while(argLen--) -; crc = table(lo8(crc) ^ *argPtr++) ^ hi8(crc); -; return ~crc; -; } - -; extern unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen); -; argPtr r24+25 / r16+r17 -; argLen r22 / r18 -; temp variables: -; byte r18 / r22 -; scratch r23 -; resCrc r24+r25 / r16+r17 -; ptr X / Z -usbCrc16: - mov ptrL, argPtrL - mov ptrH, argPtrH - ldi resCrcL, 0xFF - ldi resCrcH, 0xFF - rjmp usbCrc16LoopTest -usbCrc16ByteLoop: - ld byte, ptr+ - eor resCrcL, byte ; resCrcL is now 'x' in table() - mov byte, resCrcL ; compute parity of 'x' - swap byte - eor byte, resCrcL - mov scratch, byte - lsr byte - lsr byte - eor byte, scratch - inc byte - lsr byte - andi byte, 1 ; byte is now parity(x) - mov scratch, resCrcL - mov resCrcL, resCrcH - eor resCrcL, byte ; low byte of if(parity(x)) value ^= 0xc001; - neg byte - andi byte, 0xc0 - mov resCrcH, byte ; high byte of if(parity(x)) value ^= 0xc001; - clr byte - lsr scratch - ror byte - eor resCrcH, scratch - eor resCrcL, byte - lsr scratch - ror byte - eor resCrcH, scratch - eor resCrcL, byte -usbCrc16LoopTest: - subi argLen, 1 - brsh usbCrc16ByteLoop - com resCrcL - com resCrcH - ret - -#else /* USB_USE_FAST_CRC */ - -; This implementation is slower, but has less code size -; -; extern unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen); -; argPtr r24+25 / r16+r17 -; argLen r22 / r18 -; temp variables: -; byte r18 / r22 -; bitCnt r19 -; poly r20+r21 -; scratch r23 -; resCrc r24+r25 / r16+r17 -; ptr X / Z -usbCrc16: - mov ptrL, argPtrL - mov ptrH, argPtrH - ldi resCrcL, 0 - ldi resCrcH, 0 - ldi polyL, lo8(0xa001) - ldi polyH, hi8(0xa001) - com argLen ; argLen = -argLen - 1: modified loop to ensure that carry is set - ldi bitCnt, 0 ; loop counter with starnd condition = end condition - rjmp usbCrcLoopEntry -usbCrcByteLoop: - ld byte, ptr+ - eor resCrcL, byte -usbCrcBitLoop: - ror resCrcH ; carry is always set here (see brcs jumps to here) - ror resCrcL - brcs usbCrcNoXor - eor resCrcL, polyL - eor resCrcH, polyH -usbCrcNoXor: - subi bitCnt, 224 ; (8 * 224) % 256 = 0; this loop iterates 8 times - brcs usbCrcBitLoop -usbCrcLoopEntry: - subi argLen, -1 - brcs usbCrcByteLoop -usbCrcReady: - ret -; Thanks to Reimar Doeffinger for optimizing this CRC routine! - -#endif /* USB_USE_FAST_CRC */ - -; extern unsigned usbCrc16Append(unsigned char *data, unsigned char len); -usbCrc16Append: - rcall usbCrc16 - st ptr+, resCrcL - st ptr+, resCrcH - ret - -#undef argLen -#undef argPtrL -#undef argPtrH -#undef resCrcL -#undef resCrcH -#undef ptrL -#undef ptrH -#undef ptr -#undef byte -#undef bitCnt -#undef polyL -#undef polyH -#undef scratch - - -#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH -#ifdef __IAR_SYSTEMS_ASM__ -/* Register assignments for usbMeasureFrameLength on IAR cc */ -/* Calling conventions on IAR: - * First parameter passed in r16/r17, second in r18/r19 and so on. - * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer) - * Result is passed in r16/r17 - * In case of the "tiny" memory model, pointers are only 8 bit with no - * padding. We therefore pass argument 1 as "16 bit unsigned". - */ -# define resL r16 -# define resH r17 -# define cnt16L r30 -# define cnt16H r31 -# define cntH r18 - -#else /* __IAR_SYSTEMS_ASM__ */ -/* Register assignments for usbMeasureFrameLength on gcc */ -/* Calling conventions on gcc: - * First parameter passed in r24/r25, second in r22/23 and so on. - * Callee must preserve r1-r17, r28/r29 - * Result is passed in r24/r25 - */ -# define resL r24 -# define resH r25 -# define cnt16L r24 -# define cnt16H r25 -# define cntH r26 -#endif -# define cnt16 cnt16L - -; extern unsigned usbMeasurePacketLength(void); -; returns time between two idle strobes in multiples of 7 CPU clocks -.global usbMeasureFrameLength -usbMeasureFrameLength: - ldi cntH, 6 ; wait ~ 10 ms for D- == 0 - clr cnt16L - clr cnt16H -usbMFTime16: - dec cntH - breq usbMFTimeout -usbMFWaitStrobe: ; first wait for D- == 0 (idle strobe) - sbiw cnt16, 1 ;[0] [6] - breq usbMFTime16 ;[2] - sbic USBIN, USBMINUS ;[3] - rjmp usbMFWaitStrobe ;[4] -usbMFWaitIdle: ; then wait until idle again - sbis USBIN, USBMINUS ;1 wait for D- == 1 - rjmp usbMFWaitIdle ;2 - ldi cnt16L, 1 ;1 represents cycles so far - clr cnt16H ;1 -usbMFWaitLoop: - in cntH, USBIN ;[0] [7] - adiw cnt16, 1 ;[1] - breq usbMFTimeout ;[3] - andi cntH, USBMASK ;[4] - brne usbMFWaitLoop ;[5] -usbMFTimeout: -#if resL != cnt16L - mov resL, cnt16L - mov resH, cnt16H -#endif - ret - -#undef resL -#undef resH -#undef cnt16 -#undef cnt16L -#undef cnt16H -#undef cntH - -#endif /* USB_CFG_HAVE_MEASURE_FRAME_LENGTH */ - -;---------------------------------------------------------------------------- -; Now include the clock rate specific code -;---------------------------------------------------------------------------- - -#ifndef USB_CFG_CLOCK_KHZ -# ifdef F_CPU -# define USB_CFG_CLOCK_KHZ (F_CPU/1000) -# else -# error "USB_CFG_CLOCK_KHZ not defined in usbconfig.h and no F_CPU set!" -# endif -#endif - -#if USB_CFG_CHECK_CRC /* separate dispatcher for CRC type modules */ -# if USB_CFG_CLOCK_KHZ == 18000 -# include "usbdrvasm18-crc.inc" -# else -# error "USB_CFG_CLOCK_KHZ is not one of the supported crc-rates!" -# endif -#else /* USB_CFG_CHECK_CRC */ -# if USB_CFG_CLOCK_KHZ == 12000 -# include "usbdrvasm12.inc" -# elif USB_CFG_CLOCK_KHZ == 12800 -# include "usbdrvasm128.inc" -# elif USB_CFG_CLOCK_KHZ == 15000 -# include "usbdrvasm15.inc" -# elif USB_CFG_CLOCK_KHZ == 16000 -# include "usbdrvasm16.inc" -# elif USB_CFG_CLOCK_KHZ == 16500 -# include "usbdrvasm165.inc" -# elif USB_CFG_CLOCK_KHZ == 20000 -# include "usbdrvasm20.inc" -# else -# error "USB_CFG_CLOCK_KHZ is not one of the supported non-crc-rates!" -# endif -#endif /* USB_CFG_CHECK_CRC */ diff --git a/src/firmware/c/usbdrv/usbdrvasm.asm b/src/firmware/c/usbdrv/usbdrvasm.asm deleted file mode 100644 index 4a46fc6..0000000 --- a/src/firmware/c/usbdrv/usbdrvasm.asm +++ /dev/null @@ -1,20 +0,0 @@ -/* Name: usbdrvasm.asm - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Christian Starkjohann - * Creation Date: 2006-03-01 - * Tabsize: 4 - * Copyright: (c) 2006 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -/* -General Description: -The IAR compiler/assembler system prefers assembler files with file extension -".asm". We simply provide this file as an alias for usbdrvasm.S. - -Thanks to Oleg Semyonov for his help with the IAR tools port! -*/ - -#include "usbdrvasm.S" - -end diff --git a/src/firmware/c/usbdrv/usbdrvasm12.inc b/src/firmware/c/usbdrv/usbdrvasm12.inc deleted file mode 100644 index 16a3022..0000000 --- a/src/firmware/c/usbdrv/usbdrvasm12.inc +++ /dev/null @@ -1,392 +0,0 @@ -/* Name: usbdrvasm12.inc - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Christian Starkjohann - * Creation Date: 2004-12-29 - * Tabsize: 4 - * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -/* Do not link this file! Link usbdrvasm.S instead, which includes the - * appropriate implementation! - */ - -/* -General Description: -This file is the 12 MHz version of the asssembler part of the USB driver. It -requires a 12 MHz crystal (not a ceramic resonator and not a calibrated RC -oscillator). - -See usbdrv.h for a description of the entire driver. - -Since almost all of this code is timing critical, don't change unless you -really know what you are doing! Many parts require not only a maximum number -of CPU cycles, but even an exact number of cycles! - - -Timing constraints according to spec (in bit times): -timing subject min max CPUcycles ---------------------------------------------------------------------------- -EOP of OUT/SETUP to sync pattern of DATA0 (both rx) 2 16 16-128 -EOP of IN to sync pattern of DATA0 (rx, then tx) 2 7.5 16-60 -DATAx (rx) to ACK/NAK/STALL (tx) 2 7.5 16-60 -*/ - -;Software-receiver engine. Strict timing! Don't change unless you can preserve timing! -;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled -;max allowable interrupt latency: 34 cycles -> max 25 cycles interrupt disable -;max stack usage: [ret(2), YL, SREG, YH, shift, x1, x2, x3, cnt, x4] = 11 bytes -;Numbers in brackets are maximum cycles since SOF. -USB_INTR_VECTOR: -;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt - push YL ;2 [35] push only what is necessary to sync with edge ASAP - in YL, SREG ;1 [37] - push YL ;2 [39] -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -;---------------------------------------------------------------------------- -;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -;sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -waitForK: -;The following code results in a sampling window of 1/4 bit which meets the spec. - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError -foundK: -;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling] -;we have 1 bit time for setup purposes, then sample again. Numbers in brackets -;are cycles from center of first sync (double K) bit after the instruction - push YH ;2 [2] - lds YL, usbInputBufOffset;2 [4] - clr YH ;1 [5] - subi YL, lo8(-(usbRxBuf));1 [6] - sbci YH, hi8(-(usbRxBuf));1 [7] - - sbis USBIN, USBMINUS ;1 [8] we want two bits K [sample 1 cycle too early] - rjmp haveTwoBitsK ;2 [10] - pop YH ;2 [11] undo the push from before - rjmp waitForK ;2 [13] this was not the end of sync, retry -haveTwoBitsK: -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- - push shift ;2 [16] - push x1 ;2 [12] - push x2 ;2 [14] - - in x1, USBIN ;1 [17] <-- sample bit 0 - ldi shift, 0xff ;1 [18] - bst x1, USBMINUS ;1 [19] - bld shift, 0 ;1 [20] - push x3 ;2 [22] - push cnt ;2 [24] - - in x2, USBIN ;1 [25] <-- sample bit 1 - ser x3 ;1 [26] [inserted init instruction] - eor x1, x2 ;1 [27] - bst x1, USBMINUS ;1 [28] - bld shift, 1 ;1 [29] - ldi cnt, USB_BUFSIZE;1 [30] [inserted init instruction] - rjmp rxbit2 ;2 [32] - -;---------------------------------------------------------------------------- -; Receiver loop (numbers in brackets are cycles within byte after instr) -;---------------------------------------------------------------------------- - -unstuff0: ;1 (branch taken) - andi x3, ~0x01 ;1 [15] - mov x1, x2 ;1 [16] x2 contains last sampled (stuffed) bit - in x2, USBIN ;1 [17] <-- sample bit 1 again - ori shift, 0x01 ;1 [18] - rjmp didUnstuff0 ;2 [20] - -unstuff1: ;1 (branch taken) - mov x2, x1 ;1 [21] x1 contains last sampled (stuffed) bit - andi x3, ~0x02 ;1 [22] - ori shift, 0x02 ;1 [23] - nop ;1 [24] - in x1, USBIN ;1 [25] <-- sample bit 2 again - rjmp didUnstuff1 ;2 [27] - -unstuff2: ;1 (branch taken) - andi x3, ~0x04 ;1 [29] - ori shift, 0x04 ;1 [30] - mov x1, x2 ;1 [31] x2 contains last sampled (stuffed) bit - nop ;1 [32] - in x2, USBIN ;1 [33] <-- sample bit 3 - rjmp didUnstuff2 ;2 [35] - -unstuff3: ;1 (branch taken) - in x2, USBIN ;1 [34] <-- sample stuffed bit 3 [one cycle too late] - andi x3, ~0x08 ;1 [35] - ori shift, 0x08 ;1 [36] - rjmp didUnstuff3 ;2 [38] - -unstuff4: ;1 (branch taken) - andi x3, ~0x10 ;1 [40] - in x1, USBIN ;1 [41] <-- sample stuffed bit 4 - ori shift, 0x10 ;1 [42] - rjmp didUnstuff4 ;2 [44] - -unstuff5: ;1 (branch taken) - andi x3, ~0x20 ;1 [48] - in x2, USBIN ;1 [49] <-- sample stuffed bit 5 - ori shift, 0x20 ;1 [50] - rjmp didUnstuff5 ;2 [52] - -unstuff6: ;1 (branch taken) - andi x3, ~0x40 ;1 [56] - in x1, USBIN ;1 [57] <-- sample stuffed bit 6 - ori shift, 0x40 ;1 [58] - rjmp didUnstuff6 ;2 [60] - -; extra jobs done during bit interval: -; bit 0: store, clear [SE0 is unreliable here due to bit dribbling in hubs] -; bit 1: se0 check -; bit 2: overflow check -; bit 3: recovery from delay [bit 0 tasks took too long] -; bit 4: none -; bit 5: none -; bit 6: none -; bit 7: jump, eor -rxLoop: - eor x3, shift ;1 [0] reconstruct: x3 is 0 at bit locations we changed, 1 at others - in x1, USBIN ;1 [1] <-- sample bit 0 - st y+, x3 ;2 [3] store data - ser x3 ;1 [4] - nop ;1 [5] - eor x2, x1 ;1 [6] - bst x2, USBMINUS;1 [7] - bld shift, 0 ;1 [8] - in x2, USBIN ;1 [9] <-- sample bit 1 (or possibly bit 0 stuffed) - andi x2, USBMASK ;1 [10] - breq se0 ;1 [11] SE0 check for bit 1 - andi shift, 0xf9 ;1 [12] -didUnstuff0: - breq unstuff0 ;1 [13] - eor x1, x2 ;1 [14] - bst x1, USBMINUS;1 [15] - bld shift, 1 ;1 [16] -rxbit2: - in x1, USBIN ;1 [17] <-- sample bit 2 (or possibly bit 1 stuffed) - andi shift, 0xf3 ;1 [18] - breq unstuff1 ;1 [19] do remaining work for bit 1 -didUnstuff1: - subi cnt, 1 ;1 [20] - brcs overflow ;1 [21] loop control - eor x2, x1 ;1 [22] - bst x2, USBMINUS;1 [23] - bld shift, 2 ;1 [24] - in x2, USBIN ;1 [25] <-- sample bit 3 (or possibly bit 2 stuffed) - andi shift, 0xe7 ;1 [26] - breq unstuff2 ;1 [27] -didUnstuff2: - eor x1, x2 ;1 [28] - bst x1, USBMINUS;1 [29] - bld shift, 3 ;1 [30] -didUnstuff3: - andi shift, 0xcf ;1 [31] - breq unstuff3 ;1 [32] - in x1, USBIN ;1 [33] <-- sample bit 4 - eor x2, x1 ;1 [34] - bst x2, USBMINUS;1 [35] - bld shift, 4 ;1 [36] -didUnstuff4: - andi shift, 0x9f ;1 [37] - breq unstuff4 ;1 [38] - nop2 ;2 [40] - in x2, USBIN ;1 [41] <-- sample bit 5 - eor x1, x2 ;1 [42] - bst x1, USBMINUS;1 [43] - bld shift, 5 ;1 [44] -didUnstuff5: - andi shift, 0x3f ;1 [45] - breq unstuff5 ;1 [46] - nop2 ;2 [48] - in x1, USBIN ;1 [49] <-- sample bit 6 - eor x2, x1 ;1 [50] - bst x2, USBMINUS;1 [51] - bld shift, 6 ;1 [52] -didUnstuff6: - cpi shift, 0x02 ;1 [53] - brlo unstuff6 ;1 [54] - nop2 ;2 [56] - in x2, USBIN ;1 [57] <-- sample bit 7 - eor x1, x2 ;1 [58] - bst x1, USBMINUS;1 [59] - bld shift, 7 ;1 [60] -didUnstuff7: - cpi shift, 0x04 ;1 [61] - brsh rxLoop ;2 [63] loop control -unstuff7: - andi x3, ~0x80 ;1 [63] - ori shift, 0x80 ;1 [64] - in x2, USBIN ;1 [65] <-- sample stuffed bit 7 - nop ;1 [66] - rjmp didUnstuff7 ;2 [68] - -macro POP_STANDARD ; 12 cycles - pop cnt - pop x3 - pop x2 - pop x1 - pop shift - pop YH - endm -macro POP_RETI ; 5 cycles - pop YL - out SREG, YL - pop YL - endm - -#include "asmcommon.inc" - -;---------------------------------------------------------------------------- -; Transmitting data -;---------------------------------------------------------------------------- - -txByteLoop: -txBitloop: -stuffN1Delay: ; [03] - ror shift ;[-5] [11] [59] - brcc doExorN1 ;[-4] [60] - subi x4, 1 ;[-3] - brne commonN1 ;[-2] - lsl shift ;[-1] compensate ror after rjmp stuffDelay - nop ;[00] stuffing consists of just waiting 8 cycles - rjmp stuffN1Delay ;[01] after ror, C bit is reliably clear - -sendNakAndReti: ;0 [-19] 19 cycles until SOP - ldi x3, USBPID_NAK ;1 [-18] - rjmp usbSendX3 ;2 [-16] -sendAckAndReti: ;0 [-19] 19 cycles until SOP - ldi x3, USBPID_ACK ;1 [-18] - rjmp usbSendX3 ;2 [-16] -sendCntAndReti: ;0 [-17] 17 cycles until SOP - mov x3, cnt ;1 [-16] -usbSendX3: ;0 [-16] - ldi YL, 20 ;1 [-15] 'x3' is R20 - ldi YH, 0 ;1 [-14] - ldi cnt, 2 ;1 [-13] -; rjmp usbSendAndReti fallthrough - -; USB spec says: -; idle = J -; J = (D+ = 0), (D- = 1) or USBOUT = 0x01 -; K = (D+ = 1), (D- = 0) or USBOUT = 0x02 -; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles) - -;usbSend: -;pointer to data in 'Y' -;number of bytes in 'cnt' -- including sync byte -;uses: x1...x2, x4, shift, cnt, Y [x1 = mirror USBOUT, x2 = USBMASK, x4 = bitstuff cnt] -;Numbers in brackets are time since first bit of sync pattern is sent (start of instruction) -usbSendAndReti: - in x2, USBDDR ;[-12] 12 cycles until SOP - ori x2, USBMASK ;[-11] - sbi USBOUT, USBMINUS ;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) - out USBDDR, x2 ;[-8] <--- acquire bus - in x1, USBOUT ;[-7] port mirror for tx loop - ldi shift, 0x40 ;[-6] sync byte is first byte sent (we enter loop after ror) - ldi x2, USBMASK ;[-5] - push x4 ;[-4] -doExorN1: - eor x1, x2 ;[-2] [06] [62] - ldi x4, 6 ;[-1] [07] [63] -commonN1: -stuffN2Delay: - out USBOUT, x1 ;[00] [08] [64] <--- set bit - ror shift ;[01] - brcc doExorN2 ;[02] - subi x4, 1 ;[03] - brne commonN2 ;[04] - lsl shift ;[05] compensate ror after rjmp stuffDelay - rjmp stuffN2Delay ;[06] after ror, C bit is reliably clear -doExorN2: - eor x1, x2 ;[04] [12] - ldi x4, 6 ;[05] [13] -commonN2: - nop ;[06] [14] - subi cnt, 171 ;[07] [15] trick: (3 * 171) & 0xff = 1 - out USBOUT, x1 ;[08] [16] <--- set bit - brcs txBitloop ;[09] [25] [41] - -stuff6Delay: - ror shift ;[42] [50] - brcc doExor6 ;[43] - subi x4, 1 ;[44] - brne common6 ;[45] - lsl shift ;[46] compensate ror after rjmp stuffDelay - nop ;[47] stuffing consists of just waiting 8 cycles - rjmp stuff6Delay ;[48] after ror, C bit is reliably clear -doExor6: - eor x1, x2 ;[45] [53] - ldi x4, 6 ;[46] -common6: -stuff7Delay: - ror shift ;[47] [55] - out USBOUT, x1 ;[48] <--- set bit - brcc doExor7 ;[49] - subi x4, 1 ;[50] - brne common7 ;[51] - lsl shift ;[52] compensate ror after rjmp stuffDelay - rjmp stuff7Delay ;[53] after ror, C bit is reliably clear -doExor7: - eor x1, x2 ;[51] [59] - ldi x4, 6 ;[52] -common7: - ld shift, y+ ;[53] - tst cnt ;[55] - out USBOUT, x1 ;[56] <--- set bit - brne txByteLoop ;[57] - -;make SE0: - cbr x1, USBMASK ;[58] prepare SE0 [spec says EOP may be 15 to 18 cycles] - lds x2, usbNewDeviceAddr;[59] - lsl x2 ;[61] we compare with left shifted address - subi YL, 2 + 20 ;[62] Only assign address on data packets, not ACK/NAK in x3 - sbci YH, 0 ;[63] - out USBOUT, x1 ;[00] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle -;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: -;set address only after data packet was sent, not after handshake - breq skipAddrAssign ;[01] - sts usbDeviceAddr, x2 ; if not skipped: SE0 is one cycle longer -skipAddrAssign: -;end of usbDeviceAddress transfer - ldi x2, 1< 12.5625 MHz -max frequency: 69.286 cycles for 8 bit -> 12.99 MHz -nominal frequency: 12.77 MHz ( = sqrt(min * max)) - -sampling positions: (next even number in range [+/- 0.5]) -cycle index range: 0 ... 66 -bits: -.5, 8.875, 17.25, 25.625, 34, 42.375, 50.75, 59.125 -[0/1], [9], [17], [25/+26], [34], [+42/43], [51], [59] - -bit number: 0 1 2 3 4 5 6 7 -spare cycles 1 2 1 2 1 1 1 0 - -operations to perform: duration cycle - ---------------- - eor fix, shift 1 -> 00 - andi phase, USBMASK 1 -> 08 - breq se0 1 -> 16 (moved to 11) - st y+, data 2 -> 24, 25 - mov data, fix 1 -> 33 - ser data 1 -> 41 - subi cnt, 1 1 -> 49 - brcs overflow 1 -> 50 - -layout of samples and operations: -[##] = sample bit -<##> = sample phase -*##* = operation - -0: *00* [01] 02 03 04 <05> 06 07 -1: *08* [09] 10 11 12 <13> 14 15 *16* -2: [17] 18 19 20 <21> 22 23 -3: *24* *25* [26] 27 28 29 <30> 31 32 -4: *33* [34] 35 36 37 <38> 39 40 -5: *41* [42] 43 44 45 <46> 47 48 -6: *49* *50* [51] 52 53 54 <55> 56 57 58 -7: [59] 60 61 62 <63> 64 65 66 -*****************************************************************************/ - -/* we prefer positive expressions (do if condition) instead of negative - * (skip if condition), therefore use defines for skip instructions: - */ -#define ifioclr sbis -#define ifioset sbic -#define ifrclr sbrs -#define ifrset sbrc - -/* The registers "fix" and "data" swap their meaning during the loop. Use - * defines to keep their name constant. - */ -#define fix x2 -#define data x1 -#undef phase /* phase has a default definition to x4 */ -#define phase x3 - - -USB_INTR_VECTOR: -;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt, r0 - push YL ;2 push only what is necessary to sync with edge ASAP - in YL, SREG ;1 - push YL ;2 -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -;---------------------------------------------------------------------------- -;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -;sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -waitForK: -;The following code results in a sampling window of 1/4 bit which meets the spec. - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS ;[0] - rjmp foundK ;[1] -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError - -foundK: -;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling] -;we have 1 bit time for setup purposes, then sample again. Numbers in brackets -;are cycles from center of first sync (double K) bit after the instruction - push YH ;[2] - lds YL, usbInputBufOffset;[4] - clr YH ;[6] - subi YL, lo8(-(usbRxBuf));[7] - sbci YH, hi8(-(usbRxBuf));[8] - - sbis USBIN, USBMINUS ;[9] we want two bits K [we want to sample at 8 + 4 - 1.5 = 10.5] - rjmp haveTwoBitsK ;[10] - pop YH ;[11] undo the push from before - rjmp waitForK ;[13] this was not the end of sync, retry -haveTwoBitsK: -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- -#define fix x2 -#define data x1 - - push shift ;[12] - push x1 ;[14] - push x2 ;[16] - ldi shift, 0x80 ;[18] prevent bit-unstuffing but init low bits to 0 - ifioset USBIN, USBMINUS ;[19] [01] <--- bit 0 [10.5 + 8 = 18.5] - ori shift, 1<<0 ;[02] - push x3 ;[03] - push cnt ;[05] - push r0 ;[07] - ifioset USBIN, USBMINUS ;[09] <--- bit 1 - ori shift, 1<<1 ;[10] - ser fix ;[11] - ldi cnt, USB_BUFSIZE ;[12] - mov data, shift ;[13] - lsl shift ;[14] - nop2 ;[15] - ifioset USBIN, USBMINUS ;[17] <--- bit 2 - ori data, 3<<2 ;[18] store in bit 2 AND bit 3 - eor shift, data ;[19] do nrzi decoding - andi data, 1<<3 ;[20] - in phase, USBIN ;[21] <- phase - brne jumpToEntryAfterSet ;[22] if USBMINS at bit 3 was 1 - nop ;[23] - rjmp entryAfterClr ;[24] -jumpToEntryAfterSet: - rjmp entryAfterSet ;[24] - -;---------------------------------------------------------------------------- -; Receiver loop (numbers in brackets are cycles within byte after instr) -;---------------------------------------------------------------------------- -#undef fix -#define fix x1 -#undef data -#define data x2 - -bit7IsSet: - ifrclr phase, USBMINUS ;[62] check phase only if D- changed - lpm ;[63] - in phase, USBIN ;[64] <- phase (one cycle too late) - ori shift, 1 << 7 ;[65] - nop ;[66] -;;;;rjmp bit0AfterSet ; -> [00] == [67] moved block up to save jump -bit0AfterSet: - eor fix, shift ;[00] -#undef fix -#define fix x2 -#undef data -#define data x1 /* we now have result in data, fix is reset to 0xff */ - ifioclr USBIN, USBMINUS ;[01] <--- sample 0 - rjmp bit0IsClr ;[02] - andi shift, ~(7 << 0) ;[03] - breq unstuff0s ;[04] - in phase, USBIN ;[05] <- phase - rjmp bit1AfterSet ;[06] -unstuff0s: - in phase, USBIN ;[06] <- phase (one cycle too late) - andi fix, ~(1 << 0) ;[07] - ifioclr USBIN, USBMINUS ;[00] - ifioset USBIN, USBPLUS ;[01] - rjmp bit0IsClr ;[02] executed if first expr false or second true -se0AndStore: ; executed only if both bits 0 - st y+, x1 ;[15/17] cycles after start of byte - rjmp se0 ;[17/19] - -bit0IsClr: - ifrset phase, USBMINUS ;[04] check phase only if D- changed - lpm ;[05] - in phase, USBIN ;[06] <- phase (one cycle too late) - ori shift, 1 << 0 ;[07] -bit1AfterClr: - andi phase, USBMASK ;[08] - ifioset USBIN, USBMINUS ;[09] <--- sample 1 - rjmp bit1IsSet ;[10] - breq se0AndStore ;[11] if D- was 0 in bits 0 AND 1 and D+ was 0 in between, we have SE0 - andi shift, ~(7 << 1) ;[12] - in phase, USBIN ;[13] <- phase - breq unstuff1c ;[14] - rjmp bit2AfterClr ;[15] -unstuff1c: - andi fix, ~(1 << 1) ;[16] - nop2 ;[08] - nop2 ;[10] -bit1IsSet: - ifrclr phase, USBMINUS ;[12] check phase only if D- changed - lpm ;[13] - in phase, USBIN ;[14] <- phase (one cycle too late) - ori shift, 1 << 1 ;[15] - nop ;[16] -bit2AfterSet: - ifioclr USBIN, USBMINUS ;[17] <--- sample 2 - rjmp bit2IsClr ;[18] - andi shift, ~(7 << 2) ;[19] - breq unstuff2s ;[20] - in phase, USBIN ;[21] <- phase - rjmp bit3AfterSet ;[22] -unstuff2s: - in phase, USBIN ;[22] <- phase (one cycle too late) - andi fix, ~(1 << 2) ;[23] - nop2 ;[16] - nop2 ;[18] -bit2IsClr: - ifrset phase, USBMINUS ;[20] check phase only if D- changed - lpm ;[21] - in phase, USBIN ;[22] <- phase (one cycle too late) - ori shift, 1 << 2 ;[23] -bit3AfterClr: - st y+, data ;[24] -entryAfterClr: - ifioset USBIN, USBMINUS ;[26] <--- sample 3 - rjmp bit3IsSet ;[27] - andi shift, ~(7 << 3) ;[28] - breq unstuff3c ;[29] - in phase, USBIN ;[30] <- phase - rjmp bit4AfterClr ;[31] -unstuff3c: - in phase, USBIN ;[31] <- phase (one cycle too late) - andi fix, ~(1 << 3) ;[32] - nop2 ;[25] - nop2 ;[27] -bit3IsSet: - ifrclr phase, USBMINUS ;[29] check phase only if D- changed - lpm ;[30] - in phase, USBIN ;[31] <- phase (one cycle too late) - ori shift, 1 << 3 ;[32] -bit4AfterSet: - mov data, fix ;[33] undo this move by swapping defines -#undef fix -#define fix x1 -#undef data -#define data x2 - ifioclr USBIN, USBMINUS ;[34] <--- sample 4 - rjmp bit4IsClr ;[35] - andi shift, ~(7 << 4) ;[36] - breq unstuff4s ;[37] - in phase, USBIN ;[38] <- phase - rjmp bit5AfterSet ;[39] -unstuff4s: - in phase, USBIN ;[39] <- phase (one cycle too late) - andi fix, ~(1 << 4) ;[40] - nop2 ;[33] - nop2 ;[35] -bit4IsClr: - ifrset phase, USBMINUS ;[37] check phase only if D- changed - lpm ;[38] - in phase, USBIN ;[39] <- phase (one cycle too late) - ori shift, 1 << 4 ;[40] -bit5AfterClr: - ser data ;[41] - ifioset USBIN, USBMINUS ;[42] <--- sample 5 - rjmp bit5IsSet ;[43] - andi shift, ~(7 << 5) ;[44] - breq unstuff5c ;[45] - in phase, USBIN ;[46] <- phase - rjmp bit6AfterClr ;[47] -unstuff5c: - in phase, USBIN ;[47] <- phase (one cycle too late) - andi fix, ~(1 << 5) ;[48] - nop2 ;[41] - nop2 ;[43] -bit5IsSet: - ifrclr phase, USBMINUS ;[45] check phase only if D- changed - lpm ;[46] - in phase, USBIN ;[47] <- phase (one cycle too late) - ori shift, 1 << 5 ;[48] -bit6AfterSet: - subi cnt, 1 ;[49] - brcs jumpToOverflow ;[50] - ifioclr USBIN, USBMINUS ;[51] <--- sample 6 - rjmp bit6IsClr ;[52] - andi shift, ~(3 << 6) ;[53] - cpi shift, 2 ;[54] - in phase, USBIN ;[55] <- phase - brlt unstuff6s ;[56] - rjmp bit7AfterSet ;[57] - -jumpToOverflow: - rjmp overflow - -unstuff6s: - andi fix, ~(1 << 6) ;[50] - lpm ;[51] -bit6IsClr: - ifrset phase, USBMINUS ;[54] check phase only if D- changed - lpm ;[55] - in phase, USBIN ;[56] <- phase (one cycle too late) - ori shift, 1 << 6 ;[57] - nop ;[58] -bit7AfterClr: - ifioset USBIN, USBMINUS ;[59] <--- sample 7 - rjmp bit7IsSet ;[60] - andi shift, ~(1 << 7) ;[61] - cpi shift, 4 ;[62] - in phase, USBIN ;[63] <- phase - brlt unstuff7c ;[64] - rjmp bit0AfterClr ;[65] -> [00] == [67] -unstuff7c: - andi fix, ~(1 << 7) ;[58] - nop ;[59] - rjmp bit7IsSet ;[60] - -bit7IsClr: - ifrset phase, USBMINUS ;[62] check phase only if D- changed - lpm ;[63] - in phase, USBIN ;[64] <- phase (one cycle too late) - ori shift, 1 << 7 ;[65] - nop ;[66] -;;;;rjmp bit0AfterClr ; -> [00] == [67] moved block up to save jump -bit0AfterClr: - eor fix, shift ;[00] -#undef fix -#define fix x2 -#undef data -#define data x1 /* we now have result in data, fix is reset to 0xff */ - ifioset USBIN, USBMINUS ;[01] <--- sample 0 - rjmp bit0IsSet ;[02] - andi shift, ~(7 << 0) ;[03] - breq unstuff0c ;[04] - in phase, USBIN ;[05] <- phase - rjmp bit1AfterClr ;[06] -unstuff0c: - in phase, USBIN ;[06] <- phase (one cycle too late) - andi fix, ~(1 << 0) ;[07] - ifioclr USBIN, USBMINUS ;[00] - ifioset USBIN, USBPLUS ;[01] - rjmp bit0IsSet ;[02] executed if first expr false or second true - rjmp se0AndStore ;[03] executed only if both bits 0 -bit0IsSet: - ifrclr phase, USBMINUS ;[04] check phase only if D- changed - lpm ;[05] - in phase, USBIN ;[06] <- phase (one cycle too late) - ori shift, 1 << 0 ;[07] -bit1AfterSet: - andi shift, ~(7 << 1) ;[08] compensated by "ori shift, 1<<1" if bit1IsClr - ifioclr USBIN, USBMINUS ;[09] <--- sample 1 - rjmp bit1IsClr ;[10] - breq unstuff1s ;[11] - nop2 ;[12] do not check for SE0 if bit 0 was 1 - in phase, USBIN ;[14] <- phase (one cycle too late) - rjmp bit2AfterSet ;[15] -unstuff1s: - in phase, USBIN ;[13] <- phase - andi fix, ~(1 << 1) ;[14] - lpm ;[07] - nop2 ;[10] -bit1IsClr: - ifrset phase, USBMINUS ;[12] check phase only if D- changed - lpm ;[13] - in phase, USBIN ;[14] <- phase (one cycle too late) - ori shift, 1 << 1 ;[15] - nop ;[16] -bit2AfterClr: - ifioset USBIN, USBMINUS ;[17] <--- sample 2 - rjmp bit2IsSet ;[18] - andi shift, ~(7 << 2) ;[19] - breq unstuff2c ;[20] - in phase, USBIN ;[21] <- phase - rjmp bit3AfterClr ;[22] -unstuff2c: - in phase, USBIN ;[22] <- phase (one cycle too late) - andi fix, ~(1 << 2) ;[23] - nop2 ;[16] - nop2 ;[18] -bit2IsSet: - ifrclr phase, USBMINUS ;[20] check phase only if D- changed - lpm ;[21] - in phase, USBIN ;[22] <- phase (one cycle too late) - ori shift, 1 << 2 ;[23] -bit3AfterSet: - st y+, data ;[24] -entryAfterSet: - ifioclr USBIN, USBMINUS ;[26] <--- sample 3 - rjmp bit3IsClr ;[27] - andi shift, ~(7 << 3) ;[28] - breq unstuff3s ;[29] - in phase, USBIN ;[30] <- phase - rjmp bit4AfterSet ;[31] -unstuff3s: - in phase, USBIN ;[31] <- phase (one cycle too late) - andi fix, ~(1 << 3) ;[32] - nop2 ;[25] - nop2 ;[27] -bit3IsClr: - ifrset phase, USBMINUS ;[29] check phase only if D- changed - lpm ;[30] - in phase, USBIN ;[31] <- phase (one cycle too late) - ori shift, 1 << 3 ;[32] -bit4AfterClr: - mov data, fix ;[33] undo this move by swapping defines -#undef fix -#define fix x1 -#undef data -#define data x2 - ifioset USBIN, USBMINUS ;[34] <--- sample 4 - rjmp bit4IsSet ;[35] - andi shift, ~(7 << 4) ;[36] - breq unstuff4c ;[37] - in phase, USBIN ;[38] <- phase - rjmp bit5AfterClr ;[39] -unstuff4c: - in phase, USBIN ;[39] <- phase (one cycle too late) - andi fix, ~(1 << 4) ;[40] - nop2 ;[33] - nop2 ;[35] -bit4IsSet: - ifrclr phase, USBMINUS ;[37] check phase only if D- changed - lpm ;[38] - in phase, USBIN ;[39] <- phase (one cycle too late) - ori shift, 1 << 4 ;[40] -bit5AfterSet: - ser data ;[41] - ifioclr USBIN, USBMINUS ;[42] <--- sample 5 - rjmp bit5IsClr ;[43] - andi shift, ~(7 << 5) ;[44] - breq unstuff5s ;[45] - in phase, USBIN ;[46] <- phase - rjmp bit6AfterSet ;[47] -unstuff5s: - in phase, USBIN ;[47] <- phase (one cycle too late) - andi fix, ~(1 << 5) ;[48] - nop2 ;[41] - nop2 ;[43] -bit5IsClr: - ifrset phase, USBMINUS ;[45] check phase only if D- changed - lpm ;[46] - in phase, USBIN ;[47] <- phase (one cycle too late) - ori shift, 1 << 5 ;[48] -bit6AfterClr: - subi cnt, 1 ;[49] - brcs overflow ;[50] - ifioset USBIN, USBMINUS ;[51] <--- sample 6 - rjmp bit6IsSet ;[52] - andi shift, ~(3 << 6) ;[53] - cpi shift, 2 ;[54] - in phase, USBIN ;[55] <- phase - brlt unstuff6c ;[56] - rjmp bit7AfterClr ;[57] -unstuff6c: - andi fix, ~(1 << 6) ;[50] - lpm ;[51] -bit6IsSet: - ifrclr phase, USBMINUS ;[54] check phase only if D- changed - lpm ;[55] - in phase, USBIN ;[56] <- phase (one cycle too late) - ori shift, 1 << 6 ;[57] -bit7AfterSet: - ifioclr USBIN, USBMINUS ;[59] <--- sample 7 - rjmp bit7IsClr ;[60] - andi shift, ~(1 << 7) ;[61] - cpi shift, 4 ;[62] - in phase, USBIN ;[63] <- phase - brlt unstuff7s ;[64] - rjmp bit0AfterSet ;[65] -> [00] == [67] -unstuff7s: - andi fix, ~(1 << 7) ;[58] - nop ;[59] - rjmp bit7IsClr ;[60] - -macro POP_STANDARD ; 14 cycles - pop r0 - pop cnt - pop x3 - pop x2 - pop x1 - pop shift - pop YH - endm -macro POP_RETI ; 5 cycles - pop YL - out SREG, YL - pop YL - endm - -#include "asmcommon.inc" - -;---------------------------------------------------------------------------- -; Transmitting data -;---------------------------------------------------------------------------- - -txByteLoop: -txBitloop: -stuffN1Delay: ; [03] - ror shift ;[-5] [11] [63] - brcc doExorN1 ;[-4] [64] - subi x3, 1 ;[-3] - brne commonN1 ;[-2] - lsl shift ;[-1] compensate ror after rjmp stuffDelay - nop ;[00] stuffing consists of just waiting 8 cycles - rjmp stuffN1Delay ;[01] after ror, C bit is reliably clear - -sendNakAndReti: - ldi cnt, USBPID_NAK ;[-19] - rjmp sendCntAndReti ;[-18] -sendAckAndReti: - ldi cnt, USBPID_ACK ;[-17] -sendCntAndReti: - mov r0, cnt ;[-16] - ldi YL, 0 ;[-15] R0 address is 0 - ldi YH, 0 ;[-14] - ldi cnt, 2 ;[-13] -; rjmp usbSendAndReti fallthrough - -; USB spec says: -; idle = J -; J = (D+ = 0), (D- = 1) or USBOUT = 0x01 -; K = (D+ = 1), (D- = 0) or USBOUT = 0x02 -; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles) - -;usbSend: -;pointer to data in 'Y' -;number of bytes in 'cnt' -- including sync byte -;uses: x1...x3, shift, cnt, Y [x1 = mirror USBOUT, x2 = USBMASK, x3 = bitstuff cnt] -;Numbers in brackets are time since first bit of sync pattern is sent (start of instruction) -usbSendAndReti: - in x2, USBDDR ;[-10] 10 cycles until SOP - ori x2, USBMASK ;[-9] - sbi USBOUT, USBMINUS ;[-8] prepare idle state; D+ and D- must have been 0 (no pullups) - out USBDDR, x2 ;[-6] <--- acquire bus - in x1, USBOUT ;[-5] port mirror for tx loop - ldi shift, 0x40 ;[-4] sync byte is first byte sent (we enter loop after ror) - ldi x2, USBMASK ;[-3] -doExorN1: - eor x1, x2 ;[-2] [06] [62] - ldi x3, 6 ;[-1] [07] [63] -commonN1: -stuffN2Delay: - out USBOUT, x1 ;[00] [08] [64] <--- set bit - ror shift ;[01] - brcc doExorN2 ;[02] - subi x3, 1 ;[03] - brne commonN2 ;[04] - lsl shift ;[05] compensate ror after rjmp stuffDelay - rjmp stuffN2Delay ;[06] after ror, C bit is reliably clear -doExorN2: - eor x1, x2 ;[04] [12] - ldi x3, 6 ;[05] [13] -commonN2: - nop2 ;[06] [14] - subi cnt, 171 ;[08] [16] trick: (3 * 171) & 0xff = 1 - out USBOUT, x1 ;[09] [17] <--- set bit - brcs txBitloop ;[10] [27] [44] - -stuff6Delay: - ror shift ;[45] [53] - brcc doExor6 ;[46] - subi x3, 1 ;[47] - brne common6 ;[48] - lsl shift ;[49] compensate ror after rjmp stuffDelay - nop ;[50] stuffing consists of just waiting 8 cycles - rjmp stuff6Delay ;[51] after ror, C bit is reliably clear -doExor6: - eor x1, x2 ;[48] [56] - ldi x3, 6 ;[49] -common6: -stuff7Delay: - ror shift ;[50] [58] - out USBOUT, x1 ;[51] <--- set bit - brcc doExor7 ;[52] - subi x3, 1 ;[53] - brne common7 ;[54] - lsl shift ;[55] compensate ror after rjmp stuffDelay - rjmp stuff7Delay ;[56] after ror, C bit is reliably clear -doExor7: - eor x1, x2 ;[54] [62] - ldi x3, 6 ;[55] -common7: - ld shift, y+ ;[56] - nop ;[58] - tst cnt ;[59] - out USBOUT, x1 ;[60] [00]<--- set bit - brne txByteLoop ;[61] [01] -;make SE0: - cbr x1, USBMASK ;[02] prepare SE0 [spec says EOP may be 15 to 18 cycles] - lds x2, usbNewDeviceAddr;[03] - lsl x2 ;[05] we compare with left shifted address - subi YL, 2 + 0 ;[06] Only assign address on data packets, not ACK/NAK in r0 - sbci YH, 0 ;[07] - out USBOUT, x1 ;[00] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle -;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: -;set address only after data packet was sent, not after handshake - breq skipAddrAssign ;[01] - sts usbDeviceAddr, x2 ; if not skipped: SE0 is one cycle longer -skipAddrAssign: -;end of usbDeviceAddress transfer - ldi x2, 1< 0) - echo "$s\n"; - } -} - -function printBit($isAfterSet, $bitNum) -{ - ob_start(); - if($isAfterSet){ -?> - ifioclr USBIN, USBMINUS ;[00] <--- sample - rjmp bit#IsClr ;[01] - andi shift, ~(7 << #) ;[02] - breq unstuff#s ;[03] - in phase, USBIN ;[04] <- phase - rjmp bit@AfterSet ;[05] -unstuff#s: - in phase, USBIN ;[05] <- phase (one cycle too late) - andi fix, ~(1 << #) ;[06] - nop2 ;[-1] - nop2 ;[01] -bit#IsClr: - ifrset phase, USBMINUS ;[03] check phase only if D- changed - lpm ;[04] - in phase, USBIN ;[05] <- phase (one cycle too late) - ori shift, 1 << # ;[06] - - ifioset USBIN, USBMINUS ;[00] <--- sample - rjmp bit#IsSet ;[01] - andi shift, ~(7 << #) ;[02] - breq unstuff#c ;[03] - in phase, USBIN ;[04] <- phase - rjmp bit@AfterClr ;[05] -unstuff#c: - in phase, USBIN ;[05] <- phase (one cycle too late) - andi fix, ~(1 << #) ;[06] - nop2 ;[-1] - nop2 ;[01] -bit#IsSet: - ifrclr phase, USBMINUS ;[03] check phase only if D- changed - lpm ;[04] - in phase, USBIN ;[05] <- phase (one cycle too late) - ori shift, 1 << # ;[06] - -*****************************************************************************/ diff --git a/src/firmware/c/usbdrv/usbdrvasm15.inc b/src/firmware/c/usbdrv/usbdrvasm15.inc deleted file mode 100644 index 206e27e..0000000 --- a/src/firmware/c/usbdrv/usbdrvasm15.inc +++ /dev/null @@ -1,422 +0,0 @@ -/* Name: usbdrvasm15.inc - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: contributed by V. Bosch - * Creation Date: 2007-08-06 - * Tabsize: 4 - * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -/* Do not link this file! Link usbdrvasm.S instead, which includes the - * appropriate implementation! - */ - -/* -General Description: -This file is the 15 MHz version of the asssembler part of the USB driver. It -requires a 15 MHz crystal (not a ceramic resonator and not a calibrated RC -oscillator). - -See usbdrv.h for a description of the entire driver. - -Since almost all of this code is timing critical, don't change unless you -really know what you are doing! Many parts require not only a maximum number -of CPU cycles, but even an exact number of cycles! -*/ - -;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes -;nominal frequency: 15 MHz -> 10.0 cycles per bit, 80.0 cycles per byte -; Numbers in brackets are clocks counted from center of last sync bit -; when instruction starts - -;---------------------------------------------------------------------------- -; order of registers pushed: -; YL, SREG [sofError] YH, shift, x1, x2, x3, bitcnt, cnt, x4 -;---------------------------------------------------------------------------- -USB_INTR_VECTOR: - push YL ;2 push only what is necessary to sync with edge ASAP - in YL, SREG ;1 - push YL ;2 -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -; -; sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -; sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -;------------------------------------------------------------------------------- -; The following code results in a sampling window of < 1/4 bit -; which meets the spec. -;------------------------------------------------------------------------------- -waitForK: ;- - sbis USBIN, USBMINUS ;1 [00] <-- sample - rjmp foundK ;2 [01] - sbis USBIN, USBMINUS ; <-- sample - rjmp foundK - sbis USBIN, USBMINUS ; <-- sample - rjmp foundK - sbis USBIN, USBMINUS ; <-- sample - rjmp foundK - sbis USBIN, USBMINUS ; <-- sample - rjmp foundK - sbis USBIN, USBMINUS ; <-- sample - rjmp foundK -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError -;------------------------------------------------------------------------------ -; {3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for -; center sampling] -; we have 1 bit time for setup purposes, then sample again. -; Numbers in brackets are cycles from center of first sync (double K) -; bit after the instruction -;------------------------------------------------------------------------------ -foundK: ;- [02] - lds YL, usbInputBufOffset;2 [03+04] tx loop - push YH ;2 [05+06] - clr YH ;1 [07] - subi YL, lo8(-(usbRxBuf)) ;1 [08] [rx loop init] - sbci YH, hi8(-(usbRxBuf)) ;1 [09] [rx loop init] - push shift ;2 [10+11] - ser shift ;1 [12] - sbis USBIN, USBMINUS ;1 [-1] [13] <--sample:we want two bits K (sample 1 cycle too early) - rjmp haveTwoBitsK ;2 [00] [14] - pop shift ;2 [15+16] undo the push from before - pop YH ;2 [17+18] undo the push from before - rjmp waitForK ;2 [19+20] this was not the end of sync, retry -; The entire loop from waitForK until rjmp waitForK above must not exceed two -; bit times (= 20 cycles). - -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- -haveTwoBitsK: ;- [01] - push x1 ;2 [02+03] - push x2 ;2 [04+05] - push x3 ;2 [06+07] - push bitcnt ;2 [08+09] - in x1, USBIN ;1 [00] [10] <-- sample bit 0 - bst x1, USBMINUS ;1 [01] - bld shift, 0 ;1 [02] - push cnt ;2 [03+04] - ldi cnt, USB_BUFSIZE ;1 [05] - push x4 ;2 [06+07] tx loop - rjmp rxLoop ;2 [08] -;---------------------------------------------------------------------------- -; Receiver loop (numbers in brackets are cycles within byte after instr) -;---------------------------------------------------------------------------- -unstuff0: ;- [07] (branch taken) - andi x3, ~0x01 ;1 [08] - mov x1, x2 ;1 [09] x2 contains last sampled (stuffed) bit - in x2, USBIN ;1 [00] [10] <-- sample bit 1 again - andi x2, USBMASK ;1 [01] - breq se0Hop ;1 [02] SE0 check for bit 1 - ori shift, 0x01 ;1 [03] 0b00000001 - nop ;1 [04] - rjmp didUnstuff0 ;2 [05] -;----------------------------------------------------- -unstuff1: ;- [05] (branch taken) - mov x2, x1 ;1 [06] x1 contains last sampled (stuffed) bit - andi x3, ~0x02 ;1 [07] - ori shift, 0x02 ;1 [08] 0b00000010 - nop ;1 [09] - in x1, USBIN ;1 [00] [10] <-- sample bit 2 again - andi x1, USBMASK ;1 [01] - breq se0Hop ;1 [02] SE0 check for bit 2 - rjmp didUnstuff1 ;2 [03] -;----------------------------------------------------- -unstuff2: ;- [05] (branch taken) - andi x3, ~0x04 ;1 [06] - ori shift, 0x04 ;1 [07] 0b00000100 - mov x1, x2 ;1 [08] x2 contains last sampled (stuffed) bit - nop ;1 [09] - in x2, USBIN ;1 [00] [10] <-- sample bit 3 - andi x2, USBMASK ;1 [01] - breq se0Hop ;1 [02] SE0 check for bit 3 - rjmp didUnstuff2 ;2 [03] -;----------------------------------------------------- -unstuff3: ;- [00] [10] (branch taken) - in x2, USBIN ;1 [01] [11] <-- sample stuffed bit 3 one cycle too late - andi x2, USBMASK ;1 [02] - breq se0Hop ;1 [03] SE0 check for stuffed bit 3 - andi x3, ~0x08 ;1 [04] - ori shift, 0x08 ;1 [05] 0b00001000 - rjmp didUnstuff3 ;2 [06] -;---------------------------------------------------------------------------- -; extra jobs done during bit interval: -; -; bit 0: store, clear [SE0 is unreliable here due to bit dribbling in hubs], -; overflow check, jump to the head of rxLoop -; bit 1: SE0 check -; bit 2: SE0 check, recovery from delay [bit 0 tasks took too long] -; bit 3: SE0 check, recovery from delay [bit 0 tasks took too long] -; bit 4: SE0 check, none -; bit 5: SE0 check, none -; bit 6: SE0 check, none -; bit 7: SE0 check, reconstruct: x3 is 0 at bit locations we changed, 1 at others -;---------------------------------------------------------------------------- -rxLoop: ;- [09] - in x2, USBIN ;1 [00] [10] <-- sample bit 1 (or possibly bit 0 stuffed) - andi x2, USBMASK ;1 [01] - brne SkipSe0Hop ;1 [02] -se0Hop: ;- [02] - rjmp se0 ;2 [03] SE0 check for bit 1 -SkipSe0Hop: ;- [03] - ser x3 ;1 [04] - andi shift, 0xf9 ;1 [05] 0b11111001 - breq unstuff0 ;1 [06] -didUnstuff0: ;- [06] - eor x1, x2 ;1 [07] - bst x1, USBMINUS ;1 [08] - bld shift, 1 ;1 [09] - in x1, USBIN ;1 [00] [10] <-- sample bit 2 (or possibly bit 1 stuffed) - andi x1, USBMASK ;1 [01] - breq se0Hop ;1 [02] SE0 check for bit 2 - andi shift, 0xf3 ;1 [03] 0b11110011 - breq unstuff1 ;1 [04] do remaining work for bit 1 -didUnstuff1: ;- [04] - eor x2, x1 ;1 [05] - bst x2, USBMINUS ;1 [06] - bld shift, 2 ;1 [07] - nop2 ;2 [08+09] - in x2, USBIN ;1 [00] [10] <-- sample bit 3 (or possibly bit 2 stuffed) - andi x2, USBMASK ;1 [01] - breq se0Hop ;1 [02] SE0 check for bit 3 - andi shift, 0xe7 ;1 [03] 0b11100111 - breq unstuff2 ;1 [04] -didUnstuff2: ;- [04] - eor x1, x2 ;1 [05] - bst x1, USBMINUS ;1 [06] - bld shift, 3 ;1 [07] -didUnstuff3: ;- [07] - andi shift, 0xcf ;1 [08] 0b11001111 - breq unstuff3 ;1 [09] - in x1, USBIN ;1 [00] [10] <-- sample bit 4 - andi x1, USBMASK ;1 [01] - breq se0Hop ;1 [02] SE0 check for bit 4 - eor x2, x1 ;1 [03] - bst x2, USBMINUS ;1 [04] - bld shift, 4 ;1 [05] -didUnstuff4: ;- [05] - andi shift, 0x9f ;1 [06] 0b10011111 - breq unstuff4 ;1 [07] - nop2 ;2 [08+09] - in x2, USBIN ;1 [00] [10] <-- sample bit 5 - andi x2, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for bit 5 - eor x1, x2 ;1 [03] - bst x1, USBMINUS ;1 [04] - bld shift, 5 ;1 [05] -didUnstuff5: ;- [05] - andi shift, 0x3f ;1 [06] 0b00111111 - breq unstuff5 ;1 [07] - nop2 ;2 [08+09] - in x1, USBIN ;1 [00] [10] <-- sample bit 6 - andi x1, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for bit 6 - eor x2, x1 ;1 [03] - bst x2, USBMINUS ;1 [04] - bld shift, 6 ;1 [05] -didUnstuff6: ;- [05] - cpi shift, 0x02 ;1 [06] 0b00000010 - brlo unstuff6 ;1 [07] - nop2 ;2 [08+09] - in x2, USBIN ;1 [00] [10] <-- sample bit 7 - andi x2, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for bit 7 - eor x1, x2 ;1 [03] - bst x1, USBMINUS ;1 [04] - bld shift, 7 ;1 [05] -didUnstuff7: ;- [05] - cpi shift, 0x04 ;1 [06] 0b00000100 - brlo unstuff7 ;1 [07] - eor x3, shift ;1 [08] reconstruct: x3 is 0 at bit locations we changed, 1 at others - nop ;1 [09] - in x1, USBIN ;1 [00] [10] <-- sample bit 0 - st y+, x3 ;2 [01+02] store data - eor x2, x1 ;1 [03] - bst x2, USBMINUS ;1 [04] - bld shift, 0 ;1 [05] - subi cnt, 1 ;1 [06] - brcs overflow ;1 [07] - rjmp rxLoop ;2 [08] -;----------------------------------------------------- -unstuff4: ;- [08] - andi x3, ~0x10 ;1 [09] - in x1, USBIN ;1 [00] [10] <-- sample stuffed bit 4 - andi x1, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for stuffed bit 4 - ori shift, 0x10 ;1 [03] - rjmp didUnstuff4 ;2 [04] -;----------------------------------------------------- -unstuff5: ;- [08] - ori shift, 0x20 ;1 [09] - in x2, USBIN ;1 [00] [10] <-- sample stuffed bit 5 - andi x2, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for stuffed bit 5 - andi x3, ~0x20 ;1 [03] - rjmp didUnstuff5 ;2 [04] -;----------------------------------------------------- -unstuff6: ;- [08] - andi x3, ~0x40 ;1 [09] - in x1, USBIN ;1 [00] [10] <-- sample stuffed bit 6 - andi x1, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for stuffed bit 6 - ori shift, 0x40 ;1 [03] - rjmp didUnstuff6 ;2 [04] -;----------------------------------------------------- -unstuff7: ;- [08] - andi x3, ~0x80 ;1 [09] - in x2, USBIN ;1 [00] [10] <-- sample stuffed bit 7 - andi x2, USBMASK ;1 [01] - breq se0 ;1 [02] SE0 check for stuffed bit 7 - ori shift, 0x80 ;1 [03] - rjmp didUnstuff7 ;2 [04] - -macro POP_STANDARD ; 16 cycles - pop x4 - pop cnt - pop bitcnt - pop x3 - pop x2 - pop x1 - pop shift - pop YH - endm -macro POP_RETI ; 5 cycles - pop YL - out SREG, YL - pop YL - endm - -#include "asmcommon.inc" - -;--------------------------------------------------------------------------- -; USB spec says: -; idle = J -; J = (D+ = 0), (D- = 1) -; K = (D+ = 1), (D- = 0) -; Spec allows 7.5 bit times from EOP to SOP for replies -;--------------------------------------------------------------------------- -bitstuffN: ;- [04] - eor x1, x4 ;1 [05] - clr x2 ;1 [06] - nop ;1 [07] - rjmp didStuffN ;1 [08] -;--------------------------------------------------------------------------- -bitstuff6: ;- [04] - eor x1, x4 ;1 [05] - clr x2 ;1 [06] - rjmp didStuff6 ;1 [07] -;--------------------------------------------------------------------------- -bitstuff7: ;- [02] - eor x1, x4 ;1 [03] - clr x2 ;1 [06] - nop ;1 [05] - rjmp didStuff7 ;1 [06] -;--------------------------------------------------------------------------- -sendNakAndReti: ;- [-19] - ldi x3, USBPID_NAK ;1 [-18] - rjmp sendX3AndReti ;1 [-17] -;--------------------------------------------------------------------------- -sendAckAndReti: ;- [-17] - ldi cnt, USBPID_ACK ;1 [-16] -sendCntAndReti: ;- [-16] - mov x3, cnt ;1 [-15] -sendX3AndReti: ;- [-15] - ldi YL, 20 ;1 [-14] x3==r20 address is 20 - ldi YH, 0 ;1 [-13] - ldi cnt, 2 ;1 [-12] -; rjmp usbSendAndReti fallthrough -;--------------------------------------------------------------------------- -;usbSend: -;pointer to data in 'Y' -;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] -;uses: x1...x4, btcnt, shift, cnt, Y -;Numbers in brackets are time since first bit of sync pattern is sent -;We need not to match the transfer rate exactly because the spec demands -;only 1.5% precision anyway. -usbSendAndReti: ;- [-13] 13 cycles until SOP - in x2, USBDDR ;1 [-12] - ori x2, USBMASK ;1 [-11] - sbi USBOUT, USBMINUS ;2 [-09-10] prepare idle state; D+ and D- must have been 0 (no pullups) - in x1, USBOUT ;1 [-08] port mirror for tx loop - out USBDDR, x2 ;1 [-07] <- acquire bus - ; need not init x2 (bitstuff history) because sync starts with 0 - ldi x4, USBMASK ;1 [-06] exor mask - ldi shift, 0x80 ;1 [-05] sync byte is first byte sent - ldi bitcnt, 6 ;1 [-04] -txBitLoop: ;- [-04] [06] - sbrs shift, 0 ;1 [-03] [07] - eor x1, x4 ;1 [-02] [08] - ror shift ;1 [-01] [09] -didStuffN: ;- [09] - out USBOUT, x1 ;1 [00] [10] <-- out N - ror x2 ;1 [01] - cpi x2, 0xfc ;1 [02] - brcc bitstuffN ;1 [03] - dec bitcnt ;1 [04] - brne txBitLoop ;1 [05] - sbrs shift, 0 ;1 [06] - eor x1, x4 ;1 [07] - ror shift ;1 [08] -didStuff6: ;- [08] - nop ;1 [09] - out USBOUT, x1 ;1 [00] [10] <-- out 6 - ror x2 ;1 [01] - cpi x2, 0xfc ;1 [02] - brcc bitstuff6 ;1 [03] - sbrs shift, 0 ;1 [04] - eor x1, x4 ;1 [05] - ror shift ;1 [06] - ror x2 ;1 [07] -didStuff7: ;- [07] - ldi bitcnt, 6 ;1 [08] - cpi x2, 0xfc ;1 [09] - out USBOUT, x1 ;1 [00] [10] <-- out 7 - brcc bitstuff7 ;1 [01] - ld shift, y+ ;2 [02+03] - dec cnt ;1 [04] - brne txBitLoop ;1 [05] -makeSE0: - cbr x1, USBMASK ;1 [06] prepare SE0 [spec says EOP may be 19 to 23 cycles] - lds x2, usbNewDeviceAddr;2 [07+08] - lsl x2 ;1 [09] we compare with left shifted address -;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: -;set address only after data packet was sent, not after handshake - out USBOUT, x1 ;1 [00] [10] <-- out SE0-- from now 2 bits==20 cycl. until bus idle - subi YL, 20 + 2 ;1 [01] Only assign address on data packets, not ACK/NAK in x3 - sbci YH, 0 ;1 [02] - breq skipAddrAssign ;1 [03] - sts usbDeviceAddr, x2 ;2 [04+05] if not skipped: SE0 is one cycle longer -;---------------------------------------------------------------------------- -;end of usbDeviceAddress transfer -skipAddrAssign: ;- [03/04] - ldi x2, 1< 10.6666666 cycles per bit, 85.333333333 cycles per byte -; Numbers in brackets are clocks counted from center of last sync bit -; when instruction starts - -USB_INTR_VECTOR: -;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt - push YL ;[-25] push only what is necessary to sync with edge ASAP - in YL, SREG ;[-23] - push YL ;[-22] - push YH ;[-20] -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -;---------------------------------------------------------------------------- -;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -;sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -waitForK: -;The following code results in a sampling window of < 1/4 bit which meets the spec. - sbis USBIN, USBMINUS ;[-15] - rjmp foundK ;[-14] - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError -foundK: ;[-12] -;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling] -;we have 1 bit time for setup purposes, then sample again. Numbers in brackets -;are cycles from center of first sync (double K) bit after the instruction - push bitcnt ;[-12] -; [---] ;[-11] - lds YL, usbInputBufOffset;[-10] -; [---] ;[-9] - clr YH ;[-8] - subi YL, lo8(-(usbRxBuf));[-7] [rx loop init] - sbci YH, hi8(-(usbRxBuf));[-6] [rx loop init] - push shift ;[-5] -; [---] ;[-4] - ldi bitcnt, 0x55 ;[-3] [rx loop init] - sbis USBIN, USBMINUS ;[-2] we want two bits K (sample 2 cycles too early) - rjmp haveTwoBitsK ;[-1] - pop shift ;[0] undo the push from before - pop bitcnt ;[2] undo the push from before - rjmp waitForK ;[4] this was not the end of sync, retry -; The entire loop from waitForK until rjmp waitForK above must not exceed two -; bit times (= 21 cycles). - -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- -haveTwoBitsK: - push x1 ;[1] - push x2 ;[3] - push x3 ;[5] - ldi shift, 0 ;[7] - ldi x3, 1<<4 ;[8] [rx loop init] first sample is inverse bit, compensate that - push x4 ;[9] == leap - - in x1, USBIN ;[11] <-- sample bit 0 - andi x1, USBMASK ;[12] - bst x1, USBMINUS ;[13] - bld shift, 7 ;[14] - push cnt ;[15] - ldi leap, 0 ;[17] [rx loop init] - ldi cnt, USB_BUFSIZE;[18] [rx loop init] - rjmp rxbit1 ;[19] arrives at [21] - -;---------------------------------------------------------------------------- -; Receiver loop (numbers in brackets are cycles within byte after instr) -;---------------------------------------------------------------------------- - -; duration of unstuffing code should be 10.66666667 cycles. We adjust "leap" -; accordingly to approximate this value in the long run. - -unstuff6: - andi x2, USBMASK ;[03] - ori x3, 1<<6 ;[04] will not be shifted any more - andi shift, ~0x80;[05] - mov x1, x2 ;[06] sampled bit 7 is actually re-sampled bit 6 - subi leap, -1 ;[07] total duration = 11 bits -> subtract 1/3 - rjmp didUnstuff6 ;[08] - -unstuff7: - ori x3, 1<<7 ;[09] will not be shifted any more - in x2, USBIN ;[00] [10] re-sample bit 7 - andi x2, USBMASK ;[01] - andi shift, ~0x80;[02] - subi leap, 2 ;[03] total duration = 10 bits -> add 1/3 - rjmp didUnstuff7 ;[04] - -unstuffEven: - ori x3, 1<<6 ;[09] will be shifted right 6 times for bit 0 - in x1, USBIN ;[00] [10] - andi shift, ~0x80;[01] - andi x1, USBMASK ;[02] - breq se0 ;[03] - subi leap, -1 ;[04] total duration = 11 bits -> subtract 1/3 - nop2 ;[05] - rjmp didUnstuffE ;[06] - -unstuffOdd: - ori x3, 1<<5 ;[09] will be shifted right 4 times for bit 1 - in x2, USBIN ;[00] [10] - andi shift, ~0x80;[01] - andi x2, USBMASK ;[02] - breq se0 ;[03] - subi leap, -1 ;[04] total duration = 11 bits -> subtract 1/3 - nop2 ;[05] - rjmp didUnstuffO ;[06] - -rxByteLoop: - andi x1, USBMASK ;[03] - eor x2, x1 ;[04] - subi leap, 1 ;[05] - brpl skipLeap ;[06] - subi leap, -3 ;1 one leap cycle every 3rd byte -> 85 + 1/3 cycles per byte - nop ;1 -skipLeap: - subi x2, 1 ;[08] - ror shift ;[09] -didUnstuff6: - cpi shift, 0xfc ;[10] - in x2, USBIN ;[00] [11] <-- sample bit 7 - brcc unstuff6 ;[01] - andi x2, USBMASK ;[02] - eor x1, x2 ;[03] - subi x1, 1 ;[04] - ror shift ;[05] -didUnstuff7: - cpi shift, 0xfc ;[06] - brcc unstuff7 ;[07] - eor x3, shift ;[08] reconstruct: x3 is 1 at bit locations we changed, 0 at others - st y+, x3 ;[09] store data -rxBitLoop: - in x1, USBIN ;[00] [11] <-- sample bit 0/2/4 - andi x1, USBMASK ;[01] - eor x2, x1 ;[02] - andi x3, 0x3f ;[03] topmost two bits reserved for 6 and 7 - subi x2, 1 ;[04] - ror shift ;[05] - cpi shift, 0xfc ;[06] - brcc unstuffEven ;[07] -didUnstuffE: - lsr x3 ;[08] - lsr x3 ;[09] -rxbit1: - in x2, USBIN ;[00] [10] <-- sample bit 1/3/5 - andi x2, USBMASK ;[01] - breq se0 ;[02] - eor x1, x2 ;[03] - subi x1, 1 ;[04] - ror shift ;[05] - cpi shift, 0xfc ;[06] - brcc unstuffOdd ;[07] -didUnstuffO: - subi bitcnt, 0xab;[08] == addi 0x55, 0x55 = 0x100/3 - brcs rxBitLoop ;[09] - - subi cnt, 1 ;[10] - in x1, USBIN ;[00] [11] <-- sample bit 6 - brcc rxByteLoop ;[01] - rjmp overflow - -macro POP_STANDARD ; 14 cycles - pop cnt - pop x4 - pop x3 - pop x2 - pop x1 - pop shift - pop bitcnt - endm -macro POP_RETI ; 7 cycles - pop YH - pop YL - out SREG, YL - pop YL - endm - -#include "asmcommon.inc" - -; USB spec says: -; idle = J -; J = (D+ = 0), (D- = 1) -; K = (D+ = 1), (D- = 0) -; Spec allows 7.5 bit times from EOP to SOP for replies - -bitstuffN: - eor x1, x4 ;[5] - ldi x2, 0 ;[6] - nop2 ;[7] - nop ;[9] - out USBOUT, x1 ;[10] <-- out - rjmp didStuffN ;[0] - -bitstuff6: - eor x1, x4 ;[5] - ldi x2, 0 ;[6] Carry is zero due to brcc - rol shift ;[7] compensate for ror shift at branch destination - rjmp didStuff6 ;[8] - -bitstuff7: - ldi x2, 0 ;[2] Carry is zero due to brcc - rjmp didStuff7 ;[3] - - -sendNakAndReti: - ldi x3, USBPID_NAK ;[-18] - rjmp sendX3AndReti ;[-17] -sendAckAndReti: - ldi cnt, USBPID_ACK ;[-17] -sendCntAndReti: - mov x3, cnt ;[-16] -sendX3AndReti: - ldi YL, 20 ;[-15] x3==r20 address is 20 - ldi YH, 0 ;[-14] - ldi cnt, 2 ;[-13] -; rjmp usbSendAndReti fallthrough - -;usbSend: -;pointer to data in 'Y' -;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] -;uses: x1...x4, btcnt, shift, cnt, Y -;Numbers in brackets are time since first bit of sync pattern is sent -;We don't match the transfer rate exactly (don't insert leap cycles every third -;byte) because the spec demands only 1.5% precision anyway. -usbSendAndReti: ; 12 cycles until SOP - in x2, USBDDR ;[-12] - ori x2, USBMASK ;[-11] - sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) - in x1, USBOUT ;[-8] port mirror for tx loop - out USBDDR, x2 ;[-7] <- acquire bus -; need not init x2 (bitstuff history) because sync starts with 0 - ldi x4, USBMASK ;[-6] exor mask - ldi shift, 0x80 ;[-5] sync byte is first byte sent -txByteLoop: - ldi bitcnt, 0x35 ;[-4] [6] binary 0011 0101 -txBitLoop: - sbrs shift, 0 ;[-3] [7] - eor x1, x4 ;[-2] [8] - out USBOUT, x1 ;[-1] [9] <-- out N - ror shift ;[0] [10] - ror x2 ;[1] -didStuffN: - cpi x2, 0xfc ;[2] - brcc bitstuffN ;[3] - lsr bitcnt ;[4] - brcc txBitLoop ;[5] - brne txBitLoop ;[6] - - sbrs shift, 0 ;[7] - eor x1, x4 ;[8] -didStuff6: - out USBOUT, x1 ;[-1] [9] <-- out 6 - ror shift ;[0] [10] - ror x2 ;[1] - cpi x2, 0xfc ;[2] - brcc bitstuff6 ;[3] - ror shift ;[4] -didStuff7: - ror x2 ;[5] - sbrs x2, 7 ;[6] - eor x1, x4 ;[7] - nop ;[8] - cpi x2, 0xfc ;[9] - out USBOUT, x1 ;[-1][10] <-- out 7 - brcc bitstuff7 ;[0] [11] - ld shift, y+ ;[1] - dec cnt ;[3] - brne txByteLoop ;[4] -;make SE0: - cbr x1, USBMASK ;[5] prepare SE0 [spec says EOP may be 21 to 25 cycles] - lds x2, usbNewDeviceAddr;[6] - lsl x2 ;[8] we compare with left shifted address - subi YL, 20 + 2 ;[9] Only assign address on data packets, not ACK/NAK in x3 - sbci YH, 0 ;[10] - out USBOUT, x1 ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle -;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: -;set address only after data packet was sent, not after handshake - breq skipAddrAssign ;[0] - sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer -skipAddrAssign: -;end of usbDeviceAddress transfer - ldi x2, 1< max 52 cycles interrupt disable -;max stack usage: [ret(2), r0, SREG, YL, YH, shift, x1, x2, x3, x4, cnt] = 12 bytes -;nominal frequency: 16.5 MHz -> 11 cycles per bit -; 16.3125 MHz < F_CPU < 16.6875 MHz (+/- 1.1%) -; Numbers in brackets are clocks counted from center of last sync bit -; when instruction starts - - -USB_INTR_VECTOR: -;order of registers pushed: YL, SREG [sofError], r0, YH, shift, x1, x2, x3, x4, cnt - push YL ;[-23] push only what is necessary to sync with edge ASAP - in YL, SREG ;[-21] - push YL ;[-20] -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -;---------------------------------------------------------------------------- -;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -;sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -waitForK: -;The following code results in a sampling window of < 1/4 bit which meets the spec. - sbis USBIN, USBMINUS ;[-15] - rjmp foundK ;[-14] - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError -foundK: ;[-12] -;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling] -;we have 1 bit time for setup purposes, then sample again. Numbers in brackets -;are cycles from center of first sync (double K) bit after the instruction - push r0 ;[-12] -; [---] ;[-11] - push YH ;[-10] -; [---] ;[-9] - lds YL, usbInputBufOffset;[-8] -; [---] ;[-7] - clr YH ;[-6] - subi YL, lo8(-(usbRxBuf));[-5] [rx loop init] - sbci YH, hi8(-(usbRxBuf));[-4] [rx loop init] - mov r0, x2 ;[-3] [rx loop init] - sbis USBIN, USBMINUS ;[-2] we want two bits K (sample 2 cycles too early) - rjmp haveTwoBitsK ;[-1] - pop YH ;[0] undo the pushes from before - pop r0 ;[2] - rjmp waitForK ;[4] this was not the end of sync, retry -; The entire loop from waitForK until rjmp waitForK above must not exceed two -; bit times (= 22 cycles). - -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- -haveTwoBitsK: ;[1] - push shift ;[1] - push x1 ;[3] - push x2 ;[5] - push x3 ;[7] - ldi shift, 0xff ;[9] [rx loop init] - ori x3, 0xff ;[10] [rx loop init] == ser x3, clear zero flag - - in x1, USBIN ;[11] <-- sample bit 0 - bst x1, USBMINUS ;[12] - bld shift, 0 ;[13] - push x4 ;[14] == phase -; [---] ;[15] - push cnt ;[16] -; [---] ;[17] - ldi phase, 0 ;[18] [rx loop init] - ldi cnt, USB_BUFSIZE;[19] [rx loop init] - rjmp rxbit1 ;[20] -; [---] ;[21] - -;---------------------------------------------------------------------------- -; Receiver loop (numbers in brackets are cycles within byte after instr) -;---------------------------------------------------------------------------- -/* -byte oriented operations done during loop: -bit 0: store data -bit 1: SE0 check -bit 2: overflow check -bit 3: catch up -bit 4: rjmp to achieve conditional jump range -bit 5: PLL -bit 6: catch up -bit 7: jump, fixup bitstuff -; 87 [+ 2] cycles ------------------------------------------------------------------- -*/ -continueWithBit5: - in x2, USBIN ;[055] <-- bit 5 - eor r0, x2 ;[056] - or phase, r0 ;[057] - sbrc phase, USBMINUS ;[058] - lpm ;[059] optional nop3; modifies r0 - in phase, USBIN ;[060] <-- phase - eor x1, x2 ;[061] - bst x1, USBMINUS ;[062] - bld shift, 5 ;[063] - andi shift, 0x3f ;[064] - in x1, USBIN ;[065] <-- bit 6 - breq unstuff5 ;[066] *** unstuff escape - eor phase, x1 ;[067] - eor x2, x1 ;[068] - bst x2, USBMINUS ;[069] - bld shift, 6 ;[070] -didUnstuff6: ;[ ] - in r0, USBIN ;[071] <-- phase - cpi shift, 0x02 ;[072] - brlo unstuff6 ;[073] *** unstuff escape -didUnstuff5: ;[ ] - nop2 ;[074] -; [---] ;[075] - in x2, USBIN ;[076] <-- bit 7 - eor x1, x2 ;[077] - bst x1, USBMINUS ;[078] - bld shift, 7 ;[079] -didUnstuff7: ;[ ] - eor r0, x2 ;[080] - or phase, r0 ;[081] - in r0, USBIN ;[082] <-- phase - cpi shift, 0x04 ;[083] - brsh rxLoop ;[084] -; [---] ;[085] -unstuff7: ;[ ] - andi x3, ~0x80 ;[085] - ori shift, 0x80 ;[086] - in x2, USBIN ;[087] <-- sample stuffed bit 7 - nop ;[088] - rjmp didUnstuff7 ;[089] -; [---] ;[090] - ;[080] - -unstuff5: ;[067] - eor phase, x1 ;[068] - andi x3, ~0x20 ;[069] - ori shift, 0x20 ;[070] - in r0, USBIN ;[071] <-- phase - mov x2, x1 ;[072] - nop ;[073] - nop2 ;[074] -; [---] ;[075] - in x1, USBIN ;[076] <-- bit 6 - eor r0, x1 ;[077] - or phase, r0 ;[078] - eor x2, x1 ;[079] - bst x2, USBMINUS ;[080] - bld shift, 6 ;[081] no need to check bitstuffing, we just had one - in r0, USBIN ;[082] <-- phase - rjmp didUnstuff5 ;[083] -; [---] ;[084] - ;[074] - -unstuff6: ;[074] - andi x3, ~0x40 ;[075] - in x1, USBIN ;[076] <-- bit 6 again - ori shift, 0x40 ;[077] - nop2 ;[078] -; [---] ;[079] - rjmp didUnstuff6 ;[080] -; [---] ;[081] - ;[071] - -unstuff0: ;[013] - eor r0, x2 ;[014] - or phase, r0 ;[015] - andi x2, USBMASK ;[016] check for SE0 - in r0, USBIN ;[017] <-- phase - breq didUnstuff0 ;[018] direct jump to se0 would be too long - andi x3, ~0x01 ;[019] - ori shift, 0x01 ;[020] - mov x1, x2 ;[021] mov existing sample - in x2, USBIN ;[022] <-- bit 1 again - rjmp didUnstuff0 ;[023] -; [---] ;[024] - ;[014] - -unstuff1: ;[024] - eor r0, x1 ;[025] - or phase, r0 ;[026] - andi x3, ~0x02 ;[027] - in r0, USBIN ;[028] <-- phase - ori shift, 0x02 ;[029] - mov x2, x1 ;[030] - rjmp didUnstuff1 ;[031] -; [---] ;[032] - ;[022] - -unstuff2: ;[035] - eor r0, x2 ;[036] - or phase, r0 ;[037] - andi x3, ~0x04 ;[038] - in r0, USBIN ;[039] <-- phase - ori shift, 0x04 ;[040] - mov x1, x2 ;[041] - rjmp didUnstuff2 ;[042] -; [---] ;[043] - ;[033] - -unstuff3: ;[043] - in x2, USBIN ;[044] <-- bit 3 again - eor r0, x2 ;[045] - or phase, r0 ;[046] - andi x3, ~0x08 ;[047] - ori shift, 0x08 ;[048] - nop ;[049] - in r0, USBIN ;[050] <-- phase - rjmp didUnstuff3 ;[051] -; [---] ;[052] - ;[042] - -unstuff4: ;[053] - andi x3, ~0x10 ;[054] - in x1, USBIN ;[055] <-- bit 4 again - ori shift, 0x10 ;[056] - rjmp didUnstuff4 ;[057] -; [---] ;[058] - ;[048] - -rxLoop: ;[085] - eor x3, shift ;[086] reconstruct: x3 is 0 at bit locations we changed, 1 at others - in x1, USBIN ;[000] <-- bit 0 - st y+, x3 ;[001] -; [---] ;[002] - eor r0, x1 ;[003] - or phase, r0 ;[004] - eor x2, x1 ;[005] - in r0, USBIN ;[006] <-- phase - ser x3 ;[007] - bst x2, USBMINUS ;[008] - bld shift, 0 ;[009] - andi shift, 0xf9 ;[010] -rxbit1: ;[ ] - in x2, USBIN ;[011] <-- bit 1 - breq unstuff0 ;[012] *** unstuff escape - andi x2, USBMASK ;[013] SE0 check for bit 1 -didUnstuff0: ;[ ] Z only set if we detected SE0 in bitstuff - breq se0 ;[014] - eor r0, x2 ;[015] - or phase, r0 ;[016] - in r0, USBIN ;[017] <-- phase - eor x1, x2 ;[018] - bst x1, USBMINUS ;[019] - bld shift, 1 ;[020] - andi shift, 0xf3 ;[021] -didUnstuff1: ;[ ] - in x1, USBIN ;[022] <-- bit 2 - breq unstuff1 ;[023] *** unstuff escape - eor r0, x1 ;[024] - or phase, r0 ;[025] - subi cnt, 1 ;[026] overflow check - brcs overflow ;[027] - in r0, USBIN ;[028] <-- phase - eor x2, x1 ;[029] - bst x2, USBMINUS ;[030] - bld shift, 2 ;[031] - andi shift, 0xe7 ;[032] -didUnstuff2: ;[ ] - in x2, USBIN ;[033] <-- bit 3 - breq unstuff2 ;[034] *** unstuff escape - eor r0, x2 ;[035] - or phase, r0 ;[036] - eor x1, x2 ;[037] - bst x1, USBMINUS ;[038] - in r0, USBIN ;[039] <-- phase - bld shift, 3 ;[040] - andi shift, 0xcf ;[041] -didUnstuff3: ;[ ] - breq unstuff3 ;[042] *** unstuff escape - nop ;[043] - in x1, USBIN ;[044] <-- bit 4 - eor x2, x1 ;[045] - bst x2, USBMINUS ;[046] - bld shift, 4 ;[047] -didUnstuff4: ;[ ] - eor r0, x1 ;[048] - or phase, r0 ;[049] - in r0, USBIN ;[050] <-- phase - andi shift, 0x9f ;[051] - breq unstuff4 ;[052] *** unstuff escape - rjmp continueWithBit5;[053] -; [---] ;[054] - -macro POP_STANDARD ; 16 cycles - pop cnt - pop x4 - pop x3 - pop x2 - pop x1 - pop shift - pop YH - pop r0 - endm -macro POP_RETI ; 5 cycles - pop YL - out SREG, YL - pop YL - endm - -#include "asmcommon.inc" - - -; USB spec says: -; idle = J -; J = (D+ = 0), (D- = 1) -; K = (D+ = 1), (D- = 0) -; Spec allows 7.5 bit times from EOP to SOP for replies - -bitstuff7: - eor x1, x4 ;[4] - ldi x2, 0 ;[5] - nop2 ;[6] C is zero (brcc) - rjmp didStuff7 ;[8] - -bitstuffN: - eor x1, x4 ;[5] - ldi x2, 0 ;[6] - lpm ;[7] 3 cycle NOP, modifies r0 - out USBOUT, x1 ;[10] <-- out - rjmp didStuffN ;[0] - -#define bitStatus x3 - -sendNakAndReti: - ldi cnt, USBPID_NAK ;[-19] - rjmp sendCntAndReti ;[-18] -sendAckAndReti: - ldi cnt, USBPID_ACK ;[-17] -sendCntAndReti: - mov r0, cnt ;[-16] - ldi YL, 0 ;[-15] R0 address is 0 - ldi YH, 0 ;[-14] - ldi cnt, 2 ;[-13] -; rjmp usbSendAndReti fallthrough - -;usbSend: -;pointer to data in 'Y' -;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] -;uses: x1...x4, shift, cnt, Y -;Numbers in brackets are time since first bit of sync pattern is sent -usbSendAndReti: ; 12 cycles until SOP - in x2, USBDDR ;[-12] - ori x2, USBMASK ;[-11] - sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) - in x1, USBOUT ;[-8] port mirror for tx loop - out USBDDR, x2 ;[-7] <- acquire bus -; need not init x2 (bitstuff history) because sync starts with 0 - ldi x4, USBMASK ;[-6] exor mask - ldi shift, 0x80 ;[-5] sync byte is first byte sent - ldi bitStatus, 0xff ;[-4] init bit loop counter, works for up to 12 bytes -byteloop: -bitloop: - sbrs shift, 0 ;[8] [-3] - eor x1, x4 ;[9] [-2] - out USBOUT, x1 ;[10] [-1] <-- out - ror shift ;[0] - ror x2 ;[1] -didStuffN: - cpi x2, 0xfc ;[2] - brcc bitstuffN ;[3] - nop ;[4] - subi bitStatus, 37 ;[5] 256 / 7 ~=~ 37 - brcc bitloop ;[6] when we leave the loop, bitStatus has almost the initial value - sbrs shift, 0 ;[7] - eor x1, x4 ;[8] - ror shift ;[9] -didStuff7: - out USBOUT, x1 ;[10] <-- out - ror x2 ;[0] - cpi x2, 0xfc ;[1] - brcc bitstuff7 ;[2] - ld shift, y+ ;[3] - dec cnt ;[5] - brne byteloop ;[6] -;make SE0: - cbr x1, USBMASK ;[7] prepare SE0 [spec says EOP may be 21 to 25 cycles] - lds x2, usbNewDeviceAddr;[8] - lsl x2 ;[10] we compare with left shifted address - out USBOUT, x1 ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle -;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: -;set address only after data packet was sent, not after handshake - subi YL, 2 ;[0] Only assign address on data packets, not ACK/NAK in r0 - sbci YH, 0 ;[1] - breq skipAddrAssign ;[2] - sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer -skipAddrAssign: -;end of usbDeviceAddress transfer - ldi x2, 1< 12 cycles per bit -; Numbers in brackets are clocks counted from center of last sync bit -; when instruction starts -;register use in receive loop to receive the data bytes: -; shift assembles the byte currently being received -; x1 holds the D+ and D- line state -; x2 holds the previous line state -; cnt holds the number of bytes left in the receive buffer -; x3 holds the higher crc byte (see algorithm below) -; x4 is used as temporary register for the crc algorithm -; x5 is used for unstuffing: when unstuffing the last received bit is inverted in shift (to prevent further -; unstuffing calls. In the same time the corresponding bit in x5 is cleared to mark the bit as beening iverted -; zl lower crc value and crc table index -; zh used for crc table accesses - -;-------------------------------------------------------------------------------------------------------------- -; CRC mods: -; table driven crc checker, Z points to table in prog space -; ZL is the lower crc byte, x3 is the higher crc byte -; x4 is used as temp register to store different results -; the initialization of the crc register is not 0xFFFF but 0xFE54. This is because during the receipt of the -; first data byte an virtual zero data byte is added to the crc register, this results in the correct initial -; value of 0xFFFF at beginning of the second data byte before the first data byte is added to the crc. -; The magic number 0xFE54 results form the crc table: At tabH[0x54] = 0xFF = crcH (required) and -; tabL[0x54] = 0x01 -> crcL = 0x01 xor 0xFE = 0xFF -; bitcnt is renamed to x5 and is used for unstuffing purposes, the unstuffing works like in the 12MHz version -;-------------------------------------------------------------------------------------------------------------- -; CRC algorithm: -; The crc register is formed by x3 (higher byte) and ZL (lower byte). The algorithm uses a 'reversed' form -; i.e. that it takes the least significant bit first and shifts to the right. So in fact the highest order -; bit seen from the polynomial devision point of view is the lsb of ZL. (If this sounds strange to you i -; propose a research on CRC :-) ) -; Each data byte received is xored to ZL, the lower crc byte. This byte now builds the crc -; table index. Next the new high byte is loaded from the table and stored in x4 until we have space in x3 -; (its destination). -; Afterwards the lower table is loaded from the table and stored in ZL (the old index is overwritten as -; we don't need it anymore. In fact this is a right shift by 8 bits.) Now the old crc high value is xored -; to ZL, this is the second shift of the old crc value. Now x4 (the temp reg) is moved to x3 and the crc -; calculation is done. -; Prior to the first byte the two CRC register have to be initialized to 0xFFFF (as defined in usb spec) -; however the crc engine also runs during the receipt of the first byte, therefore x3 and zl are initialized -; to a magic number which results in a crc value of 0xFFFF after the first complete byte. -; -; This algorithm is split into the extra cycles of the different bits: -; bit7: XOR the received byte to ZL -; bit5: load the new high byte to x4 -; bit6: load the lower xor byte from the table, xor zl and x3, store result in zl (=the new crc low value) -; move x4 (the new high byte) to x3, the crc value is ready -; - - -macro POP_STANDARD ; 18 cycles - pop ZH - pop ZL - pop cnt - pop x5 - pop x3 - pop x2 - pop x1 - pop shift - pop x4 - endm -macro POP_RETI ; 7 cycles - pop YH - pop YL - out SREG, YL - pop YL - endm - -macro CRC_CLEANUP_AND_CHECK - ; the last byte has already been xored with the lower crc byte, we have to do the table lookup and xor - ; x3 is the higher crc byte, zl the lower one - ldi ZH, hi8(usbCrcTableHigh);[+1] get the new high byte from the table - lpm x2, Z ;[+2][+3][+4] - ldi ZH, hi8(usbCrcTableLow);[+5] get the new low xor byte from the table - lpm ZL, Z ;[+6][+7][+8] - eor ZL, x3 ;[+7] xor the old high byte with the value from the table, x2:ZL now holds the crc value - cpi ZL, 0x01 ;[+8] if the crc is ok we have a fixed remainder value of 0xb001 in x2:ZL (see usb spec) - brne ignorePacket ;[+9] detected a crc fault -> paket is ignored and retransmitted by the host - cpi x2, 0xb0 ;[+10] - brne ignorePacket ;[+11] detected a crc fault -> paket is ignored and retransmitted by the host - endm - - -USB_INTR_VECTOR: -;order of registers pushed: YL, SREG, YH, [sofError], x4, shift, x1, x2, x3, x5, cnt, ZL, ZH - push YL ;[-28] push only what is necessary to sync with edge ASAP - in YL, SREG ;[-26] - push YL ;[-25] - push YH ;[-23] -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -;---------------------------------------------------------------------------- -;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -;sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -waitForK: -;The following code results in a sampling window of < 1/4 bit which meets the spec. - sbis USBIN, USBMINUS ;[-17] - rjmp foundK ;[-16] - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError -foundK: ;[-15] -;{3, 5} after falling D- edge, average delay: 4 cycles -;bit0 should be at 30 (2.5 bits) for center sampling. Currently at 4 so 26 cylces till bit 0 sample -;use 1 bit time for setup purposes, then sample again. Numbers in brackets -;are cycles from center of first sync (double K) bit after the instruction - push x4 ;[-14] -; [---] ;[-13] - lds YL, usbInputBufOffset;[-12] used to toggle the two usb receive buffers -; [---] ;[-11] - clr YH ;[-10] - subi YL, lo8(-(usbRxBuf));[-9] [rx loop init] - sbci YH, hi8(-(usbRxBuf));[-8] [rx loop init] - push shift ;[-7] -; [---] ;[-6] - ldi shift, 0x80 ;[-5] the last bit is the end of byte marker for the pid receiver loop - clc ;[-4] the carry has to be clear for receipt of pid bit 0 - sbis USBIN, USBMINUS ;[-3] we want two bits K (sample 3 cycles too early) - rjmp haveTwoBitsK ;[-2] - pop shift ;[-1] undo the push from before - pop x4 ;[1] - rjmp waitForK ;[3] this was not the end of sync, retry -; The entire loop from waitForK until rjmp waitForK above must not exceed two -; bit times (= 24 cycles). - -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- -haveTwoBitsK: - push x1 ;[0] - push x2 ;[2] - push x3 ;[4] crc high byte - ldi x2, 1< jump back and store the byte - ori shift, 0x01 ;[11] invert the last received bit to prevent furhter unstuffing - in x2, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors - andi x5, 0xFE ;[1] mark this bit as inverted (will be corrected before storing shift) - eor x1, x2 ;[2] x1 and x2 have to be different because the stuff bit is always a zero - andi x1, USBMASK ;[3] mask the interesting bits - breq stuffErr ;[4] if the stuff bit is a 1-bit something went wrong - mov x1, x2 ;[5] the next bit expects the last state to be in x1 - rjmp didunstuff0 ;[6] - ;[7] jump delay of rjmp didunstuffX - -unstuff1: ;[11] this is the jump delay of breq unstuffX - in x1, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors - ori shift, 0x02 ;[1] invert the last received bit to prevent furhter unstuffing - andi x5, 0xFD ;[2] mark this bit as inverted (will be corrected before storing shift) - eor x2, x1 ;[3] x1 and x2 have to be different because the stuff bit is always a zero - andi x2, USBMASK ;[4] mask the interesting bits - breq stuffErr ;[5] if the stuff bit is a 1-bit something went wrong - mov x2, x1 ;[6] the next bit expects the last state to be in x2 - nop2 ;[7] - ;[8] - rjmp didunstuff1 ;[9] - ;[10] jump delay of rjmp didunstuffX - -unstuff2: ;[9] this is the jump delay of breq unstuffX - ori shift, 0x04 ;[10] invert the last received bit to prevent furhter unstuffing - andi x5, 0xFB ;[11] mark this bit as inverted (will be corrected before storing shift) - in x2, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors - eor x1, x2 ;[1] x1 and x2 have to be different because the stuff bit is always a zero - andi x1, USBMASK ;[2] mask the interesting bits - breq stuffErr ;[3] if the stuff bit is a 1-bit something went wrong - mov x1, x2 ;[4] the next bit expects the last state to be in x1 - nop2 ;[5] - ;[6] - rjmp didunstuff2 ;[7] - ;[8] jump delay of rjmp didunstuffX - -unstuff3: ;[9] this is the jump delay of breq unstuffX - ori shift, 0x08 ;[10] invert the last received bit to prevent furhter unstuffing - andi x5, 0xF7 ;[11] mark this bit as inverted (will be corrected before storing shift) - in x1, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors - eor x2, x1 ;[1] x1 and x2 have to be different because the stuff bit is always a zero - andi x2, USBMASK ;[2] mask the interesting bits - breq stuffErr ;[3] if the stuff bit is a 1-bit something went wrong - mov x2, x1 ;[4] the next bit expects the last state to be in x2 - nop2 ;[5] - ;[6] - rjmp didunstuff3 ;[7] - ;[8] jump delay of rjmp didunstuffX - - - -; the include has to be here due to branch distance restirctions -#define __USE_CRC__ -#include "asmcommon.inc" - - - -; USB spec says: -; idle = J -; J = (D+ = 0), (D- = 1) -; K = (D+ = 1), (D- = 0) -; Spec allows 7.5 bit times from EOP to SOP for replies -; 7.5 bit times is 90 cycles. ...there is plenty of time - - -sendNakAndReti: - ldi x3, USBPID_NAK ;[-18] - rjmp sendX3AndReti ;[-17] -sendAckAndReti: - ldi cnt, USBPID_ACK ;[-17] -sendCntAndReti: - mov x3, cnt ;[-16] -sendX3AndReti: - ldi YL, 20 ;[-15] x3==r20 address is 20 - ldi YH, 0 ;[-14] - ldi cnt, 2 ;[-13] -; rjmp usbSendAndReti fallthrough - -;usbSend: -;pointer to data in 'Y' -;number of bytes in 'cnt' -- including sync byte [range 2 ... 12] -;uses: x1...x4, btcnt, shift, cnt, Y -;Numbers in brackets are time since first bit of sync pattern is sent - -usbSendAndReti: ; 12 cycles until SOP - in x2, USBDDR ;[-12] - ori x2, USBMASK ;[-11] - sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups) - in x1, USBOUT ;[-8] port mirror for tx loop - out USBDDR, x2 ;[-6] <- acquire bus - ldi x2, 0 ;[-6] init x2 (bitstuff history) because sync starts with 0 - ldi x4, USBMASK ;[-5] exor mask - ldi shift, 0x80 ;[-4] sync byte is first byte sent -txByteLoop: - ldi bitcnt, 0x40 ;[-3]=[9] binary 01000000 -txBitLoop: ; the loop sends the first 7 bits of the byte - sbrs shift, 0 ;[-2]=[10] if we have to send a 1 don't change the line state - eor x1, x4 ;[-1]=[11] - out USBOUT, x1 ;[0] - ror shift ;[1] - ror x2 ;[2] transfers the last sent bit to the stuffing history -didStuffN: - nop ;[3] - nop ;[4] - cpi x2, 0xfc ;[5] if we sent six consecutive ones - brcc bitstuffN ;[6] - lsr bitcnt ;[7] - brne txBitLoop ;[8] restart the loop while the 1 is still in the bitcount - -; transmit bit 7 - sbrs shift, 0 ;[9] - eor x1, x4 ;[10] -didStuff7: - ror shift ;[11] - out USBOUT, x1 ;[0] transfer bit 7 to the pins - ror x2 ;[1] move the bit into the stuffing history - cpi x2, 0xfc ;[2] - brcc bitstuff7 ;[3] - ld shift, y+ ;[4] get next byte to transmit - dec cnt ;[5] decrement byte counter - brne txByteLoop ;[7] if we have more bytes start next one - ;[8] branch delay - -;make SE0: - cbr x1, USBMASK ;[8] prepare SE0 [spec says EOP may be 25 to 30 cycles] - lds x2, usbNewDeviceAddr;[9] - lsl x2 ;[11] we compare with left shifted address - out USBOUT, x1 ;[0] <-- out SE0 -- from now 2 bits = 24 cycles until bus idle - subi YL, 20 + 2 ;[1] Only assign address on data packets, not ACK/NAK in x3 - sbci YH, 0 ;[2] -;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm: -;set address only after data packet was sent, not after handshake - breq skipAddrAssign ;[3] - sts usbDeviceAddr, x2 ; if not skipped: SE0 is one cycle longer -skipAddrAssign: -;end of usbDeviceAddress transfer - ldi x2, 1< -int main (int argc, char **argv) -{ - int i, j; - for (i=0; i<512; i++){ - unsigned short crc = i & 0xff; - for(j=0; j<8; j++) crc = (crc >> 1) ^ ((crc & 1) ? 0xa001 : 0); - if((i & 7) == 0) printf("\n.byte "); - printf("0x%02x, ", (i > 0xff ? (crc >> 8) : crc) & 0xff); - if(i == 255) printf("\n"); - } - return 0; -} - -// Use the following algorithm to compute CRC values: -ushort computeCrc(uchar *msg, uchar msgLen) -{ - uchar i; - ushort crc = 0xffff; - for(i = 0; i < msgLen; i++) - crc = usbCrcTable16[lo8(crc) ^ msg[i]] ^ hi8(crc); - return crc; -} -*/ - -.balign 256 -usbCrcTableLow: -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41 -.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 - -; .balign 256 -usbCrcTableHigh: -.byte 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2 -.byte 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04 -.byte 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E -.byte 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8 -.byte 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A -.byte 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC -.byte 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6 -.byte 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10 -.byte 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32 -.byte 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4 -.byte 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE -.byte 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38 -.byte 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA -.byte 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C -.byte 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26 -.byte 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0 -.byte 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62 -.byte 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4 -.byte 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE -.byte 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68 -.byte 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA -.byte 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C -.byte 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76 -.byte 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0 -.byte 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92 -.byte 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54 -.byte 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E -.byte 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98 -.byte 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A -.byte 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C -.byte 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86 -.byte 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 - diff --git a/src/firmware/c/usbdrv/usbdrvasm20.inc b/src/firmware/c/usbdrv/usbdrvasm20.inc deleted file mode 100644 index 21fc87c..0000000 --- a/src/firmware/c/usbdrv/usbdrvasm20.inc +++ /dev/null @@ -1,359 +0,0 @@ -/* Name: usbdrvasm20.inc - * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers - * Author: Jeroen Benschop - * Based on usbdrvasm16.inc from Christian Starkjohann - * Creation Date: 2008-03-05 - * Tabsize: 4 - * Copyright: (c) 2008 by Jeroen Benschop and OBJECTIVE DEVELOPMENT Software GmbH - * License: GNU GPL v2 (see LICENSE.md), GNU GPL v3 or proprietary (CommercialLICENSE.md) - */ - -/* Do not link this file! Link usbdrvasm.S instead, which includes the - * appropriate implementation! - */ - -/* -General Description: -This file is the 20 MHz version of the asssembler part of the USB driver. It -requires a 20 MHz crystal (not a ceramic resonator and not a calibrated RC -oscillator). - -See usbdrv.h for a description of the entire driver. - -Since almost all of this code is timing critical, don't change unless you -really know what you are doing! Many parts require not only a maximum number -of CPU cycles, but even an exact number of cycles! -*/ - -#define leap2 x3 -#ifdef __IAR_SYSTEMS_ASM__ -#define nextInst $+2 -#else -#define nextInst .+0 -#endif - -;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes -;nominal frequency: 20 MHz -> 13.333333 cycles per bit, 106.666667 cycles per byte -; Numbers in brackets are clocks counted from center of last sync bit -; when instruction starts -;register use in receive loop: -; shift assembles the byte currently being received -; x1 holds the D+ and D- line state -; x2 holds the previous line state -; x4 (leap) is used to add a leap cycle once every three bytes received -; X3 (leap2) is used to add a leap cycle once every three stuff bits received -; bitcnt is used to determine when a stuff bit is due -; cnt holds the number of bytes left in the receive buffer - -USB_INTR_VECTOR: -;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt - push YL ;[-28] push only what is necessary to sync with edge ASAP - in YL, SREG ;[-26] - push YL ;[-25] - push YH ;[-23] -;---------------------------------------------------------------------------- -; Synchronize with sync pattern: -;---------------------------------------------------------------------------- -;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K] -;sync up with J to K edge during sync pattern -- use fastest possible loops -;The first part waits at most 1 bit long since we must be in sync pattern. -;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to -;waitForJ, ensure that this prerequisite is met. -waitForJ: - inc YL - sbis USBIN, USBMINUS - brne waitForJ ; just make sure we have ANY timeout -waitForK: -;The following code results in a sampling window of < 1/4 bit which meets the spec. - sbis USBIN, USBMINUS ;[-19] - rjmp foundK ;[-18] - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK - sbis USBIN, USBMINUS - rjmp foundK -#if USB_COUNT_SOF - lds YL, usbSofCount - inc YL - sts usbSofCount, YL -#endif /* USB_COUNT_SOF */ -#ifdef USB_SOF_HOOK - USB_SOF_HOOK -#endif - rjmp sofError -foundK: ;[-16] -;{3, 5} after falling D- edge, average delay: 4 cycles -;bit0 should be at 34 for center sampling. Currently at 4 so 30 cylces till bit 0 sample -;use 1 bit time for setup purposes, then sample again. Numbers in brackets -;are cycles from center of first sync (double K) bit after the instruction - push bitcnt ;[-16] -; [---] ;[-15] - lds YL, usbInputBufOffset;[-14] -; [---] ;[-13] - clr YH ;[-12] - subi YL, lo8(-(usbRxBuf));[-11] [rx loop init] - sbci YH, hi8(-(usbRxBuf));[-10] [rx loop init] - push shift ;[-9] -; [---] ;[-8] - ldi shift,0x40 ;[-7] set msb to "1" so processing bit7 can be detected - nop2 ;[-6] -; [---] ;[-5] - ldi bitcnt, 5 ;[-4] [rx loop init] - sbis USBIN, USBMINUS ;[-3] we want two bits K (sample 3 cycles too early) - rjmp haveTwoBitsK ;[-2] - pop shift ;[-1] undo the push from before - pop bitcnt ;[1] - rjmp waitForK ;[3] this was not the end of sync, retry -; The entire loop from waitForK until rjmp waitForK above must not exceed two -; bit times (= 27 cycles). - -;---------------------------------------------------------------------------- -; push more registers and initialize values while we sample the first bits: -;---------------------------------------------------------------------------- -haveTwoBitsK: - push x1 ;[0] - push x2 ;[2] - push x3 ;[4] (leap2) - ldi leap2, 0x55 ;[6] add leap cycle on 2nd,5th,8th,... stuff bit - push x4 ;[7] == leap - ldi leap, 0x55 ;[9] skip leap cycle on 2nd,5th,8th,... byte received - push cnt ;[10] - ldi cnt, USB_BUFSIZE ;[12] [rx loop init] - ldi x2, 1< -#ifndef __IAR_SYSTEMS_ASM__ -# include -#endif - -#define __attribute__(arg) /* not supported on IAR */ - -#ifdef __IAR_SYSTEMS_ASM__ -# define __ASSEMBLER__ /* IAR does not define standard macro for asm */ -#endif - -#ifdef __HAS_ELPM__ -# define PROGMEM __farflash -#else -# define PROGMEM __flash -#endif - -#define USB_READ_FLASH(addr) (*(PROGMEM char *)(addr)) - -/* The following definitions are not needed by the driver, but may be of some - * help if you port a gcc based project to IAR. - */ -#define cli() __disable_interrupt() -#define sei() __enable_interrupt() -#define wdt_reset() __watchdog_reset() -#define _BV(x) (1 << (x)) - -/* assembler compatibility macros */ -#define nop2 rjmp $+2 /* jump to next instruction */ -#define XL r26 -#define XH r27 -#define YL r28 -#define YH r29 -#define ZL r30 -#define ZH r31 -#define lo8(x) LOW(x) -#define hi8(x) (((x)>>8) & 0xff) /* not HIGH to allow XLINK to make a proper range check */ - -/* Depending on the device you use, you may get problems with the way usbdrv.h - * handles the differences between devices. Since IAR does not use #defines - * for MCU registers, we can't check for the existence of a particular - * register with an #ifdef. If the autodetection mechanism fails, include - * definitions for the required USB_INTR_* macros in your usbconfig.h. See - * usbconfig-prototype.h and usbdrv.h for details. - */ - -/* ------------------------------------------------------------------------- */ -#elif __CODEVISIONAVR__ /* check for CodeVision AVR */ -/* ------------------------------------------------------------------------- */ -/* This port is not working (yet) */ - -/* #define F_CPU _MCU_CLOCK_FREQUENCY_ seems to be defined automatically */ - -#include -#include - -#define __attribute__(arg) /* not supported on IAR */ - -#define PROGMEM __flash -#define USB_READ_FLASH(addr) (*(PROGMEM char *)(addr)) - -#ifndef __ASSEMBLER__ -static inline void cli(void) -{ - #asm("cli"); -} -static inline void sei(void) -{ - #asm("sei"); -} -#endif -#define _delay_ms(t) delay_ms(t) -#define _BV(x) (1 << (x)) -#define USB_CFG_USE_SWITCH_STATEMENT 1 /* macro for if() cascase fails for unknown reason */ - -#define macro .macro -#define endm .endmacro -#define nop2 rjmp .+0 /* jump to next instruction */ - -/* ------------------------------------------------------------------------- */ -#else /* default development environment is avr-gcc/avr-libc */ -/* ------------------------------------------------------------------------- */ - -#include -#ifdef __ASSEMBLER__ -# define _VECTOR(N) __vector_ ## N /* io.h does not define this for asm */ -#else -# include -#endif - -#if USB_CFG_DRIVER_FLASH_PAGE -# define USB_READ_FLASH(addr) pgm_read_byte_far(((long)USB_CFG_DRIVER_FLASH_PAGE << 16) | (long)(addr)) -#else -# define USB_READ_FLASH(addr) pgm_read_byte(addr) -#endif - -#define macro .macro -#define endm .endm -#define nop2 rjmp .+0 /* jump to next instruction */ - -#endif /* development environment */ - -/* for conveniecne, ensure that PRG_RDB exists */ -#ifndef PRG_RDB -# define PRG_RDB(addr) USB_READ_FLASH(addr) -#endif -#endif /* __usbportability_h_INCLUDED__ */ diff --git a/src/main/assembly/README.txt b/src/main/assembly/README.txt deleted file mode 100644 index 8b581fc..0000000 --- a/src/main/assembly/README.txt +++ /dev/null @@ -1,17 +0,0 @@ -${project.artifactId} ${project.version} -${project.url} -Copyright 2013 Klaus Reimer -See LICENSE.md for licensing information. ------------------------------------------------------------------------------- - -The lib directory contains the following JAR files: - -usb4java-*.jar (The full JAR with native libraries included) -usb4java-*-nonatives.jar (The same without the native libraries) -usb4java-*-natives.jar (Only the native libraries) - -commons-lang3-*.jar (Apache Commons Lang library needed by usb4java) -usb-*.jar (javax.usb library needed by usb4java) - -usb4java-*-sources.jar (The source code of usb4jaba) -usb4java-*-javadoc.jar (The JavaDoc of usb4java) diff --git a/src/main/assembly/tarball.xml b/src/main/assembly/tarball.xml deleted file mode 100644 index 459db04..0000000 --- a/src/main/assembly/tarball.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - tarball - - tar.bz2 - - - - - / - - LICENSE.md - - 0644 - unix - - - src/main/assembly - / - - README.txt - - 0644 - unix - true - - - - - lib - false - runtime - true - - - diff --git a/src/main/assembly/zip.xml b/src/main/assembly/zip.xml deleted file mode 100644 index 44dcb49..0000000 --- a/src/main/assembly/zip.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - zip - - zip - - - - - / - - LICENSE.md - - 0644 - dos - - - src/main/assembly - / - - README.txt - - 0644 - dos - true - - - - - lib - false - runtime - true - - *:tar.bz2 - - - - diff --git a/src/main/c/.gitignore b/src/main/c/.gitignore deleted file mode 100644 index 7cf4d5f..0000000 --- a/src/main/c/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -downloads -*.o -*.lo -*.la -*.tar.gz -autom4te.cache -Makefile -config.h -config.h.in~ -config.log -config.status -libtool -stamp-h1 -.deps -.libs -Makefile.in -aclocal.m4 -config.guess -config.h.in -config.sub -configure -depcomp -install-sh -ltmain.sh -m4 -missing -ar-lib -compile -.cproject diff --git a/src/main/c/AUTHORS b/src/main/c/AUTHORS deleted file mode 100644 index 9d14783..0000000 --- a/src/main/c/AUTHORS +++ /dev/null @@ -1,2 +0,0 @@ -Klaus Reimer -Luca Longinotti diff --git a/src/main/c/COPYING b/src/main/c/COPYING deleted file mode 100644 index 4362b49..0000000 --- a/src/main/c/COPYING +++ /dev/null @@ -1,502 +0,0 @@ - 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! diff --git a/src/main/c/ChangeLog b/src/main/c/ChangeLog deleted file mode 100644 index e69de29..0000000 diff --git a/src/main/c/Makefile.am b/src/main/c/Makefile.am deleted file mode 100644 index 87d3040..0000000 --- a/src/main/c/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -ACLOCAL_AMFLAGS=-I m4 -SUBDIRS = src diff --git a/src/main/c/NEWS b/src/main/c/NEWS deleted file mode 100644 index 4a39bdf..0000000 --- a/src/main/c/NEWS +++ /dev/null @@ -1 +0,0 @@ -Nothing new right now. \ No newline at end of file diff --git a/src/main/c/README b/src/main/c/README deleted file mode 100644 index b8e539f..0000000 --- a/src/main/c/README +++ /dev/null @@ -1,29 +0,0 @@ -This is the source code of the JNI wrapper for libusb. usb4java -already includes pre-compiled libraries for the following platforms: - -* linux-x86 -* linux-x86_64 -* linux-arm -* windows-x86 -* windows-x86_64 -* osx-x86 -* osx-x86_64 - -If you need the library on an other platform then you can easily compile it -yourself. On a Unix-compatible operating system you only need the Java JDK, -the libusb(x) library version 1.0.16 or higher and the GNU C compiler. -When everything is correctly installed then you should be able to build the -library with the following commands: - - $ ./configure - $ make - -When compilation was successful then you can find the library in the -`src/.libs` directory. Rename the file so it doesn't include any version -number (Examples: libusb4java.so, libusb4java.dylib, libusb4java.dll). - -usb4java searches for the library in the CLASSPATH directory -`org/libusb4java/-/`. On a 32 bit x86 linux machine for -example the directory name is `org/libusb4java/linux-x86`. Usually -you can find the required name in the exception thrown by usb4java when it -does not find the required library. diff --git a/src/main/c/acinclude.m4 b/src/main/c/acinclude.m4 deleted file mode 100644 index 80d4974..0000000 --- a/src/main/c/acinclude.m4 +++ /dev/null @@ -1,11 +0,0 @@ -AC_DEFUN([AC_CHECK_JAVA],[ - AC_ARG_WITH( - java-home, - [ --with-java-home=DIR Set Java home directory ], - [ - JAVA_HOME=`echo $withval` - ] - ) - CPPFLAGS="$CPPFLAGS -I$JAVA_HOME/include -I$JAVA_HOME/include/linux -I$JAVA_HOME/include/win32 -I$JAVA_HOME/include/darwin" - AC_CHECK_HEADERS(jni.h,,echo "ERROR: jni.h not found. JAVA_HOME is $JAVA_HOME. Use --with-java-home option to specify an other Java home directory."; exit 1;) -]) diff --git a/src/main/c/autogen.sh b/src/main/c/autogen.sh deleted file mode 100755 index bd40802..0000000 --- a/src/main/c/autogen.sh +++ /dev/null @@ -1,1578 +0,0 @@ -#!/bin/sh -# a u t o g e n . s h -# -# Copyright (c) 2005-2009 United States Government as represented by -# the U.S. Army Research Laboratory. -# -# 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. -# -# 3. The name of the author may not be used to endorse or promote -# products derived from this software without specific prior written -# permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. -# -### -# -# Script for automatically preparing the sources for compilation by -# performing the myriad of necessary steps. The script attempts to -# detect proper version support, and outputs warnings about particular -# systems that have autotool peculiarities. -# -# Basically, if everything is set up and installed correctly, the -# script will validate that minimum versions of the GNU Build System -# tools are installed, account for several common configuration -# issues, and then simply run autoreconf for you. -# -# If autoreconf fails, which can happen for many valid configurations, -# this script proceeds to run manual preparation steps effectively -# providing a POSIX shell script (mostly complete) reimplementation of -# autoreconf. -# -# The AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER -# environment variables and corresponding _OPTIONS variables (e.g. -# AUTORECONF_OPTIONS) may be used to override the default automatic -# detection behaviors. Similarly the _VERSION variables will override -# the minimum required version numbers. -# -# Examples: -# -# To obtain help on usage: -# ./autogen.sh --help -# -# To obtain verbose output: -# ./autogen.sh --verbose -# -# To skip autoreconf and prepare manually: -# AUTORECONF=false ./autogen.sh -# -# To verbosely try running with an older (unsupported) autoconf: -# AUTOCONF_VERSION=2.50 ./autogen.sh --verbose -# -# Author: -# Christopher Sean Morrison -# -# Patches: -# Sebastian Pipping -# -###################################################################### - -# set to minimum acceptable version of autoconf -if [ "x$AUTOCONF_VERSION" = "x" ] ; then - AUTOCONF_VERSION=2.52 -fi -# set to minimum acceptable version of automake -if [ "x$AUTOMAKE_VERSION" = "x" ] ; then - AUTOMAKE_VERSION=1.6.0 -fi -# set to minimum acceptable version of libtool -if [ "x$LIBTOOL_VERSION" = "x" ] ; then - LIBTOOL_VERSION=1.4.2 -fi - - -################## -# ident function # -################## -ident ( ) { - # extract copyright from header - __copyright="`grep Copyright $AUTOGEN_SH | head -${HEAD_N}1 | awk '{print $4}'`" - if [ "x$__copyright" = "x" ] ; then - __copyright="`date +%Y`" - fi - - # extract version from CVS Id string - __id="$Id: autogen.sh 33925 2009-03-01 23:27:06Z brlcad $" - __version="`echo $__id | sed 's/.*\([0-9][0-9][0-9][0-9]\)[-\/]\([0-9][0-9]\)[-\/]\([0-9][0-9]\).*/\1\2\3/'`" - if [ "x$__version" = "x" ] ; then - __version="" - fi - - echo "autogen.sh build preparation script by Christopher Sean Morrison" - echo " + config.guess download patch by Sebastian Pipping (2008-12-03)" - echo "revised 3-clause BSD-style license, copyright (c) $__copyright" - echo "script version $__version, ISO/IEC 9945 POSIX shell script" -} - - -################## -# USAGE FUNCTION # -################## -usage ( ) { - echo "Usage: $AUTOGEN_SH [-h|--help] [-v|--verbose] [-q|--quiet] [-d|--download] [--version]" - echo " --help Help on $NAME_OF_AUTOGEN usage" - echo " --verbose Verbose progress output" - echo " --quiet Quiet suppressed progress output" - echo " --download Download the latest config.guess from gnulib" - echo " --version Only perform GNU Build System version checks" - echo - echo "Description: This script will validate that minimum versions of the" - echo "GNU Build System tools are installed and then run autoreconf for you." - echo "Should autoreconf fail, manual preparation steps will be run" - echo "potentially accounting for several common preparation issues. The" - - echo "AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER," - echo "PROJECT, & CONFIGURE environment variables and corresponding _OPTIONS" - echo "variables (e.g. AUTORECONF_OPTIONS) may be used to override the" - echo "default automatic detection behavior." - echo - - ident - - return 0 -} - - -########################## -# VERSION_ERROR FUNCTION # -########################## -version_error ( ) { - if [ "x$1" = "x" ] ; then - echo "INTERNAL ERROR: version_error was not provided a version" - exit 1 - fi - if [ "x$2" = "x" ] ; then - echo "INTERNAL ERROR: version_error was not provided an application name" - exit 1 - fi - $ECHO - $ECHO "ERROR: To prepare the ${PROJECT} build system from scratch," - $ECHO " at least version $1 of $2 must be installed." - $ECHO - $ECHO "$NAME_OF_AUTOGEN does not need to be run on the same machine that will" - $ECHO "run configure or make. Either the GNU Autotools will need to be installed" - $ECHO "or upgraded on this system, or $NAME_OF_AUTOGEN must be run on the source" - $ECHO "code on another system and then transferred to here. -- Cheers!" - $ECHO -} - -########################## -# VERSION_CHECK FUNCTION # -########################## -version_check ( ) { - if [ "x$1" = "x" ] ; then - echo "INTERNAL ERROR: version_check was not provided a minimum version" - exit 1 - fi - _min="$1" - if [ "x$2" = "x" ] ; then - echo "INTERNAL ERROR: version check was not provided a comparison version" - exit 1 - fi - _cur="$2" - - # needed to handle versions like 1.10 and 1.4-p6 - _min="`echo ${_min}. | sed 's/[^0-9]/./g' | sed 's/\.\././g'`" - _cur="`echo ${_cur}. | sed 's/[^0-9]/./g' | sed 's/\.\././g'`" - - _min_major="`echo $_min | cut -d. -f1`" - _min_minor="`echo $_min | cut -d. -f2`" - _min_patch="`echo $_min | cut -d. -f3`" - - _cur_major="`echo $_cur | cut -d. -f1`" - _cur_minor="`echo $_cur | cut -d. -f2`" - _cur_patch="`echo $_cur | cut -d. -f3`" - - if [ "x$_min_major" = "x" ] ; then - _min_major=0 - fi - if [ "x$_min_minor" = "x" ] ; then - _min_minor=0 - fi - if [ "x$_min_patch" = "x" ] ; then - _min_patch=0 - fi - if [ "x$_cur_minor" = "x" ] ; then - _cur_major=0 - fi - if [ "x$_cur_minor" = "x" ] ; then - _cur_minor=0 - fi - if [ "x$_cur_patch" = "x" ] ; then - _cur_patch=0 - fi - - $VERBOSE_ECHO "Checking if ${_cur_major}.${_cur_minor}.${_cur_patch} is greater than ${_min_major}.${_min_minor}.${_min_patch}" - - if [ $_min_major -lt $_cur_major ] ; then - return 0 - elif [ $_min_major -eq $_cur_major ] ; then - if [ $_min_minor -lt $_cur_minor ] ; then - return 0 - elif [ $_min_minor -eq $_cur_minor ] ; then - if [ $_min_patch -lt $_cur_patch ] ; then - return 0 - elif [ $_min_patch -eq $_cur_patch ] ; then - return 0 - fi - fi - fi - return 1 -} - - -###################################### -# LOCATE_CONFIGURE_TEMPLATE FUNCTION # -###################################### -locate_configure_template ( ) { - _pwd="`pwd`" - if test -f "./configure.ac" ; then - echo "./configure.ac" - elif test -f "./configure.in" ; then - echo "./configure.in" - elif test -f "$_pwd/configure.ac" ; then - echo "$_pwd/configure.ac" - elif test -f "$_pwd/configure.in" ; then - echo "$_pwd/configure.in" - elif test -f "$PATH_TO_AUTOGEN/configure.ac" ; then - echo "$PATH_TO_AUTOGEN/configure.ac" - elif test -f "$PATH_TO_AUTOGEN/configure.in" ; then - echo "$PATH_TO_AUTOGEN/configure.in" - fi -} - - -################## -# argument check # -################## -ARGS="$*" -PATH_TO_AUTOGEN="`dirname $0`" -NAME_OF_AUTOGEN="`basename $0`" -AUTOGEN_SH="$PATH_TO_AUTOGEN/$NAME_OF_AUTOGEN" - -LIBTOOL_M4="${PATH_TO_AUTOGEN}/misc/libtool.m4" - -if [ "x$HELP" = "x" ] ; then - HELP=no -fi -if [ "x$QUIET" = "x" ] ; then - QUIET=no -fi -if [ "x$VERBOSE" = "x" ] ; then - VERBOSE=no -fi -if [ "x$VERSION_ONLY" = "x" ] ; then - VERSION_ONLY=no -fi -if [ "x$DOWNLOAD" = "x" ] ; then - DOWNLOAD=no -fi -if [ "x$AUTORECONF_OPTIONS" = "x" ] ; then - AUTORECONF_OPTIONS="-i -f" -fi -if [ "x$AUTOCONF_OPTIONS" = "x" ] ; then - AUTOCONF_OPTIONS="-f" -fi -if [ "x$AUTOMAKE_OPTIONS" = "x" ] ; then - AUTOMAKE_OPTIONS="-a -c -f" -fi -ALT_AUTOMAKE_OPTIONS="-a -c" -if [ "x$LIBTOOLIZE_OPTIONS" = "x" ] ; then - LIBTOOLIZE_OPTIONS="--automake -c -f" -fi -ALT_LIBTOOLIZE_OPTIONS="--automake --copy --force" -if [ "x$ACLOCAL_OPTIONS" = "x" ] ; then - ACLOCAL_OPTIONS="" -fi -if [ "x$AUTOHEADER_OPTIONS" = "x" ] ; then - AUTOHEADER_OPTIONS="" -fi -if [ "x$CONFIG_GUESS_URL" = "x" ] ; then - CONFIG_GUESS_URL="http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain;f=build-aux/config.guess;hb=HEAD" -fi -for arg in $ARGS ; do - case "x$arg" in - x--help) HELP=yes ;; - x-[hH]) HELP=yes ;; - x--quiet) QUIET=yes ;; - x-[qQ]) QUIET=yes ;; - x--verbose) VERBOSE=yes ;; - x-[dD]) DOWNLOAD=yes ;; - x--download) DOWNLOAD=yes ;; - x-[vV]) VERBOSE=yes ;; - x--version) VERSION_ONLY=yes ;; - *) - echo "Unknown option: $arg" - echo - usage - exit 1 - ;; - esac -done - - -##################### -# environment check # -##################### - -# sanity check before recursions potentially begin -if [ ! -f "$AUTOGEN_SH" ] ; then - echo "INTERNAL ERROR: $AUTOGEN_SH does not exist" - if [ ! "x$0" = "x$AUTOGEN_SH" ] ; then - echo "INTERNAL ERROR: dirname/basename inconsistency: $0 != $AUTOGEN_SH" - fi - exit 1 -fi - -# force locale setting to C so things like date output as expected -LC_ALL=C - -# commands that this script expects -for __cmd in echo head tail pwd ; do - echo "test" | $__cmd > /dev/null 2>&1 - if [ $? != 0 ] ; then - echo "INTERNAL ERROR: '${__cmd}' command is required" - exit 2 - fi -done -echo "test" | grep "test" > /dev/null 2>&1 -if test ! x$? = x0 ; then - echo "INTERNAL ERROR: grep command is required" - exit 1 -fi -echo "test" | sed "s/test/test/" > /dev/null 2>&1 -if test ! x$? = x0 ; then - echo "INTERNAL ERROR: sed command is required" - exit 1 -fi - - -# determine the behavior of echo -case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in - *c*,-n*) ECHO_N= ECHO_C=' -' ECHO_T=' ' ;; - *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; - *) ECHO_N= ECHO_C='\c' ECHO_T= ;; -esac - -# determine the behavior of head -case "x`echo 'head' | head -n 1 2>&1`" in - *xhead*) HEAD_N="n " ;; - *) HEAD_N="" ;; -esac - -# determine the behavior of tail -case "x`echo 'tail' | tail -n 1 2>&1`" in - *xtail*) TAIL_N="n " ;; - *) TAIL_N="" ;; -esac - -VERBOSE_ECHO=: -ECHO=: -if [ "x$QUIET" = "xyes" ] ; then - if [ "x$VERBOSE" = "xyes" ] ; then - echo "Verbose output quelled by quiet option. Further output disabled." - fi -else - ECHO=echo - if [ "x$VERBOSE" = "xyes" ] ; then - echo "Verbose output enabled" - VERBOSE_ECHO=echo - fi -fi - - -# allow a recursive run to disable further recursions -if [ "x$RUN_RECURSIVE" = "x" ] ; then - RUN_RECURSIVE=yes -fi - - -################################################ -# check for help arg and bypass version checks # -################################################ -if [ "x`echo $ARGS | sed 's/.*[hH][eE][lL][pP].*/help/'`" = "xhelp" ] ; then - HELP=yes -fi -if [ "x$HELP" = "xyes" ] ; then - usage - $ECHO "---" - $ECHO "Help was requested. No preparation or configuration will be performed." - exit 0 -fi - - -####################### -# set up signal traps # -####################### -untrap_abnormal ( ) { - for sig in 1 2 13 15; do - trap - $sig - done -} - -# do this cleanup whenever we exit. -trap ' - # start from the root - if test -d "$START_PATH" ; then - cd "$START_PATH" - fi - - # restore/delete backup files - if test "x$PFC_INIT" = "x1" ; then - recursive_restore - fi -' 0 - -# trap SIGHUP (1), SIGINT (2), SIGPIPE (13), SIGTERM (15) -for sig in 1 2 13 15; do - trap ' - $ECHO "" - $ECHO "Aborting $NAME_OF_AUTOGEN: caught signal '$sig'" - - # start from the root - if test -d "$START_PATH" ; then - cd "$START_PATH" - fi - - # clean up on abnormal exit - $VERBOSE_ECHO "rm -rf autom4te.cache" - rm -rf autom4te.cache - - if test -f "acinclude.m4.$$.backup" ; then - $VERBOSE_ECHO "cat acinclude.m4.$$.backup > acinclude.m4" - chmod u+w acinclude.m4 - cat acinclude.m4.$$.backup > acinclude.m4 - - $VERBOSE_ECHO "rm -f acinclude.m4.$$.backup" - rm -f acinclude.m4.$$.backup - fi - - { (exit 1); exit 1; } -' $sig -done - - -############################# -# look for a configure file # -############################# -if [ "x$CONFIGURE" = "x" ] ; then - CONFIGURE="`locate_configure_template`" - if [ ! "x$CONFIGURE" = "x" ] ; then - $VERBOSE_ECHO "Found a configure template: $CONFIGURE" - fi -else - $ECHO "Using CONFIGURE environment variable override: $CONFIGURE" -fi -if [ "x$CONFIGURE" = "x" ] ; then - if [ "x$VERSION_ONLY" = "xyes" ] ; then - CONFIGURE=/dev/null - else - $ECHO - $ECHO "A configure.ac or configure.in file could not be located implying" - $ECHO "that the GNU Build System is at least not used in this directory. In" - $ECHO "any case, there is nothing to do here without one of those files." - $ECHO - $ECHO "ERROR: No configure.in or configure.ac file found in `pwd`" - exit 1 - fi -fi - -#################### -# get project name # -#################### -if [ "x$PROJECT" = "x" ] ; then - PROJECT="`grep AC_INIT $CONFIGURE | grep -v '.*#.*AC_INIT' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_INIT(\([^,)]*\).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - if [ "x$PROJECT" = "xAC_INIT" ] ; then - # projects might be using the older/deprecated arg-less AC_INIT .. look for AM_INIT_AUTOMAKE instead - PROJECT="`grep AM_INIT_AUTOMAKE $CONFIGURE | grep -v '.*#.*AM_INIT_AUTOMAKE' | tail -${TAIL_N}1 | sed 's/^[ ]*AM_INIT_AUTOMAKE(\([^,)]*\).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - fi - if [ "x$PROJECT" = "xAM_INIT_AUTOMAKE" ] ; then - PROJECT="project" - fi - if [ "x$PROJECT" = "x" ] ; then - PROJECT="project" - fi -else - $ECHO "Using PROJECT environment variable override: $PROJECT" -fi -$ECHO "Preparing the $PROJECT build system...please wait" -$ECHO - - -######################## -# check for autoreconf # -######################## -HAVE_AUTORECONF=no -if [ "x$AUTORECONF" = "x" ] ; then - for AUTORECONF in autoreconf ; do - $VERBOSE_ECHO "Checking autoreconf version: $AUTORECONF --version" - $AUTORECONF --version > /dev/null 2>&1 - if [ $? = 0 ] ; then - HAVE_AUTORECONF=yes - break - fi - done -else - HAVE_AUTORECONF=yes - $ECHO "Using AUTORECONF environment variable override: $AUTORECONF" -fi - - -########################## -# autoconf version check # -########################## -_acfound=no -if [ "x$AUTOCONF" = "x" ] ; then - for AUTOCONF in autoconf ; do - $VERBOSE_ECHO "Checking autoconf version: $AUTOCONF --version" - $AUTOCONF --version > /dev/null 2>&1 - if [ $? = 0 ] ; then - _acfound=yes - break - fi - done -else - _acfound=yes - $ECHO "Using AUTOCONF environment variable override: $AUTOCONF" -fi - -_report_error=no -if [ ! "x$_acfound" = "xyes" ] ; then - $ECHO "ERROR: Unable to locate GNU Autoconf." - _report_error=yes -else - _version="`$AUTOCONF --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`" - if [ "x$_version" = "x" ] ; then - _version="0.0.0" - fi - $ECHO "Found GNU Autoconf version $_version" - version_check "$AUTOCONF_VERSION" "$_version" - if [ $? -ne 0 ] ; then - _report_error=yes - fi -fi -if [ "x$_report_error" = "xyes" ] ; then - version_error "$AUTOCONF_VERSION" "GNU Autoconf" - exit 1 -fi - - -########################## -# automake version check # -########################## -_amfound=no -if [ "x$AUTOMAKE" = "x" ] ; then - for AUTOMAKE in automake ; do - $VERBOSE_ECHO "Checking automake version: $AUTOMAKE --version" - $AUTOMAKE --version > /dev/null 2>&1 - if [ $? = 0 ] ; then - _amfound=yes - break - fi - done -else - _amfound=yes - $ECHO "Using AUTOMAKE environment variable override: $AUTOMAKE" -fi - - -_report_error=no -if [ ! "x$_amfound" = "xyes" ] ; then - $ECHO - $ECHO "ERROR: Unable to locate GNU Automake." - _report_error=yes -else - _version="`$AUTOMAKE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`" - if [ "x$_version" = "x" ] ; then - _version="0.0.0" - fi - $ECHO "Found GNU Automake version $_version" - version_check "$AUTOMAKE_VERSION" "$_version" - if [ $? -ne 0 ] ; then - _report_error=yes - fi -fi -if [ "x$_report_error" = "xyes" ] ; then - version_error "$AUTOMAKE_VERSION" "GNU Automake" - exit 1 -fi - - -######################## -# check for libtoolize # -######################## -HAVE_LIBTOOLIZE=yes -HAVE_ALT_LIBTOOLIZE=no -_ltfound=no -if [ "x$LIBTOOLIZE" = "x" ] ; then - LIBTOOLIZE=libtoolize - $VERBOSE_ECHO "Checking libtoolize version: $LIBTOOLIZE --version" - $LIBTOOLIZE --version > /dev/null 2>&1 - if [ ! $? = 0 ] ; then - HAVE_LIBTOOLIZE=no - $ECHO - if [ "x$HAVE_AUTORECONF" = "xno" ] ; then - $ECHO "Warning: libtoolize does not appear to be available." - else - $ECHO "Warning: libtoolize does not appear to be available. This means that" - $ECHO "the automatic build preparation via autoreconf will probably not work." - $ECHO "Preparing the build by running each step individually, however, should" - $ECHO "work and will be done automatically for you if autoreconf fails." - fi - - # look for some alternates - for tool in glibtoolize libtoolize15 libtoolize14 libtoolize13 ; do - $VERBOSE_ECHO "Checking libtoolize alternate: $tool --version" - _glibtoolize="`$tool --version > /dev/null 2>&1`" - if [ $? = 0 ] ; then - $VERBOSE_ECHO "Found $tool --version" - _glti="`which $tool`" - if [ "x$_glti" = "x" ] ; then - $VERBOSE_ECHO "Cannot find $tool with which" - continue; - fi - if test ! -f "$_glti" ; then - $VERBOSE_ECHO "Cannot use $tool, $_glti is not a file" - continue; - fi - _gltidir="`dirname $_glti`" - if [ "x$_gltidir" = "x" ] ; then - $VERBOSE_ECHO "Cannot find $tool path with dirname of $_glti" - continue; - fi - if test ! -d "$_gltidir" ; then - $VERBOSE_ECHO "Cannot use $tool, $_gltidir is not a directory" - continue; - fi - HAVE_ALT_LIBTOOLIZE=yes - LIBTOOLIZE="$tool" - $ECHO - $ECHO "Fortunately, $tool was found which means that your system may simply" - $ECHO "have a non-standard or incomplete GNU Autotools install. If you have" - $ECHO "sufficient system access, it may be possible to quell this warning by" - $ECHO "running:" - $ECHO - sudo -V > /dev/null 2>&1 - if [ $? = 0 ] ; then - $ECHO " sudo ln -s $_glti $_gltidir/libtoolize" - $ECHO - else - $ECHO " ln -s $_glti $_gltidir/libtoolize" - $ECHO - $ECHO "Run that as root or with proper permissions to the $_gltidir directory" - $ECHO - fi - _ltfound=yes - break - fi - done - else - _ltfound=yes - fi -else - _ltfound=yes - $ECHO "Using LIBTOOLIZE environment variable override: $LIBTOOLIZE" -fi - - -############################ -# libtoolize version check # -############################ -_report_error=no -if [ ! "x$_ltfound" = "xyes" ] ; then - $ECHO - $ECHO "ERROR: Unable to locate GNU Libtool." - _report_error=yes -else - _version="`$LIBTOOLIZE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`" - if [ "x$_version" = "x" ] ; then - _version="0.0.0" - fi - $ECHO "Found GNU Libtool version $_version" - version_check "$LIBTOOL_VERSION" "$_version" - if [ $? -ne 0 ] ; then - _report_error=yes - fi -fi -if [ "x$_report_error" = "xyes" ] ; then - version_error "$LIBTOOL_VERSION" "GNU Libtool" - exit 1 -fi - - -##################### -# check for aclocal # -##################### -if [ "x$ACLOCAL" = "x" ] ; then - for ACLOCAL in aclocal ; do - $VERBOSE_ECHO "Checking aclocal version: $ACLOCAL --version" - $ACLOCAL --version > /dev/null 2>&1 - if [ $? = 0 ] ; then - break - fi - done -else - $ECHO "Using ACLOCAL environment variable override: $ACLOCAL" -fi - - -######################## -# check for autoheader # -######################## -if [ "x$AUTOHEADER" = "x" ] ; then - for AUTOHEADER in autoheader ; do - $VERBOSE_ECHO "Checking autoheader version: $AUTOHEADER --version" - $AUTOHEADER --version > /dev/null 2>&1 - if [ $? = 0 ] ; then - break - fi - done -else - $ECHO "Using AUTOHEADER environment variable override: $AUTOHEADER" -fi - - -######################### -# check if version only # -######################### -$VERBOSE_ECHO "Checking whether to only output version information" -if [ "x$VERSION_ONLY" = "xyes" ] ; then - $ECHO - ident - $ECHO "---" - $ECHO "Version requested. No preparation or configuration will be performed." - exit 0 -fi - - -################################# -# PROTECT_FROM_CLOBBER FUNCTION # -################################# -protect_from_clobber ( ) { - PFC_INIT=1 - - # protect COPYING & INSTALL from overwrite by automake. the - # automake force option will (inappropriately) ignore the existing - # contents of a COPYING and/or INSTALL files (depending on the - # version) instead of just forcing *missing* files like it does - # for AUTHORS, NEWS, and README. this is broken but extremely - # prevalent behavior, so we protect against it by keeping a backup - # of the file that can later be restored. - - for file in COPYING INSTALL ; do - if test -f ${file} ; then - if test -f ${file}.$$.protect_from_automake.backup ; then - $VERBOSE_ECHO "Already backed up ${file} in `pwd`" - else - $VERBOSE_ECHO "Backing up ${file} in `pwd`" - $VERBOSE_ECHO "cp -p ${file} ${file}.$$.protect_from_automake.backup" - cp -p ${file} ${file}.$$.protect_from_automake.backup - fi - fi - done -} - - -############################## -# RECURSIVE_PROTECT FUNCTION # -############################## -recursive_protect ( ) { - - # for projects using recursive configure, run the build - # preparation steps for the subdirectories. this function assumes - # START_PATH was set to pwd before recursion begins so that - # relative paths work. - - # git 'r done, protect COPYING and INSTALL from being clobbered - protect_from_clobber - - if test -d autom4te.cache ; then - $VERBOSE_ECHO "Found an autom4te.cache directory, deleting it" - $VERBOSE_ECHO "rm -rf autom4te.cache" - rm -rf autom4te.cache - fi - - # find configure template - _configure="`locate_configure_template`" - if [ "x$_configure" = "x" ] ; then - return - fi - # $VERBOSE_ECHO "Looking for configure template found `pwd`/$_configure" - - # look for subdirs - # $VERBOSE_ECHO "Looking for subdirs in `pwd`" - _det_config_subdirs="`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - CHECK_DIRS="" - for dir in $_det_config_subdirs ; do - if test -d "`pwd`/$dir" ; then - CHECK_DIRS="$CHECK_DIRS \"`pwd`/$dir\"" - fi - done - - # process subdirs - if [ ! "x$CHECK_DIRS" = "x" ] ; then - $VERBOSE_ECHO "Recursively scanning the following directories:" - $VERBOSE_ECHO " $CHECK_DIRS" - for dir in $CHECK_DIRS ; do - $VERBOSE_ECHO "Protecting files from automake in $dir" - cd "$START_PATH" - eval "cd $dir" - - # recursively git 'r done - recursive_protect - done - fi -} # end of recursive_protect - - -############################# -# RESTORE_CLOBBERED FUNCION # -############################# -restore_clobbered ( ) { - - # The automake (and autoreconf by extension) -f/--force-missing - # option may overwrite COPYING and INSTALL even if they do exist. - # Here we restore the files if necessary. - - spacer=no - - for file in COPYING INSTALL ; do - if test -f ${file}.$$.protect_from_automake.backup ; then - if test -f ${file} ; then - # compare entire content, restore if needed - if test "x`cat ${file}`" != "x`cat ${file}.$$.protect_from_automake.backup`" ; then - if test "x$spacer" = "xno" ; then - $VERBOSE_ECHO - spacer=yes - fi - # restore the backup - $VERBOSE_ECHO "Restoring ${file} from backup (automake -f likely clobbered it)" - $VERBOSE_ECHO "rm -f ${file}" - rm -f ${file} - $VERBOSE_ECHO "mv ${file}.$$.protect_from_automake.backup ${file}" - mv ${file}.$$.protect_from_automake.backup ${file} - fi # check contents - elif test -f ${file}.$$.protect_from_automake.backup ; then - $VERBOSE_ECHO "mv ${file}.$$.protect_from_automake.backup ${file}" - mv ${file}.$$.protect_from_automake.backup ${file} - fi # -f ${file} - - # just in case - $VERBOSE_ECHO "rm -f ${file}.$$.protect_from_automake.backup" - rm -f ${file}.$$.protect_from_automake.backup - fi # -f ${file}.$$.protect_from_automake.backup - done - - CONFIGURE="`locate_configure_template`" - if [ "x$CONFIGURE" = "x" ] ; then - return - fi - - _aux_dir="`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_CONFIG_AUX_DIR(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - if test ! -d "$_aux_dir" ; then - _aux_dir=. - fi - - for file in config.guess config.sub ltmain.sh ; do - if test -f "${_aux_dir}/${file}" ; then - $VERBOSE_ECHO "rm -f \"${_aux_dir}/${file}.backup\"" - rm -f "${_aux_dir}/${file}.backup" - fi - done -} # end of restore_clobbered - - -############################## -# RECURSIVE_RESTORE FUNCTION # -############################## -recursive_restore ( ) { - - # restore COPYING and INSTALL from backup if they were clobbered - # for each directory recursively. - - # git 'r undone - restore_clobbered - - # find configure template - _configure="`locate_configure_template`" - if [ "x$_configure" = "x" ] ; then - return - fi - - # look for subdirs - _det_config_subdirs="`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - CHECK_DIRS="" - for dir in $_det_config_subdirs ; do - if test -d "`pwd`/$dir" ; then - CHECK_DIRS="$CHECK_DIRS \"`pwd`/$dir\"" - fi - done - - # process subdirs - if [ ! "x$CHECK_DIRS" = "x" ] ; then - $VERBOSE_ECHO "Recursively scanning the following directories:" - $VERBOSE_ECHO " $CHECK_DIRS" - for dir in $CHECK_DIRS ; do - $VERBOSE_ECHO "Checking files for automake damage in $dir" - cd "$START_PATH" - eval "cd $dir" - - # recursively git 'r undone - recursive_restore - done - fi -} # end of recursive_restore - - -####################### -# INITIALIZE FUNCTION # -####################### -initialize ( ) { - - # this routine performs a variety of directory-specific - # initializations. some are sanity checks, some are preventive, - # and some are necessary setup detection. - # - # this function sets: - # CONFIGURE - # SEARCH_DIRS - # CONFIG_SUBDIRS - - ################################## - # check for a configure template # - ################################## - CONFIGURE="`locate_configure_template`" - if [ "x$CONFIGURE" = "x" ] ; then - $ECHO - $ECHO "A configure.ac or configure.in file could not be located implying" - $ECHO "that the GNU Build System is at least not used in this directory. In" - $ECHO "any case, there is nothing to do here without one of those files." - $ECHO - $ECHO "ERROR: No configure.in or configure.ac file found in `pwd`" - exit 1 - fi - - ##################### - # detect an aux dir # - ##################### - _aux_dir="`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_CONFIG_AUX_DIR(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - if test ! -d "$_aux_dir" ; then - _aux_dir=. - else - $VERBOSE_ECHO "Detected auxillary directory: $_aux_dir" - fi - - ################################ - # detect a recursive configure # - ################################ - CONFIG_SUBDIRS="" - _det_config_subdirs="`grep AC_CONFIG_SUBDIRS $CONFIGURE | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`" - for dir in $_det_config_subdirs ; do - if test -d "`pwd`/$dir" ; then - $VERBOSE_ECHO "Detected recursive configure directory: `pwd`/$dir" - CONFIG_SUBDIRS="$CONFIG_SUBDIRS `pwd`/$dir" - fi - done - - ########################################################### - # make sure certain required files exist for GNU projects # - ########################################################### - _marker_found="" - _marker_found_message_intro='Detected non-GNU marker "' - _marker_found_message_mid='" in ' - for marker in foreign cygnus ; do - _marker_found_message=${_marker_found_message_intro}${marker}${_marker_found_message_mid} - _marker_found="`grep 'AM_INIT_AUTOMAKE.*'${marker} $CONFIGURE`" - if [ ! "x$_marker_found" = "x" ] ; then - $VERBOSE_ECHO "${_marker_found_message}`basename \"$CONFIGURE\"`" - break - fi - if test -f "`dirname \"$CONFIGURE\"/Makefile.am`" ; then - _marker_found="`grep 'AUTOMAKE_OPTIONS.*'${marker} Makefile.am`" - if [ ! "x$_marker_found" = "x" ] ; then - $VERBOSE_ECHO "${_marker_found_message}Makefile.am" - break - fi - fi - done - if [ "x${_marker_found}" = "x" ] ; then - _suggest_foreign=no - for file in AUTHORS COPYING ChangeLog INSTALL NEWS README ; do - if [ ! -f $file ] ; then - $VERBOSE_ECHO "Touching ${file} since it does not exist" - _suggest_foreign=yes - touch $file - fi - done - - if [ "x${_suggest_foreign}" = "xyes" ] ; then - $ECHO - $ECHO "Warning: Several files expected of projects that conform to the GNU" - $ECHO "coding standards were not found. The files were automatically added" - $ECHO "for you since you do not have a 'foreign' declaration specified." - $ECHO - $ECHO "Considered adding 'foreign' to AM_INIT_AUTOMAKE in `basename \"$CONFIGURE\"`" - if test -f "`dirname \"$CONFIGURE\"/Makefile.am`" ; then - $ECHO "or to AUTOMAKE_OPTIONS in your top-level Makefile.am file." - fi - $ECHO - fi - fi - - ################################################## - # make sure certain generated files do not exist # - ################################################## - for file in config.guess config.sub ltmain.sh ; do - if test -f "${_aux_dir}/${file}" ; then - $VERBOSE_ECHO "mv -f \"${_aux_dir}/${file}\" \"${_aux_dir}/${file}.backup\"" - mv -f "${_aux_dir}/${file}" "${_aux_dir}/${file}.backup" - fi - done - - ############################ - # search alternate m4 dirs # - ############################ - SEARCH_DIRS="" - for dir in m4 ; do - if [ -d $dir ] ; then - $VERBOSE_ECHO "Found extra aclocal search directory: $dir" - SEARCH_DIRS="$SEARCH_DIRS -I $dir" - fi - done - - ###################################### - # remove any previous build products # - ###################################### - if test -d autom4te.cache ; then - $VERBOSE_ECHO "Found an autom4te.cache directory, deleting it" - $VERBOSE_ECHO "rm -rf autom4te.cache" - rm -rf autom4te.cache - fi -# tcl/tk (and probably others) have a customized aclocal.m4, so can't delete it -# if test -f aclocal.m4 ; then -# $VERBOSE_ECHO "Found an aclocal.m4 file, deleting it" -# $VERBOSE_ECHO "rm -f aclocal.m4" -# rm -f aclocal.m4 -# fi - -} # end of initialize() - - -############## -# initialize # -############## - -# stash path -START_PATH="`pwd`" - -# Before running autoreconf or manual steps, some prep detection work -# is necessary or useful. Only needs to occur once per directory, but -# does need to traverse the entire subconfigure hierarchy to protect -# files from being clobbered even by autoreconf. -recursive_protect - -# start from where we started -cd "$START_PATH" - -# get ready to process -initialize - - -######################################### -# DOWNLOAD_GNULIB_CONFIG_GUESS FUNCTION # -######################################### - -# TODO - should make sure wget/curl exist and/or work before trying to -# use them. - -download_gnulib_config_guess () { - # abuse gitweb to download gnulib's latest config.guess via HTTP - config_guess_temp="config.guess.$$.download" - ret=1 - for __cmd in wget curl fetch ; do - $VERBOSE_ECHO "Checking for command ${__cmd}" - ${__cmd} --version > /dev/null 2>&1 - ret=$? - if [ ! $ret = 0 ] ; then - continue - fi - - __cmd_version=`${__cmd} --version | head -n 1 | sed -e 's/^[^0-9]\+//' -e 's/ .*//'` - $VERBOSE_ECHO "Found ${__cmd} ${__cmd_version}" - - opts="" - case ${__cmd} in - wget) - opts="-O" - ;; - curl) - opts="-o" - ;; - fetch) - opts="-t 5 -f" - ;; - esac - - $VERBOSE_ECHO "Running $__cmd \"${CONFIG_GUESS_URL}\" $opts \"${config_guess_temp}\"" - eval "$__cmd \"${CONFIG_GUESS_URL}\" $opts \"${config_guess_temp}\"" > /dev/null 2>&1 - if [ $? = 0 ] ; then - mv -f "${config_guess_temp}" ${_aux_dir}/config.guess - ret=0 - break - fi - done - - if [ ! $ret = 0 ] ; then - $ECHO "Warning: config.guess download failed from: $CONFIG_GUESS_URL" - rm -f "${config_guess_temp}" - fi -} - - -############################## -# LIBTOOLIZE_NEEDED FUNCTION # -############################## -libtoolize_needed () { - ret=1 # means no, don't need libtoolize - for feature in AC_PROG_LIBTOOL AM_PROG_LIBTOOL LT_INIT ; do - $VERBOSE_ECHO "Searching for $feature in $CONFIGURE" - found="`grep \"^$feature.*\" $CONFIGURE`" - if [ ! "x$found" = "x" ] ; then - ret=0 # means yes, need to run libtoolize - break - fi - done - return ${ret} -} - - - -############################################ -# prepare build via autoreconf or manually # -############################################ -reconfigure_manually=no -if [ "x$HAVE_AUTORECONF" = "xyes" ] ; then - $ECHO - $ECHO $ECHO_N "Automatically preparing build ... $ECHO_C" - - $VERBOSE_ECHO "$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS" - autoreconf_output="`$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS 2>&1`" - ret=$? - $VERBOSE_ECHO "$autoreconf_output" - - if [ ! $ret = 0 ] ; then - if [ "x$HAVE_ALT_LIBTOOLIZE" = "xyes" ] ; then - if [ ! "x`echo \"$autoreconf_output\" | grep libtoolize | grep \"No such file or directory\"`" = "x" ] ; then - $ECHO - $ECHO "Warning: autoreconf failed but due to what is usually a common libtool" - $ECHO "misconfiguration issue. This problem is encountered on systems that" - $ECHO "have installed libtoolize under a different name without providing a" - $ECHO "symbolic link or without setting the LIBTOOLIZE environment variable." - $ECHO - $ECHO "Restarting the preparation steps with LIBTOOLIZE set to $LIBTOOLIZE" - - export LIBTOOLIZE - RUN_RECURSIVE=no - export RUN_RECURSIVE - untrap_abnormal - - $VERBOSE_ECHO sh $AUTOGEN_SH "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" - sh "$AUTOGEN_SH" "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" - exit $? - fi - fi - - $ECHO "Warning: $AUTORECONF failed" - - if test -f ltmain.sh ; then - $ECHO "libtoolize being run by autoreconf is not creating ltmain.sh in the auxillary directory like it should" - fi - - $ECHO "Attempting to run the preparation steps individually" - reconfigure_manually=yes - else - if [ "x$DOWNLOAD" = "xyes" ] ; then - if libtoolize_needed ; then - download_gnulib_config_guess - fi - fi - fi -else - reconfigure_manually=yes -fi - - -############################ -# LIBTOOL_FAILURE FUNCTION # -############################ -libtool_failure ( ) { - - # libtool is rather error-prone in comparison to the other - # autotools and this routine attempts to compensate for some - # common failures. the output after a libtoolize failure is - # parsed for an error related to AC_PROG_LIBTOOL and if found, we - # attempt to inject a project-provided libtool.m4 file. - - _autoconf_output="$1" - - if [ "x$RUN_RECURSIVE" = "xno" ] ; then - # we already tried the libtool.m4, don't try again - return 1 - fi - - if test -f "$LIBTOOL_M4" ; then - found_libtool="`$ECHO $_autoconf_output | grep AC_PROG_LIBTOOL`" - if test ! "x$found_libtool" = "x" ; then - if test -f acinclude.m4 ; then - rm -f acinclude.m4.$$.backup - $VERBOSE_ECHO "cat acinclude.m4 > acinclude.m4.$$.backup" - cat acinclude.m4 > acinclude.m4.$$.backup - fi - $VERBOSE_ECHO "cat \"$LIBTOOL_M4\" >> acinclude.m4" - chmod u+w acinclude.m4 - cat "$LIBTOOL_M4" >> acinclude.m4 - - # don't keep doing this - RUN_RECURSIVE=no - export RUN_RECURSIVE - untrap_abnormal - - $ECHO - $ECHO "Restarting the preparation steps with libtool macros in acinclude.m4" - $VERBOSE_ECHO sh $AUTOGEN_SH "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" - sh "$AUTOGEN_SH" "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" - exit $? - fi - fi -} - - -########################### -# MANUAL_AUTOGEN FUNCTION # -########################### -manual_autogen ( ) { - - ################################################## - # Manual preparation steps taken are as follows: # - # aclocal [-I m4] # - # libtoolize --automake -c -f # - # aclocal [-I m4] # - # autoconf -f # - # autoheader # - # automake -a -c -f # - ################################################## - - ########### - # aclocal # - ########### - $VERBOSE_ECHO "$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS" - aclocal_output="`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`" - ret=$? - $VERBOSE_ECHO "$aclocal_output" - if [ ! $ret = 0 ] ; then $ECHO "ERROR: $ACLOCAL failed" && exit 2 ; fi - - ############## - # libtoolize # - ############## - if libtoolize_needed ; then - if [ "x$HAVE_LIBTOOLIZE" = "xyes" ] ; then - $VERBOSE_ECHO "$LIBTOOLIZE $LIBTOOLIZE_OPTIONS" - libtoolize_output="`$LIBTOOLIZE $LIBTOOLIZE_OPTIONS 2>&1`" - ret=$? - $VERBOSE_ECHO "$libtoolize_output" - - if [ ! $ret = 0 ] ; then $ECHO "ERROR: $LIBTOOLIZE failed" && exit 2 ; fi - else - if [ "x$HAVE_ALT_LIBTOOLIZE" = "xyes" ] ; then - $VERBOSE_ECHO "$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS" - libtoolize_output="`$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS 2>&1`" - ret=$? - $VERBOSE_ECHO "$libtoolize_output" - - if [ ! $ret = 0 ] ; then $ECHO "ERROR: $LIBTOOLIZE failed" && exit 2 ; fi - fi - fi - - ########### - # aclocal # - ########### - # re-run again as instructed by libtoolize - $VERBOSE_ECHO "$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS" - aclocal_output="`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`" - ret=$? - $VERBOSE_ECHO "$aclocal_output" - - # libtoolize might put ltmain.sh in the wrong place - if test -f ltmain.sh ; then - if test ! -f "${_aux_dir}/ltmain.sh" ; then - $ECHO - $ECHO "Warning: $LIBTOOLIZE is creating ltmain.sh in the wrong directory" - $ECHO - $ECHO "Fortunately, the problem can be worked around by simply copying the" - $ECHO "file to the appropriate location (${_aux_dir}/). This has been done for you." - $ECHO - $VERBOSE_ECHO "cp -p ltmain.sh \"${_aux_dir}/ltmain.sh\"" - cp -p ltmain.sh "${_aux_dir}/ltmain.sh" - $ECHO $ECHO_N "Continuing build preparation ... $ECHO_C" - fi - fi # ltmain.sh - - if [ "x$DOWNLOAD" = "xyes" ] ; then - download_gnulib_config_guess - fi - fi # libtoolize_needed - - ############ - # autoconf # - ############ - $VERBOSE_ECHO - $VERBOSE_ECHO "$AUTOCONF $AUTOCONF_OPTIONS" - autoconf_output="`$AUTOCONF $AUTOCONF_OPTIONS 2>&1`" - ret=$? - $VERBOSE_ECHO "$autoconf_output" - - if [ ! $ret = 0 ] ; then - # retry without the -f and check for usage of macros that are too new - ac2_59_macros="AC_C_RESTRICT AC_INCLUDES_DEFAULT AC_LANG_ASSERT AC_LANG_WERROR AS_SET_CATFILE" - ac2_55_macros="AC_COMPILER_IFELSE AC_FUNC_MBRTOWC AC_HEADER_STDBOOL AC_LANG_CONFTEST AC_LANG_SOURCE AC_LANG_PROGRAM AC_LANG_CALL AC_LANG_FUNC_TRY_LINK AC_MSG_FAILURE AC_PREPROC_IFELSE" - ac2_54_macros="AC_C_BACKSLASH_A AC_CONFIG_LIBOBJ_DIR AC_GNU_SOURCE AC_PROG_EGREP AC_PROG_FGREP AC_REPLACE_FNMATCH AC_FUNC_FNMATCH_GNU AC_FUNC_REALLOC AC_TYPE_MBSTATE_T" - - macros_to_search="" - ac_major="`echo ${AUTOCONF_VERSION}. | cut -d. -f1 | sed 's/[^0-9]//g'`" - ac_minor="`echo ${AUTOCONF_VERSION}. | cut -d. -f2 | sed 's/[^0-9]//g'`" - - if [ $ac_major -lt 2 ] ; then - macros_to_search="$ac2_59_macros $ac2_55_macros $ac2_54_macros" - else - if [ $ac_minor -lt 54 ] ; then - macros_to_search="$ac2_59_macros $ac2_55_macros $ac2_54_macros" - elif [ $ac_minor -lt 55 ] ; then - macros_to_search="$ac2_59_macros $ac2_55_macros" - elif [ $ac_minor -lt 59 ] ; then - macros_to_search="$ac2_59_macros" - fi - fi - - configure_ac_macros=__none__ - for feature in $macros_to_search ; do - $VERBOSE_ECHO "Searching for $feature in $CONFIGURE" - found="`grep \"^$feature.*\" $CONFIGURE`" - if [ ! "x$found" = "x" ] ; then - if [ "x$configure_ac_macros" = "x__none__" ] ; then - configure_ac_macros="$feature" - else - configure_ac_macros="$feature $configure_ac_macros" - fi - fi - done - if [ ! "x$configure_ac_macros" = "x__none__" ] ; then - $ECHO - $ECHO "Warning: Unsupported macros were found in $CONFIGURE" - $ECHO - $ECHO "The `basename \"$CONFIGURE\"` file was scanned in order to determine if any" - $ECHO "unsupported macros are used that exceed the minimum version" - $ECHO "settings specified within this file. As such, the following macros" - $ECHO "should be removed from configure.ac or the version numbers in this" - $ECHO "file should be increased:" - $ECHO - $ECHO "$configure_ac_macros" - $ECHO - $ECHO $ECHO_N "Ignorantly continuing build preparation ... $ECHO_C" - fi - - ################### - # autoconf, retry # - ################### - $VERBOSE_ECHO - $VERBOSE_ECHO "$AUTOCONF" - autoconf_output="`$AUTOCONF 2>&1`" - ret=$? - $VERBOSE_ECHO "$autoconf_output" - - if [ ! $ret = 0 ] ; then - # test if libtool is busted - libtool_failure "$autoconf_output" - - # let the user know what went wrong - cat </dev/null 2>&1 - then - curl -L -o "$DOWNLOADS/$UDEV_ARCHIVE" "$UDEV_URL" - else - wget -O "$DOWNLOADS/$UDEV_ARCHIVE" "$UDEV_URL" - fi - fi - - UDEV_CONFIG="--enable-split-usr --disable-gtk-doc --disable-manpages --disable-gudev \ - --disable-introspection --disable-keymap --disable-libkmod --disable-modules \ - --disable-selinux --disable-rule-generator --disable-blkid $UDEV_CONFIG" - - # Unpack and compile udev - mkdir -p "$TMPDIR" - cd "$TMPDIR" - tar xfz "$DOWNLOADS/$UDEV_ARCHIVE" - cd "$UDEV_NAME" - LIBS="$UDEV_LIBS" \ - CFLAGS="$CFLAGS $UDEV_CFLAGS" \ - ./configure --prefix="$TMPDIR" --host="$HOST" --with-pic $LIB_CONFIG $UDEV_CONFIG - make - make install-strip - - # Enable udev support if selected - LIBUSB_CONFIG="--enable-udev $LIBUSB_CONFIG" - else - # Disable udev support if not selected - LIBUSB_CONFIG="--disable-udev $LIBUSB_CONFIG" - fi - - fi - - # Download libusb if necessary - mkdir -p "$DOWNLOADS" - if [ ! -e "$DOWNLOADS/$LIBUSB_ARCHIVE" ] - then - if type curl >/dev/null 2>&1 - then - curl -L -o "$DOWNLOADS/$LIBUSB_ARCHIVE" "$LIBUSB_URL" - else - wget -O "$DOWNLOADS/$LIBUSB_ARCHIVE" "$LIBUSB_URL" - fi - fi - - # Unpack and compile libusb - mkdir -p "$TMPDIR" - cd "$TMPDIR" - tar xfj "$DOWNLOADS/$LIBUSB_ARCHIVE" - cd "$LIBUSB_NAME" - PKG_CONFIG_PATH="$TMPDIR/lib/pkgconfig" \ - LIBS="$LIBUSB_LIBS" \ - CFLAGS="$CFLAGS $LIBUSB_CFLAGS" \ - ./configure --prefix="$TMPDIR" --host="$HOST" --with-pic $LIB_CONFIG $LIBUSB_CONFIG - make - make install-strip - - # Build autoconf stuff of usb4java if needed - cd "$SRCDIR" - if [ ! -e configure ] - then - ./autogen.sh - fi - - # Build libusb4java - PKG_CONFIG_PATH="$TMPDIR/lib/pkgconfig" \ - LIBS="$USB4JAVA_LIBS" \ - CFLAGS="$CFLAGS $USB4JAVA_CFLAGS" \ - ./configure --prefix=/ --host="$HOST" $USB4JAVA_CONFIG - make clean install-strip DESTDIR="$TMPDIR" - - # Copy dist files to java resources directory - mkdir -p "$DISTDIR" - cp -faL 2>/dev/null \ - "$TMPDIR/lib/libusb4java.so" \ - "$TMPDIR/bin/libusb-1.0.dll" \ - "$DISTDIR" || true - cp -faL 2>/dev/null \ - "$TMPDIR/bin/libusb4java-1.dll" \ - "$DISTDIR/libusb4java.dll" || true - cp -faL 2>/dev/null \ - "$TMPDIR/lib/libusb4java.dylib" \ - "$DISTDIR/libusb4java.dylib" || true - - # Remove executable flag from dist files - chmod -x "$DISTDIR/"* - - # Cleanup - rm -rf "$TMPDIR" -} diff --git a/src/main/c/build/linux-arm.sh b/src/main/c/build/linux-arm.sh deleted file mode 100755 index 22acbf2..0000000 --- a/src/main/c/build/linux-arm.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 32 bit ARM linux (Raspberry Pi) - -set -e - -. $(dirname $0)/common.sh - -OS="linux" -ARCH="arm" -HOST="$ARCH-$OS-gnueabi" -CFLAGS="-Os" -UDEV_SUPPORT="no" - -build diff --git a/src/main/c/build/linux-x86.sh b/src/main/c/build/linux-x86.sh deleted file mode 100755 index 355a935..0000000 --- a/src/main/c/build/linux-x86.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 32 bit x86 linux - -set -e - -. $(dirname $0)/common.sh - -OS="linux" -ARCH="x86" -HOST="$ARCH-$OS-gnu" -CFLAGS="-m32 -O2" -UDEV_SUPPORT="yes" - -build diff --git a/src/main/c/build/linux-x86_64.sh b/src/main/c/build/linux-x86_64.sh deleted file mode 100755 index e61f153..0000000 --- a/src/main/c/build/linux-x86_64.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 64 bit x86 linux - -set -e - -. $(dirname $0)/common.sh - -OS="linux" -ARCH="x86_64" -HOST="$ARCH-$OS-gnu" -CFLAGS="-m64 -O2" -UDEV_SUPPORT="yes" -#USB4JAVA_CFLAGS="-Wl,--wrap=memcpy -DWRAP_MEMCPY" - -build diff --git a/src/main/c/build/osx-x86.sh b/src/main/c/build/osx-x86.sh deleted file mode 100755 index ccfab0e..0000000 --- a/src/main/c/build/osx-x86.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 32 bit x86 OS X -# Must run natively on a OS X machine - -set -e - -. $(dirname $0)/common.sh - -OS="osx" -ARCH="x86" -HOST="i686-apple-darwin" -CFLAGS="-arch i686 -O2" -USB4JAVA_LIBS="-lobjc -Wl,-framework,IOKit -Wl,-framework,CoreFoundation" - -build diff --git a/src/main/c/build/osx-x86_64.sh b/src/main/c/build/osx-x86_64.sh deleted file mode 100755 index 142d891..0000000 --- a/src/main/c/build/osx-x86_64.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 64 bit x86 OS X -# Must run natively on a OS X machine - -set -e - -. $(dirname $0)/common.sh - -OS="osx" -ARCH="x86_64" -HOST="$ARCH-apple-darwin" -CFLAGS="-arch x86_64 -O2" -USB4JAVA_LIBS="-lobjc -Wl,-framework,IOKit -Wl,-framework,CoreFoundation" - -build diff --git a/src/main/c/build/windows-x86.sh b/src/main/c/build/windows-x86.sh deleted file mode 100755 index 0ab3fdd..0000000 --- a/src/main/c/build/windows-x86.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 32 bit windows - -set -e - -. $(dirname $0)/common.sh - -OS="windows" -ARCH="x86" -HOST="i686-w64-mingw32" -CFLAGS="-m32 -O2 -Wl,--add-stdcall-alias" - -build diff --git a/src/main/c/build/windows-x86_64.sh b/src/main/c/build/windows-x86_64.sh deleted file mode 100755 index 26cac5f..0000000 --- a/src/main/c/build/windows-x86_64.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -# -# Builds libusb4java for 64 bit windows - -set -e - -. $(dirname $0)/common.sh - -OS="windows" -ARCH="x86_64" -HOST="$ARCH-w64-mingw32" -CFLAGS="-m64 -O2 -Wl,--add-stdcall-alias" - -build diff --git a/src/main/c/configure.ac b/src/main/c/configure.ac deleted file mode 100644 index 64b819d..0000000 --- a/src/main/c/configure.ac +++ /dev/null @@ -1,22 +0,0 @@ -AC_PREREQ([2.61]) -AC_INIT([libusb4java], [1.2.0], [usb4java@googlegroups.com]) -AM_INIT_AUTOMAKE([foreign -Wall -Werror]) -m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES(yes)]) -AC_CONFIG_MACRO_DIR([m4]) -AC_CONFIG_HEADERS([config.h]) -AC_CONFIG_SRCDIR([src/usb4java.h]) - -AC_LANG_C -AC_PROG_CC -AC_PROG_CC_STDC -AM_PROG_LIBTOOL -m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) -AC_CHECK_JAVA -AC_CHECK_SIZEOF([void *]) -PKG_CHECK_MODULES([LIBUSB], [libusb-1.0]) - -AC_CONFIG_FILES([ - Makefile - src/Makefile -]) -AC_OUTPUT diff --git a/src/main/c/src/BosDescriptor.c b/src/main/c/src/BosDescriptor.c deleted file mode 100644 index 4a65a2d..0000000 --- a/src/main/c/src/BosDescriptor.c +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "BosDescriptor.h" -#include "BosDevCapabilityDescriptor.h" - -void setBosDescriptor(JNIEnv* env, - const struct libusb_bos_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "bosDescriptorPointer"); -} - -struct libusb_bos_descriptor* unwrapBosDescriptor(JNIEnv* env, - jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, struct libusb_bos_descriptor*, - "bosDescriptorPointer"); -} - -void resetBosDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "bosDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(BosDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_descriptor *descriptor = - unwrapBosDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(BosDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_descriptor *descriptor = - unwrapBosDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * short wTotalLength() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(BosDescriptor, wTotalLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_descriptor *descriptor = - unwrapBosDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->wTotalLength; -} - -/** - * byte bNumDeviceCaps() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(BosDescriptor, bNumDeviceCaps) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_descriptor *descriptor = - unwrapBosDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bNumDeviceCaps; -} - -/** - * BosDevCapabilityDescriptor[] devCapability() - */ -JNIEXPORT jobjectArray JNICALL METHOD_NAME(BosDescriptor, devCapability) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_descriptor *descriptor = unwrapBosDescriptor( - env, this); - if (!descriptor) return NULL; - return wrapBosDevCapabilityDescriptors(env, descriptor->bNumDeviceCaps, - descriptor->dev_capability); -} diff --git a/src/main/c/src/BosDescriptor.h b/src/main/c/src/BosDescriptor.h deleted file mode 100644 index 13166eb..0000000 --- a/src/main/c/src/BosDescriptor.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_BOS_DESCRIPTOR_H -#define USB4JAVA_BOS_DESCRIPTOR_H - -#include "usb4java.h" - -void setBosDescriptor(JNIEnv*, const struct libusb_bos_descriptor*, jobject); -struct libusb_bos_descriptor* unwrapBosDescriptor(JNIEnv*, jobject); -void resetBosDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/BosDevCapabilityDescriptor.c b/src/main/c/src/BosDevCapabilityDescriptor.c deleted file mode 100644 index 6bf0cc6..0000000 --- a/src/main/c/src/BosDevCapabilityDescriptor.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "BosDevCapabilityDescriptor.h" - -jobject wrapBosDevCapabilityDescriptor(JNIEnv *env, - const struct libusb_bos_dev_capability_descriptor *descriptor) -{ - WRAP_POINTER(env, descriptor, "BosDevCapabilityDescriptor", - "bosDevCapabilityDescriptorPointer"); -} - -jobjectArray wrapBosDevCapabilityDescriptors(JNIEnv *env, int count, - struct libusb_bos_dev_capability_descriptor * const *descriptors) -{ - jobjectArray array = (jobjectArray) (*env)->NewObjectArray(env, - count, (*env)->FindClass(env, PACKAGE_DIR"/BosDevCapabilityDescriptor"), - NULL); - - for (int i = 0; i < count; i++) - (*env)->SetObjectArrayElement(env, array, i, - wrapBosDevCapabilityDescriptor(env, descriptors[i])); - - return array; -} - -struct libusb_bos_dev_capability_descriptor* - unwrapBosDevCapabilityDescriptor(JNIEnv *env, jobject obj) -{ - UNWRAP_POINTER(env, obj, struct libusb_bos_dev_capability_descriptor*, - "bosDevCapabilityDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(BosDevCapabilityDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_dev_capability_descriptor* descriptor = - unwrapBosDevCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(BosDevCapabilityDescriptor, - bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_dev_capability_descriptor* descriptor = - unwrapBosDevCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bDevCapabilityType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(BosDevCapabilityDescriptor, - bDevCapabilityType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_dev_capability_descriptor* descriptor = - unwrapBosDevCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDevCapabilityType; -} - -/** - * ByteBuffer devCapabilityData() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(BosDevCapabilityDescriptor, - devCapabilityData) -( - JNIEnv *env, jobject this -) -{ - struct libusb_bos_dev_capability_descriptor *descriptor = - unwrapBosDevCapabilityDescriptor(env, this); - if (!descriptor) return NULL; - return NewDirectReadOnlyByteBuffer(env, descriptor->dev_capability_data, descriptor->bLength - 3); -} diff --git a/src/main/c/src/BosDevCapabilityDescriptor.h b/src/main/c/src/BosDevCapabilityDescriptor.h deleted file mode 100644 index 2cd376c..0000000 --- a/src/main/c/src/BosDevCapabilityDescriptor.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_BOS_DEV_CAPABILITY_DESCRIPTOR_H -#define USB4JAVA_BOS_DEV_CAPABILITY_DESCRIPTOR_H - -#include "usb4java.h" - -jobject wrapBosDevCapabilityDescriptor(JNIEnv *, - const struct libusb_bos_dev_capability_descriptor *); -jobjectArray wrapBosDevCapabilityDescriptors(JNIEnv*, int, - struct libusb_bos_dev_capability_descriptor * const *); -struct libusb_bos_dev_capability_descriptor* - unwrapBosDevCapabilityDescriptor(JNIEnv *, jobject); - -#endif diff --git a/src/main/c/src/ConfigDescriptor.c b/src/main/c/src/ConfigDescriptor.c deleted file mode 100644 index 9a5e8d4..0000000 --- a/src/main/c/src/ConfigDescriptor.c +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "ConfigDescriptor.h" -#include "Interface.h" - -void setConfigDescriptor(JNIEnv* env, - const struct libusb_config_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "configDescriptorPointer"); -} - -struct libusb_config_descriptor* unwrapConfigDescriptor(JNIEnv* env, - jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, struct libusb_config_descriptor*, - "configDescriptorPointer"); -} - -void resetConfigDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "configDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * short wTotalLength() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(ConfigDescriptor, wTotalLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->wTotalLength; -} - -/** - * byte bNumInterfaces() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, bNumInterfaces) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bNumInterfaces; -} - -/** - * byte bConfigurationValue() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, bConfigurationValue) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bConfigurationValue; -} - -/** - * byte iConfiguration() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, iConfiguration) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->iConfiguration; -} - -/** - * byte bmAttributes() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, bmAttributes) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bmAttributes; -} - -/** - * byte bMaxPower() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ConfigDescriptor, bMaxPower) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->MaxPower; -} - -/** - * Interface[] iface() - */ -JNIEXPORT jobjectArray JNICALL METHOD_NAME(ConfigDescriptor, iface) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = unwrapConfigDescriptor( - env, this); - if (!descriptor) return NULL; - return wrapInterfaces(env, descriptor->bNumInterfaces, - descriptor->interface); -} - -/** - * ByteBuffer extra() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(ConfigDescriptor, extra) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return NULL; - return NewDirectReadOnlyByteBuffer(env, descriptor->extra, descriptor->extra_length); -} - -/** - * int extraLength() - */ -JNIEXPORT jint JNICALL METHOD_NAME(ConfigDescriptor, extraLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_config_descriptor *descriptor = - unwrapConfigDescriptor(env, this); - if (!descriptor) return 0; - return descriptor->extra_length; -} diff --git a/src/main/c/src/ConfigDescriptor.h b/src/main/c/src/ConfigDescriptor.h deleted file mode 100644 index a7d2039..0000000 --- a/src/main/c/src/ConfigDescriptor.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_CONFIG_DESCRIPTOR_H -#define USB4JAVA_CONFIG_DESCRIPTOR_H - -#include "usb4java.h" - -void setConfigDescriptor(JNIEnv*, const struct libusb_config_descriptor*, jobject); -struct libusb_config_descriptor* unwrapConfigDescriptor(JNIEnv*, jobject); -void resetConfigDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/ContainerIdDescriptor.c b/src/main/c/src/ContainerIdDescriptor.c deleted file mode 100644 index d72625b..0000000 --- a/src/main/c/src/ContainerIdDescriptor.c +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "ContainerIdDescriptor.h" - -void setContainerIdDescriptor(JNIEnv* env, - const struct libusb_container_id_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "containerIdDescriptorPointer"); -} - -struct libusb_container_id_descriptor* unwrapContainerIdDescriptor( - JNIEnv* env, jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, - struct libusb_container_id_descriptor*, - "containerIdDescriptorPointer"); -} - -void resetContainerIdDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "containerIdDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ContainerIdDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_container_id_descriptor *descriptor = - unwrapContainerIdDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ContainerIdDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_container_id_descriptor *descriptor = - unwrapContainerIdDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bDevCapabilityType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ContainerIdDescriptor, bDevCapabilityType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_container_id_descriptor *descriptor = - unwrapContainerIdDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDevCapabilityType; -} - -/** - * byte bReserved() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(ContainerIdDescriptor, bReserved) -( - JNIEnv *env, jobject this -) -{ - struct libusb_container_id_descriptor *descriptor = - unwrapContainerIdDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bReserved; -} - -/** - * ByteBuffer containerId() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(ContainerIdDescriptor, containerId) -( - JNIEnv *env, jobject this -) -{ - struct libusb_container_id_descriptor *descriptor = - unwrapContainerIdDescriptor(env, this); - if (!descriptor) return NULL; - return NewDirectReadOnlyByteBuffer(env, descriptor->ContainerID, 16); -} diff --git a/src/main/c/src/ContainerIdDescriptor.h b/src/main/c/src/ContainerIdDescriptor.h deleted file mode 100644 index 698c8c8..0000000 --- a/src/main/c/src/ContainerIdDescriptor.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_CONTAINER_ID_DESCRIPTOR_H -#define USB4JAVA_CONTAINER_ID_DESCRIPTOR_H - -#include "usb4java.h" - -void setContainerIdDescriptor(JNIEnv*, - const struct libusb_container_id_descriptor*, jobject); -struct libusb_container_id_descriptor* - unwrapContainerIdDescriptor(JNIEnv*, jobject); -void resetContainerIdDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/Context.c b/src/main/c/src/Context.c deleted file mode 100644 index 275b3b5..0000000 --- a/src/main/c/src/Context.c +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "Context.h" - -void setContext(JNIEnv* env, const libusb_context* context, jobject object) -{ - SET_POINTER(env, context, object, "contextPointer"); -} - -jobject wrapContext(JNIEnv* env, const libusb_context* context) -{ - WRAP_POINTER(env, context, "Context", "contextPointer"); -} - -libusb_context* unwrapContext(JNIEnv* env, jobject context) -{ - UNWRAP_POINTER(env, context, libusb_context*, "contextPointer"); -} - -void resetContext(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "contextPointer"); -} diff --git a/src/main/c/src/Context.h b/src/main/c/src/Context.h deleted file mode 100644 index dae4fce..0000000 --- a/src/main/c/src/Context.h +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_CONTEXT_H -#define USB4JAVA_CONTEXT_H - -#include "usb4java.h" - -void setContext(JNIEnv*, const libusb_context*, jobject); -jobject wrapContext(JNIEnv*, const libusb_context*); -libusb_context* unwrapContext(JNIEnv*, jobject); -void resetContext(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/Device.c b/src/main/c/src/Device.c deleted file mode 100644 index f91ce28..0000000 --- a/src/main/c/src/Device.c +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "Device.h" - -jobject wrapDevice(JNIEnv* env, const libusb_device* device) -{ - WRAP_POINTER(env, device, "Device", "devicePointer"); -} - -libusb_device* unwrapDevice(JNIEnv* env, jobject device) -{ - UNWRAP_POINTER(env, device, libusb_device*, "devicePointer"); -} - -void resetDevice(JNIEnv* env, jobject object) -{ - RESET_POINTER(env, object, "devicePointer"); -} diff --git a/src/main/c/src/Device.h b/src/main/c/src/Device.h deleted file mode 100644 index d6f2d2f..0000000 --- a/src/main/c/src/Device.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_DEVICE_H -#define USB4JAVA_DEVICE_H - -#include "usb4java.h" - -jobject wrapDevice(JNIEnv*, const libusb_device*); -libusb_device* unwrapDevice(JNIEnv*, jobject); -void resetDevice(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/DeviceDescriptor.c b/src/main/c/src/DeviceDescriptor.c deleted file mode 100644 index 7ecfbc6..0000000 --- a/src/main/c/src/DeviceDescriptor.c +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "DeviceDescriptor.h" - -void setDeviceDescriptor(JNIEnv* env, - const struct libusb_device_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "deviceDescriptorPointer"); -} - -struct libusb_device_descriptor* unwrapDeviceDescriptor(JNIEnv* env, - jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, struct libusb_device_descriptor*, - "deviceDescriptorPointer"); -} - -void resetDeviceDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "deviceDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * short bcdUSB() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(DeviceDescriptor, bcdUSB) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->bcdUSB; -} - -/** - * byte bDeviceClass() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bDeviceClass) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDeviceClass; -} - -/** - * byte bDeviceSubClass() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bDeviceSubClass) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDeviceSubClass; -} - -/** - * byte bDeviceProtocol() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bDeviceProtocol) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDeviceProtocol; -} - -/** - * byte bMaxPacketSize0() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bMaxPacketSize0) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bMaxPacketSize0; -} - -/** - * short idVendor() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(DeviceDescriptor, idVendor) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->idVendor; -} - -/** - * short idProduct() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(DeviceDescriptor, idProduct) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->idProduct; -} - -/** - * short bcdDevice() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(DeviceDescriptor, bcdDevice) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->bcdDevice; -} - - -/** - * byte iManufacturer() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, iManufacturer) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->iManufacturer; -} - -/** - * byte iProduct() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, iProduct) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->iProduct; -} - -/** - * byte iSerialNumber() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, iSerialNumber) - (JNIEnv *env, jobject this) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->iSerialNumber; -} - -/** - * byte bNumConfigurations() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(DeviceDescriptor, bNumConfigurations) -( - JNIEnv *env, jobject this -) -{ - struct libusb_device_descriptor* descriptor = - unwrapDeviceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bNumConfigurations; -} diff --git a/src/main/c/src/DeviceDescriptor.h b/src/main/c/src/DeviceDescriptor.h deleted file mode 100644 index faf66a7..0000000 --- a/src/main/c/src/DeviceDescriptor.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_DEVICE_DESCRIPTOR_H -#define USB4JAVA_DEVICE_DESCRIPTOR_H - -#include "usb4java.h" - -void setDeviceDescriptor(JNIEnv*, const struct libusb_device_descriptor*, jobject); -struct libusb_device_descriptor* unwrapDeviceDescriptor(JNIEnv*, jobject); -void resetDeviceDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/DeviceHandle.c b/src/main/c/src/DeviceHandle.c deleted file mode 100644 index 0f21888..0000000 --- a/src/main/c/src/DeviceHandle.c +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "DeviceHandle.h" - -void setDeviceHandle(JNIEnv* env, const libusb_device_handle* deviceHandle, - jobject object) -{ - SET_POINTER(env, deviceHandle, object, "deviceHandlePointer"); -} - -jobject wrapDeviceHandle(JNIEnv* env, const libusb_device_handle* deviceHandle) -{ - WRAP_POINTER(env, deviceHandle, "DeviceHandle", "deviceHandlePointer"); -} - -libusb_device_handle* unwrapDeviceHandle(JNIEnv* env, jobject deviceHandle) -{ - UNWRAP_POINTER(env, deviceHandle, libusb_device_handle*, "deviceHandlePointer"); -} - -void resetDeviceHandle(JNIEnv* env, jobject object) -{ - RESET_POINTER(env, object, "deviceHandlePointer"); -} diff --git a/src/main/c/src/DeviceHandle.h b/src/main/c/src/DeviceHandle.h deleted file mode 100644 index c234d4f..0000000 --- a/src/main/c/src/DeviceHandle.h +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_DEVICE_HANDLE_H -#define USB4JAVA_DEVICE_HANDLE_H - -#include "usb4java.h" - -void setDeviceHandle(JNIEnv*, const libusb_device_handle*, jobject); -jobject wrapDeviceHandle(JNIEnv*, const libusb_device_handle*); -libusb_device_handle* unwrapDeviceHandle(JNIEnv*, jobject); -void resetDeviceHandle(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/DeviceList.c b/src/main/c/src/DeviceList.c deleted file mode 100644 index 292be4f..0000000 --- a/src/main/c/src/DeviceList.c +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "DeviceList.h" -#include "Device.h" - -void setDeviceList(JNIEnv* env, libusb_device* const *list, jint size, jobject object) -{ - SET_POINTER(env, list, object, "deviceListPointer"); - - // We already have the class from the previous call. - field = (*env)->GetFieldID(env, cls, "size", "I"); - (*env)->SetIntField(env, object, field, size); -} - -libusb_device** unwrapDeviceList(JNIEnv* env, jobject list) -{ - UNWRAP_POINTER(env, list, libusb_device**, "deviceListPointer"); -} - -void resetDeviceList(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "deviceListPointer"); - - // We already have the class from the previous call. - // Reset size field to zero too. - field = (*env)->GetFieldID(env, cls, "size", "I"); - (*env)->SetIntField(env, obj, field, 0); -} - -/** - * Device get(index) - */ -JNIEXPORT jobject JNICALL METHOD_NAME(DeviceList, get) -( - JNIEnv *env, jobject this, jint index -) -{ - libusb_device* const *list = unwrapDeviceList(env, this); - if (!list) return NULL; - - jclass cls = (*env)->GetObjectClass(env, this); - jfieldID field = (*env)->GetFieldID(env, cls, "size", "I"); - int size = (*env)->GetIntField(env, this, field); - if (index < 0 || index >= size) return NULL; - - return wrapDevice(env, list[index]); -} diff --git a/src/main/c/src/DeviceList.h b/src/main/c/src/DeviceList.h deleted file mode 100644 index 23df636..0000000 --- a/src/main/c/src/DeviceList.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_DEVICE_LIST_H -#define USB4JAVA_DEVICE_LIST_H - -#include "usb4java.h" - -void setDeviceList(JNIEnv*, libusb_device* const *, jint, jobject); -libusb_device** unwrapDeviceList(JNIEnv*, jobject); -void resetDeviceList(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/EndpointDescriptor.c b/src/main/c/src/EndpointDescriptor.c deleted file mode 100644 index 07fd399..0000000 --- a/src/main/c/src/EndpointDescriptor.c +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "EndpointDescriptor.h" - -jobject wrapEndpointDescriptor(JNIEnv *env, - const struct libusb_endpoint_descriptor *descriptor) -{ - WRAP_POINTER(env, descriptor, "EndpointDescriptor", "endpointDescriptorPointer"); -} - -jobjectArray wrapEndpointDescriptors(JNIEnv *env, int count, - const struct libusb_endpoint_descriptor *descriptors) -{ - jobjectArray array = (jobjectArray) (*env)->NewObjectArray(env, - count, (*env)->FindClass(env, PACKAGE_DIR"/EndpointDescriptor"), - NULL); - - for (int i = 0; i < count; i++) - (*env)->SetObjectArrayElement(env, array, i, - wrapEndpointDescriptor(env, &descriptors[i])); - - return array; -} - -struct libusb_endpoint_descriptor *unwrapEndpointDescriptor(JNIEnv *env, - jobject obj) -{ - UNWRAP_POINTER(env, obj, struct libusb_endpoint_descriptor*, "endpointDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bEndpointAddress() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bEndpointAddress) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bEndpointAddress; -} - -/** - * byte bmAttributes() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bmAttributes) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bmAttributes; -} - -/** - * short wMaxPacketSize() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(EndpointDescriptor, wMaxPacketSize) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->wMaxPacketSize; -} - -/** - * byte bInterval() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bInterval) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bInterval; -} - -/** - * byte bRefresh() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bRefresh) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bRefresh; -} - -/** - * byte bSynchAddress() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(EndpointDescriptor, bSynchAddress) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bSynchAddress; -} - -/** - * ByteBuffer extra() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(EndpointDescriptor, extra) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor *descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return NULL; - return NewDirectReadOnlyByteBuffer(env, descriptor->extra, descriptor->extra_length); -} - -/** - * int extraLength() - */ -JNIEXPORT jint JNICALL METHOD_NAME(EndpointDescriptor, extraLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_endpoint_descriptor* descriptor = - unwrapEndpointDescriptor(env, this); - if (!descriptor) return 0; - return descriptor->extra_length; -} diff --git a/src/main/c/src/EndpointDescriptor.h b/src/main/c/src/EndpointDescriptor.h deleted file mode 100644 index e7c1f06..0000000 --- a/src/main/c/src/EndpointDescriptor.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_ENDPOINT_DESCRIPTOR_H -#define USB4JAVA_ENDPOINT_DESCRIPTOR_H - -#include "usb4java.h" - -jobject wrapEndpointDescriptor(JNIEnv*, - const struct libusb_endpoint_descriptor*); -jobjectArray wrapEndpointDescriptors(JNIEnv*, int, - const struct libusb_endpoint_descriptor*); -struct libusb_endpoint_descriptor* unwrapEndpointDescriptor(JNIEnv*, - jobject); - -#endif diff --git a/src/main/c/src/HotplugCallbackHandle.c b/src/main/c/src/HotplugCallbackHandle.c deleted file mode 100644 index b641b1f..0000000 --- a/src/main/c/src/HotplugCallbackHandle.c +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#include "HotplugCallbackHandle.h" - -void setHotplugCallbackHandle(JNIEnv* env, const libusb_hotplug_callback_handle hotplugHandle, - jobject object) -{ - SET_POINTER(env, hotplugHandle, object, "hotplugCallbackHandleValue"); -} - -libusb_hotplug_callback_handle unwrapHotplugCallbackHandle(JNIEnv* env, jobject hotplugHandle) -{ - // Hotplug callback handles are integers, starting at 1. As such, we can use the same logic - // as for pointers, and consider 0 to be uninitialized/invalid. - if (!hotplugHandle) return 0; - jclass cls = (*env)->GetObjectClass(env, hotplugHandle); - jfieldID field = (*env)->GetFieldID(env, cls, "hotplugCallbackHandleValue", "J"); - jlong val = (*env)->GetLongField(env, hotplugHandle, field); - if (!val) illegalState(env, "hotplugCallbackHandleValue is not initialized"); - return (libusb_hotplug_callback_handle) val; -} - -void resetHotplugCallbackHandle(JNIEnv* env, jobject hotplugHandle) -{ - RESET_POINTER(env, hotplugHandle, "hotplugCallbackHandleValue"); -} diff --git a/src/main/c/src/HotplugCallbackHandle.h b/src/main/c/src/HotplugCallbackHandle.h deleted file mode 100644 index 736efd0..0000000 --- a/src/main/c/src/HotplugCallbackHandle.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_HOTPLUG_CALLBACK_HANDLE_H -#define USB4JAVA_HOTPLUG_CALLBACK_HANDLE_H - -#include "usb4java.h" - -void setHotplugCallbackHandle(JNIEnv*, const libusb_hotplug_callback_handle, jobject); -libusb_hotplug_callback_handle unwrapHotplugCallbackHandle(JNIEnv*, jobject); -void resetHotplugCallbackHandle(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/Interface.c b/src/main/c/src/Interface.c deleted file mode 100644 index a74d2c5..0000000 --- a/src/main/c/src/Interface.c +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "Interface.h" -#include "InterfaceDescriptor.h" - -jobject wrapInterface(JNIEnv *env, const struct libusb_interface *iface) -{ - WRAP_POINTER(env, iface, "Interface", "interfacePointer"); -} - -jobjectArray wrapInterfaces(JNIEnv *env, int count, - const struct libusb_interface *interfaces) -{ - jobjectArray array = (jobjectArray) (*env)->NewObjectArray(env, - count, (*env)->FindClass(env, PACKAGE_DIR"/Interface"), - NULL); - for (int i = 0; i < count; i++) - (*env)->SetObjectArrayElement(env, array, i, - wrapInterface(env, &interfaces[i])); - - return array; -} - -struct libusb_interface *unwrapInterface(JNIEnv *env, jobject obj) -{ - UNWRAP_POINTER(env, obj, struct libusb_interface*, "interfacePointer"); -} - -JNIEXPORT jint JNICALL METHOD_NAME(Interface, numAltsetting) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface* interface = unwrapInterface(env, this); - if (!interface) return 0; - return interface->num_altsetting; -} - -JNIEXPORT jobjectArray JNICALL METHOD_NAME(Interface, altsetting) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface* interface = unwrapInterface(env, this); - if (!interface) return NULL; - return wrapInterfaceDescriptors(env, interface->num_altsetting, - interface->altsetting); -} diff --git a/src/main/c/src/Interface.h b/src/main/c/src/Interface.h deleted file mode 100644 index d9af0c1..0000000 --- a/src/main/c/src/Interface.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_INTERFACE_H -#define USB4JAVA_INTERFACE_H - -#include "usb4java.h" - -jobject wrapInterface(JNIEnv *, const struct libusb_interface *); -jobjectArray wrapInterfaces(JNIEnv *, int, const struct libusb_interface *); -struct libusb_interface *unwrapInterface(JNIEnv *, jobject); - -#endif diff --git a/src/main/c/src/InterfaceDescriptor.c b/src/main/c/src/InterfaceDescriptor.c deleted file mode 100644 index 4b993bb..0000000 --- a/src/main/c/src/InterfaceDescriptor.c +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "InterfaceDescriptor.h" -#include "Interface.h" -#include "EndpointDescriptor.h" - -jobject wrapInterfaceDescriptor(JNIEnv *env, - const struct libusb_interface_descriptor *descriptor) -{ - WRAP_POINTER(env, descriptor, "InterfaceDescriptor", - "interfaceDescriptorPointer"); -} - -jobjectArray wrapInterfaceDescriptors(JNIEnv *env, int count, - const struct libusb_interface_descriptor *descriptors) -{ - jobjectArray array = (jobjectArray) (*env)->NewObjectArray(env, - count, (*env)->FindClass(env, PACKAGE_DIR"/InterfaceDescriptor"), - NULL); - for (int i = 0; i < count; i++) - (*env)->SetObjectArrayElement(env, array, i, - wrapInterfaceDescriptor(env, &descriptors[i])); - - return array; -} - -struct libusb_interface_descriptor *unwrapInterfaceDescriptor(JNIEnv *env, - jobject obj) -{ - UNWRAP_POINTER(env, obj, struct libusb_interface_descriptor*, - "interfaceDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bInterfaceNumber() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bInterfaceNumber) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bInterfaceNumber; -} - -/** - * byte bAlternateSetting() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bAlternateSetting) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bAlternateSetting; -} - -/** - * byte bNumEndpoints() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bNumEndpoints) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bNumEndpoints; -} - -/** - * byte bInterfaceClass() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bInterfaceClass) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bInterfaceClass; -} - -/** - * byte bInterfaceSubClass() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bInterfaceSubClass) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bInterfaceSubClass; -} - -/** - * byte bInterfaceProtocol() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, bInterfaceProtocol) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bInterfaceProtocol; -} - -/** - * byte iInterface() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(InterfaceDescriptor, iInterface) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->iInterface; -} - -/** - * EndpointDescriptor[] endpoint() - */ -JNIEXPORT jobjectArray JNICALL METHOD_NAME(InterfaceDescriptor, endpoint) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor *descriptor = unwrapInterfaceDescriptor( - env, this); - if (!descriptor) return NULL; - return wrapEndpointDescriptors(env, descriptor->bNumEndpoints, - descriptor->endpoint); -} - -/** - * ByteBuffer extra() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(InterfaceDescriptor, extra) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor *descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return NULL; - return NewDirectReadOnlyByteBuffer(env, descriptor->extra, - descriptor->extra_length); -} - -/** - * int extraLength() - */ -JNIEXPORT jint JNICALL METHOD_NAME(InterfaceDescriptor, extraLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_interface_descriptor* descriptor = - unwrapInterfaceDescriptor(env, this); - if (!descriptor) return 0; - return descriptor->extra_length; -} diff --git a/src/main/c/src/InterfaceDescriptor.h b/src/main/c/src/InterfaceDescriptor.h deleted file mode 100644 index 9ec8318..0000000 --- a/src/main/c/src/InterfaceDescriptor.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_INTERFACE_DESCRIPTOR_H -#define USB4JAVA_INTERFACE_DESCRIPTOR_H - -#include "usb4java.h" - -jobject wrapInterfaceDescriptor(JNIEnv*, - const struct libusb_interface_descriptor*); -jobjectArray wrapInterfaceDescriptors(JNIEnv*, int, - const struct libusb_interface_descriptor*); -struct libusb_interface_descriptor *unwrapInterfaceDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/IsoPacketDescriptor.c b/src/main/c/src/IsoPacketDescriptor.c deleted file mode 100644 index 69a6b1f..0000000 --- a/src/main/c/src/IsoPacketDescriptor.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#include "IsoPacketDescriptor.h" - -jobject wrapIsoPacketDescriptor(JNIEnv *env, - const struct libusb_iso_packet_descriptor *descriptor) -{ - WRAP_POINTER(env, descriptor, "IsoPacketDescriptor", - "isoPacketDescriptorPointer"); -} - -jobjectArray wrapIsoPacketDescriptors(JNIEnv *env, int count, - const struct libusb_iso_packet_descriptor *descriptors) -{ - jobjectArray array = (jobjectArray) (*env)->NewObjectArray(env, count, - (*env)->FindClass(env, PACKAGE_DIR"/IsoPacketDescriptor"), NULL); - - for (int i = 0; i < count; i++) - (*env)->SetObjectArrayElement(env, array, i, - wrapIsoPacketDescriptor(env, &descriptors[i])); - - return array; -} - -struct libusb_iso_packet_descriptor *unwrapIsoPacketDescriptor(JNIEnv *env, - jobject obj) -{ - UNWRAP_POINTER(env, obj, struct libusb_iso_packet_descriptor*, - "isoPacketDescriptorPointer"); -} - -/** - * int length() - */ -JNIEXPORT jint JNICALL METHOD_NAME(IsoPacketDescriptor, length) -( - JNIEnv *env, jobject this -) -{ - struct libusb_iso_packet_descriptor *isopacket = - unwrapIsoPacketDescriptor(env, this); - if (!isopacket) return 0; - - return (jint) isopacket->length; -} - -/** - * void setLength(int) - */ -JNIEXPORT void JNICALL METHOD_NAME(IsoPacketDescriptor, setLength) -( - JNIEnv *env, jobject this, jint length -) -{ - struct libusb_iso_packet_descriptor *isopacket = - unwrapIsoPacketDescriptor(env, this); - if (!isopacket) return; - - isopacket->length = (unsigned int) length; -} - -/** - * int actualLength() - */ -JNIEXPORT jint JNICALL METHOD_NAME(IsoPacketDescriptor, actualLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_iso_packet_descriptor *isopacket = - unwrapIsoPacketDescriptor(env, this); - if (!isopacket) return 0; - - return (jint) isopacket->actual_length; -} - -/** - * int status() - */ -JNIEXPORT jint JNICALL METHOD_NAME(IsoPacketDescriptor, status) -( - JNIEnv *env, jobject this -) -{ - struct libusb_iso_packet_descriptor *isopacket = - unwrapIsoPacketDescriptor(env, this); - if (!isopacket) return 0; - - return isopacket->status; -} diff --git a/src/main/c/src/IsoPacketDescriptor.h b/src/main/c/src/IsoPacketDescriptor.h deleted file mode 100644 index e745219..0000000 --- a/src/main/c/src/IsoPacketDescriptor.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_ISO_PACKET_DESCRIPTOR_H -#define USB4JAVA_ISO_PACKET_DESCRIPTOR_H - -#include "usb4java.h" - -jobject wrapIsoPacketDescriptor(JNIEnv*, - const struct libusb_iso_packet_descriptor*); -jobjectArray wrapIsoPacketDescriptors(JNIEnv*, int, - const struct libusb_iso_packet_descriptor*); -struct libusb_iso_packet_descriptor *unwrapIsoPacketDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/LibUsb.c b/src/main/c/src/LibUsb.c deleted file mode 100644 index cfe2cb2..0000000 --- a/src/main/c/src/LibUsb.c +++ /dev/null @@ -1,1479 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -/** - * @name LibUsb - * - * Native methods for the LibUsb class. - * - * @author Klaus Reimer - * @author Luca Longinotti - */ - -#include -#include -#include "usb4java.h" -#include "Version.h" -#include "Context.h" -#include "Device.h" -#include "DeviceHandle.h" -#include "DeviceList.h" -#include "DeviceDescriptor.h" -#include "ConfigDescriptor.h" -#include "EndpointDescriptor.h" -#include "SsEndpointCompanionDescriptor.h" -#include "BosDescriptor.h" -#include "BosDevCapabilityDescriptor.h" -#include "Usb20ExtensionDescriptor.h" -#include "SsUsbDeviceCapabilityDescriptor.h" -#include "ContainerIdDescriptor.h" -#include "Transfer.h" -#include "HotplugCallbackHandle.h" - -static int defaultContextRefcnt = 0; - -/** - * Version getVersion() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(LibUsb, getVersion) -( - JNIEnv *env, jclass class -) -{ - return wrapVersion(env, libusb_get_version()); -} - -/** - * int getApiVersion() - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getApiVersion) -( - JNIEnv *env, jclass class -) -{ - return LIBUSB_API_VERSION; -} - -/** - * int init(Context) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, init) -( - JNIEnv *env, jclass class, jobject context -) -{ - if (!context) - { - int result = libusb_init(NULL); - if (result == LIBUSB_SUCCESS) defaultContextRefcnt++; - return result; - } - else - { - NOT_SET(env, context, "contextPointer", return 0); - - libusb_context *ctx; - int result = libusb_init(&ctx); - if (result == LIBUSB_SUCCESS) setContext(env, ctx, context); - return result; - } -} - -/** - * void exit(Context) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, exit) -( - JNIEnv *env, jclass class, jobject context -) -{ - if (!context) - { - if (defaultContextRefcnt <= 0) - { - illegalState(env, "default context is not initialized"); - return; - } - - libusb_exit(NULL); - - defaultContextRefcnt--; - } - else - { - libusb_context *ctx = unwrapContext(env, context); - if (!ctx) return; - - libusb_exit(ctx); - - resetContext(env, context); - } -} - -/** - * void setDebug(Context, int) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, setDebug) -( - JNIEnv *env, jclass class, jobject context, jint level -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_set_debug(ctx, level); -} - -/** - * int getDeviceList(Context, DeviceList) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getDeviceList) -( - JNIEnv *env, jclass class, jobject context, jobject deviceList -) -{ - NOT_NULL(env, deviceList, return 0); - NOT_SET(env, deviceList, "deviceListPointer", return 0); - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - libusb_device **list; - ssize_t result = libusb_get_device_list(ctx, &list); - if (result >= 0) setDeviceList(env, list, (jint) result, deviceList); - return (jint) result; -} - -/** - * void freeDeviceList(DeviceList, boolean) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeDeviceList) -( - JNIEnv *env, jclass class, jobject deviceList, jboolean unrefDevices -) -{ - if (!deviceList) return; - libusb_device **list = unwrapDeviceList(env, deviceList); - if (!list) return; - libusb_free_device_list(list, unrefDevices); - resetDeviceList(env, deviceList); -} - -/** - * int getBusNumber(Device) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getBusNumber) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - return libusb_get_bus_number(dev); -} - -/** - * int getPortNumber(Device) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getPortNumber) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - return libusb_get_port_number(dev); -} - -/** - * int getPortNumbers(Device, ByteBuffer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getPortNumbers) -( - JNIEnv *env, jclass class, jobject device, jobject path -) -{ - NOT_NULL(env, device, return 0); - NOT_NULL(env, path, return 0); - DIRECT_BUFFER(env, path, path_ptr, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - jlong path_size = (*env)->GetDirectBufferCapacity(env, path); - return libusb_get_port_numbers(dev, path_ptr, (int) path_size); -} - -/** - * Device getParent(Device) - */ -JNIEXPORT jobject JNICALL METHOD_NAME(LibUsb, getParent) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return NULL); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return NULL; - return wrapDevice(env, libusb_get_parent(dev)); -} - -/** - * int getDeviceAddress(Device) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getDeviceAddress) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - return libusb_get_device_address(dev); -} - -/** - * int getDeviceSpeed(Device) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getDeviceSpeed) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - return libusb_get_device_speed(dev); -} - -/** - * int getMaxPacketSize(Device, byte) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getMaxPacketSize) -( - JNIEnv *env, jclass class, jobject device, jbyte endpoint -) -{ - NOT_NULL(env, device, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - return libusb_get_max_packet_size(dev, (unsigned char) endpoint); -} - -/** - * int getMaxIsoPacketSize(Device, byte) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getMaxIsoPacketSize) -( - JNIEnv *env, jclass class, jobject device, jbyte endpoint -) -{ - NOT_NULL(env, device, return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - return libusb_get_max_iso_packet_size(dev, (unsigned char) endpoint); -} - -/** - * Device refDevice(Device) - */ -JNIEXPORT jobject JNICALL METHOD_NAME(LibUsb, refDevice) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return NULL); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return NULL; - return wrapDevice(env, libusb_ref_device(dev)); -} - -/** - * void unrefDevice(Device) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, unrefDevice) -( - JNIEnv *env, jclass class, jobject device -) -{ - NOT_NULL(env, device, return); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return; - libusb_unref_device(dev); - resetDevice(env, device); -} - -/** - * int open(Device, DeviceHandle) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, open) -( - JNIEnv *env, jclass class, jobject device, jobject handle -) -{ - NOT_NULL(env, device, return 0); - NOT_NULL(env, handle, return 0); - NOT_SET(env, handle, "deviceHandlePointer", return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - libusb_device_handle *deviceHandle; - int result = libusb_open(dev, &deviceHandle); - if (result == LIBUSB_SUCCESS) setDeviceHandle(env, deviceHandle, handle); - return result; -} - -/** - * DeviceHandle openDeviceWithVidPid(Context, short, short) - */ -JNIEXPORT jobject JNICALL METHOD_NAME(LibUsb, openDeviceWithVidPid) -( - JNIEnv *env, jclass class, jobject context, jshort vendorId, - jshort productId -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return NULL; - return wrapDeviceHandle(env, libusb_open_device_with_vid_pid( - ctx, (uint16_t) vendorId, (uint16_t) productId)); -} - -/** - * void close(DeviceHandle) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, close) -( - JNIEnv *env, jclass class, jobject handle -) -{ - NOT_NULL(env, handle, return); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return; - libusb_close(dev_handle); - resetDeviceHandle(env, handle); -} - -/** - * Device getDevice(DeviceHandle) - */ -JNIEXPORT jobject JNICALL METHOD_NAME(LibUsb, getDevice) -( - JNIEnv *env, jclass class, jobject handle -) -{ - NOT_NULL(env, handle, return NULL); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return NULL; - return wrapDevice(env, libusb_get_device(dev_handle)); -} - -/** - * int getConfiguration(DeviceHandle, IntBuffer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getConfiguration) -( - JNIEnv *env, jclass class, jobject handle, jobject buffer -) -{ - NOT_NULL(env, handle, return 0); - NOT_NULL(env, buffer, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - int config; - int result = libusb_get_configuration(dev_handle, &config); - if (result == LIBUSB_SUCCESS) - { - jclass cls = (*env)->GetObjectClass(env, buffer); - jmethodID method = (*env)->GetMethodID(env, cls, "put", "(II)Ljava/nio/IntBuffer;"); - (*env)->CallObjectMethod(env, buffer, method, 0, config); - } - return result; -} - -/** - * int setConfiguration(DeviceHandle, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, setConfiguration) -( - JNIEnv *env, jclass class, jobject handle, jint config -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_set_configuration(dev_handle, config); -} - -/** - * int claimInterface(DeviceHandle, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, claimInterface) -( - JNIEnv *env, jclass class, jobject handle, jint iface -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_claim_interface(dev_handle, iface); -} - -/** - * int releaseInterface(DeviceHandle, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, releaseInterface) -( - JNIEnv *env, jclass class, jobject handle, jint iface -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_release_interface(dev_handle, iface); -} - -/** - * int setInterfaceAltSetting(DeviceHandle, int, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, setInterfaceAltSetting) -( - JNIEnv *env, jclass class, jobject handle, jint iface, jint setting -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_set_interface_alt_setting(dev_handle, iface, setting); -} - -/** - * int clearHalt(DeviceHandle, byte) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, clearHalt) -( - JNIEnv *env, jclass class, jobject handle, jbyte endpoint -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_clear_halt(dev_handle, (unsigned char) endpoint); -} - -/** - * int resetDevice(DeviceHandle) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, resetDevice) -( - JNIEnv *env, jclass class, jobject handle -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_reset_device(dev_handle); -} - -/** - * int kernelDriverActive(DeviceHandle, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, kernelDriverActive) -( - JNIEnv *env, jclass class, jobject handle, jint iface -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_kernel_driver_active(dev_handle, iface); -} - -/** - * int detachKernelDriver(DeviceHandle, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, detachKernelDriver) -( - JNIEnv *env, jclass class, jobject handle, jint iface -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_detach_kernel_driver(dev_handle, iface); -} - -/** - * int attachKernelDriver(DeviceHandle, int) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, attachKernelDriver) -( - JNIEnv *env, jclass class, jobject handle, jint iface -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_attach_kernel_driver(dev_handle, iface); -} - -/** - * int setAutoDetachKernelDriver(DeviceHandle, boolean) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, setAutoDetachKernelDriver) -( - JNIEnv *env, jclass class, jobject handle, jboolean enable -) -{ - NOT_NULL(env, handle, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - return libusb_set_auto_detach_kernel_driver(dev_handle, enable); -} - -/** - * boolean hasCapability(int) - */ -JNIEXPORT jboolean JNICALL METHOD_NAME(LibUsb, hasCapability) -( - JNIEnv *env, jclass class, jint capability -) -{ - return (jboolean) libusb_has_capability((uint32_t) capability); -} - -/** - * string errorName(int) - */ -JNIEXPORT jstring JNICALL METHOD_NAME(LibUsb, errorName) -( - JNIEnv *env, jclass class, jint code -) -{ - return (*env)->NewStringUTF(env, libusb_error_name(code)); -} - -/** - * int setLocale(String) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, setLocale) -( - JNIEnv *env, jobject class, jstring locale -) -{ - NOT_NULL(env, locale, return 0); - const char *nativeLocale = (*env)->GetStringUTFChars(env, locale, NULL); - int result = libusb_setlocale(nativeLocale); - (*env)->ReleaseStringUTFChars(env, locale, nativeLocale); - return result; -} - -/** - * String strError(int) - */ -JNIEXPORT jstring JNICALL METHOD_NAME(LibUsb, strError) -( - JNIEnv *env, jobject class, jint code -) -{ - return (*env)->NewStringUTF(env, libusb_strerror(code)); -} - -/** - * short le16ToCpu(short) - */ -JNIEXPORT jshort JNICALL METHOD_NAME(LibUsb, le16ToCpu) -( - JNIEnv *env, jclass class, jshort x -) -{ - return (jshort) libusb_le16_to_cpu((uint16_t) x); -} - -/** - * short cpuToLe16(short) - */ -JNIEXPORT jshort JNICALL METHOD_NAME(LibUsb, cpuToLe16) -( - JNIEnv *env, jclass class, jshort x -) -{ - return (jshort) libusb_cpu_to_le16((uint16_t) x); -} - -/** - * int getDeviceDescriptor(Device, DeviceDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getDeviceDescriptor) -( - JNIEnv *env, jclass class, jobject device, jobject descriptor -) -{ - NOT_NULL(env, device, return 0); - NOT_NULL(env, descriptor, return 0); - - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - - jclass cls = (*env)->GetObjectClass(env, descriptor); - jfieldID field = (*env)->GetFieldID(env, cls, "deviceDescriptorBuffer", "Ljava/nio/ByteBuffer;"); - jobject buffer = (*env)->GetObjectField(env, descriptor, field); - - // The Java code ensures this is an appropriately sized direct ByteBuffer. - struct libusb_device_descriptor *dev_desc = (*env)->GetDirectBufferAddress(env, buffer); - - int result = libusb_get_device_descriptor(dev, dev_desc); - if (result == LIBUSB_SUCCESS) - { - setDeviceDescriptor(env, dev_desc, descriptor); - } - else - { - // Reset pointer on error, to ensure subsequent accesses will throw exceptions. - resetDeviceDescriptor(env, descriptor); - } - - return result; -} - -/** - * int deviceDescriptorStructSize() - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, deviceDescriptorStructSize) -( - JNIEnv *env, jclass class -) -{ - return sizeof(struct libusb_device_descriptor); -} - -/** - * int getStringDescriptorAscii(DeviceHandle, byte, StringBuffer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getStringDescriptorAscii) -( - JNIEnv *env, jclass class, jobject handle, jbyte index, jobject string -) -{ - NOT_NULL(env, handle, return 0); - NOT_NULL(env, string, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - // Maximum size of a descriptor is 256 bytes, -2 for length/type = 254, /2 because of Unicode = 127 characters - // and then +1 for the terminating NUL byte for C strings (the descriptor itself doesn't necessarily have one!). - unsigned char buffer[127 + 1]; - int result = libusb_get_string_descriptor_ascii( - dev_handle, (uint8_t) index, buffer, 127); - if (result >= 0) - { - buffer[result] = 0x00; - jobject tmp = (*env)->NewStringUTF(env, (char *) buffer); - jclass cls = (*env)->GetObjectClass(env, string); - jmethodID method = (*env)->GetMethodID(env, cls, "append", - "(Ljava/lang/String;)Ljava/lang/StringBuffer;"); - (*env)->CallObjectMethod(env, string, method, tmp); - } - return result; -} - -/** - * int getActiveConfigDescriptor(Device, ConfigDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getActiveConfigDescriptor) -( - JNIEnv *env, jclass class, jobject device, jobject descriptor) -{ - NOT_NULL(env, device, return 0); - NOT_NULL(env, descriptor, return 0); - NOT_SET(env, descriptor, "configDescriptorPointer", return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - struct libusb_config_descriptor *config; - int result = libusb_get_active_config_descriptor(dev, &config); - if (result == LIBUSB_SUCCESS) setConfigDescriptor(env, config, descriptor); - return result; -} - -/** - * int getConfigDescriptor(Device, byte, ConfigDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getConfigDescriptor) -( - JNIEnv *env, jclass class, jobject device, jbyte index, jobject descriptor -) -{ - NOT_NULL(env, device, return 0); - NOT_NULL(env, descriptor, return 0); - NOT_SET(env, descriptor, "configDescriptorPointer", return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - struct libusb_config_descriptor *config; - int result = libusb_get_config_descriptor(dev, (uint8_t) index, &config); - if (result == LIBUSB_SUCCESS) setConfigDescriptor(env, config, descriptor); - return result; -} - -/** - * int getConfigDescriptorByValue(Device, byte, ConfigDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getConfigDescriptorByValue) -( - JNIEnv *env, jclass class, jobject device, jbyte index, jobject descriptor -) -{ - NOT_NULL(env, device, return 0); - NOT_NULL(env, descriptor, return 0); - NOT_SET(env, descriptor, "configDescriptorPointer", return 0); - libusb_device *dev = unwrapDevice(env, device); - if (!dev) return 0; - struct libusb_config_descriptor *config; - int result = libusb_get_config_descriptor_by_value( - dev, (uint8_t) index, &config); - if (result == LIBUSB_SUCCESS) setConfigDescriptor(env, config, descriptor); - return result; -} - -/** - * void freeConfigDescriptor(ConfigDescriptor) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeConfigDescriptor) -( - JNIEnv *env, jclass class, jobject descriptor -) -{ - if (!descriptor) return; - struct libusb_config_descriptor *config = unwrapConfigDescriptor(env, - descriptor); - if (!config) return; - libusb_free_config_descriptor(config); - resetConfigDescriptor(env, descriptor); -} - -/** - * int getSsEndpointCompanionDescriptor(Context, EndpointDescriptor, SsEndpointCompanionDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getSsEndpointCompanionDescriptor) -( - JNIEnv *env, jclass class, jobject context, jobject endpointDescriptor, - jobject companionDescriptor -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - NOT_NULL(env, endpointDescriptor, return 0); - NOT_NULL(env, companionDescriptor, return 0); - NOT_SET(env, companionDescriptor, "ssEndpointCompanionDescriptorPointer", return 0); - - struct libusb_endpoint_descriptor *endpoint_descriptor = - unwrapEndpointDescriptor(env, endpointDescriptor); - if (!endpoint_descriptor) return 0; - struct libusb_ss_endpoint_companion_descriptor *companion_descriptor; - int result = libusb_get_ss_endpoint_companion_descriptor(ctx, - endpoint_descriptor, &companion_descriptor); - if (result == LIBUSB_SUCCESS) setSsEndpointCompanionDescriptor(env, companion_descriptor, - companionDescriptor); - return result; -} - -/** - * void freeSsEndpointCompanionDescriptor(SsEndpointCompanionDescriptor) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeSsEndpointCompanionDescriptor) -( - JNIEnv *env, jclass class, jobject companionDescriptor -) -{ - if (!companionDescriptor) return; - struct libusb_ss_endpoint_companion_descriptor *companion_descriptor = - unwrapSsEndpointCompanionDescriptor(env, companionDescriptor); - if (!companion_descriptor) return; - libusb_free_ss_endpoint_companion_descriptor(companion_descriptor); - resetSsEndpointCompanionDescriptor(env, companionDescriptor); -} - -/** - * int getBosDescriptor(DeviceHandle, BosDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getBosDescriptor) -( - JNIEnv *env, jclass class, jobject handle, jobject bosDescriptor -) -{ - NOT_NULL(env, handle, return 0); - NOT_NULL(env, bosDescriptor, return 0); - NOT_SET(env, bosDescriptor, "bosDescriptorPointer", return 0); - - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - struct libusb_bos_descriptor *bos_descriptor; - int result = libusb_get_bos_descriptor(dev_handle, &bos_descriptor); - if (result == LIBUSB_SUCCESS) setBosDescriptor(env, bos_descriptor, bosDescriptor); - return result; -} - -/** - * void freeBosDescriptor(BosDescriptor) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeBosDescriptor) -( - JNIEnv *env, jclass class, jobject bosDescriptor -) -{ - if (!bosDescriptor) return; - struct libusb_bos_descriptor *bos_descriptor = - unwrapBosDescriptor(env, bosDescriptor); - if (!bos_descriptor) return; - libusb_free_bos_descriptor(bos_descriptor); - resetBosDescriptor(env, bosDescriptor); -} - -/** - * int getUsb20ExtensionDescriptor(Context, BosDevCapabilityDescriptor, Usb20ExtensionDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getUsb20ExtensionDescriptor) -( - JNIEnv *env, jclass class, jobject context, jobject devCapDescriptor, - jobject extensionDescriptor -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - NOT_NULL(env, devCapDescriptor, return 0); - NOT_NULL(env, extensionDescriptor, return 0); - NOT_SET(env, extensionDescriptor, "usb20ExtensionDescriptorPointer", return 0); - - struct libusb_bos_dev_capability_descriptor *devcap_descriptor = - unwrapBosDevCapabilityDescriptor(env, devCapDescriptor); - if (!devcap_descriptor) return 0; - struct libusb_usb_2_0_extension_descriptor *extension_descriptor; - int result = libusb_get_usb_2_0_extension_descriptor(ctx, - devcap_descriptor, &extension_descriptor); - if (result == LIBUSB_SUCCESS) setUsb20ExtensionDescriptor(env, extension_descriptor, - extensionDescriptor); - return result; -} - -/** - * void freeUsb20ExtensionDescriptor(Usb20ExtensionDescriptor) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeUsb20ExtensionDescriptor) -( - JNIEnv *env, jclass class, jobject extensionDescriptor -) -{ - if (!extensionDescriptor) return; - struct libusb_usb_2_0_extension_descriptor *extension_descriptor = - unwrapUsb20ExtensionDescriptor(env, extensionDescriptor); - if (!extension_descriptor) return; - libusb_free_usb_2_0_extension_descriptor(extension_descriptor); - resetUsb20ExtensionDescriptor(env, extensionDescriptor); -} - -/** - * int getSsUsbDeviceCapabilityDescriptor(Context, BosDevCapabilityDescriptor, SsUsbDeviceCapabilityDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getSsUsbDeviceCapabilityDescriptor) -( - JNIEnv *env, jclass class, jobject context, jobject devCapDescriptor, - jobject ssUsbDeviceCapabilityDescriptor -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - NOT_NULL(env, devCapDescriptor, return 0); - NOT_NULL(env, ssUsbDeviceCapabilityDescriptor, return 0); - NOT_SET(env, ssUsbDeviceCapabilityDescriptor, "ssUsbDeviceCapabilityDescriptorPointer", return 0); - - struct libusb_bos_dev_capability_descriptor *devcap_descriptor = - unwrapBosDevCapabilityDescriptor(env, devCapDescriptor); - if (!devcap_descriptor) return 0; - struct libusb_ss_usb_device_capability_descriptor *descriptor; - int result = libusb_get_ss_usb_device_capability_descriptor(ctx, - devcap_descriptor, &descriptor); - if (result == LIBUSB_SUCCESS) setSsUsbDeviceCapabilityDescriptor(env, descriptor, - ssUsbDeviceCapabilityDescriptor); - return result; -} - -/** - * void freeSsUsbDeviceCapabilityDescriptor(SsUsbDeviceCapabilityDescriptor) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeSsUsbDeviceCapabilityDescriptor) -( - JNIEnv *env, jclass class, jobject ssUsbDeviceCapabilityDescriptor -) -{ - if (!ssUsbDeviceCapabilityDescriptor) return; - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, ssUsbDeviceCapabilityDescriptor); - if (!descriptor) return; - libusb_free_ss_usb_device_capability_descriptor(descriptor); - resetSsUsbDeviceCapabilityDescriptor(env, ssUsbDeviceCapabilityDescriptor); -} - -/** - * int getContainerIdDescriptor(Context, BosDevCapabilityDescriptor, ContainerIdDescriptor) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getContainerIdDescriptor) -( - JNIEnv *env, jclass class, jobject context, jobject devCapDescriptor, - jobject containerIdDescriptor -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - NOT_NULL(env, devCapDescriptor, return 0); - NOT_NULL(env, containerIdDescriptor, return 0); - NOT_SET(env, containerIdDescriptor, "containerIdDescriptorPointer", return 0); - - struct libusb_bos_dev_capability_descriptor *devcap_descriptor = - unwrapBosDevCapabilityDescriptor(env, devCapDescriptor); - if (!devcap_descriptor) return 0; - struct libusb_container_id_descriptor *container_id_descriptor; - int result = libusb_get_container_id_descriptor(ctx, - devcap_descriptor, &container_id_descriptor); - if (result == LIBUSB_SUCCESS) setContainerIdDescriptor(env, container_id_descriptor, - containerIdDescriptor); - return result; -} - -/** - * void freeContainerIdDescriptor(ContainerIdDescriptor) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeContainerIdDescriptor) -( - JNIEnv *env, jclass class, jobject containerIdDescriptor -) -{ - if (!containerIdDescriptor) return; - struct libusb_container_id_descriptor *container_id_descriptor = - unwrapContainerIdDescriptor(env, containerIdDescriptor); - if (!container_id_descriptor) return; - libusb_free_container_id_descriptor(container_id_descriptor); - resetContainerIdDescriptor(env, containerIdDescriptor); -} - -/** - * int controlTransfer(DeviceHandle, byte, byte, short, short, ByteBuffer, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, controlTransfer) -( - JNIEnv *env, jclass class, jobject handle, jbyte bmRequestType, - jbyte bRequest, jshort wValue, jshort wIndex, jobject data, jlong timeout -) -{ - NOT_NULL(env, handle, return 0); - NOT_NULL(env, data, return 0); - DIRECT_BUFFER(env, data, data_ptr, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - jlong data_size = (*env)->GetDirectBufferCapacity(env, data); - return libusb_control_transfer(dev_handle, (uint8_t) bmRequestType, - (uint8_t) bRequest, (uint16_t) wValue, (uint16_t) wIndex, data_ptr, - (uint16_t) data_size, (unsigned int) timeout); -} - -/** - * int bulkTransfer(DeviceHandle, byte, ByteBuffer, IntBuffer, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, bulkTransfer) -( - JNIEnv *env, jclass class, jobject handle, jbyte endpoint, - jobject data, jobject transferred, jlong timeout -) -{ - NOT_NULL(env, handle, return 0); - NOT_NULL(env, data, return 0); - NOT_NULL(env, transferred, return 0); - DIRECT_BUFFER(env, data, data_ptr, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - int sent; - jlong data_size = (*env)->GetDirectBufferCapacity(env, data); - int result = libusb_bulk_transfer(dev_handle, (unsigned char) endpoint, - data_ptr, (int) data_size, &sent, (unsigned int) timeout); - if (result == LIBUSB_SUCCESS) - { - jclass cls = (*env)->GetObjectClass(env, transferred); - jmethodID method = (*env)->GetMethodID(env, cls, "put", - "(II)Ljava/nio/IntBuffer;"); - (*env)->CallObjectMethod(env, transferred, method, 0, sent); - } - return result; -} - -/** - * int interruptTransfer(DeviceHandle, byte, ByteBuffer, IntBuffer, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, interruptTransfer) -( - JNIEnv *env, jclass class, jobject handle, jbyte endpoint, - jobject data, jobject transferred, jlong timeout -) -{ - NOT_NULL(env, handle, return 0); - NOT_NULL(env, data, return 0); - NOT_NULL(env, transferred, return 0); - DIRECT_BUFFER(env, data, data_ptr, return 0); - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle) return 0; - int sent; - jlong data_size = (*env)->GetDirectBufferCapacity(env, data); - int result = libusb_interrupt_transfer(dev_handle, (unsigned char) endpoint, - data_ptr, (int) data_size, &sent, (unsigned int) timeout); - if (result == LIBUSB_SUCCESS) - { - jclass cls = (*env)->GetObjectClass(env, transferred); - jmethodID method = (*env)->GetMethodID(env, cls, "put", - "(II)Ljava/nio/IntBuffer;"); - (*env)->CallObjectMethod(env, transferred, method, 0, sent); - } - return result; -} - -/** - * int tryLockEvents(Context) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, tryLockEvents) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - return libusb_try_lock_events(ctx); -} - -/** - * void lockEvents(Context) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, lockEvents) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_lock_events(ctx); -} - -/** - * void unlockEvents(Context) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, unlockEvents) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_unlock_events(ctx); -} - -/** - * int eventHandlingOk(Context) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, eventHandlingOk) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - return libusb_event_handling_ok(ctx); -} - -/** - * int eventHandlerActive(Context) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, eventHandlerActive) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - return libusb_event_handler_active(ctx); -} - -/** - * void lockEventWaiters(Context) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, lockEventWaiters) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_lock_event_waiters(ctx); -} - -/** - * void unlockEventWaiters(Context) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, unlockEventWaiters) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_unlock_event_waiters(ctx); -} - -/** - * int waitForEvent(Context, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, waitForEvent) -( - JNIEnv *env, jclass class, jobject context, jlong timeout -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - struct timeval tv; - tv.tv_sec = (long int) timeout / 1000000; - tv.tv_usec = (long int) timeout % 1000000; - - return libusb_wait_for_event(ctx, &tv); -} - -/** - * int handleEventsTimeoutCompleted(Context, long, IntBuffer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, handleEventsTimeoutCompleted) -( - JNIEnv *env, jclass class, jobject context, jlong timeout, - jobject completed -) -{ - int *complete = NULL; - if (completed) - { - DIRECT_BUFFER(env, completed, complete_tmp, return 0); - complete = (int *) complete_tmp; - } - - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - struct timeval tv; - tv.tv_sec = (long int) timeout / 1000000; - tv.tv_usec = (long int) timeout % 1000000; - - return libusb_handle_events_timeout_completed(ctx, &tv, complete); -} - -/** - * int handleEventsTimeout(Context, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, handleEventsTimeout) -( - JNIEnv *env, jclass class, jobject context, jlong timeout -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - struct timeval tv; - tv.tv_sec = (long int) timeout / 1000000; - tv.tv_usec = (long int) timeout % 1000000; - - return libusb_handle_events_timeout(ctx, &tv); -} - -/** - * int handleEvents(Context) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, handleEvents) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - return libusb_handle_events(ctx); -} - -/** - * int handleEventsCompleted(Context, IntBuffer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, handleEventsCompleted) -( - JNIEnv *env, jclass class, jobject context, jobject completed -) -{ - int *complete = NULL; - if (completed) - { - DIRECT_BUFFER(env, completed, complete_tmp, return 0); - complete = (int *) complete_tmp; - } - - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - - return libusb_handle_events_completed(ctx, complete); -} - -/** - * int handleEventsLocked(Context, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, handleEventsLocked) -( - JNIEnv *env, jclass class, jobject context, jlong timeout -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - struct timeval tv; - tv.tv_sec = (long int) timeout / 1000000; - tv.tv_usec = (long int) timeout % 1000000; - - return libusb_handle_events_locked(ctx, &tv); -} - -/** - * int pollfdsHandleTimeouts(Context) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, pollfdsHandleTimeouts) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - return libusb_pollfds_handle_timeouts(ctx); -} - -/** - * int getNextTimeout(Context, LongBuffer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, getNextTimeout) -( - JNIEnv *env, jclass class, jobject context, jobject timeout -) -{ - NOT_NULL(env, timeout, return 0); - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - struct timeval tv; - int result = libusb_get_next_timeout(ctx, &tv); - if (result == 1) - { - jclass cls = (*env)->GetObjectClass(env, timeout); - jmethodID method = (*env)->GetMethodID(env, cls, "put", - "(IJ)Ljava/nio/LongBuffer;"); - (*env)->CallObjectMethod(env, timeout, method, 0, - (jlong) (tv.tv_sec * 1000000 + tv.tv_usec)); - } - return result; -} - -static void LIBUSB_CALL triggerPollfdAdded(int fd, short events, void *user_data) -{ - THREAD_BEGIN(env) - - jclass fdCls = (*env)->FindClass(env, "java/io/FileDescriptor"); - jmethodID fdConstructor = (*env)->GetMethodID(env, fdCls, "", "(I)V"); - jobject fdObject = (*env)->NewObject(env, fdCls, fdConstructor, fd); - - (*env)->CallStaticVoidMethod(env, jClassLibUsb, jMethodTriggerPollfdAdded, - fdObject, (jint) events, (jlong) (intptr_t) user_data); - - THREAD_END -} - -static void LIBUSB_CALL triggerPollfdRemoved(int fd, void *user_data) -{ - THREAD_BEGIN(env) - - jclass fdCls = (*env)->FindClass(env, "java/io/FileDescriptor"); - jmethodID fdConstructor = (*env)->GetMethodID(env, fdCls, "", "(I)V"); - jobject fdObject = (*env)->NewObject(env, fdCls, fdConstructor, fd); - - (*env)->CallStaticVoidMethod(env, jClassLibUsb, jMethodTriggerPollfdRemoved, - fdObject, (jlong) (intptr_t) user_data); - - THREAD_END -} - -/** - * void setPollfdNotifiersNative(Context, long) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, setPollfdNotifiersNative) -( - JNIEnv *env, jclass class, jobject context, jlong context_id -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_set_pollfd_notifiers(ctx, &triggerPollfdAdded, &triggerPollfdRemoved, - (void *) (intptr_t) context_id); -} - -/** - * void unsetPollfdNotifiersNative(Context) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, unsetPollfdNotifiersNative) -( - JNIEnv *env, jclass class, jobject context -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return; - libusb_set_pollfd_notifiers(ctx, NULL, NULL, NULL); -} - -/** - * Transfer allocTransfer(int) - */ -JNIEXPORT jobject JNICALL METHOD_NAME(LibUsb, allocTransfer) -( - JNIEnv *env, jclass class, jint isoPackets -) -{ - struct libusb_transfer *transfer = libusb_alloc_transfer(isoPackets); - if (!transfer) return NULL; - - struct transfer_data *transferData = calloc(1, sizeof(*transferData)); - if (!transferData) - { - libusb_free_transfer(transfer); - return NULL; - } - - transfer->user_data = transferData; - transferData->maxNumIsoPackets = (size_t) isoPackets; - - jobject transferObject = wrapTransfer(env, transfer); - - // Make sure the cleanup callback is always there, as it's perfectly legal - // to not set any callback and still enable the FREE_TRANSFER flag, in which - // case one would expect the Java Transfer object to be properly cleaned up. - cleanupCallbackEnable(env, transferObject); - - return transferObject; -} - -/** - * void freeTransfer(Transfer) - */ -JNIEXPORT void JNICALL METHOD_NAME(LibUsb, freeTransfer) -( - JNIEnv *env, jclass class, jobject trans -) -{ - if (!trans) return; - struct libusb_transfer *transfer = unwrapTransfer(env, trans); - if (!transfer) return; - - cleanupGlobalReferences(env, trans); - resetTransfer(env, trans); - free(transfer->user_data); - libusb_free_transfer(transfer); -} - -/** - * int submitTransfer(Transfer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, submitTransfer) -( - JNIEnv *env, jclass class, jobject trans -) -{ - NOT_NULL(env, trans, return 0); - struct libusb_transfer *transfer = unwrapTransfer(env, trans); - if (!transfer) return 0; - - return libusb_submit_transfer(transfer); -} - -/** - * int cancelTransfer(Transfer) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, cancelTransfer) -( - JNIEnv *env, jclass class, jobject trans -) -{ - NOT_NULL(env, trans, return 0); - struct libusb_transfer *transfer = unwrapTransfer(env, trans); - if (!transfer) return 0; - - return libusb_cancel_transfer(transfer); -} - -static int LIBUSB_CALL hotplugCallback(libusb_context *context, - libusb_device *device, libusb_hotplug_event event, void *user_data) -{ - THREAD_BEGIN(env) - - jobject ctx = wrapContext(env, context); - jobject dev = wrapDevice(env, device); - - int result = (*env)->CallStaticIntMethod(env, - jClassLibUsb, jMethodHotplugCallback, ctx, dev, - (jint) event, (jlong) (intptr_t) user_data); - - THREAD_END - - return result; -} - -/** - * int hotplugRegisterCallbackNative(Context, int, int, int, int, int, - * HotplugCallbackHandle, long) - */ -JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, hotplugRegisterCallbackNative) -( - JNIEnv *env, jclass class, jobject context, jint events, jint flags, - jint vendorId, jint productId, jint deviceClass, - jobject callbackHandle, jlong hotplugId -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - - if (callbackHandle != NULL) - { - // If callbackHandle is set, the Java object must be fresh/empty. - NOT_SET(env, callbackHandle, "hotplugCallbackHandleValue", return 0); - } - - // Register the callback. - libusb_hotplug_callback_handle handle; - int result = libusb_hotplug_register_callback(ctx, events, flags, - vendorId, productId, deviceClass, &hotplugCallback, - (void *) (intptr_t) hotplugId, &handle); - - // If callbackHandle is set and registering was successful, we set the handle - // to the value we've gotten from libusb. - if ((callbackHandle != NULL) && (result == LIBUSB_SUCCESS)) - { - setHotplugCallbackHandle(env, handle, callbackHandle); - } - - return result; -} - -/* - * long hotplugDeregisterCallbackNative(Context, HotplugCallbackHandle) - */ -JNIEXPORT jlong JNICALL METHOD_NAME(LibUsb, hotplugDeregisterCallbackNative) -( - JNIEnv *env, jclass class, jobject context, jobject callbackHandle -) -{ - libusb_context *ctx = unwrapContext(env, context); - if (!ctx && context) return 0; - NOT_NULL(env, callbackHandle, return 0); - - libusb_hotplug_callback_handle handle = - unwrapHotplugCallbackHandle(env, callbackHandle); - if (!handle) return 0; - - // Deregister the callback. - libusb_hotplug_deregister_callback(ctx, handle); - - resetHotplugCallbackHandle(env, callbackHandle); - - return handle; -} diff --git a/src/main/c/src/Makefile.am b/src/main/c/src/Makefile.am deleted file mode 100644 index 65d6b77..0000000 --- a/src/main/c/src/Makefile.am +++ /dev/null @@ -1,28 +0,0 @@ -lib_LTLIBRARIES = libusb4java.la -libusb4java_la_CFLAGS = -pedantic -Wall -Wextra -Wformat=2 -Winit-self -Wunused -Wno-unused-parameter -Wuninitialized -Wundef -Wshadow -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wconversion -Wstrict-prototypes -Wredundant-decls -Wnested-externs $(LIBUSB_CFLAGS) -libusb4java_la_LIBADD = $(LIBUSB_LIBS) -libusb4java_la_LDFLAGS = -version-info 1:2:0 -no-undefined -EXTRA_DIST = *.h -libusb4java_la_SOURCES = \ - wrappers.c \ - usb4java.c \ - LibUsb.c \ - Version.c \ - Context.c \ - Device.c \ - DeviceHandle.c \ - DeviceList.c \ - DeviceDescriptor.c \ - ConfigDescriptor.c \ - Interface.c \ - InterfaceDescriptor.c \ - EndpointDescriptor.c \ - IsoPacketDescriptor.c \ - Transfer.c \ - SsEndpointCompanionDescriptor.c \ - BosDescriptor.c \ - BosDevCapabilityDescriptor.c \ - Usb20ExtensionDescriptor.c \ - SsUsbDeviceCapabilityDescriptor.c \ - ContainerIdDescriptor.c \ - HotplugCallbackHandle.c diff --git a/src/main/c/src/SsEndpointCompanionDescriptor.c b/src/main/c/src/SsEndpointCompanionDescriptor.c deleted file mode 100644 index 3f39d8e..0000000 --- a/src/main/c/src/SsEndpointCompanionDescriptor.c +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "SsEndpointCompanionDescriptor.h" -#include "Interface.h" - -void setSsEndpointCompanionDescriptor(JNIEnv* env, - const struct libusb_ss_endpoint_companion_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "ssEndpointCompanionDescriptorPointer"); -} - -struct libusb_ss_endpoint_companion_descriptor* - unwrapSsEndpointCompanionDescriptor(JNIEnv* env, jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, - struct libusb_ss_endpoint_companion_descriptor*, - "ssEndpointCompanionDescriptorPointer"); -} - -void resetSsEndpointCompanionDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "ssEndpointCompanionDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsEndpointCompanionDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_endpoint_companion_descriptor *descriptor = - unwrapSsEndpointCompanionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsEndpointCompanionDescriptor, - bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_endpoint_companion_descriptor *descriptor = - unwrapSsEndpointCompanionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bMaxBurst() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsEndpointCompanionDescriptor, bMaxBurst) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_endpoint_companion_descriptor *descriptor = - unwrapSsEndpointCompanionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bMaxBurst; -} - -/** - * byte bmAttributes() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsEndpointCompanionDescriptor, bmAttributes) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_endpoint_companion_descriptor *descriptor = - unwrapSsEndpointCompanionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bmAttributes; -} - -/** - * short wBytesPerInterval() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(SsEndpointCompanionDescriptor, wBytesPerInterval) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_endpoint_companion_descriptor *descriptor = - unwrapSsEndpointCompanionDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->wBytesPerInterval; -} diff --git a/src/main/c/src/SsEndpointCompanionDescriptor.h b/src/main/c/src/SsEndpointCompanionDescriptor.h deleted file mode 100644 index 3febd7d..0000000 --- a/src/main/c/src/SsEndpointCompanionDescriptor.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_SS_ENDPOINT_COMPANION_DESCRIPTOR_H -#define USB4JAVA_SS_ENDPOINT_COMPANION_DESCRIPTOR_H - -#include "usb4java.h" - -void setSsEndpointCompanionDescriptor(JNIEnv*, - const struct libusb_ss_endpoint_companion_descriptor*, jobject); -struct libusb_ss_endpoint_companion_descriptor* - unwrapSsEndpointCompanionDescriptor(JNIEnv*, jobject); -void resetSsEndpointCompanionDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/SsUsbDeviceCapabilityDescriptor.c b/src/main/c/src/SsUsbDeviceCapabilityDescriptor.c deleted file mode 100644 index 03e8aa4..0000000 --- a/src/main/c/src/SsUsbDeviceCapabilityDescriptor.c +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "SsUsbDeviceCapabilityDescriptor.h" - -void setSsUsbDeviceCapabilityDescriptor(JNIEnv* env, - const struct libusb_ss_usb_device_capability_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "ssUsbDeviceCapabilityDescriptorPointer"); -} - -struct libusb_ss_usb_device_capability_descriptor* unwrapSsUsbDeviceCapabilityDescriptor( - JNIEnv* env, jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, - struct libusb_ss_usb_device_capability_descriptor*, - "ssUsbDeviceCapabilityDescriptorPointer"); -} - -void resetSsUsbDeviceCapabilityDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "ssUsbDeviceCapabilityDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bDevCapabilityType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, - bDevCapabilityType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDevCapabilityType; -} - -/** - * byte bmAttributes() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, - bmAttributes) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bmAttributes; -} - -/** - * short wSpeedSupported() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, - wSpeedSupported) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->wSpeedSupported; -} - -/** - * byte bFunctionalitySupport() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, - bFunctionalitySupport) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bFunctionalitySupport; -} - -/** - * byte bU1DevExitLat() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, - bU1DevExitLat) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bU1DevExitLat; -} - -/** - * short bU2DevExitLat() - */ -JNIEXPORT jshort JNICALL METHOD_NAME(SsUsbDeviceCapabilityDescriptor, - bU2DevExitLat) -( - JNIEnv *env, jobject this -) -{ - struct libusb_ss_usb_device_capability_descriptor *descriptor = - unwrapSsUsbDeviceCapabilityDescriptor(env, this); - if (!descriptor) return 0; - return (jshort) descriptor->bU2DevExitLat; -} diff --git a/src/main/c/src/SsUsbDeviceCapabilityDescriptor.h b/src/main/c/src/SsUsbDeviceCapabilityDescriptor.h deleted file mode 100644 index bd35734..0000000 --- a/src/main/c/src/SsUsbDeviceCapabilityDescriptor.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_SS_USB_DEVICE_CAPABILITY_DESCRIPTOR_H -#define USB4JAVA_SS_USB_DEVICE_CAPABILITY_DESCRIPTOR_H - -#include "usb4java.h" - -void setSsUsbDeviceCapabilityDescriptor(JNIEnv*, - const struct libusb_ss_usb_device_capability_descriptor*, jobject); -struct libusb_ss_usb_device_capability_descriptor* - unwrapSsUsbDeviceCapabilityDescriptor(JNIEnv*, jobject); -void resetSsUsbDeviceCapabilityDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/Transfer.c b/src/main/c/src/Transfer.c deleted file mode 100644 index 7316ace..0000000 --- a/src/main/c/src/Transfer.c +++ /dev/null @@ -1,504 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#include -#include "Transfer.h" -#include "DeviceHandle.h" -#include "IsoPacketDescriptor.h" - -static void LIBUSB_CALL cleanupCallback(struct libusb_transfer *transfer); -static void LIBUSB_CALL transferCallback(struct libusb_transfer *transfer); - -jobject wrapTransfer(JNIEnv* env, const struct libusb_transfer* transfer) -{ - WRAP_POINTER(env, transfer, "Transfer", "transferPointer"); -} - -struct libusb_transfer* unwrapTransfer(JNIEnv* env, jobject obj) -{ - UNWRAP_POINTER(env, obj, struct libusb_transfer*, "transferPointer"); -} - -void resetTransfer(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "transferPointer"); - - // We already have the class from the previous call. - // Reset transferBuffer field to NULL too. - field = (*env)->GetFieldID(env, cls, "transferBuffer", - "Ljava/nio/ByteBuffer;"); - (*env)->SetObjectField(env, obj, field, NULL); -} - -/** - * void setDevHandle(DeviceHandle) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setDevHandle) -( - JNIEnv *env, jobject this, jobject handle -) -{ - libusb_device_handle *dev_handle = unwrapDeviceHandle(env, handle); - if (!dev_handle && handle) return; - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->dev_handle = dev_handle; -} - -/** - * DeviceHandle devHandle() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(Transfer, devHandle) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return NULL; - - return wrapDeviceHandle(env, transfer->dev_handle); -} - -/** - * void setFlags(byte) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setFlags) -( - JNIEnv *env, jobject this, jbyte flags -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->flags = (uint8_t) flags; -} - -/** - * byte flags() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(Transfer, flags) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return (jbyte) transfer->flags; -} - -/** - * void setEndpoint(byte) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setEndpoint) -( - JNIEnv *env, jobject this, jbyte endpoint -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->endpoint = (unsigned char) endpoint; -} - -/** - * byte endpoint() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(Transfer, endpoint) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return (jbyte) transfer->endpoint; -} - -/** - * void setType(byte) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setType) -( - JNIEnv *env, jobject this, jbyte type -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->type = (unsigned char) type; -} - -/** - * byte type() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(Transfer, type) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return (jbyte) transfer->type; -} - -/** - * void setTimeout(long) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setTimeout) -( - JNIEnv *env, jobject this, jlong timeout -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->timeout = (unsigned int) timeout; -} - -/** - * long timeout() - */ -JNIEXPORT jlong JNICALL METHOD_NAME(Transfer, timeout) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return transfer->timeout; -} - -/** - * int status() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Transfer, status) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return transfer->status; -} - -/** - * void setLengthNative(int) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setLengthNative) -( - JNIEnv *env, jobject this, jint length -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->length = length; -} - -/** - * int length() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Transfer, length) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return transfer->length; -} - -/** - * int actualLength() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Transfer, actualLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return transfer->actual_length; -} - -void cleanupGlobalReferences(JNIEnv *env, jobject obj) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, obj); - if (!transfer) return; - - struct transfer_data *transferData = - ((struct transfer_data *) transfer->user_data); - - // Cleanup all global references, if any currently exist. - if (transferData->callbackObject != NULL) - { - (*env)->DeleteGlobalRef(env, transferData->callbackObject); - } - - if (transferData->callbackUserDataObject != NULL) - { - (*env)->DeleteGlobalRef(env, transferData->callbackUserDataObject); - } - - if (transferData->transferObject != NULL) - { - (*env)->DeleteGlobalRef(env, transferData->transferObject); - } -} - -void cleanupCallbackEnable(JNIEnv *env, jobject obj) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, obj); - if (!transfer) return; - - struct transfer_data *transferData = - ((struct transfer_data *) transfer->user_data); - - transferData->transferObject = (*env)->NewGlobalRef(env, obj); - - transfer->callback = &cleanupCallback; - - transferData->callbackObject = NULL; - transferData->callbackObjectMethod = 0; -} - -static void LIBUSB_CALL cleanupCallback(struct libusb_transfer *transfer) -{ - THREAD_BEGIN(env) - - struct transfer_data *transferData = - ((struct transfer_data *) transfer->user_data); - - // The saved reference to the Java Transfer object. - jobject jTransfer = transferData->transferObject; - - // Cleanup Java Transfer object too, if requested. - if (transfer->flags & LIBUSB_TRANSFER_FREE_TRANSFER) - { - cleanupGlobalReferences(env, jTransfer); - resetTransfer(env, jTransfer); - free(transferData); - } - - THREAD_END -} - -static void LIBUSB_CALL transferCallback(struct libusb_transfer *transfer) -{ - THREAD_BEGIN(env) - - struct transfer_data *transferData = - ((struct transfer_data *) transfer->user_data); - - // The saved references to the Java TransferCallback object. - jobject jCallback = transferData->callbackObject; - jmethodID jCallbackMethod = transferData->callbackObjectMethod; - - // The saved reference to the Java Transfer object. - jobject jTransfer = transferData->transferObject; - - // Read flags before calling the Java method, as it could - // free the Transfer itself. - if (transfer->flags & LIBUSB_TRANSFER_FREE_TRANSFER) - { - // Call back into Java. - (*env)->CallVoidMethod(env, jCallback, jCallbackMethod, jTransfer); - - // Cleanup Java Transfer object too, if requested. - cleanupGlobalReferences(env, jTransfer); - resetTransfer(env, jTransfer); - free(transferData); - } - else - { - // Call back into Java. - (*env)->CallVoidMethod(env, jCallback, jCallbackMethod, jTransfer); - } - - THREAD_END -} - -/** - * void setCallback(TransferCallback) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setCallback) -( - JNIEnv *env, jobject this, jobject callback -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - struct transfer_data *transferData = - ((struct transfer_data *) transfer->user_data); - - if (transferData->transferObject != NULL) - { - (*env)->DeleteGlobalRef(env, transferData->transferObject); - } - - if (transferData->callbackObject != NULL) - { - (*env)->DeleteGlobalRef(env, transferData->callbackObject); - } - - if (callback != NULL) - { - transferData->transferObject = (*env)->NewGlobalRef(env, this); - - transfer->callback = &transferCallback; - - jclass cls = (*env)->GetObjectClass(env, callback); - jmethodID method = (*env)->GetMethodID(env, cls, "processTransfer", - "(L"PACKAGE_DIR"/Transfer;)V"); - - transferData->callbackObject = (*env)->NewGlobalRef(env, callback); - transferData->callbackObjectMethod = method; - } - else - { - cleanupCallbackEnable(env, this); - } -} - -/** - * TransferCallback callback() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(Transfer, callback) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return NULL; - - return ((struct transfer_data *) transfer->user_data)->callbackObject; -} - -/** - * void setUserData(Object) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setUserData) -( - JNIEnv *env, jobject this, jobject userData -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - struct transfer_data *transferData = - ((struct transfer_data *) transfer->user_data); - - if (transferData->callbackUserDataObject != NULL) - { - (*env)->DeleteGlobalRef(env, transferData->callbackUserDataObject); - } - - if (userData != NULL) - { - transferData->callbackUserDataObject = (*env)->NewGlobalRef(env, - userData); - } - else - { - transferData->callbackUserDataObject = NULL; - } -} - -/** - * Object userData() - */ -JNIEXPORT jobject JNICALL METHOD_NAME(Transfer, userData) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return NULL; - - return ((struct transfer_data *) transfer->user_data)->callbackUserDataObject; -} - -/** - * void setBufferNative(ByteBuffer) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setBufferNative) -( - JNIEnv *env, jobject this, jobject buffer -) -{ - unsigned char *buffer_ptr = NULL; - if (buffer) - { - DIRECT_BUFFER(env, buffer, buffer_tmp, return); - buffer_ptr = buffer_tmp; - } - - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - transfer->buffer = buffer_ptr; -} - -/** - * void setNumIsoPackets(int) - */ -JNIEXPORT void JNICALL METHOD_NAME(Transfer, setNumIsoPackets) -( - JNIEnv *env, jobject this, jint numIsoPackets -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return; - - // Check that calls to setNumIsoPackets() never set a number exceeding - // the maximum, which was originally set at allocTransfer() time. - if (((struct transfer_data *) transfer->user_data)->maxNumIsoPackets - < (size_t) numIsoPackets) - { - illegalArgument(env, - "numIsoPackets exceeds maximum allowed number set with allocTransfer()"); - return; - } - - transfer->num_iso_packets = numIsoPackets; -} - -/** - * int numIsoPackets() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Transfer, numIsoPackets) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return 0; - - return transfer->num_iso_packets; -} - -/** - * IsoPacketDescriptor[] isoPacketDesc() - */ -JNIEXPORT jobjectArray JNICALL METHOD_NAME(Transfer, isoPacketDesc) -( - JNIEnv *env, jobject this -) -{ - struct libusb_transfer *transfer = unwrapTransfer(env, this); - if (!transfer) return NULL; - - return wrapIsoPacketDescriptors(env, transfer->num_iso_packets, - transfer->iso_packet_desc); -} diff --git a/src/main/c/src/Transfer.h b/src/main/c/src/Transfer.h deleted file mode 100644 index 4710bf5..0000000 --- a/src/main/c/src/Transfer.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_TRANSFER_H -#define USB4JAVA_TRANSFER_H - -#include "usb4java.h" - -struct transfer_data -{ - jobject transferObject; - jobject callbackObject; - jmethodID callbackObjectMethod; - jobject callbackUserDataObject; - size_t maxNumIsoPackets; -}; - -void cleanupGlobalReferences(JNIEnv*, jobject); -void cleanupCallbackEnable(JNIEnv*, jobject); - -jobject wrapTransfer(JNIEnv*, const struct libusb_transfer*); -struct libusb_transfer* unwrapTransfer(JNIEnv*, jobject); -void resetTransfer(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/Usb20ExtensionDescriptor.c b/src/main/c/src/Usb20ExtensionDescriptor.c deleted file mode 100644 index e201d48..0000000 --- a/src/main/c/src/Usb20ExtensionDescriptor.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "Usb20ExtensionDescriptor.h" - -void setUsb20ExtensionDescriptor(JNIEnv* env, - const struct libusb_usb_2_0_extension_descriptor* descriptor, jobject object) -{ - SET_POINTER(env, descriptor, object, "usb20ExtensionDescriptorPointer"); -} - -struct libusb_usb_2_0_extension_descriptor* unwrapUsb20ExtensionDescriptor( - JNIEnv* env, jobject descriptor) -{ - UNWRAP_POINTER(env, descriptor, - struct libusb_usb_2_0_extension_descriptor*, - "usb20ExtensionDescriptorPointer"); -} - -void resetUsb20ExtensionDescriptor(JNIEnv* env, jobject obj) -{ - RESET_POINTER(env, obj, "usb20ExtensionDescriptorPointer"); -} - -/** - * byte bLength() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(Usb20ExtensionDescriptor, bLength) -( - JNIEnv *env, jobject this -) -{ - struct libusb_usb_2_0_extension_descriptor *descriptor = - unwrapUsb20ExtensionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bLength; -} - -/** - * byte bDescriptorType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(Usb20ExtensionDescriptor, bDescriptorType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_usb_2_0_extension_descriptor *descriptor = - unwrapUsb20ExtensionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDescriptorType; -} - -/** - * byte bDevCapabilityType() - */ -JNIEXPORT jbyte JNICALL METHOD_NAME(Usb20ExtensionDescriptor, - bDevCapabilityType) -( - JNIEnv *env, jobject this -) -{ - struct libusb_usb_2_0_extension_descriptor *descriptor = - unwrapUsb20ExtensionDescriptor(env, this); - if (!descriptor) return 0; - return (jbyte) descriptor->bDevCapabilityType; -} - -/** - * int bmAttributes() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Usb20ExtensionDescriptor, - bmAttributes) -( - JNIEnv *env, jobject this -) -{ - struct libusb_usb_2_0_extension_descriptor *descriptor = - unwrapUsb20ExtensionDescriptor(env, this); - if (!descriptor) return 0; - return (jint) descriptor->bmAttributes; -} diff --git a/src/main/c/src/Usb20ExtensionDescriptor.h b/src/main/c/src/Usb20ExtensionDescriptor.h deleted file mode 100644 index ec57bc9..0000000 --- a/src/main/c/src/Usb20ExtensionDescriptor.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_USB_2_0_EXTENSION_DESCRIPTOR_H -#define USB4JAVA_USB_2_0_EXTENSION_DESCRIPTOR_H - -#include "usb4java.h" - -void setUsb20ExtensionDescriptor(JNIEnv*, - const struct libusb_usb_2_0_extension_descriptor*, jobject); -struct libusb_usb_2_0_extension_descriptor* - unwrapUsb20ExtensionDescriptor(JNIEnv*, jobject); -void resetUsb20ExtensionDescriptor(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/Version.c b/src/main/c/src/Version.c deleted file mode 100644 index d4eebed..0000000 --- a/src/main/c/src/Version.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include "Version.h" - -jobject wrapVersion(JNIEnv* env, const struct libusb_version* pointer) -{ - WRAP_POINTER(env, pointer, "Version", "versionPointer"); -} - -const struct libusb_version* unwrapVersion(JNIEnv* env, jobject object) -{ - UNWRAP_POINTER(env, object, const struct libusb_version*, "versionPointer"); -} - -/** - * int major() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Version, major) -( - JNIEnv *env, jobject this -) -{ - const struct libusb_version *version = unwrapVersion(env, this); - if (!version) return 0; - return version->major; -} - -/** - * int minor() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Version, minor) -( - JNIEnv *env, jobject this -) -{ - const struct libusb_version *version = unwrapVersion(env, this); - if (!version) return 0; - return version->minor; -} - -/** - * int micro() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Version, micro) -( - JNIEnv *env, jobject this -) -{ - const struct libusb_version *version = unwrapVersion(env, this); - if (!version) return 0; - return version->micro; -} - -/** - * int nano() - */ -JNIEXPORT jint JNICALL METHOD_NAME(Version, nano) -( - JNIEnv *env, jobject this -) -{ - const struct libusb_version *version = unwrapVersion(env, this); - if (!version) return 0; - return version->nano; -} - -/** - * String rc() - */ -JNIEXPORT jstring JNICALL METHOD_NAME(Version, rc) -( - JNIEnv *env, jobject this -) -{ - const struct libusb_version *version = unwrapVersion(env, this); - if (!version) return NULL; - return (*env)->NewStringUTF(env, version->rc); -} - - diff --git a/src/main/c/src/Version.h b/src/main/c/src/Version.h deleted file mode 100644 index 81d7567..0000000 --- a/src/main/c/src/Version.h +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_VERSION_H -#define USB4JAVA_VERSION_H - -#include "usb4java.h" - -jobject wrapVersion(JNIEnv*, const struct libusb_version*); -const struct libusb_version* unwrapVersion(JNIEnv*, jobject); - -#endif diff --git a/src/main/c/src/usb4java.c b/src/main/c/src/usb4java.c deleted file mode 100644 index f93f477..0000000 --- a/src/main/c/src/usb4java.c +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#include "usb4java.h" - -JavaVM *jvm = NULL; - -jclass jClassLibUsb = NULL; -jmethodID jMethodTriggerPollfdAdded = NULL; -jmethodID jMethodTriggerPollfdRemoved = NULL; -jmethodID jMethodHotplugCallback = NULL; - -jint illegalArgument(JNIEnv *env, const char *message) -{ - jclass cls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); - return (*env)->ThrowNew(env, cls, message); -} - -jint illegalState(JNIEnv *env, const char *message) -{ - jclass cls = (*env)->FindClass(env, "java/lang/IllegalStateException"); - return (*env)->ThrowNew(env, cls, message); -} - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-qual" -jobject NewDirectReadOnlyByteBuffer(JNIEnv *env, const void *mem, - int mem_length) -{ - jobject buffer = (*env)->NewDirectByteBuffer(env, (void *) mem, mem_length); - - // Get a read-only buffer from this buffer. - jclass cls = (*env)->GetObjectClass(env, buffer); - jmethodID method = (*env)->GetMethodID(env, cls, "asReadOnlyBuffer", - "()Ljava/nio/ByteBuffer;"); - return (*env)->CallObjectMethod(env, buffer, method); -} -#pragma GCC diagnostic pop - -jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) -{ - // Set JVM to the current one. - jvm = vm; - - // Get the current environment. - JNIEnv *env; - jint getEnvResult = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); - if (getEnvResult != JNI_OK) - { - // Send unrecognized version to signal error and deny library load. - return -1; - } - - // Find classes and methods and cache them. - // Persistence is guaranteed by global references. - jClassLibUsb = (*env)->FindClass(env, PACKAGE_DIR"/LibUsb"); - jClassLibUsb = (*env)->NewGlobalRef(env, jClassLibUsb); - - jMethodTriggerPollfdAdded = (*env)->GetStaticMethodID(env, jClassLibUsb, - "triggerPollfdAdded", "(Ljava/io/FileDescriptor;IJ)V"); - jMethodTriggerPollfdRemoved = (*env)->GetStaticMethodID(env, jClassLibUsb, - "triggerPollfdRemoved", "(Ljava/io/FileDescriptor;J)V"); - jMethodHotplugCallback = (*env)->GetStaticMethodID(env, jClassLibUsb, - "hotplugCallback", "(L"PACKAGE_DIR"/Context;L"PACKAGE_DIR"/Device;IJ)I"); - - return JNI_VERSION_1_6; -} - -void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) -{ - // Get the current environment. - JNIEnv *env; - jint getEnvResult = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); - if (getEnvResult != JNI_OK) - { - return; - } - - // Cleanup all global references. - (*env)->DeleteGlobalRef(env, jClassLibUsb); -} diff --git a/src/main/c/src/usb4java.h b/src/main/c/src/usb4java.h deleted file mode 100644 index f64d277..0000000 --- a/src/main/c/src/usb4java.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * Copyright (C) 2013 Luca Longinotti (l@longi.li) - * See COPYING file for copying conditions - */ - -#ifndef USB4JAVA_H -#define USB4JAVA_H - -#include -#include -#include "config.h" - -#define PACKAGE_DIR "org/libusb4java" -#define METHOD_NAME(CLASS_NAME, METHOD_NAME) Java_org_libusb4java_##CLASS_NAME##_##METHOD_NAME - -#if SIZEOF_VOID_P == 4 -# define jptr jint -#elif SIZEOF_VOID_P == 8 -# define jptr jlong -#endif - -#define SET_POINTER(ENV, PTR, OBJECT, FIELD) \ - jclass cls = (*ENV)->GetObjectClass(ENV, OBJECT); \ - jfieldID field = (*ENV)->GetFieldID(ENV, cls, FIELD, "J"); \ - (*ENV)->SetLongField(ENV, OBJECT, field, (jptr) PTR); - -#define RESET_POINTER(ENV, OBJECT, FIELD) \ - jclass cls = (*ENV)->GetObjectClass(ENV, OBJECT); \ - jfieldID field = (*ENV)->GetFieldID(ENV, cls, FIELD, "J"); \ - (*ENV)->SetLongField(ENV, OBJECT, field, 0); - -#define WRAP_POINTER(ENV, PTR, CLASS_NAME, FIELD) \ - if (!PTR) return NULL; \ - jclass cls = (*ENV)->FindClass(ENV, PACKAGE_DIR"/"CLASS_NAME); \ - if (cls == NULL) return NULL; \ - jmethodID constructor = (*ENV)->GetMethodID(ENV, cls, "", "()V"); \ - if (constructor == NULL) return NULL; \ - jobject object = (*ENV)->NewObject(ENV, cls, constructor); \ - jfieldID field = (*ENV)->GetFieldID(ENV, cls, FIELD, "J"); \ - (*ENV)->SetLongField(ENV, object, field, (jptr) PTR); \ - return object; - -#define UNWRAP_POINTER(ENV, OBJECT, TYPE, FIELD) \ - if (!OBJECT) return NULL; \ - jclass cls = (*ENV)->GetObjectClass(ENV, OBJECT); \ - jfieldID field = (*ENV)->GetFieldID(ENV, cls, FIELD, "J"); \ - jptr ptr = (jptr) (*ENV)->GetLongField(ENV, OBJECT, field); \ - if (!ptr) illegalState(ENV, FIELD" is not initialized"); \ - return (TYPE) ptr; - -// GetDirectBufferAddress returns NULL if called on a non-direct buffer. -#define DIRECT_BUFFER(ENV, VAR, BUFFER, ACTION) \ - unsigned char *BUFFER = (*ENV)->GetDirectBufferAddress(ENV, VAR); \ - if (!BUFFER) \ - { \ - illegalArgument(ENV, #VAR" must be a direct buffer"); \ - ACTION; \ - } - -#define NOT_NULL(ENV, VAR, ACTION) \ - if (!VAR) \ - { \ - illegalArgument(ENV, #VAR" must not be null"); \ - ACTION; \ - } - -#define NOT_SET(ENV, VAR, FIELD, ACTION) \ - jclass cls = (*ENV)->GetObjectClass(ENV, VAR); \ - jfieldID field = (*ENV)->GetFieldID(ENV, cls, FIELD, "J"); \ - jptr ptr = (jptr) (*ENV)->GetLongField(ENV, VAR, field); \ - if (ptr) \ - { \ - illegalState(ENV, FIELD" is already initialized"); \ - ACTION; \ - } - -#define THREAD_BEGIN(ENV) \ - JNIEnv *ENV; \ - jint getEnvResult = (*jvm)->GetEnv(jvm, (void **) &ENV, JNI_VERSION_1_6); \ - if (getEnvResult == JNI_EDETACHED) \ - (*jvm)->AttachCurrentThread(jvm, (void**) &ENV, NULL); - -#define THREAD_END \ - if (getEnvResult == JNI_EDETACHED) \ - (*jvm)->DetachCurrentThread(jvm); - -// JVM access. -extern JavaVM *jvm; - -// Callback caching. -extern jclass jClassLibUsb; -extern jmethodID jMethodTriggerPollfdAdded; -extern jmethodID jMethodTriggerPollfdRemoved; -extern jmethodID jMethodHotplugCallback; - -jint illegalArgument(JNIEnv *env, const char *message); -jint illegalState(JNIEnv *env, const char *message); -jobject NewDirectReadOnlyByteBuffer(JNIEnv *env, const void *mem, - int mem_length); - -#endif diff --git a/src/main/c/src/wrappers.c b/src/main/c/src/wrappers.c deleted file mode 100644 index f11f829..0000000 --- a/src/main/c/src/wrappers.c +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer (k@ailis.de) - * See COPYING file for copying conditions - */ - -#include - -// Enforce usage of older memcpy to be compatible with older libc versions -#ifdef WRAP_MEMCPY -asm (".symver memcpy, memcpy@GLIBC_2.2.5"); -void *__wrap_memcpy(void *dest, const void *src, size_t n) -{ - return memcpy(dest, src, n); -} -#endif diff --git a/src/main/java/org/libusb4java/Interface.java b/src/main/java/org/libusb4java/Interface.java deleted file mode 100644 index f6a7b1d..0000000 --- a/src/main/java/org/libusb4java/Interface.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2013 Klaus Reimer - * See LICENSE.md for licensing information. - * - * Based on libusb : - * - * Copyright 2001 Johannes Erdfelt - * Copyright 2007-2009 Daniel Drake - * Copyright 2010-2012 Peter Stuge - * Copyright 2008-2011 Nathan Hjelm - * Copyright 2009-2012 Pete Batard - * Copyright 2009-2012 Ludovic Rousseau - * Copyright 2010-2012 Michael Plante - * Copyright 2011-2012 Hans de Goede - * Copyright 2012 Martin Pieuchot - * Copyright 2012-2013 Toby Gray - */ - -package org.libusb4java; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -/** - * A collection of alternate settings for a particular USB interface. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class Interface -{ - /** The native pointer to the descriptor structure. */ - private long interfacePointer; - - /** - * Package-private constructor to prevent manual instantiation. Interfaces - * are always created by JNI. - */ - Interface() - { - // Empty - } - - /** - * Returns the native pointer. - * - * @return The native pointer. - */ - public long getPointer() - { - return this.interfacePointer; - } - - /** - * Returns the array with interface descriptors. The length of this array is - * determined by the {@link #numAltsetting()} field. - * - * @return The array with interface descriptors. - */ - public native InterfaceDescriptor[] altsetting(); - - /** - * Returns the number of alternate settings that belong to this interface. - * - * @return The number of alternate settings. - */ - public native int numAltsetting(); - - /** - * Returns a dump of this interface. - * - * @return The interface dump. - */ - public String dump() - { - final StringBuilder builder = new StringBuilder(); - - builder.append(String.format( - "Interface:%n" + - " numAltsetting %10d", - this.numAltsetting())); - - for (final InterfaceDescriptor intDesc : this.altsetting()) - { - builder.append("%n" + intDesc.dump()); - } - - return builder.toString(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(this.altsetting()) - .append(this.numAltsetting()) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) - { - return true; - } - if (obj == null) - { - return false; - } - if (this.getClass() != obj.getClass()) - { - return false; - } - - final Interface other = (Interface) obj; - - return new EqualsBuilder() - .append(this.altsetting(), other.altsetting()) - .append(this.numAltsetting(), other.numAltsetting()) - .isEquals(); - } - - @Override - public String toString() - { - return this.dump(); - } -} diff --git a/src/main/java/org/libusb4java/package-info.java b/src/main/java/org/libusb4java/package-info.java deleted file mode 100644 index 792f0aa..0000000 --- a/src/main/java/org/libusb4java/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -/** - * Low-Level classes based on the native libusb library. - */ -package org.libusb4java; - diff --git a/src/main/java/org/usb4java/AbstractDevice.java b/src/main/java/org/usb4java/AbstractDevice.java deleted file mode 100644 index 74059cb..0000000 --- a/src/main/java/org/usb4java/AbstractDevice.java +++ /dev/null @@ -1,613 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.usb.UsbClaimException; -import javax.usb.UsbConst; -import javax.usb.UsbControlIrp; -import javax.usb.UsbDevice; -import javax.usb.UsbDeviceDescriptor; -import javax.usb.UsbDisconnectedException; -import javax.usb.UsbException; -import javax.usb.UsbPort; -import javax.usb.UsbStringDescriptor; -import javax.usb.event.UsbDeviceEvent; -import javax.usb.event.UsbDeviceListener; -import javax.usb.util.DefaultUsbControlIrp; - -import org.usb4java.descriptors.SimpleUsbStringDescriptor; -import org.libusb4java.ConfigDescriptor; -import org.libusb4java.Device; -import org.libusb4java.DeviceHandle; -import org.libusb4java.LibUsb; - -/** - * A Usb device. - * - * @author Klaus Reimer (k@ailis.de) - */ -abstract class AbstractDevice implements UsbDevice -{ - /** The USB device manager. */ - private final DeviceManager manager; - - /** The device id. */ - private final DeviceId id; - - /** The parent id. Null if no parent exists. */ - private final DeviceId parentId; - - /** The device speed. */ - private final int speed; - - /** The device configurations. */ - private List configurations; - - /** Mapping from configuration value to configuration. */ - private Map configMapping = - new HashMap(); - - /** The USB device listener list. */ - private final DeviceListenerList listeners = new DeviceListenerList(); - - /** The device handle. Null if not open. */ - private DeviceHandle handle; - - /** The number of the currently active configuration. */ - private byte activeConfigurationNumber = 0; - - /** The number of the currently claimed interface. */ - private Byte claimedInterfaceNumber = null; - - /** The port this device is connected to. */ - private UsbPort port; - - /** The IRP queue. */ - private final ControlIrpQueue queue = new ControlIrpQueue(this, - this.listeners); - - /** If kernel driver was detached when interface was claimed. */ - private boolean detachedKernelDriver; - - /** - * Constructs a new device. - * - * @param manager - * The USB device manager which is responsible for this device. - * @param id - * The device id. Must not be null. - * @param parentId - * The parent device id. May be null if this device has no parent - * (Because it is a root device). - * @param speed - * The device speed. - * @param device - * The libusb device. This reference is only valid during the - * constructor execution, so don't store it in a property or - * something like that. - * @throws LibUsbException - * When device configuration could not be read. - */ - AbstractDevice(final DeviceManager manager, final DeviceId id, - final DeviceId parentId, final int speed, final Device device) - throws LibUsbException - { - if (manager == null) - throw new IllegalArgumentException("manager must be set"); - if (id == null) throw new IllegalArgumentException("id must be set"); - this.manager = manager; - this.id = id; - this.parentId = parentId; - this.speed = speed; - - // Read device configurations - final int numConfigurations = - id.getDeviceDescriptor().bNumConfigurations() & 0xff; - final List configurations = - new ArrayList(numConfigurations); - for (int i = 0; i < numConfigurations; i += 1) - { - final ConfigDescriptor configDescriptor = new ConfigDescriptor(); - final int result = LibUsb.getConfigDescriptor(device, (byte) i, - configDescriptor); - if (result < 0) - { - throw new LibUsbException("Unable to get configuation " + i - + " for device " + id, result); - } - try - { - final Configuration config = new Configuration( - this, configDescriptor); - configurations.add(config); - this.configMapping.put(configDescriptor.bConfigurationValue(), - config); - } - finally - { - LibUsb.freeConfigDescriptor(configDescriptor); - } - } - this.configurations = Collections.unmodifiableList(configurations); - - // Determine the active configuration number - final ConfigDescriptor configDescriptor = new ConfigDescriptor(); - final int result = - LibUsb.getActiveConfigDescriptor(device, configDescriptor); - - // ERROR_NOT_FOUND is returned when device is in unconfigured state. - // On OSX it may return INVALID_PARAM in this case because of a bug - // in libusb - if (result == LibUsb.ERROR_NOT_FOUND || - result == LibUsb.ERROR_INVALID_PARAM) - { - this.activeConfigurationNumber = 0; - } - else if (result < 0) - { - throw new LibUsbException( - "Unable to read active config descriptor from device " + id, - result); - } - else - { - this.activeConfigurationNumber = - configDescriptor.bConfigurationValue(); - LibUsb.freeConfigDescriptor(configDescriptor); - } - } - - /** - * Returns the device id. - * - * @return The device id. - */ - public final DeviceId getId() - { - return this.id; - } - - /** - * Returns the parent device id. - * - * @return The parent device id or null of there is no parent. - */ - public final DeviceId getParentId() - { - return this.parentId; - } - - /** - * Ensures the device is connected. - * - * @throws UsbDisconnectedException - * When device is disconnected. - */ - final void checkConnected() - { - if (this.port == null) throw new UsbDisconnectedException(); - } - - /** - * Opens the USB device and returns the USB device handle. If device was - * already open then the old handle is returned. - * - * @return The USB device handle. - * @throws UsbException - * When USB device could not be opened. - */ - public final DeviceHandle open() throws UsbException - { - if (this.handle == null) - { - final Device device = this.manager.getLibUsbDevice(this.id); - try - { - final DeviceHandle handle = new DeviceHandle(); - final int result = LibUsb.open(device, handle); - if (result < 0) - { - throw new LibUsbException("Can't open device " - + this.id, result); - } - this.handle = handle; - } - finally - { - this.manager.releaseDevice(device); - } - } - return this.handle; - } - - /** - * Closes the device. If device is not open then nothing is done. - */ - public final void close() - { - if (this.handle != null) - { - LibUsb.close(this.handle); - this.handle = null; - } - } - - @Override - public final UsbPort getParentUsbPort() - { - checkConnected(); - return this.port; - } - - /** - * Sets the parent USB port. If port is unset then a usbDeviceDetached event - * is send. - * - * @param port - * The port to set. Null to unset. - */ - final void setParentUsbPort(final UsbPort port) - { - if (this.port == null && port == null) - throw new IllegalStateException("Device already detached"); - if (this.port != null && port != null) - throw new IllegalStateException("Device already attached"); - - // Disconnect client devices - if (port == null && isUsbHub()) - { - final Hub hub = (Hub) this; - for (final AbstractDevice device: hub.getAttachedUsbDevices()) - { - hub.disconnectUsbDevice(device); - } - } - - this.port = port; - - final Services services = Services.getInstance(); - - if (port == null) - { - this.listeners.usbDeviceDetached(new UsbDeviceEvent(this)); - services.usbDeviceDetached(this); - } - else - { - services.usbDeviceAttached(this); - } - } - - @Override - public final String getManufacturerString() throws UsbException, - UnsupportedEncodingException - { - checkConnected(); - final byte index = getUsbDeviceDescriptor().iManufacturer(); - if (index == 0) return null; - return getString(index); - } - - @Override - public final String getSerialNumberString() throws UsbException, - UnsupportedEncodingException - { - checkConnected(); - final byte index = getUsbDeviceDescriptor().iSerialNumber(); - if (index == 0) return null; - return getString(index); - } - - @Override - public final String getProductString() throws UsbException, - UnsupportedEncodingException - { - checkConnected(); - final byte index = getUsbDeviceDescriptor().iProduct(); - if (index == 0) return null; - return getString(index); - } - - @Override - public final Object getSpeed() - { - switch (this.speed) - { - case LibUsb.SPEED_FULL: - return UsbConst.DEVICE_SPEED_FULL; - case LibUsb.SPEED_LOW: - return UsbConst.DEVICE_SPEED_LOW; - default: - return UsbConst.DEVICE_SPEED_UNKNOWN; - } - } - - @Override - public final List getUsbConfigurations() - { - return this.configurations; - } - - @Override - public final Configuration getUsbConfiguration(final byte number) - { - return this.configMapping.get(number); - } - - @Override - public final boolean containsUsbConfiguration(final byte number) - { - return this.configMapping.containsKey(number); - } - - @Override - public final byte getActiveUsbConfigurationNumber() - { - return this.activeConfigurationNumber; - } - - /** - * Sets the active USB configuration. - * - * @param number - * The number of the USB configuration to activate. - * @throws UsbException - * When configuration could not be activated. - */ - final void setActiveUsbConfigurationNumber(final byte number) - throws UsbException - { - if (number != this.activeConfigurationNumber) - { - if (this.claimedInterfaceNumber != null) - throw new UsbException("Can't change configuration while an " - + "interface is still claimed"); - - final int result = LibUsb.setConfiguration(open(), number & 0xff); - if (result < 0) - throw new LibUsbException("Unable to set configuration", - result); - this.activeConfigurationNumber = number; - } - } - - /** - * Claims the specified interface. - * - * @param number - * The number of the interface to claim. - * @param force - * If claim should be forces if possible. - * @throws UsbException - * When interface could not be claimed. - */ - final void claimInterface(final byte number, final boolean force) - throws UsbException - { - if (this.claimedInterfaceNumber != null) - throw new UsbClaimException("An interface is already claimed"); - - final DeviceHandle handle = open(); - - // Detach existing driver from the device if requested and - // libusb supports it. - if (force) - { - int result = LibUsb.kernelDriverActive(handle, number); - if (result == LibUsb.ERROR_NO_DEVICE) - throw new UsbDisconnectedException(); - if (result == 1) - { - result = LibUsb.detachKernelDriver(handle, number); - if (result < 0) - throw new LibUsbException( - "Unable to detach kernel driver", result); - this.detachedKernelDriver = true; - } - } - - final int result = LibUsb.claimInterface(handle, number & 0xff); - if (result < 0) - throw new LibUsbException("Unable to claim interface", - result); - this.claimedInterfaceNumber = number; - } - - /** - * Releases a claimed interface. - * - * @param number - * The number of the interface to release. - * @throws UsbException - * When interface could not be claimed. - */ - final void releaseInterface(final byte number) throws UsbException - { - if (this.claimedInterfaceNumber == null) - throw new UsbClaimException("No interface is claimed"); - if (!Byte.valueOf(number).equals(this.claimedInterfaceNumber)) - throw new UsbClaimException("Interface not claimed"); - - final DeviceHandle handle = open(); - int result = LibUsb.releaseInterface(handle, number & 0xff); - if (result < 0) throw new LibUsbException( - "Unable to release interface", result); - - if (this.detachedKernelDriver) - { - result = LibUsb.attachKernelDriver(handle, number & 0xff); - if (result < 0) throw new LibUsbException( - "Uanble to re-attach kernel driver", result); - } - - this.claimedInterfaceNumber = null; - } - - /** - * Checks if the specified interface is claimed. - * - * @param number - * The number of the interface to check. - * @return True if interface is claimed, false if not. - */ - final boolean isInterfaceClaimed(final byte number) - { - return Byte.valueOf(number).equals(this.claimedInterfaceNumber); - } - - @Override - public final Configuration getActiveUsbConfiguration() - { - return getUsbConfiguration(getActiveUsbConfigurationNumber()); - } - - @Override - public final boolean isConfigured() - { - return getActiveUsbConfigurationNumber() != 0; - } - - @Override - public final UsbDeviceDescriptor getUsbDeviceDescriptor() - { - return this.id.getDeviceDescriptor(); - } - - @Override - public final UsbStringDescriptor getUsbStringDescriptor(final byte index) - throws UsbException - { - checkConnected(); - final short[] languages = getLanguages(); - final DeviceHandle handle = open(); - final short langId = languages.length == 0 ? 0 : languages[0]; - final ByteBuffer data = ByteBuffer.allocateDirect(256); - final int result = - LibUsb.getStringDescriptor(handle, index, langId, data); - if (result < 0) - throw new LibUsbException("Unable to get string descriptor " - + index + " from device " + this, result); - return new SimpleUsbStringDescriptor(data); - } - - @Override - public final String getString(final byte index) throws UsbException, - UnsupportedEncodingException - { - return getUsbStringDescriptor(index).getString(); - } - - /** - * Returns the languages the specified device supports. - * - * @return Array with supported language codes. Never null. May be empty. - * @throws UsbException - * When string descriptor languages could not be read. - */ - private short[] getLanguages() throws UsbException - { - final DeviceHandle handle = open(); - final ByteBuffer buffer = ByteBuffer.allocateDirect(256); - final int result = LibUsb.getDescriptor(handle, LibUsb.DT_STRING, - (byte) 0, buffer); - if (result < 0) - throw new LibUsbException( - "Unable to get string descriptor languages", result); - if (result < 2) - throw new UsbException("Received illegal descriptor length: " - + result); - final short[] languages = new short[(result - 2) / 2]; - if (languages.length == 0) return languages; - buffer.position(2); - buffer.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(languages); - return languages; - } - - @Override - public final void syncSubmit(final UsbControlIrp irp) throws UsbException - { - if (irp == null) - throw new IllegalArgumentException("irp must not be null"); - checkConnected(); - this.queue.add(irp); - irp.waitUntilComplete(); - if (irp.isUsbException()) throw irp.getUsbException(); - } - - @Override - public final void asyncSubmit(final UsbControlIrp irp) - { - if (irp == null) - throw new IllegalArgumentException("irp must not be null"); - checkConnected(); - this.queue.add(irp); - } - - @Override - public final void syncSubmit(final List list) throws UsbException - { - if (list == null) - throw new IllegalArgumentException("list must not be null"); - checkConnected(); - for (final Object item: list) - { - if (!(item instanceof UsbControlIrp)) - throw new IllegalArgumentException( - "List contains non-UsbControlIrp objects"); - syncSubmit((UsbControlIrp) item); - } - } - - @Override - public final void asyncSubmit(final List list) - { - if (list == null) - throw new IllegalArgumentException("list must not be null"); - checkConnected(); - for (final Object item: list) - { - if (!(item instanceof UsbControlIrp)) - throw new IllegalArgumentException( - "List contains non-UsbControlIrp objects"); - asyncSubmit((UsbControlIrp) item); - } - } - - @Override - public final UsbControlIrp createUsbControlIrp(final byte bmRequestType, - final byte bRequest, final short wValue, final short wIndex) - { - return new DefaultUsbControlIrp(bmRequestType, bRequest, wValue, - wIndex); - } - - @Override - public final void addUsbDeviceListener(final UsbDeviceListener listener) - { - this.listeners.add(listener); - } - - @Override - public final void removeUsbDeviceListener(final UsbDeviceListener listener) - { - this.listeners.remove(listener); - } - - @Override - public final String toString() - { - return this.id.toString(); - } -} diff --git a/src/main/java/org/usb4java/AbstractIrpQueue.java b/src/main/java/org/usb4java/AbstractIrpQueue.java deleted file mode 100644 index 35643aa..0000000 --- a/src/main/java/org/usb4java/AbstractIrpQueue.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.nio.ByteBuffer; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -import javax.usb.UsbControlIrp; -import javax.usb.UsbException; -import javax.usb.UsbIrp; -import javax.usb.UsbShortPacketException; - -import org.libusb4java.DeviceHandle; -import org.libusb4java.LibUsb; - - -/** - * Abstract base class for IRP queues. - * - * @author Klaus Reimer (k@ailis.de) - * @param - * The type of IRPs this queue holds. - */ -abstract class AbstractIrpQueue -{ - /** The queued packets. */ - private final Queue irps = new ConcurrentLinkedQueue(); - - /** The queue processor thread. */ - private Thread processor; - - /** The USB device. */ - private final AbstractDevice device; - - /** - * Constructor. - * - * @param device - * The USB device. Must not be null. - */ - AbstractIrpQueue(final AbstractDevice device) - { - if (device == null) - throw new IllegalArgumentException("device must be set"); - this.device = device; - } - - /** - * Queues the specified control IRP for processing. - * - * @param irp - * The control IRP to queue. - */ - public final void add(final T irp) - { - this.irps.add(irp); - - // Start the queue processor if not already running. - if (this.processor == null) - { - this.processor = new Thread(new Runnable() - { - @Override - public void run() - { - process(); - } - }); - this.processor.setDaemon(true); - this.processor.start(); - } - } - - /** - * Processes the queue. Methods returns when the queue is empty. - */ - final void process() - { - // Get the next IRP - T irp = this.irps.poll(); - while (irp != null) - { - // Process the IRP - try - { - processIrp(irp); - } - catch (final UsbException e) - { - irp.setUsbException(e); - } - - // Get next IRP and mark the thread as closing before sending the - // events for the previous IRP - final T nextIrp = this.irps.poll(); - if (nextIrp == null) this.processor = null; - - // Finish the previous IRP - irp.complete(); - finishIrp(irp); - - // Process next IRP (if present) - irp = nextIrp; - } - - // No more IRPs are present in the queue so terminate the thread. - this.processor = null; - synchronized (this.irps) - { - this.irps.notifyAll(); - } - } - - /** - * Processes the IRP. - * - * @param irp - * The IRP to process. - * @throws UsbException - * When processing the IRP fails. - */ - protected abstract void processIrp(final T irp) throws UsbException; - - /** - * Called after IRP has finished. This can be implemented to send events for - * example. - * - * @param irp - * The IRP which has been finished. - */ - protected abstract void finishIrp(final UsbIrp irp); - - /** - * Aborts all queued IRPs. The IRP which is currently processed can't be - * aborted. This method returns as soon as no more IRPs are in the queue and - * no more are processed. - */ - public final void abort() - { - this.irps.clear(); - while (isBusy()) - { - try - { - synchronized (this.irps) - { - if (isBusy()) this.irps.wait(); - } - } - catch (final InterruptedException e) - { - Thread.currentThread().interrupt(); - } - } - } - - /** - * Checks if queue is busy. A busy queue is a queue which is currently - * processing IRPs or which still has IRPs in the queue. - * - * @return True if queue is busy, false if not. - */ - public final boolean isBusy() - { - return !this.irps.isEmpty() || this.processor != null; - } - - /** - * Returns the configuration. - * - * @return The configuration. - */ - protected final Config getConfig() - { - return Services.getInstance().getConfig(); - } - - /** - * Returns the USB device. - * - * @return The USB device. Never null. - */ - protected final AbstractDevice getDevice() - { - return this.device; - } - - /** - * Processes the control IRP. - * - * @param irp - * The IRP to process. - * @throws UsbException - * When processing the IRP fails. - */ - protected final void processControlIrp(final UsbControlIrp irp) - throws UsbException - { - final ByteBuffer buffer = - ByteBuffer.allocateDirect(irp.getLength()); - buffer.put(irp.getData(), irp.getOffset(), irp.getLength()); - buffer.rewind(); - final DeviceHandle handle = getDevice().open(); - final int result = LibUsb.controlTransfer(handle, irp.bmRequestType(), - irp.bRequest(), irp.wValue(), irp.wIndex(), buffer, - getConfig().getTimeout()); - if (result < 0) - { - throw new LibUsbException( - "Unable to submit control message", result); - } - buffer.rewind(); - buffer.get(irp.getData(), irp.getOffset(), result); - irp.setActualLength(result); - if (irp.getActualLength() != irp.getLength() - && !irp.getAcceptShortPacket()) - { - throw new UsbShortPacketException(); - } - } -} diff --git a/src/main/java/org/libusb4java/BosDescriptor.java b/src/main/java/org/usb4java/BosDescriptor.java similarity index 99% rename from src/main/java/org/libusb4java/BosDescriptor.java rename to src/main/java/org/usb4java/BosDescriptor.java index 2d03e1c..7c8a1c8 100644 --- a/src/main/java/org/libusb4java/BosDescriptor.java +++ b/src/main/java/org/usb4java/BosDescriptor.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; diff --git a/src/main/java/org/libusb4java/BosDevCapabilityDescriptor.java b/src/main/java/org/usb4java/BosDevCapabilityDescriptor.java similarity index 98% rename from src/main/java/org/libusb4java/BosDevCapabilityDescriptor.java rename to src/main/java/org/usb4java/BosDevCapabilityDescriptor.java index 263e918..8dc6f19 100644 --- a/src/main/java/org/libusb4java/BosDevCapabilityDescriptor.java +++ b/src/main/java/org/usb4java/BosDevCapabilityDescriptor.java @@ -16,14 +16,13 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; - -import org.libusb4java.utils.DescriptorUtils; +import org.usb4java.utils.DescriptorUtils; /** * A generic representation of a BOS Device Capability descriptor. diff --git a/src/main/java/org/usb4java/Config.java b/src/main/java/org/usb4java/Config.java deleted file mode 100644 index 4f571cf..0000000 --- a/src/main/java/org/usb4java/Config.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.Properties; - -/** - * Configuration. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Config -{ - /** Base key name for properties. */ - private static final String KEY_BASE = "org.usb4java."; - - /** The default USB communication timeout in milliseconds. */ - private static final int DEFAULT_TIMEOUT = 2500; - - /** The default scan interval in milliseconds. */ - private static final int DEFAULT_SCAN_INTERVAL = 500; - - /** Key name for USB communication timeout. */ - private static final String TIMEOUT_KEY = KEY_BASE + "timeout"; - - /** Key name for USB communication timeout. */ - private static final String SCAN_INTERVAL_KEY = KEY_BASE + "scanInterval"; - - /** The timeout for USB communication in milliseconds. */ - private int timeout = DEFAULT_TIMEOUT; - - /** The scan interval in milliseconds. */ - private int scanInterval = DEFAULT_SCAN_INTERVAL; - - /** - * Constructs new configuration from the specified properties. - * - * @param properties - * The properties to read the configuration from. - */ - Config(final Properties properties) - { - // Read the USB communication timeout - if (properties.containsKey(TIMEOUT_KEY)) - { - this.timeout = Integer.valueOf(properties.getProperty(TIMEOUT_KEY)); - } - - // Read the USB device scan interval - if (properties.containsKey(SCAN_INTERVAL_KEY)) - { - this.scanInterval = Integer.valueOf(properties.getProperty( - SCAN_INTERVAL_KEY)); - } - } - - /** - * Returns the USB communication timeout in milliseconds. - * - * @return The USB communication timeout in milliseconds. - */ - public int getTimeout() - { - return this.timeout; - } - - /** - * Returns the scan interval in milliseconds. - * - * @return The scan interval in milliseconds. - */ - public int getScanInterval() - { - return this.scanInterval; - } -} diff --git a/src/main/java/org/libusb4java/ConfigDescriptor.java b/src/main/java/org/usb4java/ConfigDescriptor.java similarity index 98% rename from src/main/java/org/libusb4java/ConfigDescriptor.java rename to src/main/java/org/usb4java/ConfigDescriptor.java index 433c39d..8ccb409 100644 --- a/src/main/java/org/libusb4java/ConfigDescriptor.java +++ b/src/main/java/org/usb4java/ConfigDescriptor.java @@ -16,13 +16,13 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.utils.DescriptorUtils; +import org.usb4java.utils.DescriptorUtils; /** * A structure representing the standard USB configuration descriptor. diff --git a/src/main/java/org/usb4java/Configuration.java b/src/main/java/org/usb4java/Configuration.java deleted file mode 100644 index d6cbf96..0000000 --- a/src/main/java/org/usb4java/Configuration.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.usb.UsbConfiguration; -import javax.usb.UsbConfigurationDescriptor; -import javax.usb.UsbDisconnectedException; -import javax.usb.UsbException; - -import org.usb4java.descriptors.SimpleUsbConfigurationDescriptor; -import org.libusb4java.ConfigDescriptor; -import org.libusb4java.InterfaceDescriptor; -import org.libusb4java.LibUsb; - -/** - * usb4java implementation of JSR-80 UsbConfiguration. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Configuration implements UsbConfiguration -{ - /** The configurationDescriptor. */ - private final UsbConfigurationDescriptor descriptor; - - /** The USB device this configuration belongs to. */ - private final AbstractDevice device; - - /** - * The interfaces. This is a map from interface number to a map of alternate - * settings which maps setting numbers to actual interfaces. - */ - private final Map> interfaces = - new HashMap>(); - - /** This map contains the active USB interfaces. */ - private final Map activeSettings = - new HashMap(); - - /** - * Constructor. - * - * @param device - * The device this configuration belongs to. - * @param descriptor - * The libusb configuration descriptor. - */ - Configuration(final AbstractDevice device, - final ConfigDescriptor descriptor) - { - this.device = device; - this.descriptor = new SimpleUsbConfigurationDescriptor(descriptor); - for (org.libusb4java.Interface iface: descriptor.iface()) - { - for (InterfaceDescriptor ifaceDescriptor: iface.altsetting()) - { - final int ifaceNumber = - ifaceDescriptor.bInterfaceNumber() & 0xff; - final int settingNumber = - ifaceDescriptor.bAlternateSetting() & 0xff; - - Map settings = this.interfaces - .get(ifaceNumber); - if (settings == null) - { - settings = new HashMap(); - this.interfaces.put(ifaceNumber, settings); - } - final Interface usbInterface = - new Interface(this, ifaceDescriptor); - - // If we have no active setting for current interface number - // yet or the alternate setting number is 0 (which marks the - // default alternate setting) then set current interface as - // the active setting. - if (!this.activeSettings.containsKey(ifaceNumber) - || ifaceDescriptor.bAlternateSetting() == 0) - { - this.activeSettings.put(ifaceNumber, usbInterface); - } - - // Add the interface to the settings list - settings.put(settingNumber, usbInterface); - } - } - } - - /** - * Ensures that the device is connected. - * - * @throws UsbDisconnectedException - * When device has been disconnected. - */ - private void checkConnected() - { - this.device.checkConnected(); - } - - @Override - public boolean isActive() - { - return this.device.getActiveUsbConfigurationNumber() == this.descriptor - .bConfigurationValue(); - } - - @Override - public List getUsbInterfaces() - { - return Collections.unmodifiableList(new ArrayList( - this.activeSettings.values())); - } - - /** - * Returns the alternate settings for the specified interface. - * - * @param number - * The interface number. - * @return The alternate settings for the specified interface. - */ - Map getSettings(final byte number) - { - return this.interfaces.get(number & 0xff); - } - - /** - * Returns the number of alternate settings of the specified interface. - * - * @param number - * The interface number. - * @return The number of alternate settings. - */ - int getNumSettings(final byte number) - { - return this.interfaces.get(number & 0xff).size(); - } - - @Override - public Interface getUsbInterface(final byte number) - { - return this.activeSettings.get(number & 0xff); - } - - /** - * Sets the active USB interface setting. - * - * @param number - * THe interface number. - * @param iface - * The interface setting to activate. - * @throws UsbException - * When interface setting could not be set. - */ - void setUsbInterface(final byte number, final Interface iface) - throws UsbException - { - if (this.activeSettings.get(number & 0xff) != iface) - { - final int result = LibUsb.setInterfaceAltSetting( - this.device.open(), number, - iface.getUsbInterfaceDescriptor().bAlternateSetting()); - if (result < 0) - { - throw new LibUsbException( - "Unable to set alternate interface", result); - } - this.activeSettings.put(number & 0xff, iface); - } - } - - @Override - public boolean containsUsbInterface(final byte number) - { - return this.activeSettings.containsKey(number & 0xff); - } - - @Override - public AbstractDevice getUsbDevice() - { - return this.device; - } - - @Override - public UsbConfigurationDescriptor getUsbConfigurationDescriptor() - { - return this.descriptor; - } - - @Override - public String getConfigurationString() throws UsbException, - UnsupportedEncodingException - { - checkConnected(); - final byte iConfiguration = this.descriptor.iConfiguration(); - if (iConfiguration == 0) return null; - return this.device.getString(iConfiguration); - } - - @Override - public String toString() - { - return String.format("USB configuration %02x", - this.descriptor.bConfigurationValue()); - } -} diff --git a/src/main/java/org/libusb4java/ContainerIdDescriptor.java b/src/main/java/org/usb4java/ContainerIdDescriptor.java similarity index 98% rename from src/main/java/org/libusb4java/ContainerIdDescriptor.java rename to src/main/java/org/usb4java/ContainerIdDescriptor.java index 951de04..5b9f4ef 100644 --- a/src/main/java/org/libusb4java/ContainerIdDescriptor.java +++ b/src/main/java/org/usb4java/ContainerIdDescriptor.java @@ -16,14 +16,13 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; - -import org.libusb4java.utils.DescriptorUtils; +import org.usb4java.utils.DescriptorUtils; /** * A structure representing the Container ID descriptor. diff --git a/src/main/java/org/libusb4java/Context.java b/src/main/java/org/usb4java/Context.java similarity index 99% rename from src/main/java/org/libusb4java/Context.java rename to src/main/java/org/usb4java/Context.java index d25886e..8f1fd96 100644 --- a/src/main/java/org/libusb4java/Context.java +++ b/src/main/java/org/usb4java/Context.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; /** * Structure representing a libusb session. The concept of individual libusb diff --git a/src/main/java/org/usb4java/ControlIrpQueue.java b/src/main/java/org/usb4java/ControlIrpQueue.java deleted file mode 100644 index a093b29..0000000 --- a/src/main/java/org/usb4java/ControlIrpQueue.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.UsbControlIrp; -import javax.usb.UsbException; -import javax.usb.UsbIrp; -import javax.usb.event.UsbDeviceDataEvent; - -/** - * A queue for USB control I/O request packets. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class ControlIrpQueue extends AbstractIrpQueue -{ - /** The USB device listener list. */ - private final DeviceListenerList listeners; - - /** - * Constructor. - * - * @param device - * The USB device. - * @param listeners - * The USB device listener list. - */ - ControlIrpQueue(final AbstractDevice device, - final DeviceListenerList listeners) - { - super(device); - this.listeners = listeners; - } - - @Override - protected void processIrp(final UsbControlIrp irp) throws UsbException - { - processControlIrp(irp); - } - - @Override - protected void finishIrp(final UsbIrp irp) - { - this.listeners.dataEventOccurred(new UsbDeviceDataEvent( - getDevice(), (UsbControlIrp) irp)); - } -} diff --git a/src/main/java/org/libusb4java/ControlSetup.java b/src/main/java/org/usb4java/ControlSetup.java similarity index 98% rename from src/main/java/org/libusb4java/ControlSetup.java rename to src/main/java/org/usb4java/ControlSetup.java index d7324b5..c7a798d 100644 --- a/src/main/java/org/libusb4java/ControlSetup.java +++ b/src/main/java/org/usb4java/ControlSetup.java @@ -16,12 +16,12 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import org.libusb4java.utils.BufferUtils; +import org.usb4java.utils.BufferUtils; /** * Setup packet for control transfers. diff --git a/src/main/java/org/libusb4java/Device.java b/src/main/java/org/usb4java/Device.java similarity index 99% rename from src/main/java/org/libusb4java/Device.java rename to src/main/java/org/usb4java/Device.java index 397820c..1d21913 100644 --- a/src/main/java/org/libusb4java/Device.java +++ b/src/main/java/org/usb4java/Device.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; /** * Structure representing a USB device detected on the system. diff --git a/src/main/java/org/libusb4java/DeviceDescriptor.java b/src/main/java/org/usb4java/DeviceDescriptor.java similarity index 98% rename from src/main/java/org/libusb4java/DeviceDescriptor.java rename to src/main/java/org/usb4java/DeviceDescriptor.java index c087006..0764ffd 100644 --- a/src/main/java/org/libusb4java/DeviceDescriptor.java +++ b/src/main/java/org/usb4java/DeviceDescriptor.java @@ -16,14 +16,14 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.utils.BufferUtils; -import org.libusb4java.utils.DescriptorUtils; +import org.usb4java.utils.BufferUtils; +import org.usb4java.utils.DescriptorUtils; /** * A structure representing the standard USB device descriptor. diff --git a/src/main/java/org/libusb4java/DeviceHandle.java b/src/main/java/org/usb4java/DeviceHandle.java similarity index 99% rename from src/main/java/org/libusb4java/DeviceHandle.java rename to src/main/java/org/usb4java/DeviceHandle.java index 3715809..f13cbe5 100644 --- a/src/main/java/org/libusb4java/DeviceHandle.java +++ b/src/main/java/org/usb4java/DeviceHandle.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; /** * Structure representing a handle on a USB device. diff --git a/src/main/java/org/usb4java/DeviceId.java b/src/main/java/org/usb4java/DeviceId.java deleted file mode 100644 index 3bad2a9..0000000 --- a/src/main/java/org/usb4java/DeviceId.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.io.Serializable; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import org.usb4java.descriptors.SimpleUsbDeviceDescriptor; - -/** - * Unique USB device ID. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class DeviceId implements Serializable -{ - /** The serial versionUID. */ - private static final long serialVersionUID = 1L; - - /** The bus number. */ - private final int busNumber; - - /** The device address. */ - private final int deviceAddress; - - /** The port this device is connected to. 0 if unknown. */ - private final int portNumber; - - /** The device descriptor. */ - private final SimpleUsbDeviceDescriptor deviceDescriptor; - - /** - * Constructs a new device id. - * - * @param busNumber - * The number of the bus the device is connected to. - * @param deviceAddress - * The address of the device. - * @param portNumber - * The number of the port the device is connected to. 0 if - * unknown. - * @param deviceDescriptor - * The device descriptor. Must not be null. - */ - DeviceId(final int busNumber, final int deviceAddress, - final int portNumber, final SimpleUsbDeviceDescriptor deviceDescriptor) - { - if (deviceDescriptor == null) - throw new IllegalArgumentException("deviceDescriptor must be set"); - this.busNumber = busNumber; - this.portNumber = portNumber; - this.deviceAddress = deviceAddress; - this.deviceDescriptor = deviceDescriptor; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(this.busNumber) - .append(this.deviceAddress) - .append(this.portNumber) - .append(this.deviceDescriptor) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final DeviceId other = (DeviceId) obj; - return new EqualsBuilder() - .append(this.busNumber, other.busNumber) - .append(this.deviceAddress, other.deviceAddress) - .append(this.portNumber, other.portNumber) - .append(this.deviceDescriptor, other.deviceDescriptor) - .isEquals(); - } - - /** - * Returns the bus number. - * - * @return The bus number. - */ - public int getBusNumber() - { - return this.busNumber; - } - - /** - * Returns the device address. - * - * @return The device address. - */ - public int getDeviceAddress() - { - return this.deviceAddress; - } - - /** - * Returns the number of the port the device is connected to. - * - * @return The port number or 0 if unknown. - */ - public int getPortNumber() - { - return this.portNumber; - } - - /** - * Returns the device descriptor. - * - * @return The device descriptor. Never null. - */ - public SimpleUsbDeviceDescriptor getDeviceDescriptor() - { - return this.deviceDescriptor; - } - - @Override - public String toString() - { - return String.format("Bus %03d Device %03d: ID %04x:%04x", - this.busNumber, this.deviceAddress, - this.deviceDescriptor.idVendor(), - this.deviceDescriptor.idProduct()); - } - - /** - * Checks if the specified two device IDs are equal. They are also equal if - * they are both null. - * - * @param a - * The first device ID. - * @param b - * The second device ID. - * @return True if the device IDs are equal, false if not. - */ - public static boolean equals(final DeviceId a, final DeviceId b) - { - if (a == null && b == null) return true; - if (a == null || b == null) return false; - return a.equals(b); - } -} diff --git a/src/main/java/org/libusb4java/DeviceList.java b/src/main/java/org/usb4java/DeviceList.java similarity index 99% rename from src/main/java/org/libusb4java/DeviceList.java rename to src/main/java/org/usb4java/DeviceList.java index 8408442..df21e95 100644 --- a/src/main/java/org/libusb4java/DeviceList.java +++ b/src/main/java/org/usb4java/DeviceList.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.util.Iterator; diff --git a/src/main/java/org/libusb4java/DeviceListIterator.java b/src/main/java/org/usb4java/DeviceListIterator.java similarity index 97% rename from src/main/java/org/libusb4java/DeviceListIterator.java rename to src/main/java/org/usb4java/DeviceListIterator.java index 09aa427..46c6e76 100644 --- a/src/main/java/org/libusb4java/DeviceListIterator.java +++ b/src/main/java/org/usb4java/DeviceListIterator.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import java.util.Iterator; diff --git a/src/main/java/org/usb4java/DeviceListenerList.java b/src/main/java/org/usb4java/DeviceListenerList.java deleted file mode 100644 index 75a7fb1..0000000 --- a/src/main/java/org/usb4java/DeviceListenerList.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.event.UsbDeviceDataEvent; -import javax.usb.event.UsbDeviceErrorEvent; -import javax.usb.event.UsbDeviceEvent; -import javax.usb.event.UsbDeviceListener; - -/** - * USB device listener list. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class DeviceListenerList extends - EventListenerList implements UsbDeviceListener -{ - /** - * Constructs a new USB device listener list. - */ - DeviceListenerList() - { - super(); - } - - @Override - public UsbDeviceListener[] toArray() - { - return getListeners().toArray( - new UsbDeviceListener[getListeners().size()]); - } - - @Override - public void usbDeviceDetached(final UsbDeviceEvent event) - { - for (final UsbDeviceListener listener: toArray()) - { - listener.usbDeviceDetached(event); - } - } - - @Override - public void errorEventOccurred(final UsbDeviceErrorEvent event) - { - for (final UsbDeviceListener listener: toArray()) - { - listener.errorEventOccurred(event); - } - } - - @Override - public void dataEventOccurred(final UsbDeviceDataEvent event) - { - for (final UsbDeviceListener listener: toArray()) - { - listener.dataEventOccurred(event); - } - } -} diff --git a/src/main/java/org/usb4java/DeviceManager.java b/src/main/java/org/usb4java/DeviceManager.java deleted file mode 100644 index b4586ad..0000000 --- a/src/main/java/org/usb4java/DeviceManager.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.usb.UsbException; -import javax.usb.UsbHub; - -import org.usb4java.descriptors.SimpleUsbDeviceDescriptor; -import org.libusb4java.Context; -import org.libusb4java.Device; -import org.libusb4java.DeviceDescriptor; -import org.libusb4java.DeviceList; -import org.libusb4java.LibUsb; - -/** - * Manages the USB devices. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class DeviceManager -{ - /** The virtual USB root hub. */ - private final RootHub rootHub; - - /** The libusb context. */ - private final Context context; - - /** If scanner already scanned for devices. */ - private boolean scanned = false; - - /** The scan interval in milliseconds. */ - private final int scanInterval; - - /** The currently connected devices. */ - private final Map devices = Collections - .synchronizedMap(new HashMap()); - - /** - * Constructs a new device manager. - * - * @param rootHub - * The root hub. Must not be null. - * @param scanInterval - * The scan interval in milliseconds. - * @throws UsbException - * When USB initialization fails. - */ - DeviceManager(final RootHub rootHub, final int scanInterval) - throws UsbException - { - if (rootHub == null) - throw new IllegalArgumentException("rootHub must be set"); - this.scanInterval = scanInterval; - this.rootHub = rootHub; - this.context = new Context(); - final int result = LibUsb.init(this.context); - if (result != 0) - throw new LibUsbException("Unable to initialize libusb", result); - } - - /** - * Dispose the USB device manager. This exits the USB context opened by the - * constructor. - */ - public void dispose() - { - LibUsb.exit(this.context); - } - - /** - * Creates a device ID from the specified device. - * - * @param device - * The libusb device. Must not be null. - * @return The device id. - * @throws LibUsbException - * When device descriptor could not be read from the specified - * device. - */ - private DeviceId createId(final Device device) throws LibUsbException - { - if (device == null) - throw new IllegalArgumentException("device must be set"); - final int busNumber = LibUsb.getBusNumber(device); - final int addressNumber = LibUsb.getDeviceAddress(device); - final int portNumber = LibUsb.getPortNumber(device); - final DeviceDescriptor deviceDescriptor = new DeviceDescriptor(); - final int result = LibUsb.getDeviceDescriptor(device, deviceDescriptor); - if (result < 0) - { - throw new LibUsbException( - "Unable to get device descriptor for device " + addressNumber - + " at bus " + busNumber, result); - } - return new DeviceId(busNumber, addressNumber, portNumber, - new SimpleUsbDeviceDescriptor(deviceDescriptor)); - } - - /** - * Scans the specified ports for removed devices. - * - * @param ports - * The ports to scan for removals. - */ - private void scanRemovedDevices(final UsbPorts ports) - { - for (AbstractDevice device: ports.getAttachedUsbDevices()) - { - // Scan for removed child devices if current device is a hub - if (device.isUsbHub()) scanRemovedDevices((Hub) device); - - // If device is no longer present then remove it - if (!this.devices.containsKey(device.getId())) - ports.disconnectUsbDevice(device); - } - } - - /** - * Scans the specified ports for new devices. - * - * @param ports - * The ports to scan for new devices. - * @param hubId - * The hub ID. Null if scanned hub is the root hub. - */ - private void scanNewDevices(final UsbPorts ports, - final DeviceId hubId) - { - for (AbstractDevice device: this.devices.values()) - { - // Get parent ID from device and reset it to null if we don't - // know this parent device (This happens on Windows because some - // devices/hubs can't be fully enumerated.) - DeviceId parentId = device.getParentId(); - if (!this.devices.containsKey(parentId)) parentId = null; - - if (DeviceId.equals(parentId, hubId)) - { - if (!ports.isUsbDeviceAttached(device)) - { - // Connect new devices to the ports of the current hub. - ports.connectUsbDevice(device); - } - - // Scan for removed child devices if current device is a hub - if (device.isUsbHub()) scanNewDevices((Hub) device, - device.getId()); - } - } - - } - - /** - * Scans the specified hub for changes. - * - * @param hub - * The hub to scan. - */ - public void scan(final UsbHub hub) - { - try - { - updateDeviceList(); - } - catch (LibUsbException e) - { - throw new ScanException("Unable to scan for USB devices: " + e, e); - } - - if (hub.isRootUsbHub()) - { - final RootHub rootHub = (RootHub) hub; - scanRemovedDevices(rootHub); - scanNewDevices(rootHub, null); - } - else - { - final Hub nonRootHub = (Hub) hub; - scanRemovedDevices(nonRootHub); - scanNewDevices(nonRootHub, nonRootHub.getId()); - } - } - - /** - * Updates the device list by adding newly connected devices to it and by - * removing no longer connected devices. - * - * @throws LibUsbException - * When libusb reported an error which we can't ignore during - * scan. - */ - private void updateDeviceList() throws LibUsbException - { - final List current = new ArrayList(); - - // Get device list from libusb and abort if it failed - final DeviceList devices = new DeviceList(); - final int result = LibUsb.getDeviceList(this.context, devices); - if (result < 0) - throw new LibUsbException("Unable to get USB device list", - result); - - try - { - // Iterate over all currently connected devices - for (final Device libUsbDevice: devices) - { - try - { - final DeviceId id = createId(libUsbDevice); - - AbstractDevice device = this.devices.get(id); - if (device == null) - { - final Device parent = LibUsb.getParent(libUsbDevice); - final DeviceId parentId = parent == null ? null : - createId(parent); - final int speed = LibUsb.getDeviceSpeed(libUsbDevice); - final boolean isHub = id.getDeviceDescriptor() - .bDeviceClass() == LibUsb.CLASS_HUB; - if (isHub) - { - device = new Hub(this, id, parentId, - speed, libUsbDevice); - } - else - { - device = new NonHub(this, id, - parentId, speed, libUsbDevice); - } - - // Add new device to global device list. - this.devices.put(id, device); - } - - // Remember current device as "current" - current.add(id); - } - catch (LibUsbException e) - { - // Devices which can't be enumerated are ignored - continue; - } - } - - this.devices.keySet().retainAll(current); - } - finally - { - LibUsb.freeDeviceList(devices, true); - } - } - - /** - * Scans the USB busses for new or removed devices. - */ - public synchronized void scan() - { - scan(this.rootHub); - this.scanned = true; - } - - /** - * Returns the libusb device for the specified id. The device must be freed - * after use. - * - * @param id - * The id of the device to return. Must not be null. - * @return device The libusb device. Never null. - * @throws DeviceNotFoundException - * When the device was not found. - * @throws LibUsbException - * When libusb reported an error while enumerating USB devices. - */ - public Device getLibUsbDevice(final DeviceId id) throws LibUsbException - { - if (id == null) throw new IllegalArgumentException("id must be set"); - - final DeviceList devices = new DeviceList(); - final int result = LibUsb.getDeviceList(this.context, devices); - if (result < 0) - throw new LibUsbException("Unable to get USB device list", - result); - try - { - for (Device device: devices) - { - try - { - if (id.equals(createId(device))) - { - LibUsb.refDevice(device); - return device; - } - } - catch (LibUsbException e) - { - // Devices for which no ID can be created are ignored - continue; - } - } - } - finally - { - LibUsb.freeDeviceList(devices, true); - } - - throw new DeviceNotFoundException(id); - } - - /** - * Releases the specified device. - * - * @param device - * The device to release. Must not be null. - */ - public void releaseDevice(final Device device) - { - if (device == null) - throw new IllegalArgumentException("device must be set"); - LibUsb.unrefDevice(device); - } - - /** - * Starts scanning in the background. - */ - public void start() - { - // Do not start the scan thread when interval is set to 0 - final int scanInterval = this.scanInterval; - if (scanInterval == 0) return; - - final Thread thread = new Thread(new Runnable() - { - @Override - public void run() - { - while (true) - { - try - { - Thread.sleep(scanInterval); - } - catch (final InterruptedException e) - { - Thread.currentThread().interrupt(); - } - scan(); - } - } - }); - thread.setDaemon(true); - thread.start(); - } - - /** - * Scans for devices but only if this was not already done. - */ - public void firstScan() - { - if (!this.scanned) scan(); - } -} diff --git a/src/main/java/org/usb4java/DeviceNotFoundException.java b/src/main/java/org/usb4java/DeviceNotFoundException.java deleted file mode 100644 index 6597ac4..0000000 --- a/src/main/java/org/usb4java/DeviceNotFoundException.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -/** - * Thrown when a USB device was not found by id. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class DeviceNotFoundException extends RuntimeException -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The device id. */ - private final DeviceId id; - - /** - * Constructor. - * - * @param id - * The ID of the device which was not found. - */ - DeviceNotFoundException(final DeviceId id) - { - super("USB Device not found: " + id); - this.id = id; - } - - /** - * Returns the device id. - * - * @return The device id. - */ - public DeviceId getId() - { - return this.id; - } -} diff --git a/src/main/java/org/usb4java/Endpoint.java b/src/main/java/org/usb4java/Endpoint.java deleted file mode 100644 index 1118e01..0000000 --- a/src/main/java/org/usb4java/Endpoint.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.UsbConst; -import javax.usb.UsbEndpoint; -import javax.usb.UsbEndpointDescriptor; -import javax.usb.UsbPipe; - -import org.usb4java.descriptors.SimpleUsbEndpointDescriptor; -import org.libusb4java.EndpointDescriptor; - -/** - * usb4java implementation of UsbEndpoint. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Endpoint implements UsbEndpoint -{ - /** The interface this endpoint belongs to. */ - private final Interface iface; - - /** The endpoint descriptor. */ - private final UsbEndpointDescriptor descriptor; - - /** The USB pipe for this endpoint. */ - private final Pipe pipe; - - /** - * Constructor. - * - * @param iface - * The interface this endpoint belongs to. - * @param descriptor - * The libusb endpoint descriptor. - */ - Endpoint(final Interface iface, - final EndpointDescriptor descriptor) - { - this.iface = iface; - this.descriptor = new SimpleUsbEndpointDescriptor(descriptor); - this.pipe = new Pipe(this); - } - - @Override - public Interface getUsbInterface() - { - return this.iface; - } - - @Override - public UsbEndpointDescriptor getUsbEndpointDescriptor() - { - return this.descriptor; - } - - @Override - public byte getDirection() - { - final byte address = this.descriptor.bEndpointAddress(); - return (byte) (address & UsbConst.ENDPOINT_DIRECTION_MASK); - } - - @Override - public byte getType() - { - final byte attribs = this.descriptor.bmAttributes(); - return (byte) (attribs & UsbConst.ENDPOINT_TYPE_MASK); - } - - @Override - public UsbPipe getUsbPipe() - { - return this.pipe; - } -} diff --git a/src/main/java/org/libusb4java/EndpointDescriptor.java b/src/main/java/org/usb4java/EndpointDescriptor.java similarity index 98% rename from src/main/java/org/libusb4java/EndpointDescriptor.java rename to src/main/java/org/usb4java/EndpointDescriptor.java index e417015..072c7c0 100644 --- a/src/main/java/org/libusb4java/EndpointDescriptor.java +++ b/src/main/java/org/usb4java/EndpointDescriptor.java @@ -16,13 +16,13 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.utils.DescriptorUtils; +import org.usb4java.utils.DescriptorUtils; /** * A structure representing the standard USB endpoint descriptor. diff --git a/src/main/java/org/usb4java/EventListenerList.java b/src/main/java/org/usb4java/EventListenerList.java deleted file mode 100644 index fe599d8..0000000 --- a/src/main/java/org/usb4java/EventListenerList.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EventListener; -import java.util.List; - -/** - * Base class for event listener lists. - * - * @author Klaus Reimer (k@ailis.de) - * @param - * The event listener type. - */ -abstract class EventListenerList -{ - /** The list with registered listeners. */ - private final List listeners = Collections - .synchronizedList(new ArrayList()); - - /** - * Adds a listener. - * - * @param listener - * The listener to add. - */ - public final void add(final T listener) - { - if (this.listeners.contains(listener)) return; - this.listeners.add(listener); - } - - /** - * Removes a listener. - * - * @param listener - * The listener to remove. - */ - public final void remove(final T listener) - { - this.listeners.remove(listener); - } - - /** - * Removes all registered listeners. - */ - public final void clear() - { - this.listeners.clear(); - } - - /** - * Returns an array with the currently registered listeners. The returned - * array is detached from the internal list of registered listeners. - * - * @return Array with registered listeners. - */ - public abstract T[] toArray(); - - /** - * Returns the listeners list. - * - * @return The listeners list. - */ - protected final List getListeners() - { - return this.listeners; - } -} diff --git a/src/main/java/org/libusb4java/HotplugCallback.java b/src/main/java/org/usb4java/HotplugCallback.java similarity index 98% rename from src/main/java/org/libusb4java/HotplugCallback.java rename to src/main/java/org/usb4java/HotplugCallback.java index 23ad164..ca99b8c 100644 --- a/src/main/java/org/libusb4java/HotplugCallback.java +++ b/src/main/java/org/usb4java/HotplugCallback.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; /** * Hotplug callback.. diff --git a/src/main/java/org/libusb4java/HotplugCallbackHandle.java b/src/main/java/org/usb4java/HotplugCallbackHandle.java similarity index 99% rename from src/main/java/org/libusb4java/HotplugCallbackHandle.java rename to src/main/java/org/usb4java/HotplugCallbackHandle.java index 4ffdbd0..d6ab390 100644 --- a/src/main/java/org/libusb4java/HotplugCallbackHandle.java +++ b/src/main/java/org/usb4java/HotplugCallbackHandle.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; /** * Hotplug Callback Handle. diff --git a/src/main/java/org/usb4java/Hub.java b/src/main/java/org/usb4java/Hub.java deleted file mode 100644 index bab2637..0000000 --- a/src/main/java/org/usb4java/Hub.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.List; - -import javax.usb.UsbHub; - -import org.libusb4java.Device; - -/** - * usb4java implementation of JSR-80 UsbHub. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Hub extends AbstractDevice implements UsbHub, - UsbPorts -{ - /** The hub ports. */ - private final Ports ports = new Ports(this); - - /** - * Constructs a new USB hub device. - * - * @param manager - * The USB device manager which is responsible for this device. - * @param id - * THe device id. Must not be null. - * @param parentId - * The parent id. may be null if this device has no parent. - * @param speed - * The device speed. - * @param device - * The libusb device. This reference is only valid during the - * constructor execution, so don't store it in a property or - * something like that. - * @throws LibUsbException - * When device configuration could not be read. - */ - Hub(final DeviceManager manager, final DeviceId id, - final DeviceId parentId, final int speed, final Device device) - throws LibUsbException - { - super(manager, id, parentId, speed, device); - } - - @Override - public byte getNumberOfPorts() - { - return this.ports.getNumberOfPorts(); - } - - @Override - public List getUsbPorts() - { - return this.ports.getUsbPorts(); - } - - @Override - public Port getUsbPort(final byte number) - { - return this.ports.getUsbPort(number); - } - - @Override - public List getAttachedUsbDevices() - { - return this.ports.getAttachedUsbDevices(); - } - - @Override - public boolean isUsbDeviceAttached(final AbstractDevice device) - { - return this.ports.isUsbDeviceAttached(device); - } - - @Override - public boolean isRootUsbHub() - { - return false; - } - - @Override - public void connectUsbDevice(final AbstractDevice device) - { - this.ports.connectUsbDevice(device); - } - - @Override - public void disconnectUsbDevice(final AbstractDevice device) - { - this.ports.disconnectUsbDevice(device); - } - - @Override - public int hashCode() - { - return getId().hashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final AbstractDevice other = (AbstractDevice) obj; - return getId().equals(other.getId()); - } - - @Override - public boolean isUsbHub() - { - return true; - } -} diff --git a/src/main/java/org/usb4java/Interface.java b/src/main/java/org/usb4java/Interface.java index 8c0dbfc..f242dfa 100644 --- a/src/main/java/org/usb4java/Interface.java +++ b/src/main/java/org/usb4java/Interface.java @@ -1,224 +1,128 @@ /* - * Copyright (C) 2011 Klaus Reimer + * Copyright 2013 Klaus Reimer * See LICENSE.md for licensing information. + * + * Based on libusb : + * + * Copyright 2001 Johannes Erdfelt + * Copyright 2007-2009 Daniel Drake + * Copyright 2010-2012 Peter Stuge + * Copyright 2008-2011 Nathan Hjelm + * Copyright 2009-2012 Pete Batard + * Copyright 2009-2012 Ludovic Rousseau + * Copyright 2010-2012 Michael Plante + * Copyright 2011-2012 Hans de Goede + * Copyright 2012 Martin Pieuchot + * Copyright 2012-2013 Toby Gray */ package org.usb4java; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.usb.UsbDisconnectedException; -import javax.usb.UsbException; -import javax.usb.UsbInterface; -import javax.usb.UsbInterfaceDescriptor; -import javax.usb.UsbInterfacePolicy; -import javax.usb.UsbNotActiveException; - -import org.usb4java.descriptors.SimpleUsbInterfaceDescriptor; -import org.libusb4java.EndpointDescriptor; -import org.libusb4java.InterfaceDescriptor; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; /** - * usb4java implementation of UsbInterface. - * + * A collection of alternate settings for a particular USB interface. + * * @author Klaus Reimer (k@ailis.de) */ -final class Interface implements UsbInterface +public final class Interface { - /** The configuration this interface belongs to. */ - private final Configuration configuration; - - /** The interface descriptor. */ - private final UsbInterfaceDescriptor descriptor; - - /** The endpoints of this interface. */ - private final Map endpoints = - new HashMap(); + /** The native pointer to the descriptor structure. */ + private long interfacePointer; /** - * Constructor. - * - * @param configuration - * The USB configuration this interface belongs to. - * @param descriptor - * The libusb interface descriptor. + * Package-private constructor to prevent manual instantiation. Interfaces + * are always created by JNI. */ - Interface(final Configuration configuration, - final InterfaceDescriptor descriptor) + Interface() { - this.configuration = configuration; - this.descriptor = new SimpleUsbInterfaceDescriptor(descriptor); - for (EndpointDescriptor endpointDescriptor: descriptor.endpoint()) + // Empty + } + + /** + * Returns the native pointer. + * + * @return The native pointer. + */ + public long getPointer() + { + return this.interfacePointer; + } + + /** + * Returns the array with interface descriptors. The length of this array is + * determined by the {@link #numAltsetting()} field. + * + * @return The array with interface descriptors. + */ + public native InterfaceDescriptor[] altsetting(); + + /** + * Returns the number of alternate settings that belong to this interface. + * + * @return The number of alternate settings. + */ + public native int numAltsetting(); + + /** + * Returns a dump of this interface. + * + * @return The interface dump. + */ + public String dump() + { + final StringBuilder builder = new StringBuilder(); + + builder.append(String.format( + "Interface:%n" + + " numAltsetting %10d", + this.numAltsetting())); + + for (final InterfaceDescriptor intDesc : this.altsetting()) { - final Endpoint endpoint = - new Endpoint(this, endpointDescriptor); - this.endpoints.put(endpointDescriptor.bEndpointAddress(), endpoint); + builder.append("%n" + intDesc.dump()); } - } - - /** - * Ensures this setting and configuration is active. - * - * @throws UsbNotActiveException - * When the setting or the configuration is not active. - */ - private void checkActive() - { - if (!this.configuration.isActive()) - throw new UsbNotActiveException("Configuration is not active"); - if (!isActive()) - throw new UsbNotActiveException("Setting is not active"); - } - - /** - * Ensures that the device is connected. - * - * @throws UsbDisconnectedException - * When device has been disconnected. - */ - private void checkConnected() - { - this.configuration.getUsbDevice().checkConnected(); + return builder.toString(); } @Override - public void claim() throws UsbException + public int hashCode() { - claim(null); + return new HashCodeBuilder() + .append(this.altsetting()) + .append(this.numAltsetting()) + .toHashCode(); } @Override - public void claim(final UsbInterfacePolicy policy) throws UsbException + public boolean equals(final Object obj) { - checkActive(); - checkConnected(); - final AbstractDevice device = this.configuration.getUsbDevice(); - device.claimInterface(this.descriptor.bInterfaceNumber(), - policy != null && policy.forceClaim(this)); - this.configuration.setUsbInterface( - this.descriptor.bInterfaceNumber(), this); + if (this == obj) + { + return true; + } + if (obj == null) + { + return false; + } + if (this.getClass() != obj.getClass()) + { + return false; + } + + final Interface other = (Interface) obj; + + return new EqualsBuilder() + .append(this.altsetting(), other.altsetting()) + .append(this.numAltsetting(), other.numAltsetting()) + .isEquals(); } - @Override - public void release() throws UsbException - { - checkActive(); - checkConnected(); - this.configuration.getUsbDevice().releaseInterface( - this.descriptor.bInterfaceNumber()); - } - - @Override - public boolean isClaimed() - { - return this.configuration.getUsbDevice().isInterfaceClaimed( - this.descriptor.bInterfaceNumber()); - } - - @Override - public boolean isActive() - { - return this.configuration.getUsbInterface(this.descriptor - .bInterfaceNumber()) == this; - } - - @Override - public int getNumSettings() - { - return this.configuration.getNumSettings(this.descriptor - .bInterfaceNumber()); - } - - @Override - public byte getActiveSettingNumber() - { - checkActive(); - return this.configuration - .getUsbInterface(this.descriptor.bInterfaceNumber()) - .getUsbInterfaceDescriptor().bAlternateSetting(); - } - - @Override - public Interface getActiveSetting() - { - checkActive(); - return this.configuration.getUsbInterface(this.descriptor - .bInterfaceNumber()); - } - - @Override - public Interface getSetting(final byte number) - { - return (this.configuration).getSettings( - this.descriptor.bInterfaceNumber()).get(number & 0xff); - } - - @Override - public boolean containsSetting(final byte number) - { - return (this.configuration).getSettings( - this.descriptor.bInterfaceNumber()).containsKey(number & 0xff); - } - - @Override - public List getSettings() - { - return Collections.unmodifiableList(new ArrayList( - this.configuration.getSettings( - this.descriptor.bInterfaceNumber()).values())); - } - - @Override - public List getUsbEndpoints() - { - return Collections.unmodifiableList(new ArrayList( - this.endpoints.values())); - } - - @Override - public Endpoint getUsbEndpoint(final byte address) - { - return this.endpoints.get(address); - } - - @Override - public boolean containsUsbEndpoint(final byte address) - { - return this.endpoints.containsKey(address); - } - - @Override - public Configuration getUsbConfiguration() - { - return this.configuration; - } - - @Override - public UsbInterfaceDescriptor getUsbInterfaceDescriptor() - { - return this.descriptor; - } - - @Override - public String getInterfaceString() throws UsbException, - UnsupportedEncodingException - { - checkConnected(); - final byte iInterface = this.descriptor.iInterface(); - if (iInterface == 0) return null; - return this.configuration.getUsbDevice().getString(iInterface); - } - @Override public String toString() { - return String.format("USB interface %02x", - this.descriptor.bInterfaceNumber()); - } + return this.dump(); + } } diff --git a/src/main/java/org/libusb4java/InterfaceDescriptor.java b/src/main/java/org/usb4java/InterfaceDescriptor.java similarity index 98% rename from src/main/java/org/libusb4java/InterfaceDescriptor.java rename to src/main/java/org/usb4java/InterfaceDescriptor.java index 3cab011..2e6d4ac 100644 --- a/src/main/java/org/libusb4java/InterfaceDescriptor.java +++ b/src/main/java/org/usb4java/InterfaceDescriptor.java @@ -16,13 +16,13 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.utils.DescriptorUtils; +import org.usb4java.utils.DescriptorUtils; /** * A structure representing the standard USB interface descriptor. diff --git a/src/main/java/org/usb4java/IrpQueue.java b/src/main/java/org/usb4java/IrpQueue.java deleted file mode 100644 index d20f452..0000000 --- a/src/main/java/org/usb4java/IrpQueue.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -import javax.usb.UsbConst; -import javax.usb.UsbControlIrp; -import javax.usb.UsbEndpoint; -import javax.usb.UsbEndpointDescriptor; -import javax.usb.UsbException; -import javax.usb.UsbIrp; -import javax.usb.UsbShortPacketException; - -import org.libusb4java.DeviceHandle; -import org.libusb4java.LibUsb; - -/** - * A queue for USB I/O request packets. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class IrpQueue extends AbstractIrpQueue -{ - /** The USB pipe. */ - private final Pipe pipe; - - /** - * Constructor. - * - * @param pipe - * The USB pipe - */ - IrpQueue(final Pipe pipe) - { - super(pipe.getDevice()); - this.pipe = pipe; - } - - @Override - protected void finishIrp(final UsbIrp irp) - { - this.pipe.sendEvent(irp); - } - - @Override - protected void processIrp(final UsbIrp irp) throws UsbException - { - final UsbEndpoint endpoint = this.pipe.getUsbEndpoint(); - final byte direction = endpoint.getDirection(); - final byte type = endpoint.getType(); - if (type == UsbConst.ENDPOINT_TYPE_CONTROL) - { - processControlIrp((UsbControlIrp) irp); - return; - } - - switch (direction) - { - case UsbConst.ENDPOINT_DIRECTION_OUT: - irp.setActualLength(write(irp.getData(), irp.getOffset(), - irp.getLength())); - if (irp.getActualLength() < irp.getLength() - && !irp.getAcceptShortPacket()) - { - throw new UsbShortPacketException(); - } - break; - - case UsbConst.ENDPOINT_DIRECTION_IN: - irp.setActualLength(read(irp.getData(), irp.getOffset(), - irp.getLength())); - if (irp.getActualLength() < irp.getLength() - && !irp.getAcceptShortPacket()) - { - throw new UsbShortPacketException(); - } - break; - - default: - throw new UsbException("Invalid direction: " - + direction); - } - } - - /** - * Returns the USB endpoint descriptor. - * - * @return The USB endpoint descriptor. - */ - private UsbEndpointDescriptor getEndpointDescriptor() - { - return this.pipe.getUsbEndpoint().getUsbEndpointDescriptor(); - } - - /** - * Reads bytes from an interrupt endpoint into the specified data array. - * - * @param data - * The data array to write the read bytes to. - * @param offset - * The offset in the data array to write the read bytes to. - * @param len - * The number of bytes to read. - * @throws UsbException - * When transfer fails. - * @return The number of read bytes. - */ - private int read(final byte[] data, final int offset, final int len) - throws UsbException - { - final UsbEndpointDescriptor descriptor = getEndpointDescriptor(); - final byte type = this.pipe.getUsbEndpoint().getType(); - final DeviceHandle handle = getDevice().open(); - int read = 0; - while (read < len) - { - final int size = - Math.min(len - read, descriptor.wMaxPacketSize() & 0xffff); - final ByteBuffer buffer = ByteBuffer.allocateDirect(size); - final int result = transfer(handle, descriptor, type, buffer); - buffer.rewind(); - buffer.get(data, offset + read, result); - read += result; - - // Short packet detected, aborting - if (result < size) break; - } - return read; - } - - /** - * Writes the specified bytes to a interrupt endpoint. - * - * @param data - * The data array with the bytes to write. - * @param offset - * The offset in the data array to write. - * @param len - * The number of bytes to write. - * @throws UsbException - * When transfer fails. - * @return The number of written bytes. - */ - private int write(final byte[] data, final int offset, final int len) - throws UsbException - { - final UsbEndpointDescriptor descriptor = getEndpointDescriptor(); - final byte type = this.pipe.getUsbEndpoint().getType(); - final DeviceHandle handle = getDevice().open(); - int written = 0; - while (written < len) - { - final int size = - Math.min(len - written, descriptor.wMaxPacketSize() & 0xffff); - final ByteBuffer buffer = ByteBuffer.allocateDirect(size); - buffer.put(data, offset + written, size); - buffer.rewind(); - final int result = transfer(handle, descriptor, type, buffer); - written += result; - - // Short packet detected, aborting - if (result < size) break; - } - return written; - } - - /** - * Transfers data from or to the device. - * - * @param handle - * The device handle. - * @param descriptor - * The endpoint descriptor. - * @param type - * The endpoint type. - * @param buffer - * The data buffer. - * @return The number of transferred bytes. - * @throws UsbException - * When data transfer fails. - */ - private int transfer(final DeviceHandle handle, - final UsbEndpointDescriptor descriptor, final int type, - final ByteBuffer buffer) throws UsbException - { - final IntBuffer transferred = IntBuffer.allocate(1); - int result; - if (type == UsbConst.ENDPOINT_TYPE_BULK) - { - result = LibUsb.bulkTransfer(handle, - descriptor.bEndpointAddress(), buffer, transferred, - getConfig().getTimeout()); - if (result < 0) - { - throw new LibUsbException( - "Transfer error on bulk endpoint", result); - } - } - else if (type == UsbConst.ENDPOINT_TYPE_INTERRUPT) - { - result = LibUsb.interruptTransfer(handle, - descriptor.bEndpointAddress(), buffer, transferred, - getConfig().getTimeout()); - if (result < 0) - { - throw new LibUsbException( - "Transfer error on interrupt endpoint", result); - } - } - else - { - throw new UsbException("Unsupported endpoint type: " + type); - } - return transferred.get(0); - } -} diff --git a/src/main/java/org/libusb4java/IsoPacketDescriptor.java b/src/main/java/org/usb4java/IsoPacketDescriptor.java similarity index 99% rename from src/main/java/org/libusb4java/IsoPacketDescriptor.java rename to src/main/java/org/usb4java/IsoPacketDescriptor.java index 1eb46c1..5a1336c 100644 --- a/src/main/java/org/libusb4java/IsoPacketDescriptor.java +++ b/src/main/java/org/usb4java/IsoPacketDescriptor.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; /** * Isochronous packet descriptor. diff --git a/src/main/java/org/libusb4java/LibUsb.java b/src/main/java/org/usb4java/LibUsb.java similarity index 99% rename from src/main/java/org/libusb4java/LibUsb.java rename to src/main/java/org/usb4java/LibUsb.java index bac7714..a9dc384 100644 --- a/src/main/java/org/libusb4java/LibUsb.java +++ b/src/main/java/org/usb4java/LibUsb.java @@ -17,7 +17,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.io.FileDescriptor; import java.nio.ByteBuffer; @@ -27,8 +27,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.lang3.tuple.ImmutablePair; - -import org.libusb4java.utils.BufferUtils; +import org.usb4java.utils.BufferUtils; /** * Static class providing the constants and functions of libusb. diff --git a/src/main/java/org/usb4java/LibUsbException.java b/src/main/java/org/usb4java/LibUsbException.java deleted file mode 100644 index 7caaa63..0000000 --- a/src/main/java/org/usb4java/LibUsbException.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013 Klaus Reimer - * See LICENSE.md for licensing information. - * - * Based on libusb : - * - * Copyright 2001 Johannes Erdfelt - * Copyright 2007-2009 Daniel Drake - * Copyright 2010-2012 Peter Stuge - * Copyright 2008-2011 Nathan Hjelm - * Copyright 2009-2012 Pete Batard - * Copyright 2009-2012 Ludovic Rousseau - * Copyright 2010-2012 Michael Plante - * Copyright 2011-2012 Hans de Goede - * Copyright 2012 Martin Pieuchot - * Copyright 2012-2013 Toby Gray - */ - -package org.usb4java; - -import javax.usb.UsbException; - -import org.libusb4java.LibUsb; - -/** - * libusb-specific USB exception. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class LibUsbException extends UsbException -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The error code. */ - private final int errorCode; - - /** - * Constructor. - * - * @param message - * The error message. - * @param errorCode - * The error code. - */ - public LibUsbException(final String message, final int errorCode) - { - super(String.format("USB error %d: %s: %s", -errorCode, message, - LibUsb.strError(errorCode))); - this.errorCode = errorCode; - } - - /** - * Returns the error code. - * - * @return The error code - */ - public int getErrorCode() - { - return this.errorCode; - } -} diff --git a/src/main/java/org/libusb4java/Loader.java b/src/main/java/org/usb4java/Loader.java similarity index 99% rename from src/main/java/org/libusb4java/Loader.java rename to src/main/java/org/usb4java/Loader.java index c0fca61..666a39b 100644 --- a/src/main/java/org/libusb4java/Loader.java +++ b/src/main/java/org/usb4java/Loader.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import java.io.File; import java.io.FileOutputStream; diff --git a/src/main/java/org/libusb4java/LoaderException.java b/src/main/java/org/usb4java/LoaderException.java similarity index 96% rename from src/main/java/org/libusb4java/LoaderException.java rename to src/main/java/org/usb4java/LoaderException.java index 4a05cc5..252f947 100644 --- a/src/main/java/org/libusb4java/LoaderException.java +++ b/src/main/java/org/usb4java/LoaderException.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; /** * Thrown when JNI library could not be loaded. diff --git a/src/main/java/org/usb4java/NonHub.java b/src/main/java/org/usb4java/NonHub.java deleted file mode 100644 index a71132e..0000000 --- a/src/main/java/org/usb4java/NonHub.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import org.libusb4java.Device; - -/** - * A non-hub USB device. - * - * @author Klaus Reimer (k@ailis.de) - */ -class NonHub extends AbstractDevice -{ - /** - * Constructs a new non-hub USB device. - * - * @param manager - * The USB device manager which is responsible for this device. - * @param id - * The device id. Must not be null. - * @param parentId - * The parent device id. May be null if this device has no parent - * (Because it is a root device). - * @param speed - * The device speed. - * @param device - * The libusb device. This reference is only valid during the - * constructor execution, so don't store it in a property or - * something like that. - * @throws LibUsbException - * When device configuration could not be read. - */ - NonHub(final DeviceManager manager, final DeviceId id, - final DeviceId parentId, final int speed, final Device device) - throws LibUsbException - { - super(manager, id, parentId, speed, device); - } - - @Override - public int hashCode() - { - return getId().hashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final NonHub other = (NonHub) obj; - return getId().equals(other.getId()); - } - - @Override - public boolean isUsbHub() - { - return false; - } -} diff --git a/src/main/java/org/usb4java/Pipe.java b/src/main/java/org/usb4java/Pipe.java deleted file mode 100644 index 87bdcb4..0000000 --- a/src/main/java/org/usb4java/Pipe.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.List; - -import javax.usb.UsbConfiguration; -import javax.usb.UsbControlIrp; -import javax.usb.UsbDisconnectedException; -import javax.usb.UsbException; -import javax.usb.UsbInterface; -import javax.usb.UsbIrp; -import javax.usb.UsbNotActiveException; -import javax.usb.UsbNotClaimedException; -import javax.usb.UsbNotOpenException; -import javax.usb.UsbPipe; -import javax.usb.event.UsbPipeDataEvent; -import javax.usb.event.UsbPipeErrorEvent; -import javax.usb.event.UsbPipeListener; -import javax.usb.util.DefaultUsbControlIrp; -import javax.usb.util.DefaultUsbIrp; - - -/** - * usb4java implementation of UsbPipe. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Pipe implements UsbPipe -{ - /** The endpoint this pipe belongs to. */ - private final Endpoint endpoint; - - /** The USB pipe listeners. */ - private final PipeListenerList listeners = new PipeListenerList(); - - /** If pipe is open or not. */ - private boolean opened; - - /** The request queue. */ - private final IrpQueue queue; - - /** - * Constructor. - * - * @param endpoint - * The endpoint this pipe belongs to. - */ - Pipe(final Endpoint endpoint) - { - this.endpoint = endpoint; - this.queue = new IrpQueue(this); - } - - /** - * Returns the USB device. - * - * @return The USB device. - */ - public AbstractDevice getDevice() - { - return this.endpoint.getUsbInterface().getUsbConfiguration() - .getUsbDevice(); - } - - /** - * Ensures the pipe is active. - * - * @throws UsbNotActiveException - * When pipe is not active - */ - private void checkActive() - { - if (!isActive()) - throw new UsbNotActiveException("Pipe is not active."); - } - - /** - * Ensures the interface is active. - * - * @throws UsbNotClaimedException - * When interface is not claimed. - */ - private void checkClaimed() - { - if (!this.endpoint.getUsbInterface().isClaimed()) - throw new UsbNotClaimedException("Interface is not claimed."); - } - - /** - * Ensures the device is connected. - * - * @throws UsbDisconnectedException - * When device has been disconnected. - */ - private void checkConnected() - { - getDevice().checkConnected(); - } - - /** - * Ensures the pipe is open. - * - * @throws UsbNotOpenException - * When pipe is not open. - */ - private void checkOpen() - { - if (!isOpen()) - throw new UsbNotOpenException("Pipe is not open."); - } - - @Override - public void open() throws UsbException - { - checkActive(); - checkClaimed(); - checkConnected(); - if (this.opened) throw new UsbException("Pipe is already open"); - this.opened = true; - } - - @Override - public void close() throws UsbException - { - checkActive(); - checkClaimed(); - checkConnected(); - if (!this.opened) throw new UsbException("Pipe is already closed"); - if (this.queue.isBusy()) - throw new UsbException("Pipe is still busy"); - this.opened = false; - } - - @Override - public boolean isActive() - { - final UsbInterface iface = this.endpoint.getUsbInterface(); - final UsbConfiguration config = iface.getUsbConfiguration(); - return iface.isActive() && config.isActive(); - } - - @Override - public boolean isOpen() - { - return this.opened; - } - - @Override - public Endpoint getUsbEndpoint() - { - return this.endpoint; - } - - @Override - public int syncSubmit(final byte[] data) throws UsbException - { - final UsbIrp irp = asyncSubmit(data); - irp.waitUntilComplete(); - if (irp.isUsbException()) throw irp.getUsbException(); - return irp.getActualLength(); - } - - @Override - public UsbIrp asyncSubmit(final byte[] data) - { - if (data == null) - throw new IllegalArgumentException("data must not be null"); - final UsbIrp irp = createUsbIrp(); - irp.setAcceptShortPacket(true); - irp.setData(data); - asyncSubmit(irp); - return irp; - } - - @Override - public void syncSubmit(final UsbIrp irp) throws UsbException - { - if (irp == null) - throw new IllegalArgumentException("irp must not be null"); - asyncSubmit(irp); - irp.waitUntilComplete(); - if (irp.isUsbException()) throw irp.getUsbException(); - } - - @Override - public void asyncSubmit(final UsbIrp irp) - { - if (irp == null) - throw new IllegalArgumentException("irp must not be null"); - checkActive(); - checkConnected(); - checkOpen(); - this.queue.add(irp); - } - - @Override - public void syncSubmit(final List list) throws UsbException - { - for (final Object item: list) - { - final UsbIrp irp = (UsbIrp) item; - syncSubmit(irp); - } - } - - @Override - public void asyncSubmit(final List list) - { - for (final Object item: list) - { - final UsbIrp irp = (UsbIrp) item; - asyncSubmit(irp); - } - } - - @Override - public void abortAllSubmissions() - { - checkActive(); - checkConnected(); - checkOpen(); - this.queue.abort(); - } - - @Override - public UsbIrp createUsbIrp() - { - return new DefaultUsbIrp(); - } - - @Override - public UsbControlIrp createUsbControlIrp(final byte bmRequestType, - final byte bRequest, - final short wValue, final short wIndex) - { - return new DefaultUsbControlIrp(bmRequestType, bRequest, wValue, - wIndex); - } - - @Override - public void addUsbPipeListener(final UsbPipeListener listener) - { - this.listeners.add(listener); - } - - @Override - public void removeUsbPipeListener(final UsbPipeListener listener) - { - this.listeners.remove(listener); - } - - /** - * Sends event to all event listeners. - * - * @param irp - * Then request package - */ - public void sendEvent(final UsbIrp irp) - { - if (irp.isUsbException()) - { - this.listeners.errorEventOccurred(new UsbPipeErrorEvent(this, irp)); - } - else - { - this.listeners.dataEventOccurred(new UsbPipeDataEvent(this, irp)); - } - } - - @Override - public String toString() - { - return String.format("USB pipe of endpoint %02x", - this.endpoint.getUsbEndpointDescriptor().bEndpointAddress()); - } -} diff --git a/src/main/java/org/usb4java/PipeListenerList.java b/src/main/java/org/usb4java/PipeListenerList.java deleted file mode 100644 index bbeb4ec..0000000 --- a/src/main/java/org/usb4java/PipeListenerList.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.event.UsbPipeDataEvent; -import javax.usb.event.UsbPipeErrorEvent; -import javax.usb.event.UsbPipeListener; - -/** - * USB pipe listener list. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class PipeListenerList extends - EventListenerList implements UsbPipeListener -{ - /** - * Constructs a new USB pipe listener list. - */ - PipeListenerList() - { - super(); - } - - @Override - public UsbPipeListener[] toArray() - { - return getListeners().toArray( - new UsbPipeListener[getListeners().size()]); - } - - @Override - public void errorEventOccurred(final UsbPipeErrorEvent event) - { - for (final UsbPipeListener listener: toArray()) - { - listener.errorEventOccurred(event); - } - } - - @Override - public void dataEventOccurred(final UsbPipeDataEvent event) - { - for (final UsbPipeListener listener: toArray()) - { - listener.dataEventOccurred(event); - } - } -} diff --git a/src/main/java/org/libusb4java/PollfdListener.java b/src/main/java/org/usb4java/PollfdListener.java similarity index 98% rename from src/main/java/org/libusb4java/PollfdListener.java rename to src/main/java/org/usb4java/PollfdListener.java index 5b265e9..58ef9a3 100644 --- a/src/main/java/org/libusb4java/PollfdListener.java +++ b/src/main/java/org/usb4java/PollfdListener.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.io.FileDescriptor; diff --git a/src/main/java/org/usb4java/Port.java b/src/main/java/org/usb4java/Port.java deleted file mode 100644 index 266a5c2..0000000 --- a/src/main/java/org/usb4java/Port.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.UsbHub; -import javax.usb.UsbPort; - -/** - * usb4java implementation of UsbPort. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Port implements UsbPort -{ - /** The USB hub this port belongs to. */ - private final UsbHub hub; - - /** The port number. */ - private final byte portNumber; - - /** The attached device. */ - private AbstractDevice device; - - /** - * Constructor. - * - * @param hub - * The USB hub this port belongs to. - * @param portNumber - * The port number. - */ - Port(final UsbHub hub, final byte portNumber) - { - this.hub = hub; - this.portNumber = portNumber; - } - - @Override - public byte getPortNumber() - { - return this.portNumber; - } - - @Override - public UsbHub getUsbHub() - { - return this.hub; - } - - @Override - public AbstractDevice getUsbDevice() - { - return this.device; - } - - @Override - public boolean isUsbDeviceAttached() - { - return this.device != null; - } - - /** - * Connects the specified device to this port. - * - * @param device - * The device to connect. - */ - void connectUsbDevice(final AbstractDevice device) - { - if (device == null) - throw new IllegalArgumentException("device must not be null"); - if (this.device != null) - throw new IllegalStateException( - "Port already has a connected device"); - this.device = device; - device.setParentUsbPort(this); - } - - /** - * Disconnects the currently connected device. - */ - void disconnectUsbDevice() - { - if (this.device == null) - throw new IllegalStateException("Port has no connected device"); - final AbstractDevice device = this.device; - this.device = null; - device.setParentUsbPort(null); - } -} diff --git a/src/main/java/org/usb4java/Ports.java b/src/main/java/org/usb4java/Ports.java deleted file mode 100644 index de16d0d..0000000 --- a/src/main/java/org/usb4java/Ports.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.usb.UsbHub; - -/** - * A list of USB ports. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class Ports - implements UsbPorts -{ - /** The hub ports. */ - private final List ports = new ArrayList(); - - /** The hub these ports belong to. */ - private final UsbHub hub; - - /** - * Constructor. - * - * @param hub - * The hub the port belongs to. - */ - Ports(final UsbHub hub) - { - this.hub = hub; - addPort(); - } - - /** - * Adds a new port and returns it. - * - * @return The added port. - */ - private Port addPort() - { - final byte portNo = (byte) (this.ports.size() + 1); - final Port port = new Port(this.hub, portNo); - this.ports.add(port); - return port; - } - - /** - * Returns the first free port or adds a new one if no free port was found. - * - * @return The first free port. - */ - private Port getFreePort() - { - for (final Port port: this.ports) - { - if (!port.isUsbDeviceAttached()) return port; - } - return addPort(); - } - - @Override - public byte getNumberOfPorts() - { - return (byte) this.ports.size(); - } - - @Override - public List getUsbPorts() - { - return Collections.unmodifiableList(this.ports); - } - - @Override - public Port getUsbPort(final byte number) - { - final int index = (number & 0xff) - 1; - if (index < 0 || index >= this.ports.size()) return null; - return this.ports.get(index); - } - - @Override - public List getAttachedUsbDevices() - { - final List devices = new ArrayList(); - synchronized (this.ports) - { - for (final Port port: this.ports) - { - if (port.isUsbDeviceAttached()) - { - devices.add(port.getUsbDevice()); - } - } - } - return Collections.unmodifiableList(devices); - } - - @Override - public boolean isUsbDeviceAttached(final AbstractDevice device) - { - synchronized (this.ports) - { - for (final Port port: this.ports) - { - if (device.equals(port.getUsbDevice())) return true; - } - } - return false; - } - - @Override - public void connectUsbDevice(final AbstractDevice device) - { - synchronized (this.ports) - { - final Port port = getFreePort(); - port.connectUsbDevice(device); - } - } - - @Override - public void disconnectUsbDevice(final AbstractDevice device) - { - synchronized (this.ports) - { - for (final Port port: this.ports) - { - if (device.equals(port.getUsbDevice())) - { - port.disconnectUsbDevice(); - } - } - } - } -} diff --git a/src/main/java/org/usb4java/RootHub.java b/src/main/java/org/usb4java/RootHub.java deleted file mode 100644 index f05ae1f..0000000 --- a/src/main/java/org/usb4java/RootHub.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.ArrayList; -import java.util.List; - -import javax.usb.UsbConfiguration; -import javax.usb.UsbConst; -import javax.usb.UsbControlIrp; -import javax.usb.UsbDeviceDescriptor; -import javax.usb.UsbException; -import javax.usb.UsbHub; -import javax.usb.UsbPort; -import javax.usb.UsbStringDescriptor; -import javax.usb.event.UsbDeviceListener; -import javax.usb.util.DefaultUsbControlIrp; - -import org.usb4java.descriptors.SimpleUsbDeviceDescriptor; - -/** - * The virtual USB root hub. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class RootHub implements UsbHub, - UsbPorts -{ - /** The manufacturer string. */ - private static final String MANUFACTURER = "usb4java"; - - /** The manufacturer string. */ - private static final String PRODUCT = "root hub"; - - /** The serial number. */ - private static final String SERIAL_NUMBER = "1.0.0"; - - /** The configurations. */ - private final List configurations = - new ArrayList(1); - - /** The device descriptor. */ - private final UsbDeviceDescriptor descriptor = - new SimpleUsbDeviceDescriptor( - UsbConst.DESCRIPTOR_MIN_LENGTH_DEVICE, - UsbConst.DESCRIPTOR_TYPE_DEVICE, - (short) 0x101, - UsbConst.HUB_CLASSCODE, - (byte) 0, - (byte) 0, - (byte) 8, - (short) 0xffff, - (short) 0xffff, - (byte) 0, - (byte) 1, - (byte) 2, - (byte) 3, - (byte) 1); - - /** The device listeners. */ - private final DeviceListenerList listeners = new DeviceListenerList(); - - /** The root hub ports. */ - private final Ports rootPorts = new Ports(this); - - /** - * Constructor. - */ - RootHub() - { - this.configurations.add(new RootHubConfiguration(this)); - } - - @Override - public UsbPort getParentUsbPort() - { - return null; - } - - @Override - public boolean isUsbHub() - { - return true; - } - - @Override - public String getManufacturerString() - { - return MANUFACTURER; - } - - @Override - public String getSerialNumberString() - { - return SERIAL_NUMBER; - } - - @Override - public String getProductString() - { - return PRODUCT; - } - - @Override - public Object getSpeed() - { - return UsbConst.DEVICE_SPEED_UNKNOWN; - } - - @Override - public List getUsbConfigurations() - { - return this.configurations; - } - - @Override - public UsbConfiguration getUsbConfiguration(final byte number) - { - if (number != 1) return null; - return this.configurations.get(0); - } - - @Override - public boolean containsUsbConfiguration(final byte number) - { - return number == 1; - } - - @Override - public byte getActiveUsbConfigurationNumber() - { - return 1; - } - - @Override - public UsbConfiguration getActiveUsbConfiguration() - { - return this.configurations.get(0); - } - - @Override - public boolean isConfigured() - { - return true; - } - - @Override - public UsbDeviceDescriptor getUsbDeviceDescriptor() - { - return this.descriptor; - } - - @Override - public UsbStringDescriptor getUsbStringDescriptor(final byte index) - throws UsbException - { - throw new UsbException( - "Can't get USB string descriptor from virtual device"); - } - - @Override - public String getString(final byte index) throws UsbException - { - throw new UsbException("Can't get string from virtual device"); - } - - @Override - public void syncSubmit(final UsbControlIrp irp) throws UsbException - { - throw new UsbException("Can't syncSubmit on virtual device"); - } - - @Override - public void asyncSubmit(final UsbControlIrp irp) throws UsbException - { - throw new UsbException("Can't asyncSubmit on virtual device"); - } - - @Override - public void syncSubmit(final List list) throws UsbException - { - throw new UsbException("Can't syncSubmit on virtual device"); - } - - @Override - public void asyncSubmit(final List list) throws UsbException - { - throw new UsbException("Can't asyncSubmit on virtual device"); - } - - @Override - public UsbControlIrp createUsbControlIrp(final byte bmRequestType, - final byte bRequest, - final short wValue, final short wIndex) - { - return new DefaultUsbControlIrp(bmRequestType, bRequest, wValue, - wIndex); - } - - @Override - public void addUsbDeviceListener(final UsbDeviceListener listener) - { - this.listeners.add(listener); - } - - @Override - public void removeUsbDeviceListener(final UsbDeviceListener listener) - { - this.listeners.remove(listener); - } - - @Override - public byte getNumberOfPorts() - { - return this.rootPorts.getNumberOfPorts(); - } - - @Override - public List getUsbPorts() - { - return this.rootPorts.getUsbPorts(); - } - - @Override - public Port getUsbPort(final byte number) - { - return this.rootPorts.getUsbPort(number); - } - - @Override - public List getAttachedUsbDevices() - { - return this.rootPorts.getAttachedUsbDevices(); - } - - @Override - public boolean isUsbDeviceAttached(final AbstractDevice device) - { - return this.rootPorts.isUsbDeviceAttached(device); - } - - @Override - public boolean isRootUsbHub() - { - return true; - } - - @Override - public void connectUsbDevice(final AbstractDevice device) - { - this.rootPorts.connectUsbDevice(device); - } - - @Override - public void disconnectUsbDevice(final AbstractDevice device) - { - this.rootPorts.disconnectUsbDevice(device); - } - - @Override - public String toString() - { - return this.getManufacturerString() + " " + this.getProductString() + - " " + this.getSerialNumberString(); - } -} diff --git a/src/main/java/org/usb4java/RootHubConfiguration.java b/src/main/java/org/usb4java/RootHubConfiguration.java deleted file mode 100644 index ff85975..0000000 --- a/src/main/java/org/usb4java/RootHubConfiguration.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.ArrayList; -import java.util.List; - -import javax.usb.UsbConfiguration; -import javax.usb.UsbConfigurationDescriptor; -import javax.usb.UsbConst; -import javax.usb.UsbDevice; -import javax.usb.UsbInterface; - -import org.usb4java.descriptors.SimpleUsbConfigurationDescriptor; - -/** - * Virtual USB configuration used by the virtual USB root hub. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class RootHubConfiguration implements UsbConfiguration -{ - /** The virtual interfaces. */ - private final List interfaces = - new ArrayList(); - - /** The device this configuration belongs to. */ - private final UsbDevice device; - - /** The USB configuration descriptor. */ - private final UsbConfigurationDescriptor descriptor = - new SimpleUsbConfigurationDescriptor( - UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION, - UsbConst.DESCRIPTOR_TYPE_CONFIGURATION, - (byte) (UsbConst.DESCRIPTOR_MIN_LENGTH_CONFIGURATION - + UsbConst.DESCRIPTOR_MIN_LENGTH_INTERFACE), - (byte) 1, - (byte) 1, - (byte) 0, - (byte) 0x80, - (byte) 0); - - /** - * Constructor. - * - * @param device - * The device this configuration belongs to. - */ - RootHubConfiguration(final UsbDevice device) - { - this.device = device; - this.interfaces.add(new RootHubInterface(this)); - } - - @Override - public boolean isActive() - { - return true; - } - - @Override - public List getUsbInterfaces() - { - return this.interfaces; - } - - @Override - public UsbInterface getUsbInterface(final byte number) - { - if (number != 0) return null; - return this.interfaces.get(0); - } - - @Override - public boolean containsUsbInterface(final byte number) - { - return number == 0; - } - - @Override - public UsbDevice getUsbDevice() - { - return this.device; - } - - @Override - public UsbConfigurationDescriptor getUsbConfigurationDescriptor() - { - return this.descriptor; - } - - @Override - public String getConfigurationString() - { - return null; - } -} diff --git a/src/main/java/org/usb4java/RootHubInterface.java b/src/main/java/org/usb4java/RootHubInterface.java deleted file mode 100644 index e683dbb..0000000 --- a/src/main/java/org/usb4java/RootHubInterface.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.ArrayList; -import java.util.List; - -import javax.usb.UsbConfiguration; -import javax.usb.UsbConst; -import javax.usb.UsbEndpoint; -import javax.usb.UsbException; -import javax.usb.UsbInterface; -import javax.usb.UsbInterfaceDescriptor; -import javax.usb.UsbInterfacePolicy; - -import org.usb4java.descriptors.SimpleUsbInterfaceDescriptor; - -/** - * The virtual USB interfaces used by the virtual USB root hub. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class RootHubInterface implements UsbInterface -{ - /** The list of endpoints. */ - private final List endpoints = new ArrayList(0); - - /** The list of alternate settings. */ - private final List settings = new ArrayList(0); - - /** The USB configuration. */ - private final UsbConfiguration configuration; - - /** The interface descriptor. */ - private final UsbInterfaceDescriptor descriptor = - new SimpleUsbInterfaceDescriptor( - UsbConst.DESCRIPTOR_MIN_LENGTH_INTERFACE, - UsbConst.DESCRIPTOR_TYPE_INTERFACE, - (byte) 0, - (byte) 0, - (byte) 0, - UsbConst.HUB_CLASSCODE, - (byte) 0, - (byte) 0, - (byte) 0); - - /** - * Constructor. - * - * @param configuration - * The USB configuration. - */ - RootHubInterface(final UsbConfiguration configuration) - { - this.configuration = configuration; - } - - @Override - public void claim() throws UsbException - { - throw new UsbException("Virtual interfaces can't be claimed"); - } - - @Override - public void claim(final UsbInterfacePolicy policy) throws UsbException - { - throw new UsbException("Virtual interfaces can't be claimed"); - } - - @Override - public void release() throws UsbException - { - throw new UsbException("Virtual interfaces can't be released"); - } - - @Override - public boolean isClaimed() - { - return true; - } - - @Override - public boolean isActive() - { - return true; - } - - @Override - public int getNumSettings() - { - return 0; - } - - @Override - public byte getActiveSettingNumber() - { - return 0; - } - - @Override - public UsbInterface getActiveSetting() - { - return this; - } - - @Override - public UsbInterface getSetting(final byte number) - { - return this; - } - - @Override - public boolean containsSetting(final byte number) - { - return false; - } - - @Override - public List getSettings() - { - return this.settings; - } - - @Override - public List getUsbEndpoints() - { - return this.endpoints; - } - - @Override - public UsbEndpoint getUsbEndpoint(final byte address) - { - return null; - } - - @Override - public boolean containsUsbEndpoint(final byte address) - { - return false; - } - - @Override - public UsbConfiguration getUsbConfiguration() - { - return this.configuration; - } - - @Override - public UsbInterfaceDescriptor getUsbInterfaceDescriptor() - { - return this.descriptor; - } - - @Override - public String getInterfaceString() - { - return null; - } -} diff --git a/src/main/java/org/usb4java/ScanException.java b/src/main/java/org/usb4java/ScanException.java deleted file mode 100644 index fb3eda9..0000000 --- a/src/main/java/org/usb4java/ScanException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -/** - * Thrown when USB device scan fails. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class ScanException extends RuntimeException -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** - * Constructor. - * - * @param message - * The error message. - * @param cause - * The root cause. - */ - ScanException(final String message, final Throwable cause) - { - super(message, cause); - } -} diff --git a/src/main/java/org/usb4java/Services.java b/src/main/java/org/usb4java/Services.java deleted file mode 100644 index 3d6cf0f..0000000 --- a/src/main/java/org/usb4java/Services.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.UsbDevice; -import javax.usb.UsbException; -import javax.usb.UsbHostManager; -import javax.usb.UsbHub; -import javax.usb.UsbServices; -import javax.usb.event.UsbServicesEvent; -import javax.usb.event.UsbServicesListener; - -import org.libusb4java.Loader; -import org.libusb4java.LoaderException; - -/** - * usb4java implementation of JSR-80 UsbServices. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class Services implements UsbServices -{ - /** The implementation description. */ - private static final String IMP_DESCRIPTION = "usb4java"; - - /** The implementation version. */ - private static final String IMP_VERSION = "1.2.0"; - - /** The API version. */ - private static final String API_VERSION = "1.0.2"; - - /** The USB services listeners. */ - private final ServicesListenerList listeners = - new ServicesListenerList(); - - /** The virtual USB root hub. */ - private final RootHub rootHub; - - /** The USB device scanner. */ - private final DeviceManager deviceManager; - - /** If devices should be scanned by hierarchy. */ - private final Config config; - - /** - * Constructor. - * - * @throws UsbException - * When properties could not be loaded. - * @throws LoaderException - * When native libraries could not be loaded. - */ - public Services() throws UsbException - { - this.config = new Config(UsbHostManager.getProperties()); - Loader.load(); - this.rootHub = new RootHub(); - this.deviceManager = new DeviceManager(this.rootHub, - this.config.getScanInterval()); - this.deviceManager.start(); - } - - @Override - public UsbHub getRootUsbHub() - { - this.deviceManager.firstScan(); - return this.rootHub; - } - - @Override - public void addUsbServicesListener(final UsbServicesListener listener) - { - this.listeners.add(listener); - } - - @Override - public void removeUsbServicesListener(final UsbServicesListener listener) - { - this.listeners.remove(listener); - } - - @Override - public String getApiVersion() - { - return API_VERSION; - } - - @Override - public String getImpVersion() - { - return IMP_VERSION; - } - - @Override - public String getImpDescription() - { - return IMP_DESCRIPTION; - } - - /** - * Informs listeners about a new attached device. - * - * @param device - * The new attached device. - */ - void usbDeviceAttached(final UsbDevice device) - { - this.listeners.usbDeviceAttached(new UsbServicesEvent(this, device)); - } - - /** - * Informs listeners about a detached device. - * - * @param device - * The detached device. - */ - void usbDeviceDetached(final UsbDevice device) - { - this.listeners.usbDeviceDetached(new UsbServicesEvent(this, device)); - } - - /** - * Returns the configuration. - * - * @return The configuration. - */ - Config getConfig() - { - return this.config; - } - - /** - * Returns the usb4java services. - * - * @return The usb4java services. - */ - static Services getInstance() - { - try - { - return (Services) UsbHostManager.getUsbServices(); - } - catch (final ClassCastException e) - { - throw new ServicesException("Looks like usb4java is not the " - + "configured USB services implementation: " + e, e); - } - catch (final UsbException e) - { - throw new ServicesException("Unable to create USB services: " - + e, e); - } - } - - /** - * Manually scans for USB device connection changes. - */ - public void scan() - { - this.deviceManager.scan(); - } -} diff --git a/src/main/java/org/usb4java/ServicesException.java b/src/main/java/org/usb4java/ServicesException.java deleted file mode 100644 index 7604710..0000000 --- a/src/main/java/org/usb4java/ServicesException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -/** - * Thrown when usb4java services could not be created. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class ServicesException extends RuntimeException -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** - * Constructor. - * - * @param message - * The error message. - * @param cause - * The root cause. - */ - ServicesException(final String message, final Throwable cause) - { - super(message, cause); - } -} diff --git a/src/main/java/org/usb4java/ServicesListenerList.java b/src/main/java/org/usb4java/ServicesListenerList.java deleted file mode 100644 index 3830d0c..0000000 --- a/src/main/java/org/usb4java/ServicesListenerList.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import javax.usb.event.UsbServicesEvent; -import javax.usb.event.UsbServicesListener; - -/** - * USB services listener list. - * - * @author Klaus Reimer (k@ailis.de) - */ -final class ServicesListenerList extends - EventListenerList implements UsbServicesListener -{ - /** - * Constructs a new USB services listener list. - */ - ServicesListenerList() - { - super(); - } - - @Override - public UsbServicesListener[] toArray() - { - return getListeners().toArray( - new UsbServicesListener[getListeners().size()]); - } - - @Override - public void usbDeviceAttached(final UsbServicesEvent event) - { - for (final UsbServicesListener listener: toArray()) - { - listener.usbDeviceAttached(event); - } - } - - @Override - public void usbDeviceDetached(final UsbServicesEvent event) - { - for (final UsbServicesListener listener: toArray()) - { - listener.usbDeviceDetached(event); - } - } -} diff --git a/src/main/java/org/libusb4java/SsEndpointCompanionDescriptor.java b/src/main/java/org/usb4java/SsEndpointCompanionDescriptor.java similarity index 99% rename from src/main/java/org/libusb4java/SsEndpointCompanionDescriptor.java rename to src/main/java/org/usb4java/SsEndpointCompanionDescriptor.java index b5d15de..2033435 100644 --- a/src/main/java/org/libusb4java/SsEndpointCompanionDescriptor.java +++ b/src/main/java/org/usb4java/SsEndpointCompanionDescriptor.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; diff --git a/src/main/java/org/libusb4java/SsUsbDeviceCapabilityDescriptor.java b/src/main/java/org/usb4java/SsUsbDeviceCapabilityDescriptor.java similarity index 99% rename from src/main/java/org/libusb4java/SsUsbDeviceCapabilityDescriptor.java rename to src/main/java/org/usb4java/SsUsbDeviceCapabilityDescriptor.java index 4b05d0b..c581adc 100644 --- a/src/main/java/org/libusb4java/SsUsbDeviceCapabilityDescriptor.java +++ b/src/main/java/org/usb4java/SsUsbDeviceCapabilityDescriptor.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; diff --git a/src/main/java/org/libusb4java/Transfer.java b/src/main/java/org/usb4java/Transfer.java similarity index 99% rename from src/main/java/org/libusb4java/Transfer.java rename to src/main/java/org/usb4java/Transfer.java index 7976a5c..9bfbb4e 100644 --- a/src/main/java/org/libusb4java/Transfer.java +++ b/src/main/java/org/usb4java/Transfer.java @@ -17,7 +17,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import java.nio.ByteBuffer; diff --git a/src/main/java/org/libusb4java/TransferCallback.java b/src/main/java/org/usb4java/TransferCallback.java similarity index 96% rename from src/main/java/org/libusb4java/TransferCallback.java rename to src/main/java/org/usb4java/TransferCallback.java index 426030d..c156118 100644 --- a/src/main/java/org/libusb4java/TransferCallback.java +++ b/src/main/java/org/usb4java/TransferCallback.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; /** * Asynchronous transfer callback. diff --git a/src/main/java/org/libusb4java/Usb20ExtensionDescriptor.java b/src/main/java/org/usb4java/Usb20ExtensionDescriptor.java similarity index 99% rename from src/main/java/org/libusb4java/Usb20ExtensionDescriptor.java rename to src/main/java/org/usb4java/Usb20ExtensionDescriptor.java index ea8279c..d2c02fc 100644 --- a/src/main/java/org/libusb4java/Usb20ExtensionDescriptor.java +++ b/src/main/java/org/usb4java/Usb20ExtensionDescriptor.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; diff --git a/src/main/java/org/usb4java/UsbPorts.java b/src/main/java/org/usb4java/UsbPorts.java deleted file mode 100644 index 7079763..0000000 --- a/src/main/java/org/usb4java/UsbPorts.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import java.util.List; - -import javax.usb.UsbDevice; -import javax.usb.UsbPort; - -/** - * A list of USB ports. - * - * @author Klaus Reimer (k@ailis.de) - * @param

- * The USB port type. - * @param - * The USB device type. - */ -interface UsbPorts

-{ - /** - * Returns the number of ports. - * - * @return The number of ports. - */ - byte getNumberOfPorts(); - - /** - * Returns the ports. - * - * @return The ports. - */ - List

getUsbPorts(); - - /** - * Returns the USB port with the specified port number. - * - * @param number - * The USB port number. - * @return The USB port or null if no such port. - */ - P getUsbPort(final byte number); - - /** - * Returns the attached USB devices. - * - * @return The attached USB devices. - */ - List getAttachedUsbDevices(); - - /** - * Checks if the specified device is attached to one of the ports. - * - * @param device - * The device to search. - * @return True if device is connected, false if not. - */ - boolean isUsbDeviceAttached(D device); - - /** - * Connects a new device to this hub. - * - * @param device - * The device to add to this hub. - */ - void connectUsbDevice(D device); - - /** - * Disconnects the specified device from the hub. - * - * @param device - * The device to disconnected from the hub. - */ - void disconnectUsbDevice(D device); -} diff --git a/src/main/java/org/libusb4java/Version.java b/src/main/java/org/usb4java/Version.java similarity index 99% rename from src/main/java/org/libusb4java/Version.java rename to src/main/java/org/usb4java/Version.java index 435cad9..7a60091 100644 --- a/src/main/java/org/libusb4java/Version.java +++ b/src/main/java/org/usb4java/Version.java @@ -16,7 +16,7 @@ * Copyright 2012-2013 Toby Gray */ -package org.libusb4java; +package org.usb4java; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; diff --git a/src/main/java/org/usb4java/adapter/UsbDeviceAdapter.java b/src/main/java/org/usb4java/adapter/UsbDeviceAdapter.java deleted file mode 100644 index 6f08459..0000000 --- a/src/main/java/org/usb4java/adapter/UsbDeviceAdapter.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.adapter; - -import javax.usb.event.UsbDeviceDataEvent; -import javax.usb.event.UsbDeviceErrorEvent; -import javax.usb.event.UsbDeviceEvent; -import javax.usb.event.UsbDeviceListener; - -/** - * An abstract adapter class for receiving USB device events. The methods in - * this class are empty. This class exists as convenience for creating listener - * objects. - * - * @author Klaus Reimer (k@ailis.de) - */ -public abstract class UsbDeviceAdapter implements UsbDeviceListener -{ - @Override - public void usbDeviceDetached(final UsbDeviceEvent event) - { - // Empty - } - - @Override - public void errorEventOccurred(final UsbDeviceErrorEvent event) - { - // Empty - } - - @Override - public void dataEventOccurred(final UsbDeviceDataEvent event) - { - // Empty - } -} diff --git a/src/main/java/org/usb4java/adapter/UsbPipeAdapter.java b/src/main/java/org/usb4java/adapter/UsbPipeAdapter.java deleted file mode 100644 index 66c2210..0000000 --- a/src/main/java/org/usb4java/adapter/UsbPipeAdapter.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.adapter; - -import javax.usb.event.UsbPipeDataEvent; -import javax.usb.event.UsbPipeErrorEvent; -import javax.usb.event.UsbPipeListener; - -/** - * An abstract adapter class for receiving USB pipe events. The methods in - * this class are empty. This class exists as convenience for creating listener - * objects. - * - * @author Klaus Reimer (k@ailis.de) - */ -public abstract class UsbPipeAdapter implements UsbPipeListener -{ - @Override - public void errorEventOccurred(final UsbPipeErrorEvent event) - { - // Empty - } - - @Override - public void dataEventOccurred(final UsbPipeDataEvent event) - { - // Empty - } -} diff --git a/src/main/java/org/usb4java/adapter/UsbServicesAdapter.java b/src/main/java/org/usb4java/adapter/UsbServicesAdapter.java deleted file mode 100644 index 7911dcf..0000000 --- a/src/main/java/org/usb4java/adapter/UsbServicesAdapter.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.adapter; - -import javax.usb.event.UsbServicesEvent; -import javax.usb.event.UsbServicesListener; - -/** - * An abstract adapter class for receiving USB service events. The methods in - * this class are empty. This class exists as convenience for creating listener - * objects. - * - * @author Klaus Reimer (k@ailis.de) - */ -public abstract class UsbServicesAdapter implements UsbServicesListener -{ - @Override - public void usbDeviceAttached(final UsbServicesEvent event) - { - // Empty - } - - @Override - public void usbDeviceDetached(final UsbServicesEvent event) - { - // Empty - } -} diff --git a/src/main/java/org/usb4java/adapter/package-info.java b/src/main/java/org/usb4java/adapter/package-info.java deleted file mode 100644 index 82c3486..0000000 --- a/src/main/java/org/usb4java/adapter/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -/** - * Event adapter classes. - */ -package org.usb4java.adapter; diff --git a/src/main/java/org/usb4java/descriptors/SimpleUsbConfigurationDescriptor.java b/src/main/java/org/usb4java/descriptors/SimpleUsbConfigurationDescriptor.java deleted file mode 100644 index f43413f..0000000 --- a/src/main/java/org/usb4java/descriptors/SimpleUsbConfigurationDescriptor.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import javax.usb.UsbConfigurationDescriptor; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.ConfigDescriptor; - -/** - * Simple USB configuration descriptor. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class SimpleUsbConfigurationDescriptor extends SimpleUsbDescriptor - implements UsbConfigurationDescriptor -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The total length. */ - private final short wTotalLength; - - /** The number of interfaces. */ - private final byte bNumInterfaces; - - /** The configuration value. */ - private final byte bConfigurationValue; - - /** The configuration string descriptor index. */ - private final byte iConfiguration; - - /** The attributes. */ - private final byte bmAttributes; - - /** The maximum power. */ - private final byte bMaxPower; - - /** - * Constructor. - * - * @param bLength - * The descriptor length. - * @param bDescriptorType - * The descriptor type. - * @param wTotalLength - * The total length. - * @param bNumInterfaces - * The number of interfaces. - * @param bConfigurationValue - * The configuration value. - * @param iConfiguration - * The configuration string descriptor index. - * @param bmAttributes - * The attributes. - * @param bMaxPower - * The maximum power. - */ - public SimpleUsbConfigurationDescriptor(final byte bLength, - final byte bDescriptorType, final short wTotalLength, - final byte bNumInterfaces, final byte bConfigurationValue, - final byte iConfiguration, final byte bmAttributes, - final byte bMaxPower) - { - super(bLength, bDescriptorType); - this.wTotalLength = wTotalLength; - this.bNumInterfaces = bNumInterfaces; - this.bConfigurationValue = bConfigurationValue; - this.iConfiguration = iConfiguration; - this.bmAttributes = bmAttributes; - this.bMaxPower = bMaxPower; - } - - /** - * Construct from a libusb4java configuration descriptor. - * - * @param descriptor - * The descriptor from which to copy the data. - */ - public SimpleUsbConfigurationDescriptor(ConfigDescriptor descriptor) - { - this(descriptor.bLength(), - descriptor.bDescriptorType(), - descriptor.wTotalLength(), - descriptor.bNumInterfaces(), - descriptor.bConfigurationValue(), - descriptor.iConfiguration(), - descriptor.bmAttributes(), - descriptor.bMaxPower()); - } - - @Override - public short wTotalLength() - { - return this.wTotalLength; - } - - @Override - public byte bNumInterfaces() - { - return this.bNumInterfaces; - } - - @Override - public byte bConfigurationValue() - { - return this.bConfigurationValue; - } - - @Override - public byte iConfiguration() - { - return this.iConfiguration; - } - - @Override - public byte bmAttributes() - { - return this.bmAttributes; - } - - @Override - public byte bMaxPower() - { - return this.bMaxPower; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(bDescriptorType()) - .append(bLength()) - .append(this.bConfigurationValue) - .append(this.bMaxPower) - .append(this.bNumInterfaces) - .append(this.bmAttributes) - .append(this.iConfiguration) - .append(this.wTotalLength) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final SimpleUsbConfigurationDescriptor other = - (SimpleUsbConfigurationDescriptor) obj; - return new EqualsBuilder() - .append(bLength(), other.bLength()) - .append(bDescriptorType(), other.bDescriptorType()) - .append(this.bConfigurationValue, other.bConfigurationValue) - .append(this.bMaxPower, other.bMaxPower) - .append(this.bNumInterfaces, other.bNumInterfaces) - .append(this.bmAttributes, other.bmAttributes) - .append(this.iConfiguration, other.iConfiguration) - .append(this.wTotalLength, other.wTotalLength) - .isEquals(); - } - - @Override - public String toString() - { - return dump(this); - } - - /** - * Dumps the specified USB configuration descriptor into a string and - * returns it. - * - * @param descriptor - * The USB configuration descriptor to dump. - * @return The descriptor dump. - */ - public static String dump(final UsbConfigurationDescriptor descriptor) - { - return String.format( - "Configuration Descriptor:%n" + - " bLength %18d%n" + - " bDescriptorType %10d%n" + - " wTotalLength %13d%n" + - " bNumInterfaces %11d%n" + - " bConfigurationValue %6d%n" + - " iConfiguration %11d%n" + - " bmAttributes %13s%n" + - " %s%n" + - "%s" + - " bMaxPower %16smA%n", - descriptor.bLength(), - descriptor.bDescriptorType(), - descriptor.wTotalLength() & 0xffff, - descriptor.bNumInterfaces() & 0xff, - descriptor.bConfigurationValue() & 0xff, - descriptor.iConfiguration() & 0xff, - String.format("0x%02x", descriptor.bmAttributes() & 0xff), - ((descriptor.bmAttributes() & 64) == 0) ? ("(Bus Powered)") - : ("Self Powered"), - ((descriptor.bmAttributes() & 32) == 0) ? ("") - : String.format(" Remote Wakeup%n"), - (descriptor.bMaxPower() & 0xff) * 2); - } -} diff --git a/src/main/java/org/usb4java/descriptors/SimpleUsbDescriptor.java b/src/main/java/org/usb4java/descriptors/SimpleUsbDescriptor.java deleted file mode 100644 index 0730e54..0000000 --- a/src/main/java/org/usb4java/descriptors/SimpleUsbDescriptor.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import java.io.Serializable; - -import javax.usb.UsbDescriptor; - -/** - * Base class for all simple USB descriptors. - * - * @author Klaus Reimer (k@ailis.de) - */ -public abstract class SimpleUsbDescriptor implements UsbDescriptor, - Serializable -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The descriptor length. */ - private final byte bLength; - - /** The descriptor type. */ - private final byte bDescriptorType; - - /** - * Constructor. - * - * @param bLength - * The descriptor length. - * @param bDescriptorType - * The descriptor type. - */ - public SimpleUsbDescriptor(final byte bLength, final byte bDescriptorType) - { - this.bLength = bLength; - this.bDescriptorType = bDescriptorType; - } - - @Override - public final byte bLength() - { - return this.bLength; - } - - @Override - public final byte bDescriptorType() - { - return this.bDescriptorType; - } -} diff --git a/src/main/java/org/usb4java/descriptors/SimpleUsbDeviceDescriptor.java b/src/main/java/org/usb4java/descriptors/SimpleUsbDeviceDescriptor.java deleted file mode 100644 index b4a67f5..0000000 --- a/src/main/java/org/usb4java/descriptors/SimpleUsbDeviceDescriptor.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import javax.usb.UsbDeviceDescriptor; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.DeviceDescriptor; -import org.libusb4java.utils.DescriptorUtils; - -/** - * Simple USB device descriptor. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class SimpleUsbDeviceDescriptor extends SimpleUsbDescriptor - implements UsbDeviceDescriptor -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The USB specification version number. */ - private final short bcdUSB; - - /** The device class. */ - private final byte bDeviceClass; - - /** The device sub class. */ - private final byte bDeviceSubClass; - - /** The device protocol. */ - private final byte bDeviceProtocol; - - /** The maximum packet size for endpoint zero. */ - private final byte bMaxPacketSize0; - - /** The vendor ID. */ - private final short idVendor; - - /** The product ID. */ - private final short idProduct; - - /** The device release number. */ - private final short bcdDevice; - - /** The manufacturer string descriptor index. */ - private final byte iManufacturer; - - /** The product string descriptor index. */ - private final byte iProduct; - - /** The serial number string descriptor index. */ - private final byte iSerialNumber; - - /** The number of configurations. */ - private final byte bNumConfigurations; - - /** - * Constructor. - * - * @param bLength - * The descriptor length. - * @param bDescriptorType - * The descriptor type. - * @param bcdUSB - * The USB specification version number. - * @param bDeviceClass - * The device class. - * @param bDeviceSubClass - * The device sub class. - * @param bDeviceProtocol - * The device protocol. - * @param bMaxPacketSize0 - * The maximum packet size for endpoint zero. - * @param idVendor - * The vendor ID. - * @param idProduct - * The product ID. - * @param bcdDevice - * The device release number. - * @param iManufacturer - * The manufacturer string descriptor index. - * @param iProduct - * The product string descriptor index. - * @param iSerialNumber - * The serial number string descriptor index. - * @param bNumConfigurations - * The number of configurations. - */ - public SimpleUsbDeviceDescriptor(final byte bLength, - final byte bDescriptorType, final short bcdUSB, - final byte bDeviceClass, final byte bDeviceSubClass, - final byte bDeviceProtocol, final byte bMaxPacketSize0, - final short idVendor, final short idProduct, final short bcdDevice, - final byte iManufacturer, final byte iProduct, - final byte iSerialNumber, final byte bNumConfigurations) - { - super(bLength, bDescriptorType); - this.bcdUSB = bcdUSB; - this.bDeviceClass = bDeviceClass; - this.bDeviceSubClass = bDeviceSubClass; - this.bDeviceProtocol = bDeviceProtocol; - this.bMaxPacketSize0 = bMaxPacketSize0; - this.idVendor = idVendor; - this.idProduct = idProduct; - this.bcdDevice = bcdDevice; - this.iManufacturer = iManufacturer; - this.iProduct = iProduct; - this.iSerialNumber = iSerialNumber; - this.bNumConfigurations = bNumConfigurations; - } - - /** - * Construct from a libusb4java device descriptor. - * - * @param descriptor - * The descriptor from which to copy the data. - */ - public SimpleUsbDeviceDescriptor(DeviceDescriptor descriptor) - { - this(descriptor.bLength(), - descriptor.bDescriptorType(), - descriptor.bcdUSB(), - descriptor.bDeviceClass(), - descriptor.bDeviceSubClass(), - descriptor.bDeviceProtocol(), - descriptor.bMaxPacketSize0(), - descriptor.idVendor(), - descriptor.idProduct(), - descriptor.bcdDevice(), - descriptor.iManufacturer(), - descriptor.iProduct(), - descriptor.iSerialNumber(), - descriptor.bNumConfigurations()); - } - - @Override - public short bcdUSB() - { - return this.bcdUSB; - } - - @Override - public byte bDeviceClass() - { - return this.bDeviceClass; - } - - @Override - public byte bDeviceSubClass() - { - return this.bDeviceSubClass; - } - - @Override - public byte bDeviceProtocol() - { - return this.bDeviceProtocol; - } - - @Override - public byte bMaxPacketSize0() - { - return this.bMaxPacketSize0; - } - - @Override - public short idVendor() - { - return this.idVendor; - } - - @Override - public short idProduct() - { - return this.idProduct; - } - - @Override - public short bcdDevice() - { - return this.bcdDevice; - } - - @Override - public byte iManufacturer() - { - return this.iManufacturer; - } - - @Override - public byte iProduct() - { - return this.iProduct; - } - - @Override - public byte iSerialNumber() - { - return this.iSerialNumber; - } - - @Override - public byte bNumConfigurations() - { - return this.bNumConfigurations; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(bDescriptorType()) - .append(bLength()) - .append(this.bDeviceClass) - .append(this.bDeviceProtocol) - .append(this.bDeviceSubClass) - .append(this.bMaxPacketSize0) - .append(this.bNumConfigurations) - .append(this.bcdDevice) - .append(this.bcdUSB) - .append(this.iManufacturer) - .append(this.iProduct) - .append(this.iSerialNumber) - .append(this.idProduct) - .append(this.idVendor) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final SimpleUsbDeviceDescriptor other = (SimpleUsbDeviceDescriptor) obj; - return new EqualsBuilder() - .append(bLength(), other.bLength()) - .append(bDescriptorType(), other.bDescriptorType()) - .append(this.bDeviceClass, other.bDeviceClass) - .append(this.bDeviceProtocol, other.bDeviceProtocol) - .append(this.bDeviceSubClass, other.bDeviceSubClass) - .append(this.bMaxPacketSize0, other.bMaxPacketSize0) - .append(this.bNumConfigurations, other.bNumConfigurations) - .append(this.bcdDevice, other.bcdDevice) - .append(this.bcdUSB, other.bcdUSB) - .append(this.iManufacturer, other.iManufacturer) - .append(this.iProduct, other.iProduct) - .append(this.iSerialNumber, other.iSerialNumber) - .append(this.idProduct, other.idProduct) - .append(this.idVendor, other.idVendor) - .isEquals(); - } - - @Override - public String toString() - { - return dump(this); - } - - /** - * Dumps the specified USB device descriptor into a string and returns it. - * - * @param descriptor - * The USB device descriptor to dump. - * @return The descriptor dump. - */ - public static String dump(final UsbDeviceDescriptor descriptor) - { - return String.format( - "Device Descriptor:%n" + - " bLength %18d%n" + - " bDescriptorType %10d%n" + - " bcdUSB %19s%n" + - " bDeviceClass %13d %s%n" + - " bDeviceSubClass %10d%n" + - " bDeviceProtocol %10d%n" + - " bMaxPacketSize0 %10d%n" + - " idVendor %17s%n" + - " idProduct %16s%n" + - " bcdDevice %16s%n" + - " iManufacturer %12d%n" + - " iProduct %17d%n" + - " iSerial %18d%n" + - " bNumConfigurations %7d%n", - descriptor.bLength(), - descriptor.bDescriptorType(), - DescriptorUtils.decodeBCD(descriptor.bcdUSB()), - descriptor.bDeviceClass() & 0xff, - DescriptorUtils.getUSBClassName(descriptor.bDeviceClass()), - descriptor.bDeviceSubClass() & 0xff, - descriptor.bDeviceProtocol() & 0xff, - descriptor.bMaxPacketSize0() & 0xff, - String.format("0x%04x", descriptor.idVendor() & 0xffff), - String.format("0x%04x", descriptor.idProduct() & 0xffff), - DescriptorUtils.decodeBCD(descriptor.bcdDevice()), - descriptor.iManufacturer() & 0xff, - descriptor.iProduct() & 0xff, - descriptor.iSerialNumber() & 0xff, - descriptor.bNumConfigurations() & 0xff); - } -} diff --git a/src/main/java/org/usb4java/descriptors/SimpleUsbEndpointDescriptor.java b/src/main/java/org/usb4java/descriptors/SimpleUsbEndpointDescriptor.java deleted file mode 100644 index 13bafe7..0000000 --- a/src/main/java/org/usb4java/descriptors/SimpleUsbEndpointDescriptor.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import javax.usb.UsbEndpointDescriptor; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.EndpointDescriptor; -import org.libusb4java.utils.DescriptorUtils; - -/** - * Simple USB endpoint descriptor. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class SimpleUsbEndpointDescriptor extends SimpleUsbDescriptor - implements UsbEndpointDescriptor -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The poll interval. */ - private final byte bInterval; - - /** The maximum packet size. */ - private final short wMaxPacketSize; - - /** The endpoint attributes. */ - private final byte bmAttributes; - - /** The endpoint address. */ - private final byte bEndpointAddress; - - /** - * Constructor. - * - * @param bLength - * The descriptor length. - * @param bDescriptorType - * The descriptor type. - * @param bEndpointAddress - * The address of the endpoint. - * @param bmAttributes - * The endpoint attributes. - * @param wMaxPacketSize - * The maximum packet size. - * @param bInterval - * The poll interval. - */ - public SimpleUsbEndpointDescriptor(final byte bLength, - final byte bDescriptorType, final byte bEndpointAddress, - final byte bmAttributes, final short wMaxPacketSize, - final byte bInterval) - { - super(bLength, bDescriptorType); - this.bEndpointAddress = bEndpointAddress; - this.wMaxPacketSize = wMaxPacketSize; - this.bmAttributes = bmAttributes; - this.bInterval = bInterval; - } - - /** - * Construct from a libusb4java endpoint descriptor. - * - * @param descriptor - * The descriptor from which to copy the data. - */ - public SimpleUsbEndpointDescriptor(EndpointDescriptor descriptor) - { - this(descriptor.bLength(), - descriptor.bDescriptorType(), - descriptor.bEndpointAddress(), - descriptor.bmAttributes(), - descriptor.wMaxPacketSize(), - descriptor.bInterval()); - } - - @Override - public byte bEndpointAddress() - { - return this.bEndpointAddress; - } - - @Override - public byte bmAttributes() - { - return this.bmAttributes; - } - - @Override - public short wMaxPacketSize() - { - return this.wMaxPacketSize; - } - - @Override - public byte bInterval() - { - return this.bInterval; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(bDescriptorType()) - .append(bLength()) - .append(this.bEndpointAddress) - .append(this.bInterval) - .append(this.bmAttributes) - .append(this.wMaxPacketSize) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final SimpleUsbEndpointDescriptor other = - (SimpleUsbEndpointDescriptor) obj; - return new EqualsBuilder() - .append(bLength(), other.bLength()) - .append(bDescriptorType(), other.bDescriptorType()) - .append(this.bEndpointAddress, other.bEndpointAddress) - .append(this.bInterval, other.bInterval) - .append(this.bmAttributes, other.bmAttributes) - .append(this.wMaxPacketSize, other.wMaxPacketSize) - .isEquals(); - } - - @Override - public String toString() - { - return dump(this); - } - - /** - * Dumps the specified USB endpoint descriptor into a string and returns it. - * - * @param descriptor - * The USB endpoint descriptor to dump. - * @return The descriptor dump. - */ - public static String dump(final UsbEndpointDescriptor descriptor) - { - return String.format( - "Endpoint Descriptor:%n" + - " bLength %18d%n" + - " bDescriptorType %10d%n" + - " bEndpointAddress %9s EP %d %s%n" + - " bmAttributes %13d%n" + - " Transfer Type %s%n" + - " Synch Type %s%n" + - " Usage Type %s%n" + - " wMaxPacketSize %11d%n" + - " bInterval %16d%n", - descriptor.bLength(), - descriptor.bDescriptorType(), - String.format("0x%02x", descriptor.bEndpointAddress() & 0xff), - descriptor.bEndpointAddress() & 0x0f, - DescriptorUtils.getDirectionName(descriptor.bEndpointAddress()), - descriptor.bmAttributes() & 0xff, - DescriptorUtils.getTransferTypeName(descriptor.bmAttributes()), - DescriptorUtils.getSynchTypeName(descriptor.bmAttributes()), - DescriptorUtils.getUsageTypeName(descriptor.bmAttributes()), - descriptor.wMaxPacketSize() & 0xffff, - descriptor.bInterval() & 0xff); - } -} diff --git a/src/main/java/org/usb4java/descriptors/SimpleUsbInterfaceDescriptor.java b/src/main/java/org/usb4java/descriptors/SimpleUsbInterfaceDescriptor.java deleted file mode 100644 index 2481ae9..0000000 --- a/src/main/java/org/usb4java/descriptors/SimpleUsbInterfaceDescriptor.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (C) 2011 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import javax.usb.UsbInterfaceDescriptor; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.libusb4java.InterfaceDescriptor; -import org.libusb4java.utils.DescriptorUtils; - -/** - * Simple USB interface descriptor. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class SimpleUsbInterfaceDescriptor extends SimpleUsbDescriptor - implements UsbInterfaceDescriptor -{ - /** Serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The interface number. */ - private final byte bInterfaceNumber; - - /** The alternate setting number. */ - private final byte bAlternateSetting; - - /** The number of endpoints. */ - private final byte bNumEndpoints; - - /** The interface class. */ - private final byte bInterfaceClass; - - /** The interface sub class. */ - private final byte bInterfaceSubClass; - - /** The interface protocol. */ - private final byte bInterfaceProtocol; - - /** The interface string descriptor index. */ - private final byte iInterface; - - /** - * Constructor. - * - * @param bLength - * The descriptor length. - * @param bDescriptorType - * The descriptor type. - * @param bInterfaceNumber - * The interface number. - * @param bAlternateSetting - * The alternate setting number. - * @param bNumEndpoints - * The number of endpoints. - * @param bInterfaceClass - * The interface class. - * @param bInterfaceSubClass - * The interface sub class. - * @param bInterfaceProtocol - * The interface protocol. - * @param iInterface - * The interface string descriptor index. - */ - public SimpleUsbInterfaceDescriptor(final byte bLength, - final byte bDescriptorType, final byte bInterfaceNumber, - final byte bAlternateSetting, final byte bNumEndpoints, - final byte bInterfaceClass, final byte bInterfaceSubClass, - final byte bInterfaceProtocol, final byte iInterface) - { - super(bLength, bDescriptorType); - this.bInterfaceNumber = bInterfaceNumber; - this.bAlternateSetting = bAlternateSetting; - this.bNumEndpoints = bNumEndpoints; - this.bInterfaceClass = bInterfaceClass; - this.bInterfaceSubClass = bInterfaceSubClass; - this.bInterfaceProtocol = bInterfaceProtocol; - this.iInterface = iInterface; - } - - /** - * Construct from a libusb4java interface descriptor. - * - * @param descriptor - * The descriptor from which to copy the data. - */ - public SimpleUsbInterfaceDescriptor(InterfaceDescriptor descriptor) - { - this(descriptor.bLength(), - descriptor.bDescriptorType(), - descriptor.bInterfaceNumber(), - descriptor.bAlternateSetting(), - descriptor.bNumEndpoints(), - descriptor.bInterfaceClass(), - descriptor.bInterfaceSubClass(), - descriptor.bInterfaceProtocol(), - descriptor.iInterface()); - } - - @Override - public byte bInterfaceNumber() - { - return this.bInterfaceNumber; - } - - @Override - public byte bAlternateSetting() - { - return this.bAlternateSetting; - } - - @Override - public byte bNumEndpoints() - { - return this.bNumEndpoints; - } - - @Override - public byte bInterfaceClass() - { - return this.bInterfaceClass; - } - - @Override - public byte bInterfaceSubClass() - { - return this.bInterfaceSubClass; - } - - @Override - public byte bInterfaceProtocol() - { - return this.bInterfaceProtocol; - } - - @Override - public byte iInterface() - { - return this.iInterface; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(bDescriptorType()) - .append(bLength()) - .append(this.bAlternateSetting) - .append(this.bInterfaceClass) - .append(this.bInterfaceNumber) - .append(this.bInterfaceProtocol) - .append(this.bInterfaceSubClass) - .append(this.bNumEndpoints) - .append(this.iInterface) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final SimpleUsbInterfaceDescriptor other = - (SimpleUsbInterfaceDescriptor) obj; - return new EqualsBuilder() - .append(bLength(), other.bLength()) - .append(bDescriptorType(), other.bDescriptorType()) - .append(this.bAlternateSetting, other.bAlternateSetting) - .append(this.bInterfaceClass, other.bInterfaceClass) - .append(this.bInterfaceNumber, other.bInterfaceNumber) - .append(this.bInterfaceProtocol, other.bInterfaceProtocol) - .append(this.bInterfaceSubClass, other.bInterfaceSubClass) - .append(this.bNumEndpoints, other.bNumEndpoints) - .append(this.iInterface, other.iInterface) - .isEquals(); - } - - @Override - public String toString() - { - return dump(this); - } - - /** - * Dumps the specified USB interface descriptor into a string and returns - * it. - * - * @param descriptor - * The USB interface descriptor to dump. - * @return The descriptor dump. - */ - public static String dump(final UsbInterfaceDescriptor descriptor) - { - return String.format( - "Interface Descriptor:%n" + - " bLength %18d%n" + - " bDescriptorType %10d%n" + - " bInterfaceNumber %9d%n" + - " bAlternateSetting %8d%n" + - " bNumEndpoints %12d%n" + - " bInterfaceClass %10d %s%n" + - " bInterfaceSubClass %7d%n" + - " bInterfaceProtocol %7d%n" + - " iInterface %15d%n", - descriptor.bLength(), - descriptor.bDescriptorType(), - descriptor.bInterfaceNumber() & 0xff, - descriptor.bAlternateSetting() & 0xff, - descriptor.bNumEndpoints() & 0xff, - descriptor.bInterfaceClass() & 0xff, - DescriptorUtils.getUSBClassName(descriptor.bInterfaceClass()), - descriptor.bInterfaceSubClass() & 0xff, - descriptor.bInterfaceProtocol() & 0xff, - descriptor.iInterface() & 0xff); - } -} diff --git a/src/main/java/org/usb4java/descriptors/SimpleUsbStringDescriptor.java b/src/main/java/org/usb4java/descriptors/SimpleUsbStringDescriptor.java deleted file mode 100644 index 895ebbd..0000000 --- a/src/main/java/org/usb4java/descriptors/SimpleUsbStringDescriptor.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; - -import javax.usb.UsbStringDescriptor; - -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -/** - * Simple string descriptor. - * - * @author Klaus Reimer (k@ailis.de) - */ -public final class SimpleUsbStringDescriptor extends SimpleUsbDescriptor - implements UsbStringDescriptor -{ - /** The serial version UID. */ - private static final long serialVersionUID = 1L; - - /** The string data in UTF-16LE encoding. */ - private final byte[] bString; - - /** - * Constructs a new string descriptor by reading the descriptor data - * from the specified byte buffer. - * - * @param data - * The descriptor data as a byte buffer. - */ - public SimpleUsbStringDescriptor(final ByteBuffer data) - { - super(data.get(0), data.get(1)); - - data.position(2); - this.bString = new byte[bLength() - 2]; - data.get(this.bString); - } - - /** - * Constructs a new string descriptor with the specified data. - * - * @param bLength - * The descriptor length. - * @param bDescriptorType - * The descriptor type. - * @param string - * The string. - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - public SimpleUsbStringDescriptor(final byte bLength, - final byte bDescriptorType, final String string) - throws UnsupportedEncodingException - { - super(bLength, bDescriptorType); - this.bString = string.getBytes("UTF-16LE"); - } - - /** - * Copy constructor. - * - * @param descriptor - * The descriptor from which to copy the data. - */ - public SimpleUsbStringDescriptor(final UsbStringDescriptor descriptor) - { - super(descriptor.bLength(), descriptor.bDescriptorType()); - this.bString = descriptor.bString().clone(); - } - - @Override - public byte[] bString() - { - return this.bString.clone(); - } - - @Override - public String getString() throws UnsupportedEncodingException - { - return new String(this.bString, "UTF-16LE"); - } - - @Override - public boolean equals(final Object obj) - { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - final SimpleUsbStringDescriptor other = (SimpleUsbStringDescriptor) obj; - return new EqualsBuilder() - .append(bLength(), other.bLength()) - .append(bDescriptorType(), other.bDescriptorType()) - .append(this.bString, other.bString) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(bDescriptorType()) - .append(bLength()) - .append(this.bString) - .toHashCode(); - } - - @Override - public String toString() - { - return new String(this.bString, Charset.forName("UTF-16LE")); - } -} diff --git a/src/main/java/org/usb4java/descriptors/package-info.java b/src/main/java/org/usb4java/descriptors/package-info.java deleted file mode 100644 index 988b4e7..0000000 --- a/src/main/java/org/usb4java/descriptors/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -/** - * USB Descriptor implementations. - */ -package org.usb4java.descriptors; diff --git a/src/main/java/org/usb4java/package-info.java b/src/main/java/org/usb4java/package-info.java index bcb89a7..1553bbd 100644 --- a/src/main/java/org/usb4java/package-info.java +++ b/src/main/java/org/usb4java/package-info.java @@ -4,6 +4,7 @@ */ /** - * The main usb4java package. + * Low-Level classes based on the native libusb library. */ package org.usb4java; + diff --git a/src/main/java/org/libusb4java/utils/BufferUtils.java b/src/main/java/org/usb4java/utils/BufferUtils.java similarity index 98% rename from src/main/java/org/libusb4java/utils/BufferUtils.java rename to src/main/java/org/usb4java/utils/BufferUtils.java index c7e6e97..ba92e00 100644 --- a/src/main/java/org/libusb4java/utils/BufferUtils.java +++ b/src/main/java/org/usb4java/utils/BufferUtils.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java.utils; +package org.usb4java.utils; import java.nio.ByteBuffer; import java.nio.IntBuffer; diff --git a/src/main/java/org/libusb4java/utils/DescriptorUtils.java b/src/main/java/org/usb4java/utils/DescriptorUtils.java similarity index 98% rename from src/main/java/org/libusb4java/utils/DescriptorUtils.java rename to src/main/java/org/usb4java/utils/DescriptorUtils.java index 92e1a41..52edf48 100644 --- a/src/main/java/org/libusb4java/utils/DescriptorUtils.java +++ b/src/main/java/org/usb4java/utils/DescriptorUtils.java @@ -3,17 +3,17 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java.utils; +package org.usb4java.utils; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; -import org.libusb4java.ConfigDescriptor; -import org.libusb4java.DeviceDescriptor; -import org.libusb4java.EndpointDescriptor; -import org.libusb4java.InterfaceDescriptor; -import org.libusb4java.LibUsb; +import org.usb4java.ConfigDescriptor; +import org.usb4java.DeviceDescriptor; +import org.usb4java.EndpointDescriptor; +import org.usb4java.InterfaceDescriptor; +import org.usb4java.LibUsb; /** * Utility methods used for descriptor dumps. diff --git a/src/main/java/org/libusb4java/utils/package-info.java b/src/main/java/org/usb4java/utils/package-info.java similarity index 83% rename from src/main/java/org/libusb4java/utils/package-info.java rename to src/main/java/org/usb4java/utils/package-info.java index 2c66c2b..07427df 100644 --- a/src/main/java/org/libusb4java/utils/package-info.java +++ b/src/main/java/org/usb4java/utils/package-info.java @@ -6,4 +6,4 @@ /** * Utility classes providing static helper methods. */ -package org.libusb4java.utils; +package org.usb4java.utils; diff --git a/src/main/resources/org/libusb4java/linux-x86_64/libusb4java.so b/src/main/resources/org/libusb4java/linux-x86_64/libusb4java.so deleted file mode 100644 index d519348..0000000 Binary files a/src/main/resources/org/libusb4java/linux-x86_64/libusb4java.so and /dev/null differ diff --git a/src/test/java/javax/usb/tck/BulkIOErrorConditionsTest.java b/src/test/java/javax/usb/tck/BulkIOErrorConditionsTest.java deleted file mode 100755 index 44d8e0f..0000000 --- a/src/test/java/javax/usb/tck/BulkIOErrorConditionsTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ -------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040916 raulortz Redesign TCK to create base and optional - * tests. Separate setConfig, setInterface - * and isochronous transfers as optionals. - */ - -//import java.util.*; -import javax.usb.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; -//import javax.usb.util.*; - -import junit.framework.TestCase; - -/** - * IO Error conditions - *

- * This test verifies that error conditions are generated and proper - * exceptions are thrown in the operation. - * - * @author Thanh Ngo - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class BulkIOErrorConditionsTest extends TestCase -{ - //------------------------------------------------------------------------- - // Ctor(s) - // - - - public BulkIOErrorConditionsTest() - { - thisTest = new IOErrorConditionsTest(UsbConst.ENDPOINT_TYPE_BULK); - } - - //------------------------------------------------------------------------- - // Protected overridden methods - // - - protected void setUp() throws Exception { - thisTest.setUp(); - - } - - protected void tearDown() throws Exception { - thisTest.tearDown(); - } - - - - /** - * Null Data Buffer - */ - public void testNullDataBufferInIrp() - { - thisTest.testNullDataBufferInIrp(); - } - /** - * Null Data Buffer - */ - public void testNullDataBufferAsByteArray() - { - thisTest.testNullDataBufferAsByteArray(); - } - - /** - * Action against a closed pipe - */ - public void testActionAgainstClosePipeAbortAllSubmissions() - { - thisTest.testActionAgainstClosePipeAbortAllSubmissions(); - } - /** - * Action against a closed pipe - */ - public void testActionAgainstClosePipeSubmit() - { - thisTest.testActionAgainstClosePipeSubmit(); - } - - /** - * Close a pipe with pending operation - */ - public void testClosePipePendingAction() - { - thisTest.testClosePipePendingAction(); - } - - // Moved method testOpenPipeOnInactiveAlternateSetting into the optional setInterface tests @P1D7 - - /** - * Open a pipe on an unclaimed interface - */ - public void testOpenPipeOnUnclaimedInterface() - { - thisTest.testOpenPipeOnUnclaimedInterface(); - } - - /** - * Claim an already claimed interface - */ - public void testClaimAnAlreadyClaimedInterface() - { - thisTest.testClaimAnAlreadyClaimedInterface(); - - } - - - private IOErrorConditionsTest thisTest = null; -} diff --git a/src/test/java/javax/usb/tck/BulkIOTests.java b/src/test/java/javax/usb/tck/BulkIOTests.java deleted file mode 100755 index a71ccfc..0000000 --- a/src/test/java/javax/usb/tck/BulkIOTests.java +++ /dev/null @@ -1,576 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -package javax.usb.tck; - -import java.util.*; - -import javax.usb.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.*; - -/** - * Bulk IO Test -- Synchronous and asynchronous byte[], IRP, and IRP List submissions - *

- * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class BulkIOTests extends TestCase -{ - public void setUp() throws Exception - { - endpointType = UsbConst.ENDPOINT_TYPE_BULK; - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - Assert.assertNotNull("Device required for test not found",usbDevice); - IOMethods.createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, usbPipeListGlobal); - super.setUp(); - } - public void tearDown() throws Exception - { - IOMethods.releaseListOfPipes(usbPipeListGlobal); - super.tearDown(); - } - - public void testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer8bytes_passthrough() - { - - byte testType = IOTests.BYTE_ARRAY; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_PASSTHROUGH}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {8}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - - public void testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer16bytes_invertBits() - { - - byte testType = IOTests.BYTE_ARRAY; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {16}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - public void testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer24bytes_invertAltBits() - { - - byte testType = IOTests.BYTE_ARRAY; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_ALTERNATE_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {24}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer17bytes_passthrough() - { - byte testType = IOTests.BYTE_ARRAY; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_PASSTHROUGH}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {17}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer66bytes_invertBits() - { - byte testType = IOTests.BYTE_ARRAY; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {66}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer129bytes_invertAltBits() - { - byte testType = IOTests.BYTE_ARRAY; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_ALTERNATE_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {129}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - public void testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer8bytes_invertBits() - { - - byte testType = IOTests.IRP; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {8}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - public void testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer16bytes_invertAltBits() - { - - byte testType = IOTests.IRP; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_ALTERNATE_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {16}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - public void testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer64bytes_passthrough() - { - - byte testType = IOTests.IRP; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_PASSTHROUGH}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {64}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer25bytes_invertBits() - { - byte testType = IOTests.IRP; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {25}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer72bytes_invertAltBits() - { - byte testType = IOTests.IRP; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_ALTERNATE_BITS}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {72}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer130bytes_passthrough() - { - byte testType = IOTests.IRP; - /* - * values from table - */ - int numberOfIrps = 1; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_PASSTHROUGH}; - - boolean[] IrpAcceptShortPacket = {true}; - boolean[] verifyAcceptShortPacket = {true}; - - - int []OUTLength = {130}; - int []OUTOffset = {0}; - int []OUTExpectedActualLength = {OUTLength[0]}; - Exception[] OUTExpectedException = {null}; - - int []INLength = {OUTLength[0]}; - int []INOffset = {OUTOffset[0]}; - int []INExpectedActualLength = {OUTLength[0]}; - Exception[] INExpectedException = {null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - public void testIRPListBuffersMultiplesOfMaxPacketSizeOf8bytes() - { - - byte testType = IOTests.IRPLIST; - /* - * values from table - */ - int numberOfIrps = 3; - int endpointmaxPacketSize = 8; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_BITS, IOTests.TRANSFORM_TYPE_INVERT_ALTERNATE_BITS, - IOTests.TRANSFORM_TYPE_PASSTHROUGH}; - - boolean[] IrpAcceptShortPacket = {true, true, true}; - boolean[] verifyAcceptShortPacket = {true, true, true}; - - - int []OUTLength = {8,16, 24}; - int []OUTOffset = {0, 8, 24}; - int []OUTExpectedActualLength = {OUTLength[0], OUTLength[1], OUTLength[2]}; - Exception[] OUTExpectedException = {null, null, null}; - - int []INLength = {OUTLength[0], OUTLength[1], OUTLength[2]}; - int []INOffset = {OUTOffset[0], OUTOffset[1], OUTOffset[2]}; - int []INExpectedActualLength = {OUTLength[0],OUTLength[1], OUTLength[2]}; - Exception[] INExpectedException = {null, null, null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testIRPListBuffersNOTMultiplesOfMaxPacketSizeOf64bytes() - { - byte testType = IOTests.IRPLIST; - /* - * values from table - */ - int numberOfIrps = 3; - int endpointmaxPacketSize = 64; - byte []transformType = {IOTests.TRANSFORM_TYPE_INVERT_BITS, IOTests.TRANSFORM_TYPE_INVERT_ALTERNATE_BITS, - IOTests.TRANSFORM_TYPE_PASSTHROUGH}; - - boolean[] IrpAcceptShortPacket = {true, true, true}; - boolean[] verifyAcceptShortPacket = {true, true, true}; - - - int []OUTLength = {12, 75, 130}; - int []OUTOffset = {0, 12, 87}; - int []OUTExpectedActualLength = {OUTLength[0], OUTLength[1], OUTLength[2]}; - Exception[] OUTExpectedException = {null, null, null}; - - int []INLength = {OUTLength[0], OUTLength[1], OUTLength[2]}; - int []INOffset = {OUTOffset[0], OUTOffset[1], OUTOffset[2]}; - int []INExpectedActualLength = {OUTLength[0],OUTLength[1], OUTLength[2]}; - Exception[] INExpectedException = {null, null, null}; - - IOTests thisIOTest = new IOTests(usbDevice, usbPipeListGlobal, endpointType, testType); - thisIOTest.RoundTripIOTest(testType, numberOfIrps, endpointmaxPacketSize, - IrpAcceptShortPacket, verifyAcceptShortPacket, OUTLength, OUTOffset, OUTExpectedActualLength, - OUTExpectedException, - INLength, INOffset, INExpectedActualLength, - INExpectedException, - transformType ); - - }; - /** - * Constructor - */ - public BulkIOTests() - { - super(); - }; - - protected BulkIOTests(UsbDevice newUsbDevice, List newUsbPipeList, byte newEndpointType) - { - usbPipeListGlobal = newUsbPipeList; - usbDevice = newUsbDevice; - endpointType = newEndpointType; - }; - - - - private List usbPipeListGlobal = new ArrayList(); - private byte endpointType; - private UsbDevice usbDevice; - - - private static void printDebug(String infoString) - { - if ( printDebug ) - { - System.out.println(infoString); - } - } - private static boolean printDebug = false; - //private static boolean printDebug = true; -} diff --git a/src/test/java/javax/usb/tck/BulkIOTestwithSynchronizedUsbPipe.java b/src/test/java/javax/usb/tck/BulkIOTestwithSynchronizedUsbPipe.java deleted file mode 100755 index 5e5d0be..0000000 --- a/src/test/java/javax/usb/tck/BulkIOTestwithSynchronizedUsbPipe.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -package javax.usb.tck; - -import java.util.*; - -import javax.usb.*; -import javax.usb.util.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.*; - -/** - * Bulk IO Test -- Synchronous and asynchronous byte[], IRP, and IRP List submissions - * using UsbUtil.synchronizedUsbPipe - *

- * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class BulkIOTestwithSynchronizedUsbPipe extends TestCase -{ - public void setUp() throws Exception - { - endpointType = UsbConst.ENDPOINT_TYPE_BULK; - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - Assert.assertNotNull("Device required for test not found",usbDevice); - IOMethods.createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, usbPipeListNotSynchronized); - for ( int i=0; i - * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * This test verifies that UsbShortPacketException is received when expected. - * - * @author Leslie Blair - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class BulkShortPacketIOTests extends TestCase -{ - public void setUp() throws Exception - { - endpointType = UsbConst.ENDPOINT_TYPE_BULK; - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - Assert.assertNotNull("Device required for test not found",usbDevice); - IOMethods.createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, usbPipeListGlobal); - assertFalse("No pipes of specified endpoint were found.", (0 == usbPipeListGlobal.size())); - super.setUp(); - } - public void tearDown() throws Exception - { - IOMethods.releaseListOfPipes(usbPipeListGlobal); - super.tearDown(); - } - - - public void testShortPacketException() - { - //repeat the test for the number of iteration specified - for ( int iterations=0; (iterations < IOShortPacketTest.totalIterations); iterations++ ) - { - //first, do all transfers sync and then do async - for ( int syncOrAsync=0; syncOrAsync - * This test verifies pipes can be opened on a control endpoint other than - * endpoint 0. The programmable device used in this test suite supports - * only one control pipe, the default control pipe. The target device for - * this test will be the device with at least one non default control pipe - * as specified in the hardware configurations. Because the target device - * is not programmable, minimal communication verification will be performed - * with the non default control pipe endpoint. - * @author Joshua Lowry - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class ControlIOTest extends TestCase -{ - - public ControlIOTest(String name) - { - super(name); - } - - /** - * The setUp method reinitializes the private variables between test cases, - * so no run will affect the next run. - * @throws Exception - */ - protected void setUp() throws Exception { - usbCtrlIODev = null; - usbCtrlIOInterface = null; - usbCtrlIOInterfaceDesc = null; - usbCtrlIOEndpoint = null; - usbCtrlIOEndpointDesc = null; - usbCtrlIOPipe = null; - numDataEvents = 0; - numErrorEvents = 0; - LastUsbPipeDataEvent = new ArrayList(); - LastUsbPipeErrorEvent = new ArrayList(); - } - - /** - * The tearDown method closes the the UsbPipe if it is left open and - * releases the UsbInterface if it is left claimed after a test, so a - * failing test case doesn't prevent the next test case from running. - * @throws Exception - */ - protected void tearDown() throws Exception { - LastUsbPipeDataEvent.clear(); - LastUsbPipeErrorEvent.clear(); - try - { - if ( usbCtrlIOPipe.isOpen() ) - { - usbCtrlIOPipe.abortAllSubmissions(); - usbCtrlIOPipe.close(); - } - } catch ( UsbNotOpenException uNOE ) - { - fail("ControlIO Pipe reports is opened but throws UsbNotOpenException when " + - "close or abortAllSubmissions method called: " + uNOE.getMessage()); - } catch ( UsbNotActiveException uNAE ) { - fail("ControlIO Pipe reports is opened but throws UsbNotActiveExceptio when " + - "close or abortAllSubmissions method called: " + uNAE.getMessage()); - } catch ( UsbDisconnectedException uDE ) { - fail("ControlIO Pipe reports is opened but throws UsbDisconnectedException when " + - "close or abortAllSubmissions method called: " + uDE.getMessage()); - } catch ( UsbException uE ) { - fail("The close method was unable to close the ControlIO Pipe: " + uE.getMessage()); - } - try - { - if ( usbCtrlIOInterface.isClaimed() ) - usbCtrlIOInterface.release(); - } catch ( UsbClaimException uCE ) - { - fail("UsbInterface reports interface is claimed, release method throws" + - "UsbClaimException (device not claimed): " + uCE.getMessage()); - } catch ( UsbException uE ) - { - fail("release method unable to release UsbInterface: " + uE.getMessage()); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - } - - /** - * Finds the first USB device with a UsbEndpoint with the - * ENDPOINT_TYPE_CONTROL type other than Endpoint 0. If it finds such a - * device, this method ensures that the control UsbEndpoint's interface is - * the active UsbInterface, claims that UsbInterface and opens its UsbPipe, - * as well as asserting that alll the methods relating to the open succeed. - * If it doesn't find such a UsbEndpoint, the method fails. - * @throws Exception - */ - protected void openControlIOPipe() throws Exception { - short wMaxPacketSize; - - usbCtrlIODev = new FindControlIODevice().getControlIODevice(); - assertNotNull("There is no device with a control pipe other than the default connected", - usbCtrlIODev); - - usbCtrlIOEndpoint = FindControlIODevice.getControlIOEndpoint(usbCtrlIODev); - usbCtrlIOEndpointDesc = usbCtrlIOEndpoint.getUsbEndpointDescriptor(); - assertNotNull("There is no endpoint other than Endpoint0 that is the control type", - usbCtrlIOEndpoint); - assertTrue("This endpoint should not be endpoint0", - usbCtrlIOEndpointDesc.bEndpointAddress() != (byte) 0x00); - assertEquals("The endpoint type is not Control", - UsbConst.ENDPOINT_TYPE_CONTROL, usbCtrlIOEndpoint.getType()); - - usbCtrlIOInterface = usbCtrlIOEndpoint.getUsbInterface(); - usbCtrlIOInterfaceDesc = usbCtrlIOInterface.getUsbInterfaceDescriptor(); - - // @P2D23 - UsbConfiguration usbCtrlIOConfig; - UsbConfigurationDescriptor usbCtrlIOConfigDesc; - - usbCtrlIOConfig = usbCtrlIOInterface.getUsbConfiguration(); - usbCtrlIOConfigDesc = usbCtrlIOConfig.getUsbConfigurationDescriptor(); - - assertTrue("The configuration, interface & alternate setting for the Control Enpoint isn't active", - usbCtrlIOInterface.isActive()); - // @P2D2 - - try - { - usbCtrlIOInterface.claim(); - } catch ( UsbNotActiveException uNAE ) - { - fail("The interface should be active when claim is called"); - } catch ( UsbClaimException uCE ) - { - fail("The interface should not be claimed when claim is called"); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( UsbException uE ) // @P1C - { - fail("The interface was unable to be claimed"); - } - - assertTrue("The current interface w/the control endpoint is not claimed after claim is called", - usbCtrlIOInterface.isClaimed()); - usbCtrlIOPipe = usbCtrlIOEndpoint.getUsbPipe(); - assertTrue("The Control I/O Pipe is not active!", usbCtrlIOPipe.isActive()); - usbCtrlIOPipe.addUsbPipeListener(usbCtrlIOPipeListener); - assertFalse("The Control I/O Pipe should not be open before open is called", - usbCtrlIOPipe.isOpen()); - - try - { - usbCtrlIOPipe.open(); - } catch ( UsbNotActiveException uNAE ) - { - fail("The pipe's configuration and interface should be active when open is called"); - } catch ( UsbNotClaimedException uNCE ) - { - fail("The pipe's interface should be claimed when open is called"); - } catch ( UsbException uE ) - { - fail("The interface was unable to be opened"); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - assertTrue("The Control I/O Pipe should be open after open is called", - usbCtrlIOPipe.isOpen()); - assertNotNull("No Endpoint Descriptor was returned while attempting to open the Control I/O Pipe", - usbCtrlIOEndpointDesc); - assertNotNull("The Control Pipe was not opened", - usbCtrlIOPipe); - - wMaxPacketSize = usbCtrlIOEndpointDesc.wMaxPacketSize(); - switch ( wMaxPacketSize ) - { - case 8: - case 16: - case 32: - case 64: - break; - default: - fail("The max packet size does not conform to a valid max packet size for control pipes"); - break; - } - - } - - /** - * Closes the UsbPipe and releases the UsbInterface for the UsbEndpoint - * found in the openControlIOPipe() method. It also tests everything - * related to closing the UsbPipe and releasing the UsbInterface. - * @throws Exception - */ - protected void closeControlIOPipe() throws Exception { - assertTrue("UsbPipe.isOpen() should be true before UsbPipe.close() is called", - usbCtrlIOPipe.isOpen()); - - try - { - usbCtrlIOPipe.close(); - } catch ( UsbException uE ) - { - fail("The Control I/O Pipe couldn't be closed"); - } catch ( UsbNotOpenException uNOE ) - { - fail("The Control I/O Pipe threw a UsbNotOpenException on closing an open pipe"); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - assertFalse("UsbPipe.isOpen() should be false after UsbPipe.close() is called", - usbCtrlIOPipe.isOpen()); - usbCtrlIOPipe.removeUsbPipeListener(usbCtrlIOPipeListener); - assertTrue("The Control I/O Interface should be claimed before UsbInterface.release() is called", - usbCtrlIOInterface.isClaimed()); - - try - { - usbCtrlIOInterface.release(); - } catch ( UsbClaimException uCE ) - { - fail("A claimed interface shouldn't throw the UsbClaimException"); - } catch ( UsbException uE ) - { - fail("The interface could not be released."); - } catch ( UsbNotActiveException uNAE ) - { - fail("An active interface setting shouldn't throw the UsbNotActiveException"); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - assertFalse("The Control I/O Interface shouldn't be claimed after UsbInterface.release() is called", - usbCtrlIOInterface.isClaimed()); - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a UsbControlIrp OUT to the device. It submits the - * UsbControlIrp ten times, and checks that it got either a UsbPipeDataEvent - * or a UsbPipeErrorEvent back. If it gets a data event back, it compares - * the Irp in the data event to the Irp submitted and checks that the - * buffered data did not change, and if it gets an error event back, it - * makes sure that the exception in the event is not null. It also checks - * that the UsbControlIrp is complete immediately after the syncSubmit - * returns. - * @throws Exception - */ - public void testControlIOSyncSubmitIrp_OUT() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_OUT | - UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; - byte bRequest = UsbConst.REQUEST_CLEAR_FEATURE; - short wValue = (short) 0x0000; - short wIndex = usbCtrlIOEndpointDesc.bEndpointAddress(); - byte buffer[] = new byte[0]; - int usbCtrlIOIrpOffset; - int usbCtrlIOIrpLength; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer); - usbCtrlIOIrpOffset = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength = usbCtrlIOIrp.getLength(); - - assertFalse("OUT Irp #" + (i+1) + ": UsbCotrolIrp should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - - try - { - usbCtrlIOPipe.syncSubmit(usbCtrlIOIrp); - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for OUT syncSubmit #" + (i+1)); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for OUT syncSubmit #" + (i+1)); - } catch ( UsbException uE ) - { - assertNotNull("The OUT syncSubmit UsbException should not be null", - uE); - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - assertEquals("The UsbException for the Irp should match the exception caught", - usbCtrlIOIrp.getUsbException(), uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - if ( !usbCtrlIOIrp.isComplete() ) - { - fail("OUT Irp #" + (i+1) + ": The UsbControlIrp is not complete after syncSubmit"); - } - - for ( int j = 0; j < 400; j++ ) - { - Thread.sleep(5); - if ( numDataEvents + numErrorEvents > i ) - { - break; - } - } - if ( numDataEvents + numErrorEvents <= i ) - { - fail("No UsbPipeDataEvent or UsbPipeErrorEvent received"); - } - - assertEquals("The OUT UsbControlIrp data should not be altered", - buffer, usbCtrlIOIrp.getData()); - assertEquals("The OUT bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The OUT bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The OUT getOffset() shouldn't be altered", - usbCtrlIOIrpOffset, usbCtrlIOIrp.getOffset()); - assertEquals("The OUT getLength() shouldn't be altered", - usbCtrlIOIrpLength, usbCtrlIOIrp.getLength()); - - if ( !usbCtrlIOIrp.isUsbException() ) - { - UsbPipeDataEvent lastUsbPipeDE = - (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - // TODO No idea why these two arrays should match. Ignoring for now - //assertEquals("The OUT data event getData doesn't match the OUT Irp getData", - // usbCtrlIOIrp.getData(), lastUsbPipeDE.getData()); - assertEquals("The OUT data event UsbIrp ActualLength doesn't match the OUT Irp ActualLenth", - usbCtrlIOIrp.getActualLength(), lastUsbPipeDE.getUsbIrp().getActualLength()); - assertEquals("The OUT data event UsbIrp getOffset doesn't match the OUT Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The OUT data event UsbIrp getLength doesn't match the OUT Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The OUT data event UsbPipe doesn't match the one the Irp was submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The OUT error event's UsbPipe doesn't match the one the Irp was submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - if ( numDataEvents + numErrorEvents > 10 ) - { - fail("A total of 10 UsbPipeDataEvents and UsbPipeErrorEvents are expected, " + numDataEvents - + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a UsbControlIrp IN from the device. It submits the - * UsbControlIrp ten times, and checks that it got either a UsbPipeDataEvent - * or a UsbPipeErrorEvent back. If it gets a data event back, it compares - * the Irp in the data event to the Irp submitted and checks that the - * buffered data is not null, and if it gets an error event back, it makes - * sure that the exception in the event is not null. It also checks that - * the UsbControlIrp is complete immediately after the syncSubmit returns. - * @throws Exception - */ - public void testControlIOSyncSubmitIrp_IN() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_IN | - UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; - byte bRequest = UsbConst.REQUEST_GET_DESCRIPTOR; - short wValue = - (short) ((UsbConst.DESCRIPTOR_TYPE_STRING * (short) 0x0100) | - 0x0001); - short wIndex = (short) 0x0000; - byte buffer[] = new byte[64]; - int usbCtrlIOIrpOffset; - int usbCtrlIOIrpLength; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer); - usbCtrlIOIrp.setAcceptShortPacket(false); - usbCtrlIOIrpOffset = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength = usbCtrlIOIrp.getLength(); - - assertFalse("IN Irp #" + (i+1) + ": UsbCotrolIrp should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - assertFalse("IN Irp #" + (i+1) + ": UsbControlIrp.getAcceptShortPacket should be set to false", - usbCtrlIOIrp.getAcceptShortPacket()); - - try - { - usbCtrlIOPipe.syncSubmit(usbCtrlIOIrp); - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for IN syncSubmit #" + (i+1)); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for IN syncSubmit #" + (i+1)); - } catch ( UsbException uE ) - { - assertNotNull("The IN syncSubmit UsbException should not be null", - uE); - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - assertEquals("The UsbException for the Irp should match the exception caught", - usbCtrlIOIrp.getUsbException(), uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - if ( !usbCtrlIOIrp.isComplete() ) - { - fail("IN Irp #" + (i+1) + ": The UsbControlIrp is not complete after syncSubmit"); - } - - for ( int j = 0; j < 400; j++ ) - { - Thread.sleep(5); - if ( numDataEvents + numErrorEvents > i ) - { - break; - } - } - if ( numDataEvents + numErrorEvents <= i ) - { - fail("No UsbPipeDataEvent or UsbPipeErrorEvent received"); - } - - assertNotNull("The IN UsbControlIrp data should not be NULL", - usbCtrlIOIrp.getData()); - assertEquals("The IN bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The IN bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The IN getOffset() shouldn't be altered", - usbCtrlIOIrpOffset, usbCtrlIOIrp.getOffset()); - assertEquals("The IN getLength() shouldn't be altered", - usbCtrlIOIrpLength, usbCtrlIOIrp.getLength()); - - if ( !usbCtrlIOIrp.isUsbException() ) - { - UsbPipeDataEvent lastUsbPipeDE = - (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - assertNotNull("The IN data event getData shouldn't be NULL", - lastUsbPipeDE.getData()); - assertTrue("The IN data event UsbIrp ActualLength should be >= 0", - lastUsbPipeDE.getUsbIrp().getActualLength() >= (byte) 0); - assertEquals("The IN data event UsbIrp getOffsetdoesn't match the IN Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The IN data event UsbIrp getLength doesn't match the IN Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The IN data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertNotNull("No USB Exception was embedded in the IN Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The IN error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - if ( numDataEvents + numErrorEvents > 10 ) - { - fail("A total of 10 UsbPipeDataEvents and UsbPipeErrorEvents are expected, " + numDataEvents - + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a list of UsbControlIrps OUT to the device. It submits - * the list, and checks that it got either got ten UsbPipeDataEvents (one - * for each Irp in the list) or no more than nine UsbPipeDataEvents and a - * UsbPipeErrorEvent back. For each data event it receives, it compares the - * Irp in the data event to the Irp submitted and checks that the buffered - * data did not change. For each error event received, it makes sure that - * the exception in the event is not null. It also checks that the - * UsbControlIrp is complete for all Irps in the list immediately after the - * syncSubmit returns. - * @throws Exception - */ - public void testControlIOSyncSubmitIrpList_OUT() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - UsbException exceptionReceived = null; - List usbCtrlIOIrpList = new ArrayList(); - int usbCtrlIOIrpOffset[] = new int[10]; - int usbCtrlIOIrpLength[] = new int[10]; - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_OUT | - UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; - byte bRequest = UsbConst.REQUEST_CLEAR_FEATURE; - byte buffer[] = new byte[10]; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - short wValue = (short) 0x0000; - short wIndex = usbCtrlIOEndpointDesc.bEndpointAddress(); - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer,i,0); - usbCtrlIOIrpOffset[i] = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength[i] = usbCtrlIOIrp.getLength(); - - assertFalse("OUT Irp #" + (i+1) + " in List: UsbCotrolIrp in a list should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - usbCtrlIOIrpList.add((Object) usbCtrlIOIrp); - } - - try - { - usbCtrlIOPipe.syncSubmit(usbCtrlIOIrpList); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for OUT syncSubmit"); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for OUT syncSubmit"); - } catch ( UsbException uE ) - { - exceptionReceived = uE; - assertNotNull("The OUT syncSubmit UsbException should not be null", - uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - for ( int i = 0; i < 4000; i++ ) - { - Thread.sleep(5); - if ( numDataEvents == 10 || numErrorEvents >= 1 ) - break; - } - if ( numDataEvents + numErrorEvents < 10 && numErrorEvents == 0 ) - fail("10 UsbPipeDataEvents or 0 or more UsbPipeDataEvents & 1 or more UsbPipeErrorEvents expected, " + - numDataEvents + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - else if ( numDataEvents + numErrorEvents > 10 ) - fail("A maximum total of 10 UsbPipeDataEvents & ErrorEvents were expected, " + - numDataEvents + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - - for ( int i = 0; i < 10; i++ ) - { - usbCtrlIOIrp = (UsbControlIrp)usbCtrlIOIrpList.remove(0); - - if ( i < numDataEvents + numErrorEvents ) - { - assertTrue("OUT Irp #" + (i+1) + " in List: The UsbControlIrp is not complete after syncSubmit", - usbCtrlIOIrp.isComplete()); - if ( i < numDataEvents ) - { - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } else - { - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - } - } else - { - assertFalse("OUT Irp #" + (i+1) + " in List: The UsbControlIrp should not be complete since it wasn't submitted", - usbCtrlIOIrp.isComplete()); - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } - - assertEquals("The OUT UsbControlIrp data should not be altered", - buffer, usbCtrlIOIrp.getData()); - assertEquals("The OUT bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The OUT bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The OUT getOffset() shouldn't be altered", - usbCtrlIOIrpOffset[i], usbCtrlIOIrp.getOffset()); - assertEquals("The OUT getLength() shouldn't be altered", - usbCtrlIOIrpLength[i], usbCtrlIOIrp.getLength()); - - if ( usbCtrlIOIrp.isComplete() && !usbCtrlIOIrp.isUsbException() ) - { - UsbPipeDataEvent lastUsbPipeDE = - (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - // TODO No idea why these two arrays should match. Ignoring for now - //assertEquals("The OUT data event getData doesn't match the OUT Irp getData", - // usbCtrlIOIrp.getData(), lastUsbPipeDE.getData()); - assertEquals("The OUT data event UsbIrp ActualLength doesn't match the OUT Irp ActualLenth", - usbCtrlIOIrp.getActualLength(), lastUsbPipeDE.getUsbIrp().getActualLength()); - assertEquals("The OUT data event UsbIrp getOffset doesn't match the OUT Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The OUT data event UsbIrp getLength doesn't match the OUT Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The OUT data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else if ( usbCtrlIOIrp.isUsbException() ) - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The OUT error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a list of UsbControlIrps IN from the device. It submits - * the list, and checks that it got either got ten UsbPipeDataEvents (one - * for each Irp in the list) or no more than nine UsbPipeDataEvents and a - * UsbPipeErrorEvent back. For each data event it receives, it compares the - * Irp in the data event to the Irp submitted and checks that the buffered - * data is not null. For each error event received, it makes sure that the - * exception in the event is not null. It also checks that the - * UsbControlIrp is complete for all Irps in the list immediately after the - * syncSubmit returns. - * @throws Exception - */ - public void testControlIOSyncSubmitIrpList_IN() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - UsbException exceptionReceived = null; - List usbCtrlIOIrpList = new ArrayList(); - int usbCtrlIOIrpOffset[] = new int[10]; - int usbCtrlIOIrpLength[] = new int[10]; - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_IN | - UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; - byte bRequest = UsbConst.REQUEST_GET_DESCRIPTOR; - byte buffer[] = new byte[640]; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - short wValue = - (short) ((UsbConst.DESCRIPTOR_TYPE_STRING * (short) 0x0100) | - 0x0001); - short wIndex = (short) 0x0000; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer,(i*64),64); - usbCtrlIOIrp.setAcceptShortPacket(false); - usbCtrlIOIrpOffset[i] = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength[i] = usbCtrlIOIrp.getLength(); - - assertFalse("IN Irp #" + (i+1) + " in List: UsbCotrolIrp in a list should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - assertFalse("IN Irp #" + (i+1) + " in List: UsbControlIrp.getAcceptShortPacket should be set to false", - usbCtrlIOIrp.getAcceptShortPacket()); - usbCtrlIOIrpList.add((Object) usbCtrlIOIrp); - } - - try - { - usbCtrlIOPipe.syncSubmit(usbCtrlIOIrpList); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for IN syncSubmit"); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for IN syncSubmit"); - } catch ( UsbException uE ) - { - exceptionReceived = uE; - assertNotNull("The IN syncSubmit UsbException should not be null", - uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - for ( int i = 0; i < 4000; i++ ) - { - Thread.sleep(5); - if ( numDataEvents == 10 || numErrorEvents >= 1 ) - break; - } - if ( numDataEvents + numErrorEvents < 10 && numErrorEvents == 0 ) - fail("10 UsbPipeDataEvents or 0 or more UsbPipeDataEvents & 1 or more UsbPipeErrorEvents expected, " + - numDataEvents + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - else if ( numDataEvents + numErrorEvents > 10 ) - fail("A maximum total of 10 UsbPipeDataEvents & ErrorEvents were expected, " + - numDataEvents + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - - for ( int i = 0; i < 10; i++ ) - { - usbCtrlIOIrp = (UsbControlIrp)usbCtrlIOIrpList.get(i); - - if ( i < numDataEvents + numErrorEvents ) - { - assertTrue("OUT Irp #" + (i+1) + " in List: The UsbControlIrp is not complete after syncSubmit", - usbCtrlIOIrp.isComplete()); - if ( i < numDataEvents ) - { - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } else - { - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - } - } else - { - assertFalse("OUT Irp #" + (i+1) + " in List: The UsbControlIrp should not be complete since it wasn't submitted", - usbCtrlIOIrp.isComplete()); - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } - - assertNotNull("The IN UsbControlIrp data should not be NULL", - usbCtrlIOIrp.getData()); - assertEquals("The IN bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The IN bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The IN getOffset() shouldn't be altered", - usbCtrlIOIrpOffset[i], usbCtrlIOIrp.getOffset()); - assertEquals("The IN getLength() shouldn't be altered", - usbCtrlIOIrpLength[i], usbCtrlIOIrp.getLength()); - - if ( usbCtrlIOIrp.isComplete() && !usbCtrlIOIrp.isUsbException() ) - { - UsbPipeDataEvent lastUsbPipeDE = - (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - assertNotNull("The IN data event getData shouldn't be NULL", - lastUsbPipeDE.getData()); - assertTrue("The IN data event ActualLength should be >= 0", - lastUsbPipeDE.getUsbIrp().getActualLength() >= (byte) 0); - assertEquals("The IN data event UsbIrp getOffset doesn't match the IN Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The IN data event UsbIrp getLength doesn't match the IN Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The IN data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else if ( usbCtrlIOIrp.isUsbException() ) - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The IN error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does an - * asyncSubmit with a UsbControlIrp OUT to the device. It submits the - * UsbControlIrp ten times, and checks thatit got either a UsbPipeDataEvent - * or a UsbPipeErrorEvent back. If it gets a data event back, it compares - * the Irp in the data event to the Irp submitted and checks that the - * buffered data did not change, and if it gets an error event back, it - * makes sure that the exception in the event is not null. It also checks - * that the UsbControlIrp is complete when waitForComplete(5000) is called - * on the UsbControlIrp after the asyncSubmit returns. - * @throws Exception - */ - public void testControlIOAsyncSubmitIrp_OUT() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_OUT | - UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; - byte bRequest = UsbConst.REQUEST_CLEAR_FEATURE; - short wValue = (short) 0x0000; - short wIndex = usbCtrlIOEndpointDesc.bEndpointAddress(); - byte buffer[] = new byte[0]; - int usbCtrlIOIrpOffset; - int usbCtrlIOIrpLength; - int lastNumDataEvents = numDataEvents; - int lastNumErrorEvents = numErrorEvents; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer); - usbCtrlIOIrpOffset = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength = usbCtrlIOIrp.getLength(); - - assertFalse("OUT Irp #" + (i+1) + ": UsbCotrolIrp should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - - try - { - usbCtrlIOPipe.asyncSubmit(usbCtrlIOIrp); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for OUT asyncSubmit #" + (i+1)); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for OUT asyncSubmit #" + (i+1)); - } catch ( UsbException uE ) - { - assertNotNull("The OUT asyncSubmit UsbException should not be null", - uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - usbCtrlIOIrp.waitUntilComplete(5000); - assertTrue("OUT Irp #" + (i+1) + ": The UsbCotrolIrp should be complete after waitUntilComplete", - usbCtrlIOIrp.isComplete()); - - for ( int j = 0; j < 400; j++ ) - { - Thread.sleep(5); - if ( numDataEvents + numErrorEvents > i ) - { - if ( numDataEvents > lastNumDataEvents ) - { - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } else - { - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - } - break; - } - } - if ( numDataEvents + numErrorEvents <= i ) - { - fail("No UsbPipeDataEvent or UsbPipeErrorEvent received"); - } - - assertEquals("The OUT UsbControlIrp data should not be altered", - buffer, usbCtrlIOIrp.getData()); - assertEquals("The OUT bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The OUT bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The OUT getOffset() shouldn't be altered", - usbCtrlIOIrpOffset, usbCtrlIOIrp.getOffset()); - assertEquals("The OUT getLength() shouldn't be altered", - usbCtrlIOIrpLength, usbCtrlIOIrp.getLength()); - - if ( !usbCtrlIOIrp.isUsbException() ) - { - UsbPipeDataEvent lastUsbPipeDE = - (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - // TODO No idea why these two arrays should match. Ignoring for now - //assertEquals("The OUT data event getData doesn't match the OUT Irp getData", - // usbCtrlIOIrp.getData(), lastUsbPipeDE.getData()); - assertEquals("The OUT data event UsbIrp ActualLength doesn't match the OUT Irp ActualLenth", - usbCtrlIOIrp.getActualLength(), lastUsbPipeDE.getUsbIrp().getActualLength()); - assertEquals("The OUT data event UsbIrp getOffset doesn't match the OUT Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The OUT data event UsbIrp getLength doesn't match the OUT Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The OUT data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The OUT error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - if ( numDataEvents + numErrorEvents > 10 ) - { - fail("A total of 10 UsbPipeDataEvents and UsbPipeErrorEvents are expected, " + numDataEvents - + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a UsbControlIrp IN from the device. It submits the - * UsbControlIrp ten times, and checks that it got either a UsbPipeDataEvent - * or a UsbPipeErrorEvent back. If it gets a data event back, it compares - * the Irp in the data event to the Irp submitted and checks that the - * buffered data is not null, and if it gets an error event back, it makes - * sure that the exception in the event is not null. It also checks that - * the UsbControlIrp is complete when waitForComplete(5000) is called on the - * UsbControlIrp after the asyncSubmit returns. - * @throws Exception - */ - public void testControlIOAsyncSubmitIrp_IN() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_IN | - UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; - byte bRequest = UsbConst.REQUEST_GET_DESCRIPTOR; - short wValue = - (short) ((UsbConst.DESCRIPTOR_TYPE_STRING * (short) 0x0100) | - 0x0001); - short wIndex = (short) 0x0000; - byte buffer[] = new byte[64]; - int usbCtrlIOIrpOffset; - int usbCtrlIOIrpLength; - int lastNumDataEvents = numDataEvents; - int lastNumErrorEvents = numErrorEvents; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer); - usbCtrlIOIrp.setAcceptShortPacket(false); - usbCtrlIOIrpOffset = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength = usbCtrlIOIrp.getLength(); - - assertFalse("IN Irp #" + (i+1) + ": UsbCotrolIrp should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - assertFalse("IN Irp #" + (i+1) + ": UsbControlIrp.getAcceptShortPacket should be set to false", - usbCtrlIOIrp.getAcceptShortPacket()); - - try - { - usbCtrlIOPipe.asyncSubmit(usbCtrlIOIrp); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for IN asyncSubmit #" + (i+1)); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for IN asyncSubmit #" + (i+1)); - } catch ( UsbException uE ) - { - assertNotNull("The IN asyncSubmit UsbException should not be null", - uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - usbCtrlIOIrp.waitUntilComplete(5000); - assertTrue("IN Irp #" + (i+1) + ": The UsbCotrolIrp should be complete after waitUntilComplete", - usbCtrlIOIrp.isComplete()); - - for ( int j = 0; j < 400; j++ ) - { - Thread.sleep(5); - if ( numDataEvents + numErrorEvents > i ) - { - if ( numDataEvents > lastNumDataEvents ) - { - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - } else - { - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - } - break; - } - } - if ( numDataEvents + numErrorEvents <= i ) - { - fail("No UsbPipeDataEvent or UsbPipeErrorEvent received"); - } - - assertNotNull("The IN UsbControlIrp data should not be NULL", - usbCtrlIOIrp.getData()); - assertEquals("The IN bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The IN bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The IN getOffset() shouldn't be altered", - usbCtrlIOIrpOffset, usbCtrlIOIrp.getOffset()); - assertEquals("The IN getLength() shouldn't be altered", - usbCtrlIOIrpLength, usbCtrlIOIrp.getLength()); - - if ( !usbCtrlIOIrp.isUsbException() ) - { - UsbPipeDataEvent lastUsbPipeDE = - (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - assertNotNull("The IN data event getData shouldn't be NULL", - lastUsbPipeDE.getData()); - assertTrue("The IN data event ActualLength should be >= 0", - lastUsbPipeDE.getUsbIrp().getActualLength() >= (byte) 0); - assertEquals("The IN data event UsbIrp getOffset doesn't match the IN Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The IN data event UsbIrp getLength doesn't match the IN Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The IN data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertNotNull("No USB Exception was embedded in the IN Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The IN error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - if ( numDataEvents + numErrorEvents > 10 ) - { - fail("A total of 10 UsbPipeDataEvents and UsbPipeErrorEvents are expected, " + numDataEvents - + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a list of UsbControlIrps OUT to the device. It submits - * the list, and checks that it got either a total of ten UsbPipeDataEvents - * and UsbPipeErrorEvents (a data event or error event for each Irp in the - * list) back. For each data event it receives, it compares the Irp in the - * data event to the Irp submitted and checks that the buffered data did not - * change. For each error event received it makes sure that the exception in - * the event is not null. It also checks that the UsbControlIrp is complete - * when waitForComplete(5000) is called on all UsbControlIrps in the list - * after the asyncSubmit returns. - * @throws Exception - */ - public void testControlIOAsyncSubmitIrpList_OUT() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - List usbCtrlIOIrpList = new ArrayList(); - int usbCtrlIOIrpOffset[] = new int[10]; - int usbCtrlIOIrpLength[] = new int[10]; - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_OUT | - UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; - byte bRequest = UsbConst.REQUEST_CLEAR_FEATURE; - byte buffer[] = new byte[10]; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - short wValue = (short) 0x0000; - short wIndex = usbCtrlIOEndpointDesc.bEndpointAddress(); - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer,i,0); - usbCtrlIOIrpOffset[i] = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength[i] = usbCtrlIOIrp.getLength(); - - assertFalse("OUT Irp #" + (i+1) + " in List: UsbCotrolIrp in a list should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - usbCtrlIOIrpList.add((Object) usbCtrlIOIrp); - } - - try - { - usbCtrlIOPipe.asyncSubmit(usbCtrlIOIrpList); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for OUT asyncSubmit"); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for OUT asyncSubmit"); - } catch ( UsbException uE ) - { - assertNotNull("The OUT asyncSubmit UsbException should not be null", - uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - for ( int i = 0; i < 10; i++ ) - { - usbCtrlIOIrp = (UsbControlIrp)usbCtrlIOIrpList.get(i); - - usbCtrlIOIrp.waitUntilComplete(5000); - assertTrue("OUT Irp #" + (i+1) + " in List: The UsbControlIrp is not complete after waitForComplete", - usbCtrlIOIrp.isComplete()); - - for ( int j = 0; j < 400; j++ ) - { - Thread.sleep(5); - if ( numDataEvents + numErrorEvents > i ) - break; - } - } - - if ( numDataEvents + numErrorEvents != 10 ) - fail("A total of 10 UsbPipeDataEvents and UsbPipeDataEvents are expected, " + - numDataEvents + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - - for ( int i = 0; i < 10; i++ ) - { - usbCtrlIOIrp = (UsbControlIrp)usbCtrlIOIrpList.remove(0); - - assertEquals("The OUT UsbControlIrp data should not be altered", - buffer, usbCtrlIOIrp.getData()); - assertEquals("The OUT bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The OUT bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The OUT getOffset() shouldn't be altered", - usbCtrlIOIrpOffset[i], usbCtrlIOIrp.getOffset()); - assertEquals("The OUT getLength() shouldn't be altered", - usbCtrlIOIrpLength[i], usbCtrlIOIrp.getLength()); - - if ( LastUsbPipeDataEvent.size() > 0 ) - { - UsbPipeDataEvent lastUsbPipeDE = (UsbPipeDataEvent) LastUsbPipeDataEvent.get(0); - - if ( usbCtrlIOIrpOffset[i] == lastUsbPipeDE.getUsbIrp().getOffset() && - usbCtrlIOIrpLength[i] == lastUsbPipeDE.getUsbIrp().getLength() ) - { - lastUsbPipeDE = (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - // TODO No idea why these two arrays should match. Ignoring for now - //assertEquals("The OUT data event getData doesn't match the OUT Irp getData", - // usbCtrlIOIrp.getData(), lastUsbPipeDE.getData()); - assertEquals("The OUT data event UsbIrp ActualLength doesn't match the OUT Irp ActualLenth", - usbCtrlIOIrp.getActualLength(), lastUsbPipeDE.getUsbIrp().getActualLength()); - assertEquals("The OUT data event UsbIrp getOffset doesn't match the OUT Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The OUT data event UsbIrp getLength doesn't match the OUT Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The OUT data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else - { - UsbPipeErrorEvent lastUsbPipeEE = (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The OUT error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } else - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The OUT error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes a UsbPipe opened by the openControlIOPipe() method and does a - * syncSubmit with a list of UsbControlIrps IN from the device. It submits - * the list, and checks that it got either a total of ten UsbPipeDataEvents - * and UsbPipeErrorEvents (a data event or error event for each Irp in the - * list) back. For each data event it receives, it compares the Irp in the - * data event to the Irp submitted and checks that the buffered data is not - * null. For each error event received, it makes sure that the exception in - * the event is not null. It also checks that the UsbControlIrp is complete - * when waitForComplete(5000) is called on all UsbControlIrps in the list - * after the asyncSubmit returns. - * @throws Exception - */ - public void testControlIOAsyncSubmitIrpList_IN() throws Exception{ - UsbControlIrp usbCtrlIOIrp; - List usbCtrlIOIrpList = new ArrayList(); - int usbCtrlIOIrpOffset[] = new int[10]; - int usbCtrlIOIrpLength[] = new int[10]; - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_IN | - UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; - byte bRequest = UsbConst.REQUEST_GET_DESCRIPTOR; - byte buffer[] = new byte[640]; - - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - - for ( int i = 0; i < 10; i++ ) - { - short wValue = - (short) ((UsbConst.DESCRIPTOR_TYPE_STRING * (short) 0x0100) | - 0x0001); - short wIndex = (short) 0x0000; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer,(i*64),64); - usbCtrlIOIrp.setAcceptShortPacket(false); - usbCtrlIOIrpOffset[i] = usbCtrlIOIrp.getOffset(); - usbCtrlIOIrpLength[i] = usbCtrlIOIrp.getLength(); - - assertFalse("IN Irp #" + (i+1) + " in List: UsbCotrolIrp in a list should not be complete before the submit", - usbCtrlIOIrp.isComplete()); - assertFalse("IN Irp #" + (i+1) + " in List: UsbControlIrp.getAcceptShortPacket should be set to false", - usbCtrlIOIrp.getAcceptShortPacket()); - usbCtrlIOIrpList.add((Object) usbCtrlIOIrp); - } - - try - { - usbCtrlIOPipe.asyncSubmit(usbCtrlIOIrpList); - } catch ( IllegalArgumentException uIAE ) - { - fail("The buffer is set to NULL for IN asyncSubmit"); - } catch ( UsbNotOpenException uNOE ) - { - fail("The pipe is not open for IN asyncSubmit"); - } catch ( UsbException uE ) - { - assertNotNull("The IN asyncSubmit UsbException should not be null", - uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - for ( int i = 0; i < 10; i++ ) - { - usbCtrlIOIrp = (UsbControlIrp)usbCtrlIOIrpList.get(i); - - usbCtrlIOIrp.waitUntilComplete(5000); - assertTrue("OUT Irp #" + (i+1) + " in List: The UsbControlIrp is not complete after waitForComplete", - usbCtrlIOIrp.isComplete()); - - for ( int j = 0; j < 400; j++ ) - { - Thread.sleep(5); - if ( numDataEvents + numErrorEvents > i ) - break; - } - } - - if ( numDataEvents + numErrorEvents != 10 ) - fail("A total of 10 UsbPipeDataEvents and UsbPipeDataEvents are expected, " + - numDataEvents + " UsbPipeDataEvents & " + numErrorEvents + " UsbPipeErrorEvents received"); - - for ( int i = 0; i < 10; i++ ) - { - usbCtrlIOIrp = (UsbControlIrp)usbCtrlIOIrpList.get(i); - - assertNotNull("The IN UsbControlIrp data should not be NULL", - usbCtrlIOIrp.getData()); - assertEquals("The IN bmRequestType shouldn't be altered", - bmRequestType, usbCtrlIOIrp.bmRequestType()); - assertEquals("The IN bRequest shouldn't be altered", - bRequest, usbCtrlIOIrp.bRequest()); - assertEquals("The IN getOffset() shouldn't be altered", - usbCtrlIOIrpOffset[i], usbCtrlIOIrp.getOffset()); - assertEquals("The IN getLength() shouldn't be altered", - usbCtrlIOIrpLength[i], usbCtrlIOIrp.getLength()); - - if ( LastUsbPipeDataEvent.size() > 0 ) - { - UsbPipeDataEvent lastUsbPipeDE = (UsbPipeDataEvent) LastUsbPipeDataEvent.get(0); - - if ( usbCtrlIOIrpOffset[i] == lastUsbPipeDE.getUsbIrp().getOffset() && - usbCtrlIOIrpLength[i] == lastUsbPipeDE.getUsbIrp().getLength() ) - { - lastUsbPipeDE = (UsbPipeDataEvent) LastUsbPipeDataEvent.remove(0); - - assertFalse("The usbCtrlIOIrp.isUsbException should be set to FALSE", - usbCtrlIOIrp.isUsbException()); - assertNotNull("The IN data event getData shouldn't be NULL", - lastUsbPipeDE.getData()); - assertTrue("The IN data event ActualLength should be >= 0", - lastUsbPipeDE.getUsbIrp().getActualLength() >= (byte) 0); - assertEquals("The IN data event UsbIrp getOffset doesn't match the IN Irp getOffset", - usbCtrlIOIrp.getOffset(), lastUsbPipeDE.getUsbIrp().getOffset()); - assertEquals("The IN data event UsbIrp getLength doesn't match the IN Irp getLength", - usbCtrlIOIrp.getLength(), lastUsbPipeDE.getUsbIrp().getLength()); - assertEquals("The IN data event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeDE.getUsbPipe()); - } else - { - UsbPipeErrorEvent lastUsbPipeEE = (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The IN error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } else - { - UsbPipeErrorEvent lastUsbPipeEE = - (UsbPipeErrorEvent) LastUsbPipeErrorEvent.remove(0); - - assertTrue("The usbCtrlIOIrp.isUsbException should be set to TRUE", - usbCtrlIOIrp.isUsbException()); - assertNotNull("No USB Exception was embedded in the OUT Error Event", - lastUsbPipeEE.getUsbException()); - assertEquals("The UsbException for the Irp should match the error event exception", - usbCtrlIOIrp.getUsbException(), lastUsbPipeEE.getUsbException()); - assertEquals("The IN error event UsbPipe doesn't match the UsbPipe submitted on", - usbCtrlIOPipe, lastUsbPipeEE.getUsbPipe()); - } - } - - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - } - - /** - * Takes an open UsbPipe and calls the UsbPipe.abortAllSubmissions method to - * test that it doesn't throw any exceptions on an open pipe. - * @throws Exception - */ - public void testAbortAllSubmissionsOpenPipe() throws Exception { - try - { - openControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening the Control I/O Pipe"); - } - assertTrue("The usbPipe.isOpen() method should be true on an open pipe", - usbCtrlIOPipe.isOpen()); - try - { - usbCtrlIOPipe.abortAllSubmissions(); - } catch ( UsbNotOpenException uNOE ) - { - fail("AbortAllSubmissions threw a UsbNotOpenException on an open pipe"); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - try - { - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while closing the Control I/O Pipe"); - } - assertFalse("The usbPipe.isOpen() method should be false on a closed pipe", - usbCtrlIOPipe.isOpen()); - } - - /** - * Takes a closed UsbPipe and calls the UsbPipe.abortAllSubmissions method - * to test that it throws a UsbNotOpenException on a closed pipe. - * @throws Exception - */ - public void testAbortAllSubmissionsClosedPipe() - { - try - { - openControlIOPipe(); - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening or closing the Control I/O Pipe"); - } - assertFalse("The usbPipe.isOpen() method should be false on a closed pipe", - usbCtrlIOPipe.isOpen()); - try - { - usbCtrlIOPipe.abortAllSubmissions(); - fail("abortAllSubmissions didn't throw a UsbNotOpenException on a closed pipe"); - } catch ( UsbNotOpenException uNOE ) - { - assertNotNull("The UsbNotOpenException shouldn't be null", - uNOE); - } - } - - /** - * Takes a closed UsbPipe and calls the UsbPipe.syncSubmit method with a - * UsbControlIrp to test that it throws a UsbNotOpenException on a closed - * pipe. - * @throws Exception - */ - public void testSyncSubmitClosedPipe() - { - try - { - openControlIOPipe(); - closeControlIOPipe(); - } catch ( Exception e ) - { - fail("There was an exception while opening or closing the Control I/O Pipe"); - } - assertFalse("The usbPipe.isOpen() method should be fale on a closed pipe", - usbCtrlIOPipe.isOpen()); - try - { - UsbControlIrp usbCtrlIOIrp; - byte bmRequestType = - UsbConst.REQUESTTYPE_TYPE_STANDARD | - UsbConst.ENDPOINT_DIRECTION_OUT | - UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; - byte bRequest = UsbConst.REQUEST_CLEAR_FEATURE; - short wValue = (short) 0x0000; - short wIndex = usbCtrlIOEndpointDesc.bEndpointAddress(); - byte buffer[] = new byte[0]; - int usbCtrlIOIrpOffset; - int usbCtrlIOIrpLength; - - usbCtrlIOIrp = usbCtrlIOPipe.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex); - usbCtrlIOIrp.setData(buffer); - usbCtrlIOPipe.syncSubmit(usbCtrlIOIrp); - fail("syncSubmit didn't throw a UsbNotOpenException on a closed pipe"); - } catch ( UsbNotOpenException uNOE ) - { - assertNotNull("The UsbNotOpenException shouldn't be null", - uNOE); - } catch ( UsbException uE ) - { - fail("UsbNotOpenException expected. Submitting on a closed pipe should not throw a generic UsbException" + uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( java.lang.IllegalArgumentException iAE ) // @P1C - { - fail("Submit should not throw IllegalArguementException w/valid Irp is used"); - } - } - - /** - * This method listens for all the UsbPipeDataEvents and UsbPipeErrorEvents - * and tests that they are not null. It then makes sure that the data and - * error events are available for the test cases above to access to ensure - * that they correspond to data or error events expected within the test - * cases. - */ - protected UsbPipeListener usbCtrlIOPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent uPDE) - { - numDataEvents++; - assertNotNull("The Data Event object shouldn't be null", uPDE); - LastUsbPipeDataEvent.add((Object) uPDE); - } - public void errorEventOccurred(UsbPipeErrorEvent uPEE) - { - numErrorEvents++; - assertNotNull("The Error Event object shouldn't be null", uPEE); - LastUsbPipeErrorEvent.add((Object) uPEE); - } - }; - - //************************************************************************** - // Private variables accessable between the tests - - private UsbDevice usbCtrlIODev; - private UsbInterface usbCtrlIOInterface; - private UsbInterfaceDescriptor usbCtrlIOInterfaceDesc; - private UsbEndpoint usbCtrlIOEndpoint; - private UsbEndpointDescriptor usbCtrlIOEndpointDesc; - private UsbPipe usbCtrlIOPipe; - private List LastUsbPipeDataEvent; - private List LastUsbPipeErrorEvent; - private int numDataEvents; - private int numErrorEvents; -} diff --git a/src/test/java/javax/usb/tck/DefaultControlPipeTestErrorConditions.java b/src/test/java/javax/usb/tck/DefaultControlPipeTestErrorConditions.java deleted file mode 100755 index 75b4367..0000000 --- a/src/test/java/javax/usb/tck/DefaultControlPipeTestErrorConditions.java +++ /dev/null @@ -1,753 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -import java.util.*; - -import javax.usb.*; -import javax.usb.event.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.TestCase; - -/** - * Default Control Pipe Test -- Error Conditions - *

- * This test verifies that control transfers operations work successfully - * on the Default Control Pipe and that proper events are generated and proper - * exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class DefaultControlPipeTestErrorConditions extends TestCase -{ - public void setUp() throws Exception - { - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - assertNotNull("Device required for test not found",usbDevice); - super.setUp(); - - } - public void tearDown() throws Exception - { - if ( debug ) - { - /* Print out some debug info - */ - System.out.println("iterations = " + iterations); - System.out.println("numSubmits = " + numSubmits); - System.out.println("numDataEvents = " + numDataEvents); - System.out.println("numExceptionEvents = " + numExceptionEvents); - System.out.println("numDetachEvents = " + numDetachEvents); - } - super.tearDown(); - } - - public void testUsbShortPacketException() - { - usbDevice.addUsbDeviceListener(deviceListener); - - for ( int i=0; (i < iterations); i++ ) - { - for ( int j=0; j - * @param SyncOrAsync - * @param OUTbmRequestType bmRequestType used for OUT IRP - * @param OUTbRequest bRequest used for OUT IRP - * @param OUTwValue wValue used for OUT IRP (always 0x00=VENDOR_REQUEST_DATA_OUT for OUT IRPs) - * @param OUTwIndex wIndex for OUT IRP is start index for IRP at device end (usually zero even if offset is non-zero) - * @param OUTwLength wLength is length of OUT IRP (set by setData() or setLength() method of IRP) - * @param OUTIrpAcceptShortPacket acceptShortPacket setting for IRP (this value only used for checking default value of true. - * acceptShortPacket is NOT set in RoundTripTest) - * @param OUTverifyAcceptShortPacket Specify whether to verify acceptShortPacket - * @param OUTIrpLength Length of IRP to be read from byte[]. Set indirectly by setData(). Same as wLength for this test, - * @param OUTIrpOffset Offset in byte[] at which to start reading IRP. - * @param OUTIrpExpectedActualLength ActualLength is the length of data actually transmitted in IRP. Same as wLength for OUT. - * @param INbmRequestType bmRequestType used for IN IRP - * @param INbRequest bRequest used for IN IRP (always 0xB0=VENDOR_REQUEST_TRANSFER_DATA) - * @param INwValue wValue used for IN IRP (always 0x80=VENDOR_REQUEST_DATA_IN for IN IRPs) - * @param INwIndex wIndex for IN IRP is start index for reading IRP at device end (usually zero even if offset is non-zero) - * @param INwLength wLength is length of IN IRP to be read from device - * @param INIrpAcceptShortPacket acceptShortPacket setting for IRP (this value only used for checking default value of true. - * acceptShortPacket is NOT set in RoundTripTest) - * @param INverifyAcceptShortPacket Specify whether to verify acceptShortPacket - * @param INIrpLength Length of IN data buffer - * @param INIrpOffset Offset at which to start writing IN data buffer - * @param INIrpExpectedActualLength Actual length of data in IN buffer after submit complete. - * @param INIrpExpectedException Expected exception - * @param bTransformType TRANSFORM_TYPE_PASSTHROUGH = (byte)0x01 (only transform used for this test) - */ - - private void RoundTripTestPossibleErrors(boolean SyncOrAsync, byte OUTbmRequestType, byte OUTbRequest, short OUTwValue, short OUTwIndex, short OUTwLength, - boolean OUTIrpAcceptShortPacket, boolean OUTverifyAcceptShortPacket, int OUTIrpLength, int OUTIrpOffset, int OUTIrpExpectedActualLength, - Exception OUTIrpExpectedException, - byte INbmRequestType, byte INbRequest, short INwValue, short INwIndex, short INwLength, - boolean INIrpAcceptShortPacket, boolean INverifyAcceptShortPacket, int INIrpLength, int INIrpOffset, int INIrpExpectedActualLength, - UsbException INIrpExpectedException, - byte bTransformType ) - { - - if ( SyncOrAsync == SYNC_SUBMIT ) - { - VerifyIrpMethods.printDebug("RoundTripTestPossibleErrors -- SYNC"); - } - else - { - VerifyIrpMethods.printDebug("RoundTripTestPossibleErrors -- ASYNC"); - } - - byte[] expectedData = null; - Exception caughtException = null; - UsbDeviceEvent LastUsbDeviceEvent = null; - - assertNotNull("usbDevice is null, but should not be null.", usbDevice); - - //create Control IRP - UsbControlIrp usbControlIrpOUT = usbDevice.createUsbControlIrp(OUTbmRequestType, OUTbRequest, OUTwValue, OUTwIndex); - - //set data in control IRP OUT and data should remain unchanged after submission - TransmitBuffer transmitBuffer = new TransmitBuffer(bTransformType, OUTwLength); - byte[] OUTbuffer = transmitBuffer.getOutBuffer(); - usbControlIrpOUT.setData(OUTbuffer); - - //Don't check return on send because exceptions must be verified in this test - caughtException = SendUsbControlIrp(SyncOrAsync, usbDevice, usbControlIrpOUT); - - //set generic LastUsbDeviceEvent - LastUsbDeviceEvent = null; - if ( LastUsbDeviceErrorEvent == null ) - { - LastUsbDeviceEvent = LastUsbDeviceDataEvent; - } - else - { - LastUsbDeviceEvent = LastUsbDeviceErrorEvent; - } - - if ( debug ) - { - System.out.println("LastUsbDeviceDataEvent is " + LastUsbDeviceDataEvent); - System.out.println("LastUsbDeviceErrorEvent is " + LastUsbDeviceErrorEvent); - System.out.println("LastUsbDeviceEvent is " + LastUsbDeviceEvent); - } - - //You can either have expected data or an expected exception; not both - if ( OUTIrpExpectedException == null ) - { - expectedData = transmitBuffer.getOutBuffer(); - } - else - { - expectedData = null; - } - - //verify OUT IRP after successful transmit - VerifyIrpMethods.verifyUsbControlIrpAfterEvent(usbControlIrpOUT, - (EventObject)LastUsbDeviceEvent, - expectedData, - OUTIrpExpectedActualLength, - OUTIrpExpectedException, - OUTIrpAcceptShortPacket, - OUTverifyAcceptShortPacket, - OUTIrpOffset, - OUTIrpLength, - OUTbmRequestType, - OUTbRequest, - OUTwValue, - OUTwIndex); - /* - * For syncSubmit, all exceptions should be thrown on submit and should equal expected exception. - * For asyncSubmit, exceptions might not be thrown on submit so they will only be checked against - * expected exception if one was actually thrown. - */ - if ( (SyncOrAsync == SYNC_SUBMIT) && (OUTIrpExpectedException != null) ) - { - assertEquals("For sync submit, expected exceptions should be thrown on submit", - OUTIrpExpectedException, caughtException); - } - else if ( (SyncOrAsync == ASYNC_SUBMIT) && (caughtException != null) ) - { - assertEquals("For async submit, any caught exceptions should be match expected exception", - OUTIrpExpectedException, caughtException); - } - - //Only do IN if there was no error event on the out - if ( LastUsbDeviceErrorEvent == null ) - { - //Reset device events to null after verifications are complete - LastUsbDeviceErrorEvent = null; - LastUsbDeviceDataEvent = null; - - UsbControlIrp usbControlIrpIN = usbDevice.createUsbControlIrp(INbmRequestType, INbRequest, INwValue, INwIndex); - - //create data buffer in control IRP IN - byte[] INBuffer = new byte[INwLength]; - usbControlIrpIN.setData(INBuffer); - usbControlIrpIN.setAcceptShortPacket(INIrpAcceptShortPacket); - - //Don't check return on send because exceptions must be verified in this test - caughtException = SendUsbControlIrp(SyncOrAsync, usbDevice, usbControlIrpIN); - - //set generic LastUsbDeviceEvent - LastUsbDeviceEvent = null; - if ( LastUsbDeviceErrorEvent == null ) - { - LastUsbDeviceEvent = LastUsbDeviceDataEvent; - } - else - { - LastUsbDeviceEvent = LastUsbDeviceErrorEvent; - } - - if ( debug ) - { - System.out.println("LastUsbDeviceDataEvent is " + LastUsbDeviceDataEvent); - System.out.println("LastUsbDeviceErrorEvent is " + LastUsbDeviceErrorEvent); - System.out.println("LastUsbDeviceEvent is " + LastUsbDeviceEvent); - } - - //You can either have expected data or an expected exception; not both - if ( INIrpExpectedException == null ) - { - expectedData = transmitBuffer.getInBuffer(); - } - else - { - expectedData = null; - } - - //verify OUT IRP after successful transmit - VerifyIrpMethods.verifyUsbControlIrpAfterEvent(usbControlIrpIN, - (EventObject) LastUsbDeviceEvent, - expectedData, - INIrpExpectedActualLength, - INIrpExpectedException, - INIrpAcceptShortPacket, - INverifyAcceptShortPacket, - INIrpOffset, - INIrpLength, - INbmRequestType, - INbRequest, - INwValue, - INwIndex); - /* - * For syncSubmit, all exceptions should be thrown on submit and should equal expected exception. - * For asyncSubmit, exceptions might not be thrown on submit so they will only be checked against - * expected exception if one was actually thrown. - */ - if ( (SyncOrAsync == SYNC_SUBMIT) && (OUTIrpExpectedException != null) ) - { - assertEquals("For sync submit, expected exceptions should be thrown on submit", - OUTIrpExpectedException, caughtException); - } - else if ( (SyncOrAsync == ASYNC_SUBMIT) && (caughtException != null) ) - { - assertEquals("For async submit, any caught exceptions should be match expected exception", - OUTIrpExpectedException, caughtException); - } - - - } - //Reset device events to null after verifications are complete - LastUsbDeviceErrorEvent = null; - LastUsbDeviceDataEvent = null; - }; - - /** - * The OneWayTestPossibleErrors is a USB Standard Request that is either OUT or IN - * @param SyncOrAsync SYNC_SUBMIT or ASYNC_SUBMIT - * @param SentbmRequestType bmRequestType for IRP to be sent - * @param SentbRequest bRequest for IRP to be sent - * @param SentwValue wValue for IRP to be sent - * @param SentwIndex wIndex for IRP to be sent - * @param SentwLength wLength for IRP to be sent - * @param SentIrpAcceptShortPacket acceptShortPacket setting of IRP to be sent - * @param SentIrpLength Length of byte[] data to be sent - * @param SentIrpOffset Starting offset of byte[] data to be sent - * @param SentData byte[] to be set in IRP - * @param expectedbmRequestType expected bmRequestType - * @param expectedbRequest expected bRequest - * @param expectedwValue expected wValue - * @param expectedwIndex expected wIndex - * @param expectedwLength expected wLength - * @param expectedAcceptShortPacket expected acceptShortPacket setting - * @param verifyAcceptShortPacket Specify whether or not to verify acceptShortPacket - * @param expectedLength expected unchanged length for byte[] - * @param expectedOffset expected unchaged offset for byte[] - * @param expectedActualLength expected actual length of data sent or received - * @param expectedException expectedException - * @param expectedData expected byte[] - */ - private void OneWayTestPossibleErrors(boolean SyncOrAsync,byte SentbmRequestType, byte SentbRequest, short SentwValue, short SentwIndex, short SentwLength, - boolean SentIrpAcceptShortPacket, int SentIrpLength, int SentIrpOffset, byte []SentData, - byte expectedbmRequestType, byte expectedbRequest, short expectedwValue, short expectedwIndex, short expectedwLength, - boolean expectedAcceptShortPacket, boolean verifyAcceptShortPacket, int expectedLength, int expectedOffset, int expectedActualLength, - Exception expectedException, - byte [] expectedData) - { - if ( SyncOrAsync == SYNC_SUBMIT ) - { - VerifyIrpMethods.printDebug("OneWayTestPossibleErrors -- SYNC"); - } - else - { - VerifyIrpMethods.printDebug("OneWayTestPossibleErrors -- ASYNC"); - } - - Exception caughtException = null; - - //make sure usbDevice has been set - assertNotNull("usbDevice is null, but should not be null.", usbDevice); - - //create Control IRP - UsbControlIrp usbControlIrp = usbDevice.createUsbControlIrp(SentbmRequestType, SentbRequest, SentwValue, SentwIndex); - - //set variable parts of Irp - usbControlIrp.setAcceptShortPacket(SentIrpAcceptShortPacket); - - if ( SentData != null ) - { - //if SentData is not null, then go ahead and set the data - usbControlIrp.setData(SentData); - - } - else - { - //if SentData is null, that is a signal to force the error condition where - //a null buffer is set in the IRP - try - { - usbControlIrp.setData(SentData); - fail("java.lang.IllegalArgumentException should have been thrown, but no expception was thrown." ); - } - catch ( java.lang.IllegalArgumentException e ) - { - //should have come through here - VerifyIrpMethods.printDebug("Got illegal argument exception for attempting to set a null buffer."); - return; //there will be nothing to verify - } - catch ( Exception e ) - { - fail("java.lang.IllegalArgumentException should have been thrown, but expception " - + e.getMessage() + " was thrown instead."); - } - - //Don't verify return since we need to check exceptions for this test - - } - - caughtException = SendUsbControlIrp(SyncOrAsync, usbDevice, usbControlIrp); - - //set generic LAstUsbDeviceEvent - UsbDeviceEvent LastUsbDeviceEvent = null; - if ( LastUsbDeviceErrorEvent == null ) - { - LastUsbDeviceEvent = LastUsbDeviceDataEvent; - } - else - { - LastUsbDeviceEvent = LastUsbDeviceErrorEvent; - } - - if ( debug ) - { - System.out.println("LastUsbDeviceDataEvent is " + LastUsbDeviceDataEvent); - System.out.println("LastUsbDeviceDataEvent is " + LastUsbDeviceErrorEvent); - System.out.println("LastUsbDeviceDataEvent is " + LastUsbDeviceEvent); - } - - //verify OUT IRP after transmit - VerifyIrpMethods.verifyUsbControlIrpAfterEvent(usbControlIrp, - (EventObject)LastUsbDeviceEvent, - expectedData, - expectedActualLength, - expectedException, - expectedAcceptShortPacket, - verifyAcceptShortPacket, - expectedOffset, - expectedLength, - expectedbmRequestType, - expectedbRequest, - expectedwValue, - expectedwIndex); - /* - * For syncSubmit, all exceptions should be thrown on submit and should equal expected exception. - * For asyncSubmit, exceptions might not be thrown on submit so they will only be checked against - * expected exception if one was actually thrown. - */ - if ( (SyncOrAsync == SYNC_SUBMIT) && (expectedException != null) ) - { - assertEquals("For sync submit, expected exceptions should be thrown on submit", - expectedException.getClass(), caughtException.getClass()); - } - else if ( (SyncOrAsync == ASYNC_SUBMIT) && (caughtException != null) ) - { - assertEquals("For async submit, any caught exceptions should be match expected exception", - expectedException, caughtException); - } - - //Reset device events to null after verifications are complete - LastUsbDeviceErrorEvent = null; - LastUsbDeviceDataEvent = null; - }; - - private UsbDeviceListener deviceListener = new UsbDeviceListener() - { - public void dataEventOccurred(UsbDeviceDataEvent uddE) - { - numDataEvents++; - assertNotNull(uddE); - LastUsbDeviceDataEvent = uddE; - if ( debug ) - { - System.out.println("Data event occurred. uddE = " + uddE + "numDataEvents = " + numDataEvents); - } - } - public void errorEventOccurred(UsbDeviceErrorEvent udeE) - { - numExceptionEvents++; - assertNotNull(udeE); - LastUsbDeviceErrorEvent = udeE; - if ( debug ) - { - System.out.println("Error event occurred. Exception is " + udeE.getUsbException().getMessage()); - System.out.println("Error event occurred. udeE = " + udeE + "numErrorEvents = " + numExceptionEvents); - } - } - public void usbDeviceDetached(UsbDeviceEvent udE) - { - numDetachEvents++; - assertNotNull(udE); - fail("No devices should be detached during this test."); - } - }; - - /** - * Send the UsbControlIrp to the UsbDevice on the DCP. - * @param SyncOrAsync SYNC_SUBMIT or ASYNC_SUBMIT - * @param usbDevice - * @param usbControlIrp - * @param caughtException - * @return - */ - private Exception SendUsbControlIrp(boolean SyncOrAsync, UsbDevice usbDevice, UsbControlIrp usbControlIrp) - { - Exception caughtException = null; - try - { - if ( SyncOrAsync == SYNC_SUBMIT ) - { - usbDevice.syncSubmit(usbControlIrp); - } - else - { - usbDevice.asyncSubmit(usbControlIrp); - usbControlIrp.waitUntilComplete(5000); - } - assertTrue("isComplete() not true for IRP after waitUntilComplete(..)", usbControlIrp.isComplete()); - - numSubmits++; - } - catch ( Exception uE ) - { - /* The exception sould indicate the reason for the failure. - * For this example, we'll just stop trying. - */ - if ( debug ) - { - System.out.println("DCP submission failed : " + uE.getMessage()); - } - caughtException = uE; - //fail("DCP submission failed." + uE.getMessage()); - //System.out.println("DCP submission failed : " + uE.getMessage()); - - } - finally - { - try - { - /* - * Wait for device event before leaving submit routine - */ - for ( int i = 0; i < 100; i++ ) - { - if ( (LastUsbDeviceDataEvent != null)| - (LastUsbDeviceErrorEvent != null) ) - { - //System.out.println("Data event took less than " + ((i+1) * 20 ) +" milliseconds"); - break; - } - Thread.sleep( 20 ); //wait 20 ms before checkin for event - } - - if ( (LastUsbDeviceDataEvent == null) && (LastUsbDeviceErrorEvent == null) ) - { - fail("Did not receive a data event or an error event after submit."); - } - } - catch ( InterruptedException e ) - { - fail("Sleep was interrupted"); - //e.printStackTrace(); - } - } - return caughtException; - }; - - /* - * Constructors - */ - public DefaultControlPipeTestErrorConditions() - { - super(); - } - protected DefaultControlPipeTestErrorConditions(UsbDevice newUsbDevice) - { - usbDevice = newUsbDevice; - } - - private static final byte VENDOR_REQUEST_TRANSFER_DATA = (byte)0xB0; - private static final short VENDOR_REQUEST_DATA_OUT = 0x00; - private static final short VENDOR_REQUEST_DATA_IN = 0x80; - private static final byte TRANSFORM_TYPE_PASSTHROUGH = (byte)0x01; - private static final byte TRANSFORM_TYPE_INVERT_BITS = (byte)0x02; - private static final byte TRANSFORM_INVERT_ALTERNATE_BITS = (byte)0x03; - - - private UsbDeviceDataEvent LastUsbDeviceDataEvent; - private UsbDeviceErrorEvent LastUsbDeviceErrorEvent; - private UsbDevice usbDevice; -// private boolean debug = true; - private boolean debug = false; - private int iterations = 10; - private int numSubmits = 0; - private int numDataEvents = 0; - private int numExceptionEvents = 0; - private int numDetachEvents = 0; - private static final boolean SYNC_SUBMIT = true; - private static final boolean ASYNC_SUBMIT = false; - boolean [] transmitList= {SYNC_SUBMIT, ASYNC_SUBMIT}; - private static final byte[] manufacturerString = { (byte) 26, //length of descriptor - (byte) UsbConst.DESCRIPTOR_TYPE_STRING, - (byte)'M',(byte) 0x00, - (byte)'a',(byte) 0x00, - (byte)'n',(byte) 0x00, - (byte)'u',(byte) 0x00, - (byte)'f',(byte) 0x00, - (byte)'a',(byte) 0x00, - (byte)'c',(byte) 0x00, - (byte)'t',(byte) 0x00, - (byte)'u',(byte) 0x00, - (byte)'r',(byte) 0x00, - (byte)'e',(byte) 0x00, - (byte)'r',(byte) 0x00}; -} diff --git a/src/test/java/javax/usb/tck/DefaultControlPipeTestErrorConditionswithSynchronizedUsbDevice.java b/src/test/java/javax/usb/tck/DefaultControlPipeTestErrorConditionswithSynchronizedUsbDevice.java deleted file mode 100755 index 98a58cd..0000000 --- a/src/test/java/javax/usb/tck/DefaultControlPipeTestErrorConditionswithSynchronizedUsbDevice.java +++ /dev/null @@ -1,75 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - - -import javax.usb.*; -import javax.usb.util.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.TestCase; - -/** - * Default Control Pipe Test -- Error Conditions - * using UsbUtilSynchronizedUsbDevice - *

- * This test is the same as the DefaultControlPipeTestErrorConditions except a - * UsbUtil.SynchronizedUsbDevice is used in place of a UsbDevice. - *

- * This test verifies that control transfers operations work successfully - * on the Default Control Pipe and that proper events are generated and proper - * exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class DefaultControlPipeTestErrorConditionswithSynchronizedUsbDevice extends TestCase -{ - public void setUp() throws Exception - { - originalUsbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - usbDevice = new UsbUtil.SynchronizedUsbDevice(originalUsbDevice); - assertNotNull("Device required for test not found",usbDevice); - DCPIRPTestErrorConditions = new DefaultControlPipeTestErrorConditions(usbDevice); - super.setUp(); - - } - public void tearDown() throws Exception - { - super.tearDown(); - } - - public void testUsbShortPacketException() - { - DCPIRPTestErrorConditions.testUsbShortPacketException(); - }; - - // TODO No idea how to detect a STALL condition in libusb 0.1 - public void disabled_testUsbStallException() - { - DCPIRPTestErrorConditions.disabled_testUsbStallException(); - }; - - public void testNotCallingsetDataForIRP() - { - DCPIRPTestErrorConditions.testNotCallingsetDataForIRP(); - }; - - - - private UsbDevice originalUsbDevice; - private UsbDevice usbDevice; - DefaultControlPipeTestErrorConditions DCPIRPTestErrorConditions; -} diff --git a/src/test/java/javax/usb/tck/DefaultControlPipeTestIRP.java b/src/test/java/javax/usb/tck/DefaultControlPipeTestIRP.java deleted file mode 100755 index e17535a..0000000 --- a/src/test/java/javax/usb/tck/DefaultControlPipeTestIRP.java +++ /dev/null @@ -1,903 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ ------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040804 raulortz Support for UsbDisconnectedException - */ - -import java.util.*; - -import javax.usb.*; -import javax.usb.event.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.TestCase; - -/** - * Default Control Pipe Test -- Synchronous and asynchronous IRP submissions - *

- * This test verifies that control transfers operations work successfully - * on the Default Control Pipe and that proper events are generated and proper - * exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class DefaultControlPipeTestIRP extends TestCase -{ - public void setUp() throws Exception - { - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - assertNotNull("Device required for test not found",usbDevice); - super.setUp(); - } - public void tearDown() throws Exception - { - - if ( debug ) - { - /* Print out some debug info - */ - System.out.println("iterations = " + iterations); - System.out.println("numSubmits = " + numSubmits); - System.out.println("numDataEvents = " + numDataEvents); - System.out.println("numExceptionEvents = " + numExceptionEvents); - System.out.println("numDetachEvents = " + numDetachEvents); - } - super.tearDown(); - } - - public void testBuffersMultiplesOfMaxPacketSize_1packets() - { - usbDevice.addUsbDeviceListener(deviceListener); - for ( int i=0; (i < iterations); i++ ) - { - for ( int j=0; j - * This test verifies that control transfers operations work successfully - * on the Default Control Pipe and that proper events are generated and proper - * exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class DefaultControlPipeTestIRPList extends TestCase -{ - - - public void setUp() throws Exception - { - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - assertNotNull("Device required for test not found",usbDevice); - super.setUp(); - - } - public void tearDown() throws Exception - { - if ( debug ) - { - - /* - *Print out some debug info - */ - System.out.println("iterations = " + iterations); - System.out.println("numSubmits = " + numSubmits); - System.out.println("numDataEvents = " + numDataEvents); - System.out.println("numExceptionEvents = " + numExceptionEvents); - System.out.println("numDetachEvents = " + numDetachEvents); - - } - super.tearDown(); - - } - - - - /** - * testBuffersMultiplesOfMaxPacketSize()--send OUT data which will be saved in device and made - * available on next IN request. Size of OUT data will be a multiple of maxPacketSize (64 bytes) - */ - public void testBuffersMultiplesOfMaxPacketSize() - { - usbDevice.addUsbDeviceListener(deviceListener); - for ( int i=0; (i < iterations); i++ ) - { - for ( int j=0; j - * This test is the same as the DefaultControlPipeTestIRPList except a - * UsbUtil.SynchronizedUsbDevice is used in place of a UsbDevice. - *

- * This test verifies that control transfers operations work successfully - * on the Default Control Pipe and that proper events are generated and proper - * exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class DefaultControlPipeTestIRPListwithSynchronizedUsbDevice extends TestCase -{ - - - public void setUp() throws Exception - { - originalUsbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - usbDevice = new UsbUtil.SynchronizedUsbDevice(originalUsbDevice); - assertNotNull("Device required for test not found",usbDevice); - DCPIRPTestList = new DefaultControlPipeTestIRPList(usbDevice); - super.setUp(); - - } - public void tearDown() throws Exception - { - super.tearDown(); - } - - - - /** - * testBuffersMultiplesOfMaxPacketSize()--send OUT data which will be saved in device and made - * available on next IN request. Size of OUT data will be a multiple of maxPacketSize (64 bytes) - */ - public void testBuffersMultiplesOfMaxPacketSize() - { - DCPIRPTestList.testBuffersMultiplesOfMaxPacketSize(); - }; - - /** - * testBuffersNotMultiplesOfMaxPacketSize()--send OUT data which will be saved in device and made - * available on next IN request. Size of OUT data will not be a multiple of maxPacketSize (64 bytes). - */ - public void testBuffersNotMultiplesOfMaxPacketSize() - { - DCPIRPTestList.testBuffersNotMultiplesOfMaxPacketSize(); - }; - - private UsbDevice originalUsbDevice; - private UsbDevice usbDevice; - DefaultControlPipeTestIRPList DCPIRPTestList; -} - diff --git a/src/test/java/javax/usb/tck/DefaultControlPipeTestIRPwithSynchronizedUsbDevice.java b/src/test/java/javax/usb/tck/DefaultControlPipeTestIRPwithSynchronizedUsbDevice.java deleted file mode 100755 index 33f1fd6..0000000 --- a/src/test/java/javax/usb/tck/DefaultControlPipeTestIRPwithSynchronizedUsbDevice.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -package javax.usb.tck; - -import javax.usb.*; -import javax.usb.util.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.TestCase; - -/** - * Default Control Pipe Test -- Synchronous and asynchronous IRP submissions - * using UsbUtilSynchronizedUsbDevice - *

- * This test is the same as the DefaultControlPipeTestIRP except a - * UsbUtil.SynchronizedUsbDevice is used in place of a UsbDevice. - *

- * This test verifies that control transfers operations work successfully - * on the Default Control Pipe and that proper events are generated and proper - * exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class DefaultControlPipeTestIRPwithSynchronizedUsbDevice extends TestCase -{ - public void setUp() throws Exception - { - originalUsbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - usbDevice = new UsbUtil.SynchronizedUsbDevice(originalUsbDevice); - assertNotNull("Device required for test not found",usbDevice); - DCPIRPTest = new DefaultControlPipeTestIRP(usbDevice); - super.setUp(); - - } - public void tearDown() throws Exception - { - super.tearDown(); - } - - public void testBuffersMultiplesOfMaxPacketSize_1packets() - { - - DCPIRPTest.testBuffersMultiplesOfMaxPacketSize_1packets(); - - }; - public void testBuffersMultiplesOfMaxPacketSize_2packets() - { - DCPIRPTest.testBuffersMultiplesOfMaxPacketSize_2packets(); - }; - - public void testBuffersMultiplesOfMaxPacketSize_moreThan2Packets() - { - DCPIRPTest.testBuffersMultiplesOfMaxPacketSize_moreThan2Packets(); - }; - - public void testBuffersNotMultiplesOfMaxPacketSize_1packets() - { - DCPIRPTest.testBuffersNotMultiplesOfMaxPacketSize_1packets(); - }; - - public void testBuffersNotMultiplesOfMaxPacketSize_2packets() - { - DCPIRPTest.testBuffersNotMultiplesOfMaxPacketSize_2packets(); - }; - - public void testBuffersNotMultiplesOfMaxPacketSize_MoreThan2packets() - { - DCPIRPTest.testBuffersNotMultiplesOfMaxPacketSize_MoreThan2packets(); - }; - - public void testRequestClearFeature() - { - DCPIRPTest.testRequestClearFeature(); - }; - - public void testRequestGetDescriptor() - { - DCPIRPTest.testRequestGetDescriptor(); - }; - - - private UsbDevice originalUsbDevice; - private UsbDevice usbDevice; - DefaultControlPipeTestIRP DCPIRPTest; -} \ No newline at end of file diff --git a/src/test/java/javax/usb/tck/FindControlIODevice.java b/src/test/java/javax/usb/tck/FindControlIODevice.java deleted file mode 100755 index d4392df..0000000 --- a/src/test/java/javax/usb/tck/FindControlIODevice.java +++ /dev/null @@ -1,330 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) IBM Corporation, 2004 - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License. - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - * - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ -------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 041222 raulortz Redesign TCK to create base and optional - * tests. Separate setConfig, setInterface - * and isochronous transfers as optionals. - */ - -import java.util.*; -import javax.usb.*; -import javax.usb.util.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -/** - * FindControlIODevice - *

- * This Singleton class finds the first device with a UsbEndpoint with the type - * ENDPOINT_TYPE_CONTROL and returns the device. Used by the - * ControlIODevice class. - * usage: (FindControlIODevice.getInstance()).getControlIODevice() - * @author Joshua Lowry - */ - -@SuppressWarnings("all") -public class FindControlIODevice extends Object -{ - //-------------------------------------------------------------------------- - // Ctor(s) - // - - /** - * The constructor is protected as this is a singleton class. - */ - protected FindControlIODevice() - { - } - - //-------------------------------------------------------------------------- - // Public methods - // - - /** - * Creates and returns the sole instance of the FindControlIODevice class. - * @return FindControlIODevice - */ - public static FindControlIODevice getInstance() - { - if ( instance == null ) - { - instance = new FindControlIODevice(); - instance.init(); - } - return instance; - } - - //-------------------------------------------------------------------------- - // Protected methods - // - - /** Initializes the FindControlIODevice instance */ - protected void init() - { - // empty - } - - - //-------------------------------------------------------------------------- - // Public methods - // - - /** - * Finds the first device with a Control Pipe other than the default Control - * Pipe and returns it. Returns null if no such device is found. - * @return UsbDevice - */ - public UsbDevice getControlIODevice() - { - virtualRootUsbHub = getVirtualRootUsbHub(); - usbDevices = null; - // get all connected devices - if ( debug ) - { - usbDevices = getAllUsbDevices(virtualRootUsbHub); - System.out.println("Found " + usbDevices.size() + " devices total."); - } - usbDevices = getUsbDevicesWithCtrlEndpoint(virtualRootUsbHub); - if ( usbDevices.isEmpty() ) - { - if ( debug ) - { - System.out.println("List Empty"); - } - return null; - } else - { - // return the first item - return(UsbDevice)usbDevices.get(0); - } - } - - /** - * Finds a list of devices with a Control Pipe other than the default Cotrol - * Pipe and returns it. Returns null if no devices are found. - * @return UsbDevice - */ - public List getControlIODevicesList() - { - virtualRootUsbHub = getVirtualRootUsbHub(); - usbDevices = null; - // get all connected devices - if ( debug ) - { - usbDevices = getAllUsbDevices(virtualRootUsbHub); - System.out.println("Found " + usbDevices.size() + " devices total."); - } - usbDevices = getUsbDevicesWithCtrlEndpoint(virtualRootUsbHub); - if ( usbDevices.isEmpty() ) - { - if ( debug ) - { - System.out.println("List Empty"); - } - return null; - } - - // return the list - return usbDevices; - } - - //-------------------------------------------------------------------------- - // Private methods - // - - /* - * Get the virtual root UsbHub. - * @return - */ - private static UsbHub getVirtualRootUsbHub() - { - UsbServices services = null; - UsbHub virtualRootUsbHub = null; - - /* First we need to get the UsbServices. - * This might throw either an UsbException or SecurityException. - * A SecurityException means we're not allowed to access the USB bus, - * while a UsbException indicates there is a problem either in - * the javax.usb implementation or the OS USB support. - */ - try - { - services = UsbHostManager.getUsbServices(); - } catch ( UsbException uE ) - { - throw new RuntimeException("Error : " + uE.getMessage()); - } catch ( SecurityException sE ) - { - throw new RuntimeException("Error : " + sE.getMessage()); - } - - /* Now we need to get the virtual root UsbHub, - * everything is connected to it. The Virtual Root UsbHub - * doesn't actually correspond to any physical device, it's - * strictly virtual. Each of the devices connected to one of its - * ports corresponds to a physical host controller located in - * the system. Those host controllers are (usually) located inside - * the computer, e.g. as a PCI board, or a chip on the mainboard, - * or a PCMCIA card. The virtual root UsbHub aggregates all these - * host controllers. - * - * This also may throw an UsbException or SecurityException. - */ - try - { - virtualRootUsbHub = services.getRootUsbHub(); - } catch ( UsbException uE ) - { - throw new RuntimeException("Error : " + uE.getMessage()); - } catch ( SecurityException sE ) - { - throw new RuntimeException("Error : " + sE.getMessage()); - } - - return virtualRootUsbHub; - } - - - /* - * This forms an inclusive list of all UsbDevices connected to this - * UsbDevice. - *

- * The list includes the provided device. If the device is also a hub, - * the list will include all devices connected to it, recursively. - * @param usbDevice The UsbDevice to use. - * @return - */ - private static List getAllUsbDevices(UsbDevice usbDevice) - { - List list = new ArrayList(); - - list.add(usbDevice); - - /* this is just normal recursion. Nothing special. */ - if ( usbDevice.isUsbHub() ) - { - List devices = ((UsbHub)usbDevice).getAttachedUsbDevices(); - for ( int i=0; i - * The list includes the provided device. If the device is also a hub, - * the list will include all devices connected to it, recursively. - * @param usbDevice The UsbDevice to use. - * @return An inclusive List of all connected UsbDevices. - */ - private static List getAllUsbDevices(UsbDevice usbDevice) - { - List list = new ArrayList(); - - list.add(usbDevice); - - /* this is just normal recursion. Nothing special. */ - if ( usbDevice.isUsbHub() ) - { - List devices = ((UsbHub)usbDevice).getAttachedUsbDevices(); - for ( int i=0; i - * This test verifies that devices can be attached and detached at runtime - * (hot plugging) and checks that proper UsbServices events are generated. - * @author Charles Jaeger - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class HotPlugTest extends TestCase -{ - - /* - * Assumed event flow on a renumeration of the Cypress board is... - * DeviceListener.DataEvent - response from syncSubmit of IRP - * DeviceListener.DetachedEvent - device is offlined - * ServiceListener.DetachedEvent - service is offlined - * ServiceListener.AttachedEvent - service is online - * - * Assumed device under test is a Cypress board with the BulkInt - * image running. - */ - - public void setUp() - { - try - { - usbServices = UsbHostManager.getUsbServices(); - } catch ( java.lang.SecurityException se ) - { - fail("SecurityException was not expected: " + se); - } catch ( UsbException ue ) - { - fail("UsbException was not expected: " + ue); - } - - // traverse the topology tree to locate the test device - usbDevice = - FindProgrammableDevice.getInstance().getProgrammableDevice(); - - assertTrue("USB Device was not configured", usbDevice.isConfigured()); - - // add a listener to receive events when the host has changes - // (e.g. device is unplugged or is plugged in) - usbServices.addUsbServicesListener(servicesListener); - - // add a listener to detect when the device is detached. - usbDevice.addUsbDeviceListener(deviceListener); - - // init for each test -> - numSubmits = 0; - - numDeviceDataEvents = 0; - numDeviceDetachEvents = 0; - numDeviceErrorEvents = 0; - lastUsbDeviceDataEvent = null; - lastUsbDeviceErrorEvent = null; - lastUsbDeviceDetachedEvent = null; - - numServicesAttachEvents = 0; - numServicesDetachEvents = 0; - lastServicesAttachEvent = null; - lastServicesDetachEvent = null; - // <- - - } - - public void tearDown() - { - - if ( debug ) - { - - /* Print out some debug info - */ - System.out.println("numSubmits = " + numSubmits); - System.out.println("numDataEvents = " + numDeviceDataEvents); - System.out.println("numExceptionEvents = " + numDeviceErrorEvents); - System.out.println("numDetachEvents = " + numDeviceDetachEvents); - System.out.println( - "numServicesAttachEvents = " + numServicesAttachEvents); - System.out.println( - "numServicesDetachEvents = " + numServicesDetachEvents); - - } - - usbDevice.removeUsbDeviceListener(deviceListener); - usbServices.removeUsbServicesListener(servicesListener); - - } - - /** - * Tests that the setUp() passes all assertions. - */ - public void testSetUp() - { - - // was setup successful in init of members? - assertNotNull("UsbDevice required for test not found", usbDevice); - assertNotNull( - "UsbHostManager returned null instead of usbServices object", - usbServices); - - // test the numXXX members - assertEquals("Devices detached should be 0", numDeviceDetachEvents, 0); - - assertEquals( - "Device commands issued should be 0", - numDeviceDataEvents, - 0); - - assertEquals("Device error count should be 0", numDeviceErrorEvents, 0); - - assertEquals( - "Services detached should be 0", - numServicesDetachEvents, - 0); - - assertEquals( - "Services attached should be 0", - numServicesAttachEvents, - 0); - - assertEquals("Board commands should be 0", numSubmits, 0); - - // test the lastXXX members - assertNull(lastUsbDeviceDataEvent); - assertNull(lastUsbDeviceErrorEvent); - assertNull(lastUsbDeviceDetachedEvent); - - assertNull(lastServicesAttachEvent); - assertNull(lastServicesDetachEvent); - - // - assertNotNull("usbDevice should already exist.", usbDevice); - } - - public void testUsbServicesEvent() - { - UsbServicesEvent event = new UsbServicesEvent(usbServices, usbDevice); - assertNotNull("UsbServicesEvent constructor failed.", event); - - //test methods of the UsbServicesEvent - assertNotNull( - "UsbServicesEvent.getUsbServices() returned null", - event.getUsbServices()); - assertNotNull( - "UsbServicesEvent.getUsbDevice() returned null", - event.getUsbDevice()); - - } - - /** - * Test the method that will send the reset command to the Cypress board. - */ - public void testSimulateHotPlug() - { - - // send reset command to the Cypress board - simulateHotPlug(); - - // verify that all expected events were captured - assertNotNull( - "Did not receive a DeviceListener DataEvent after submitting IRP.", - lastUsbDeviceDataEvent); - - assertNotNull( - "Did not receive a DeviceListener DetachedEvent (indicating reset not issued).", - lastUsbDeviceDetachedEvent); - - assertNotNull( - "Did not receive a ServicesListener acknowledging detach.", - lastServicesDetachEvent); - - assertNotNull( - "Did not receive a ServicesListener acknowledging attach.", - lastServicesAttachEvent); - - // Were the number of returned events correct? - assertEquals( - "The device should detach once during the run", - numDeviceDetachEvents, - 1); - - assertEquals("Only 1 command is sent", numDeviceDataEvents, 1); - - assertEquals("No errors should occur", numDeviceErrorEvents, 0); - - assertEquals( - "The service should detach once during the run", - numServicesDetachEvents, - 1); - - assertEquals( - "The service attached once during the run", - numServicesAttachEvents, - 1); - } - - /** - * Verify that proper exceptions are thrown (w/o failure) for all other IO - * calls to a disconnected device - * - * TODO This test required a pretty good timing between the test device and - * the host. Sometimes it works, sometimes it doesn't. So I disabled it for - * now. - */ - public void disabled_testExceptionsOnDisconnectedDevice() - { - - //local variable - boolean isOK = false; - - // make sure the board is online - assertNotNull("The Cypress board is not online", usbDevice); - - // flush any events from the listeners. - // ... automatically done by the setUp() process - - // reset the board - try - { - submitRenumerateIrp(); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("Resetting the board should not issue any exceptions."); - } - - // verify that the correct exceptions are returned for this offline device. - - if ( null == lastServicesDetachEvent ) - { - - if ( debug ) - { - System.out.println( - "-> public void testExceptionsOnDisconnectedDevice()"); - System.out.println(" -> submitRenumerateIrp()"); - } - - // UsbException - try - { - submitRenumerateIrp(); - fail("UsbException expected"); - } catch ( UsbException e ) - { - isOK = true; - if ( debug ) - System.out.println("UsbException thrown" + e); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("An Exception other than UsbException was detected."); - } - - isOK = false; - - // IllegalArgumentException - If the UsbControlIrp is not valid. - try - { - submitBadIrp(); - fail("IllegalArgumentException was expected."); - } catch ( IllegalArgumentException e ) - { - // System.out.println("good"); - isOK = true; - if ( debug ) - System.out.println("IllegalArgumentException thrown"); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("Exception other than IllegalArgumentException was detected"); - } - - } else - { - fail("Can't proceed because the service got up and running quickly."); - } - - if ( null != lastServicesDetachEvent ) - { - fail("The service may have attached during test, so results are inconclusive."); - } - - // make sure board is up before leaving. - isOK = false; - try - { - waitForServiceAttachedEvent(20000); - isOK = true; - } catch ( InterruptedException e ) - { - e.printStackTrace(); - fail("Timed out before all events were seen."); - } finally - { - if ( !isOK ) - fail("UsbDevice was not detected as going online"); - } - } - - /** - * Verify proper events are generated after disconnecting. - */ - public void testDisconnectEvents() - { - // make sure the board is online - assertNotNull("The Cypress board is not online", usbDevice); - - // reset the board - try - { - submitRenumerateIrp(); - } catch ( UsbException e ) - { - e.printStackTrace(); - fail("Resetting the board should not issue any exceptions."); - } - - // make sure all the disconnect events from the listeners fire - try - { - // the total time to wait for the wanted disconnect events to occur - waitForServiceDetachedEvent(20000); - - // Disconnect events follow - // in the expected sequential order... - assertNotNull( - "The device did not detach within time", - lastUsbDeviceDetachedEvent); - assertNotNull( - "The service did not detach within time", - lastServicesDetachEvent); - assertEquals( - "1 Device detach events expected", - numDeviceDetachEvents, - 1); - assertEquals( - "1 Service detach events expected", - numServicesDetachEvents, - 1); - assertEquals("0 Device errors expected", numDeviceErrorEvents, 0); - - // make sure board is up before leaving. - waitForServiceAttachedEvent(5000); - - } catch ( InterruptedException e ) - { - e.printStackTrace(); - fail("Timed out before all events were seen."); - } - } - - /** - * Verify proper events are generated after hot plugging. - */ - public void testPlugInEvents() - { - // make sure the board is online - assertNotNull("usbDevice should already be online.", usbDevice); - - try - { - // the setUp() flushes any events from the listeners - - // reset the board - submitRenumerateIrp(); - - // wait til the board comes back up - waitForServiceAttachedEvent(20000); - - // verify that all the events from the listeners fire - - assertNotNull( - "Did not receive a DeviceListener DataEvent after submitting IRP.", - lastUsbDeviceDataEvent); - - assertNotNull( - "Did not receive a DeviceListener DetachedEvent (indicating reset not issued).", - lastUsbDeviceDetachedEvent); - - assertNotNull( - "Did not receive a ServicesListener acknowledging detach.", - lastServicesDetachEvent); - - assertNotNull( - "Did not receive a ServicesListener acknowledging attach.", - lastServicesAttachEvent); - - // Were the number of returned events correct? - assertEquals( - "The device should detach once during the run", - numDeviceDetachEvents, - 1); - - assertEquals("Only 1 command is sent", numDeviceDataEvents, 1); - - assertEquals("No errors should occur", numDeviceErrorEvents, 0); - - assertEquals( - "The service should detach once during the run", - numServicesDetachEvents, - 1); - - assertEquals( - "The service attached once during the run", - numServicesAttachEvents, - 1); - } catch ( InterruptedException e ) - { - e.printStackTrace(); - fail("Sleep was interrupted"); - } catch ( UsbException uE ) - { - /* The exception should indicate the reason for the failure. - * For this example, we'll just stop trying. - */ - fail("DCP submission failed. " + uE.toString()); - } - } - - /** - * Run a disconnect, reconnect cycle and then verify that 10 transfers will - * succeed without data error. - */ - public void testNoErrorsOnDataTransfers() - { - - // the setUp() flushes any events from the listeners - - // make sure the board is online - assertNotNull("usbDevice should already be online.", usbDevice); - assertTrue("usbDevice is not configured.", usbDevice.isConfigured()); - - //set up the board's: endpoints, pipes, etc .. - Board theBoard = new Board(usbDevice); - - // test: while online, data can be sent without error... - try - { - theBoard.sendData(); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("Exception not expected."); - } - // tested: while online, data can be sent without error... - - // While transferring data through input and output endpoints - // (loop bulk data), unplug the device. - // (Vendor request to Cypress Board to renumerate will simulate unplug.) - try - { - theBoard.testAsyncInFailure(); - } catch ( InterruptedException ie ) - { - fail("Timed out while waiting for the device detach event."); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("Resetting the board should not issue any exceptions."); - } - // tested: when offline, abort all submissions - - try - { - waitForServiceAttachedEvent(20000); - } catch ( InterruptedException ie ) - { - fail("Timed out while waiting for the device detach event."); - } - - // test: when online again, send data without error - // wait for the device to come back up - try - { - waitForServiceAttachedEvent(10000); - setUp(); - theBoard = new Board(usbDevice); - theBoard.sendData(); - theBoard.tearDown(); - } catch ( InterruptedException ie ) - { - fail("Timed out waiting for service attach event."); - } catch ( Exception e ) - { - e.printStackTrace(); - fail("Exception not expected."); - } - // tested: when online again, send data without error - } - - /** - * Tell the Cypress board to initiate its reset and binary upload method. - * in order to simulate human involved device detach and attach action. - * Returns successfully once device service is attached; otherwise - * a fails method is asserted. - */ - private void simulateHotPlug() - { - /* This will block until the submission is complete. - * Note that submissions (except interrupt and bulk in-direction) - * will not block indefinitely, they will complete or fail within - * a finite amount of time. See MouseDriver.HidMouseRunnable for more details. - */ - try - { - submitRenumerateIrp(); - - waitForDeviceDataOrErrorEvent(2000); - - waitForDeviceDetachedEvent(5000); - - waitForServiceDetachedEvent(2000); - - waitForServiceAttachedEvent(10000); - - } catch ( InterruptedException e ) - { - e.printStackTrace(); - fail("Sleep was interrupted"); - } catch ( UsbException uE ) - { - /* The exception should indicate the reason for the failure. - * For this example, we'll just stop trying. - */ - fail("DCP submission failed. " + uE.toString()); - } - } - - /** - * Generates the Renumerate command for the cypress board as a UsbControlIrp - * @return the UsbControlIrp ready for use - */ - private UsbControlIrp getRenumerateIrp() - { - - byte sentbmRequestType = - UsbConst.REQUESTTYPE_DIRECTION_OUT - | UsbConst.REQUESTTYPE_TYPE_VENDOR - | UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; - - short sentwIndex = 0; //first isochronous IN endpoint - - // An IRP - UsbControlIrp usbControlIrp = - usbDevice.createUsbControlIrp( - sentbmRequestType, - VENDOR_REQUEST_RENUMERATE, - VENDOR_REQUEST_DATA_OUT, - sentwIndex); - - //set variable parts of Irp - byte[] sentData = new byte[0]; - usbControlIrp.setData(sentData); - usbControlIrp.setAcceptShortPacket(true); - - return usbControlIrp; - } - - /** - * Generates an IRP that will cause the IllegalArgumentException - * on syncSubmit to the Cypress board - * @return the UsbControlIrp ready for use - private UsbControlIrp getBadIrp() { - UsbControlIrp badIrp = getRenumerateIrp(); - //set Irp data to cause IllegalArgumentException on syncSubmit - - return badIrp; - } - */ - - /** - * Sends a reset and binary upload call to the Cypress board. - * @throws UsbException - */ - private void submitRenumerateIrp() throws UsbException { - try - { - - UsbControlIrp usbControlIrp = getRenumerateIrp(); - assertNotNull("usbControlIrp should not be null", usbControlIrp); - - usbDevice.syncSubmit(usbControlIrp); - numSubmits++; - } catch ( IllegalArgumentException e ) - { - e.printStackTrace(); - fail("IllegalArgumentException was not expected."); - } - } - - /** - * Sends an invalid UsbControlIrp to the Cypress board. - * @throws IllegalArgumentException - */ - private void submitBadIrp() throws IllegalArgumentException { - - // An IRP - UsbControlIrp usbControlIrp = getRenumerateIrp(); - assertNotNull("usbControlIrp should not be null", usbControlIrp); - - //set Irp data to cause IllegalArgumentException on syncSubmit - usbControlIrp.setData(null); - - try - { - usbDevice.syncSubmit(usbControlIrp); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( UsbException e ) // @P1A - { - e.printStackTrace(); - fail("UsbException not expected."); - } - numSubmits++; - } - - /** - * Wait for deviceListener deviceData or deviceError event before continuing. - * @param timeout minimum number of milliseconds before timeout is issued (suggested minimum: 2000) - * @throws InterruptedException raised if timeout occurs - */ - private void waitForDeviceDataOrErrorEvent(int timeout) - throws InterruptedException { - // up to 2 sec min timeout on submission - for ( int i = 0; i < (timeout / 20); i++ ) - { - - if ( (lastUsbDeviceDataEvent != null) - || (lastUsbDeviceErrorEvent != null) ) - { - if ( debug ) - System.out.println( - "waitForDeviceDataOrErrorEvent took less than " - + ((i + 1) * 20) - + " milliseconds"); - break; - } - Thread.sleep(20); //wait 20 ms before checkin for event - } - } - - /** - * Wait for deviceListener deviceDetached event before continuing - * @param timeout minimum number of milliseconds before timeout is issued (suggested minimum: 5000) - * @throws InterruptedException raised if timeout occurs - */ - private void waitForDeviceDetachedEvent(int timeout) - throws InterruptedException { - for ( int i = 0; i < (timeout / 20); i++ ) - { - - if ( lastUsbDeviceDetachedEvent != null ) - { - if ( debug ) - System.out.println( - "waitForDeviceDetachedEvent took less than " - + ((i + 1) * 20) - + " milliseconds"); - break; - } - Thread.sleep(20); //wait 20 ms before checkin for event - } - if ( lastUsbDeviceDetachedEvent == null ) - { - throw new InterruptedException( - "DeviceDetachedEvent not found within " + timeout + " ms"); - } - - } - - /** - * Wait for servicesListener deviceDetached event before continuing - * @param timeout minimum number of milliseconds before timeout is issued (suggested minimum: 2000) - * @throws InterruptedException raised if timeout occurs - */ - private void waitForServiceDetachedEvent(int timeout) - throws InterruptedException { - - for ( int i = 0; i < (timeout / 20); i++ ) - { - - if ( lastServicesDetachEvent != null ) - { - if ( debug ) - System.out.println( - "waitForServiceDetachedEvent took less than " - + ((i + 1) * 20) - + " milliseconds"); - break; - } - Thread.sleep(20); //wait 20 ms before checkin for event - } - } - - /** - * Wait for servicesListener deviceAttached event before continuing - * @param timeout minimum number of milliseconds before timeout is issued (suggested minimum: 5000) - * @throws InterruptedException raised if timeout occurs - */ - private void waitForServiceAttachedEvent(int timeout) - throws InterruptedException { - for ( int i = 0; i < (timeout / 20); i++ ) - { - - if ( (null != lastServicesAttachEvent) && (usbDevice.isConfigured() ) ) - { - if ( debug ) - System.out.println( - "waitForServiceAttachedEvent took less than " - + ((i + 1) * 20) - + " milliseconds"); - break; - } - Thread.sleep(20); //wait 20 ms before checkin for event - } - } - - private class Board - { - - // attributes - private UsbInterface iface; - private UsbPipe inPipe; - private UsbPipe outPipe; - private boolean hasRenumerated = false; - private boolean hasSubmittedAsyncIn = false; - - // Concrete instance of a UsbPipeListener interface - private UsbPipeListener inPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent updE) - { - } - public void errorEventOccurred(UsbPipeErrorEvent upeE) - { - if ( hasRenumerated && hasSubmittedAsyncIn ) // ok - { - } else //err - { - upeE.getUsbException().printStackTrace(); - fail ("No in pipe errors are expected at this point."); - } - } - }; - - private UsbPipeListener outPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent updE) - { - } - public void errorEventOccurred(UsbPipeErrorEvent upeE) - { - fail("No out pipe errors should occur during this test."); - } - }; - - // default no arg ctor not allowed - private Board() - { - } - - //ctor - public Board(UsbDevice usbDevice) - { - config(usbDevice); - } - - /** - * set up endpoints, pipes, etc .. - */ - private void config(UsbDevice usbDevice) - { - - try - { - // set the endpoints - List endpoints = null; - - /** - * select alternate setting for the programmable board (AS0 or AS1) - * @param usbDevice The UsbDevice obj - */ - if ( usbDevice.isConfigured() ) - { - iface = usbDevice.getUsbConfiguration((byte) 1).getUsbInterface((byte) 0); - - iface.claim(); - - // @P2D4 - iface = iface.getActiveSetting(); - - if ( debug ) - System.out.println("Select Alternate Setting 1"); - - endpoints = iface.getUsbEndpoints(); - - UsbEndpoint inEndpoint8 = - findEndpoint( - endpoints, - UsbConst.REQUESTTYPE_DIRECTION_IN, - UsbConst.ENDPOINT_TYPE_BULK, - 8); - - UsbEndpoint outEndpoint8 = - findEndpoint( - endpoints, - UsbConst.REQUESTTYPE_DIRECTION_OUT, - UsbConst.ENDPOINT_TYPE_BULK, - 8); - - inPipe = inEndpoint8.getUsbPipe(); - outPipe = outEndpoint8.getUsbPipe(); - inPipe.addUsbPipeListener(inPipeListener); - outPipe.addUsbPipeListener(outPipeListener); - inPipe.open(); - outPipe.open(); - } else - { - fail("device is not configured!"); - } - - } catch ( UsbClaimException uce ) - { - fail("UsbClaimException: " + uce); - } catch ( UsbDisconnectedException uDE ) // @P1A - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( UsbException ue ) - { - fail("UsbException: " + ue); - } catch ( UsbNotActiveException unae ) - { - unae.printStackTrace(); - fail("UsbNotActiveException: " + unae); - } - } - - public void testAsyncInFailure() throws Exception - { - int dataSize = 8; - byte[] inData = new byte[dataSize]; - - UsbIrp irp = inPipe.createUsbIrp(); - irp.setData(inData); - inPipe.asyncSubmit(irp); - - hasSubmittedAsyncIn = true; - - hasRenumerated = true; - submitRenumerateIrp(); - waitForServiceAttachedEvent(20000); - } - - - public void tearDown() - { - try - { - inPipe.abortAllSubmissions(); - outPipe.abortAllSubmissions(); - inPipe.close(); - outPipe.close(); - inPipe.removeUsbPipeListener(inPipeListener); - outPipe.removeUsbPipeListener(outPipeListener); - - if ( null != iface ) - { - if ( debug ) - System.out.println("releasing interface!!!!"); - iface.release(); - if ( debug ) - System.out.println("released interface!!!!"); - } - } catch ( UsbClaimException uce ) - { - fail("UsbClaimException: " + uce); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( UsbException ue ) - { - fail("UsbException: " + ue); - } catch ( UsbNotActiveException unae ) - { - fail("UsbNotActiveException: " + unae); - } - } - - /** - * Performs bulk data transfer for 10 datum. - * @exception - */ - public void sendData() throws Exception { - for ( int tries = 0; tries < 10; tries++ ) - { - try - { - sendDatum(); - } catch ( Exception e ) - { - fail("The following exception was caught"); - e.printStackTrace(); - throw e; - } - } - } - - /** - * Will throw an exception if a buffer it sends is different than the one it receives. - */ - private void sendDatum() throws Exception { - byte txType = TRANSFORM_TYPE_PASSTHROUGH; - int dataSize = 8; - byte[] inData = new byte[dataSize]; - - TransmitBuffer txBuffer = new TransmitBuffer(txType, dataSize); - try // @P1A - { // @P1A - outPipe.syncSubmit(txBuffer.getOutBuffer()); // @P1C - inPipe.syncSubmit(inData); // @P1C - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - if ( txBuffer.compareBuffers(inData) ) - { - // it's all good, display the data - if ( debug ) - { - System.out.print("Received data was: "); - for ( int i = 0; i < dataSize; i++ ) - System.out.print(inData[i] + ","); - System.out.println(); - } - } else - { - throw new Exception("received inData from pipe was != outData."); - } - } - - /** - * find endpoint that match the requirement - * @param totalEndpoints The List of End Points - * @param inDirection The direction ( 81 = in, 00 = out) - * @param inType The endpoint type ( 3 - interrupt, 2 - bulk) - * @param inSize The endpoint size (8 or 64 bytes for this programmable board) - */ - private UsbEndpoint findEndpoint( - List totalEndpoints, - int inDirection, - int inType, - int inSize) - { - boolean found = false; - for ( int j = 0; j < totalEndpoints.size(); j++ ) - { - UsbEndpoint ep = (UsbEndpoint) totalEndpoints.get(j); - int direction = ep.getDirection(); - int type = ep.getType(); - int maxPackageSize = - ep.getUsbEndpointDescriptor().wMaxPacketSize(); - int endpointAddress = - ep.getUsbEndpointDescriptor().bEndpointAddress(); - if ( (byte) (inDirection & 0x80) == (byte) direction - && inType == type - && inSize == maxPackageSize ) - { - return ep; - } - - } - if ( debug ) - System.out.println("End point NOT FOUND!!!"); - return null; - } - } - - private final UsbServicesListener servicesListener = - new UsbServicesListener() - { - - public void usbDeviceAttached(UsbServicesEvent use) - { - if ( debug ) - System.out.println("UsbServicesListener.usbDeviceAttached()"); - numServicesAttachEvents++; - assertNotNull(use); - lastServicesAttachEvent = use; - assertNotNull( - "Device was attached: ", - lastServicesAttachEvent.toString()); - } - - public void usbDeviceDetached(UsbServicesEvent use) - { - if ( debug ) - System.out.println("UsbServicesListener.usbDeviceDetached()"); - numServicesDetachEvents++; - assertNotNull(use); - lastServicesDetachEvent = use; - assertNotNull( - "Device was detached: ", - lastServicesDetachEvent.toString()); - - //testing attributes of the UsbServicesEvent - assertNotNull( - "UsbServicesEvent.getUsbServices() returned null", - use.getUsbServices()); - assertNotNull( - "UsbServicesEvent.getUsbDevice() returned null", - use.getUsbDevice()); - } - }; - - private final UsbDeviceListener deviceListener = new UsbDeviceListener() - { - - public void dataEventOccurred(UsbDeviceDataEvent uddE) - { - numDeviceDataEvents++; - // fail("Test that we get a data event"); - // assertEquals(0,numDataEvents); - assertNotNull(uddE); - lastUsbDeviceDataEvent = uddE; - if ( debug ) - System.out.println( - "UsbDeviceListener.dataEventOccurred(). uddE = " - + uddE - + "numDataEvents = " - + numDeviceDataEvents); - } - - public void errorEventOccurred(UsbDeviceErrorEvent udeE) - { - numDeviceErrorEvents++; - assertNotNull(udeE); - lastUsbDeviceErrorEvent = udeE; - if ( debug ) - System.out.println( - "UsbDeviceListener.errorEventOccurred(). uddE = " - + udeE - + "numExceptionEvents = " - + numDeviceErrorEvents); - assertNotNull( - "Should not have null UsbException on UsbDeviceErrorEvent.", - udeE.getUsbException()); - } - - public void usbDeviceDetached(UsbDeviceEvent udE) - { - numDeviceDetachEvents++; - assertNotNull(udE); - lastUsbDeviceDetachedEvent = udE; - if ( debug ) - System.out.println( - "UsbDeviceListener.usbDeviceDetached(). object = " - + udE - + "numDeviceDetachEvents = " - + numDeviceDetachEvents); - assertNotNull( - "Should not have null UsbDevice on usbDeviceEvent.", - udE.getUsbDevice()); - } - }; - - // for debugging - private boolean debug = false; - - // instances of USB classes - private UsbDevice usbDevice; - private UsbHostManager usbHostManager; - private UsbServices usbServices; - - private UsbDeviceDataEvent lastUsbDeviceDataEvent; - private UsbDeviceErrorEvent lastUsbDeviceErrorEvent; - private UsbDeviceEvent lastUsbDeviceDetachedEvent; - private UsbServicesEvent lastServicesDetachEvent, lastServicesAttachEvent; - - private static int numSubmits = 0; - private static int numDeviceDataEvents = 0; - private static int numDeviceErrorEvents = 0; - private static int numDeviceDetachEvents = 0; - private static int numServicesAttachEvents = 0; - private static int numServicesDetachEvents = 0; - - private static final short VENDOR_REQUEST_DATA_OUT = 0x00; - private static final byte VENDOR_REQUEST_RENUMERATE = (byte) 0xA8; - private static final byte TRANSFORM_TYPE_PASSTHROUGH = (byte) 0x01; - - private static final byte[] manufacturerString = - {(byte) 26, //length of descriptor - (byte) UsbConst.DESCRIPTOR_TYPE_STRING, - (byte) 'M', - (byte) 0x00, - (byte) 'a', - (byte) 0x00, - (byte) 'n', - (byte) 0x00, - (byte) 'u', - (byte) 0x00, - (byte) 'f', - (byte) 0x00, - (byte) 'a', - (byte) 0x00, - (byte) 'c', - (byte) 0x00, - (byte) 't', - (byte) 0x00, - (byte) 'u', - (byte) 0x00, - (byte) 'r', - (byte) 0x00, - (byte) 'e', - (byte) 0x00, - (byte) 'r', - (byte) 0x00}; -} diff --git a/src/test/java/javax/usb/tck/IOErrorConditionsTest.java b/src/test/java/javax/usb/tck/IOErrorConditionsTest.java deleted file mode 100755 index 32e191d..0000000 --- a/src/test/java/javax/usb/tck/IOErrorConditionsTest.java +++ /dev/null @@ -1,982 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ ------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040804 raulortz Support for UsbDisconnectedException - * $P2 tck.rel1 040916 raulortz Redesign TCK to create base and optional - * tests. Separate setConfig, setInterface - * and isochronous transfers as optionals. - */ - -import java.util.*; -import javax.usb.*; -import javax.usb.util.*; - -import org.junit.Ignore; - -import junit.framework.TestCase; - -/** - * IO Error conditions - *

- * This test verifies that error conditions are generated and proper - * exceptions are thrown in the operation. - * - * @author Thanh Ngo - */ - -@SuppressWarnings("all") -@Ignore("These tests are triggered by other tests and must not run directly") -public class IOErrorConditionsTest extends TestCase -{ - //------------------------------------------------------------------------- - // Ctor(s) - // - - public IOErrorConditionsTest(String name) - { - super(name); - } - public IOErrorConditionsTest(int typeOfTest) - { - testType = typeOfTest; - } - - //------------------------------------------------------------------------- - // Protected overridden methods - // - - protected void setUp() throws Exception { - printDebug("setUp"); - - - usbDevice = programmableDevice.getProgrammableDevice(); - assertTrue("Find Programmable board Failed! Got a null instance", - usbDevice != null); - - - super.setUp(); - } - - protected void tearDown() throws Exception { - printDebug("tearDown"); - try // @P1A - { // @P1A - if ( (outPipe!=null)&&(outPipe.isOpen()) ) // @P1C - { // @P1C - outPipe.abortAllSubmissions(); // @P1C - IOMethods.closePipe(outPipe); // @P1C - } // @P1C - if ( (inPipe!=null)&&(inPipe.isOpen()) ) // @P1C - { // @P1C - inPipe.abortAllSubmissions(); // @P1C - IOMethods.closePipe(inPipe); // @P1C - } // @P1C - if ( (myIface!=null)&&(myIface.isClaimed()) ) // @P1C - { // @P1C - IOMethods.releaseInterface(myIface); // @P1C - } // @P1C - } catch ( UsbDisconnectedException uDE ) // @P1A - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - super.tearDown(); - } - - //------------------------------------------------------------------------- - // Public testXyz() methods - // - - /** - * Null Data Buffer - */ - public void testNullDataBufferInIrp() - { - printDebug("testNullDataBufferInIrp"); - if ( testType == bulkTest ) - { - doTestNullDataBufferInIrp(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - - doTestNullDataBufferInIrp(UsbConst.ENDPOINT_TYPE_INTERRUPT); - - } else if ( testType == isochronousTest ) - { - doTestNullDataBufferInIrp(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - } - /** - * Null Data Buffer - */ - public void testNullDataBufferAsByteArray() - { - printDebug("testNullDataBufferAsByteArray"); - if ( testType == bulkTest ) - { - doTestNullDataBufferAsByteArray(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - doTestNullDataBufferAsByteArray(UsbConst.ENDPOINT_TYPE_INTERRUPT); - - } else if ( testType == isochronousTest ) - { - doTestNullDataBufferAsByteArray(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - } - - /** - * Action against a closed pipe - */ - public void testActionAgainstClosePipeAbortAllSubmissions() - { - printDebug("testActionAgainstClosePipeAbortAllSubmissions"); - if ( testType == bulkTest ) - { - - doTestActionAgainstClosePipeAbortAllSubmissions(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - doTestActionAgainstClosePipeAbortAllSubmissions(UsbConst.ENDPOINT_TYPE_INTERRUPT); - } else if ( testType == isochronousTest ) - { - doTestActionAgainstClosePipeAbortAllSubmissions(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - - - } - /** - * Action against a closed pipe - */ - public void testActionAgainstClosePipeSubmit() - { - printDebug("testActionAgainstClosePipeSubmit"); - if ( testType == bulkTest ) - { - - doTestActionAgainstClosePipeSubmit(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - doTestActionAgainstClosePipeSubmit(UsbConst.ENDPOINT_TYPE_INTERRUPT); - } else if ( testType == isochronousTest ) - { - doTestActionAgainstClosePipeSubmit(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - - - } - - /** - * Close a pipe with pending operation - */ - public void testClosePipePendingAction() - - { - printDebug("testClosePipePendingAction"); - if ( testType == bulkTest ) - { - doTestClosePipePendingAction(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - doTestClosePipePendingAction(UsbConst.ENDPOINT_TYPE_INTERRUPT); - } else if ( testType == isochronousTest ) - { - doTestClosePipePendingAction(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - - - } - - /** - * Open a pipe on an inactive interface - */ - public void testOpenPipeOnInactiveAlternateSetting() - { - printDebug("testOpenPipeOnInactiveAlternateSetting"); - if ( testType == bulkTest ) - { - - doTestOpenPipeOnInactiveAlternateSetting(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - doTestOpenPipeOnInactiveAlternateSetting(UsbConst.ENDPOINT_TYPE_INTERRUPT); - } else if ( testType == isochronousTest ) - { - doTestOpenPipeOnInactiveAlternateSetting(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - } - - /** - * Open a pipe on an unclaimed interface - */ - public void testOpenPipeOnUnclaimedInterface() - { - printDebug("testOpenPipeOnUnclaimedInterface"); - if ( testType == bulkTest ) - { - - doTestOpenPipeOnUnclaimedInterface(UsbConst.ENDPOINT_TYPE_BULK); - } else if ( testType == intTest ) - { - doTestOpenPipeOnUnclaimedInterface(UsbConst.ENDPOINT_TYPE_INTERRUPT); - } else if ( testType == isochronousTest ) - { - doTestOpenPipeOnUnclaimedInterface(UsbConst.ENDPOINT_TYPE_ISOCHRONOUS); - } else - { - fail("Test is defined for only bulk and isochronous endpoints."); - } - - } - - /** - * Claim an already claimed interface - */ - public void testClaimAnAlreadyClaimedInterface() - { - printDebug("testClaimAnAlreadyClaimedInterface"); - - - myIface = null; - boolean usbe = false; - - if ( usbDevice.isConfigured() ) - { - UsbConfiguration usbConfiguration = - usbDevice.getUsbConfiguration((byte) 1); - myIface = usbConfiguration.getUsbInterface((byte) 0); - - //claim the interface - IOMethods.claimInterface(myIface); - - try - { - assertTrue("in doTestClaimAnAlreadyClaimedInterface() --isClaimed() should == true): ", - myIface.isClaimed()); - myIface.claim(); - fail("should caused UsbClaimException!"); - } catch ( UsbClaimException uce ) - { - - usbe = true; - } catch ( UsbException ue ) - { - fail("UsbClaimException expected. unexpected UsbException!" + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - fail("UsbClaimException expected. unexpected Exception" + e); - } - - if ( !usbe ) - assertTrue("Test Claim an already claimed interface did not throw UsbNotClaimedException!", false); - - } else - { - fail("device is not configured!"); - } - - - - } - -// /** -// * Claim an inactive interface -// */ -// public void testClaimAnInactiveInterface() -// { -// boolean usbe = false; -// UsbInterface inActiveInterface = getInactiveInterface(); -// if ( null == inActiveInterface ) -// { -// fail("could not locate an inactive interface to test!"); -// } -// try -// { -// inActiveInterface.claim(); -// fail("should throw Exception when claim an inactive interface!"); -// } -// catch ( UsbClaimException uce ) -// { -// } -// catch ( UsbException ue ) -// { -// } -// catch ( UsbNotActiveException unae ) -// { -// } -// } - - - /** - * private functions - */ - - /** - * Test error conditions -- Null Data Buffer - */ - private void doTestNullDataBufferAsByteArray(int endpointType) - { - outPipe = null; - UsbEndpoint outEndpoint = null; - - //UsbInterface myIface = null; - UsbIrp usbIrp = null; - boolean usbe = false; - - - if ( usbDevice.isConfigured() ) - { - - outEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_OUT); - - assertFalse("could not find output endpoint", null == outEndpoint); - - // @P2D4 - assertTrue("Interface was not claimed!", myIface.isClaimed()); - - //we have an endpoint; now try submitting a null byte array and an IRP - //with a null data - - outPipe = outEndpoint.getUsbPipe(); - assertTrue("output pipe is not active!!!", outPipe.isActive()); - IOMethods.openPipe(outPipe); - - //submit null byte array - byte [] nullBuffer = null; - try - { - outPipe.syncSubmit(nullBuffer); - fail("Expected a UsbException when submitting a null byte array."); - } catch ( IllegalArgumentException iAE ) - { - usbe = true; - } catch ( UsbException uE ) - { - fail("java.lang.IllegalArgumentException was expected. Unexpected UsbException on submitting null buffer:" + uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - fail("java.lang.IllegalArgumentException was expected. Unexpected generic exception." + e); - } - - assertTrue("java.lang.IllegalArgumentException not received when submitting a null byte []", usbe); - - - } else - { - fail ("UsbDevice is not configured!"); - } - - - } - /** - * Test error conditions -- Null Data Buffer - */ - private void doTestNullDataBufferInIrp(int endpointType) - { - - outPipe = null; - UsbEndpoint outEndpoint = null; - - //UsbInterface myIface = null; - UsbIrp usbIrp = null; - boolean usbe = false; - - - if ( usbDevice.isConfigured() ) - { - - outEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_OUT); - - assertFalse("could not find output endpoint", null == outEndpoint); - - // @P2D4 - assertTrue("Interface was not claimed!", myIface.isClaimed()); - - //we have an endpoint; now try submitting a null byte array and an IRP - //with a null data - - outPipe = outEndpoint.getUsbPipe(); - assertTrue("output pipe is not active!!!", outPipe.isActive()); - IOMethods.openPipe(outPipe); - - //submit null byte array - byte [] nullBuffer = null; - - - //submit IRP with null data - - usbIrp = outPipe.createUsbIrp(); - - try - { - usbIrp.setData(nullBuffer); - fail("Expected a UsbException when setting null data in IRP."); - outPipe.syncSubmit(usbIrp); - fail("Expected a UsbException when submitting an IRP with a null byte array in IRP."); - } catch ( IllegalArgumentException iAE ) - { - usbe = true; - } catch ( UsbException uE ) - { - fail("java.lang.IllegalArgumentException was expected. Unexpected UsbException on settin null data in IRP:" + uE); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - fail("java.lang.IllegalArgumentException was expected. Unexpected generic exception." + e); - } - - assertTrue("java.lang.IllegalArgumentException not received when submitting a null byte [] in IRP", usbe); - - } else - { - fail ("UsbDevice is not configured!"); - } - - } - - /** - * Test error conditions -- Action against a closed pipe - */ - private void doTestActionAgainstClosePipeAbortAllSubmissions(int endpointType) - { - - - - outPipe = null; - UsbEndpoint outEndpoint = null; - boolean usbe = false; - - - if ( usbDevice.isConfigured() ) - { - - outEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_OUT); - - assertFalse("could not find output endpoint", null == outEndpoint); - outPipe = outEndpoint.getUsbPipe(); - assertTrue("output pipe is not active!!!", outPipe.isActive()); - assertFalse("pipe should not be open.", outPipe.isOpen()); - - // @P2D4 - assertTrue("Interface was not claimed!", myIface.isClaimed()); - - - try - { - outPipe.abortAllSubmissions(); // should throw UsbNotOpenException - assertFalse("Pipe should have been closed at this part of the test.", outPipe.isOpen()); - fail("abortAllSumissions should have thrown a UsbNotOpenException when called on a closed pipe."); - } catch ( UsbNotOpenException ue ) - { - usbe = true; - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - fail ("UsbNotOpenException was expected. Unexpected exception: " + e); - } - - - - if ( !usbe ) - assertTrue("Test Action Agains Close Pipe abortAllSubmission() did not throw UsbNotOpenException!", false); - - } - - else - { - fail ("UsbDevice is not configured!"); - } - - } - /** - * Test error conditions -- Action against a closed pipe - */ - private void doTestActionAgainstClosePipeSubmit(int endpointType) - { - - outPipe = null; - UsbEndpoint outEndpoint = null; - boolean usbe = false; - - - if ( usbDevice.isConfigured() ) - { - - outEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_OUT); - - assertFalse("could not find output endpoint", null == outEndpoint); - outPipe = outEndpoint.getUsbPipe(); - assertTrue("output pipe is not active!!!", outPipe.isActive()); - assertFalse("pipe should not be open.", outPipe.isOpen()); - - // @P2D4 - assertTrue("Interface was not claimed!", myIface.isClaimed()); - - - try - { - byte [] data = {1,2,3,4,5}; - outPipe.syncSubmit(data); - assertFalse("Pipe should have been closed at this part of the test.", outPipe.isOpen()); - fail("Submit should have thrown a UsbNotOpenException when called on a closed pipe."); - } catch ( UsbNotOpenException ue ) - { - usbe = true; - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1A - - { - fail ("UsbNotOpenException was expected. Unexpected exception: " + e); - } - - - if ( !usbe ) - assertTrue("Test Action Agains Close Pipe Submit did not throw UsbNotOpenException!", false); - - } - - else - { - fail ("UsbDevice is not configured!"); - } - - - - - - - } - - /** - * Test error conditions -- Close a pipe with pending operation - */ - private void doTestClosePipePendingAction(int endpointType) - { - - inPipe = null; - boolean usbe = false; - UsbEndpoint inEndpoint = null; - - // get an out endpoint - if ( usbDevice.isConfigured() ) - { - - inEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_IN); - - assertFalse("could not find endpoint", null == inEndpoint); - - inPipe = inEndpoint.getUsbPipe(); - assertTrue("output pipe is not active!!!", inPipe.isActive()); - assertFalse("pipe should not be open.", inPipe.isOpen()); - - // @P2D4 - assertTrue("Interface was not claimed!", myIface.isClaimed()); - - // open the pipe - IOMethods.openPipe(inPipe); - assertTrue("pipe should be opened", inPipe.isOpen()); - - try - { - //List listOfIrps = new ArrayList(); - List inList = new ArrayList(); - UsbIrp inIrp = null; - - for ( int i = 0; i < 1000; i++ ) - { - - inIrp = inPipe.createUsbIrp(); - inIrp.setData(new byte[inPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize()]); // @P2A - inList.add(inIrp); - } - inPipe.asyncSubmit(inList); - inPipe.close(); // should throw UsbException - fail ("UsbException should have been thrown when closing pipe with pending submissions."); - } catch ( UsbException ue ) - { - usbe = true; - - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - fail("Unexpected Exception: " + e); - } - if ( !usbe ) - assertTrue("Test Close Pipe With Pending Operations usbPipe.close() did not throw UsbException!", false); - - - } else - { - fail ("UsbDevice is not configured!"); - } - - } - - /** - * Test error conditions -- Open a pipe on an inactive interface - */ - private void doTestOpenPipeOnInactiveAlternateSetting(int endpointType) - { - - - myIface = null; - boolean usbe = false; - UsbEndpoint inEndpoint = null; - inPipe = null; - - - if ( usbDevice.isConfigured() ) - { - inEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_IN); - if ( (endpointType == UsbConst.ENDPOINT_TYPE_BULK)|| - (endpointType == UsbConst.ENDPOINT_TYPE_INTERRUPT) ) - { - - - assertFalse("could not find endpoint", null == inEndpoint); - // @P2D3 - } else - { - - - assertFalse("could not find endpoint", null == inEndpoint); - // @P2D3 - } - - inPipe = inEndpoint.getUsbPipe(); - assertFalse("Pipe should not be active!!!", - inPipe.isActive()); - - - if ( !myIface.isActive() ) - { - try - { - inPipe.open(); - fail("should caused UsbNotActiveException!"); - } catch ( UsbNotActiveException ue ) - { - usbe = true; - } catch ( UsbException ue ) - { - fail("UsbNotActiveException was expected. Unexpected UsbException: " + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - fail("UsbNotActiveException was expected. Unexpected Exception: " + e); - } - } else - { - fail("Interface should have been inactive at this point."); - } - if ( !usbe ) - assertTrue("Test Open Pipe On Inactive Interface did not throw UsbNotActiveException!", false); - - } - - - else - { - fail ("UsbDevice is not configured!"); - } - - assertFalse("Leaving routine but interface was not released!", myIface.isClaimed()); - } - - - private void doTestOpenPipeOnUnclaimedInterface(int endpointType) - { - myIface = null; - boolean usbe = false; - UsbEndpoint inEndpoint = null; - inPipe = null; - - - if ( usbDevice.isConfigured() ) - { - inEndpoint = getEndpointOfType(usbDevice, endpointType, UsbConst.REQUESTTYPE_DIRECTION_IN); - - - assertFalse("could not find endpoint", null == inEndpoint); - - // @P2D4 - try - { - inEndpoint.getUsbInterface().release(); - } catch ( UsbClaimException ue ) - { - fail("The interface should have been durring getEndpointOfType method call!"); - } catch ( UsbException ue ) - { - fail("Unexpected exception: " + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - if ( myIface.isActive() ) - { - inPipe = inEndpoint.getUsbPipe(); - assertTrue("pipe is not active!!!", - inPipe.isActive()); - try - { - - - inPipe.open(); - fail("should caused UsbNotClaimedException!"); - - } catch ( UsbNotClaimedException ue ) - { - usbe = true; - } catch ( UsbException ue ) - { - fail("UsbNotClaimedException was expected. Unexpected UsbException: " + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1A - { - fail("UsbNotClaimedException was expected. Unexpected Exception: " + e); - - } - if ( !usbe ) - assertTrue("Test Open Pipe On Unclaimed Interface did not throw UsbNotClaimedException!", false); - } - - else - { - fail("Interface should have been active."); - } - - - } - - - - } - - -// /** -// * looking for an inactive interface -// * return null if not found -// */ -// private UsbInterface getInactiveInterface() -// { -// UsbConfiguration config = null; -// UsbHub virtualRootUsbHub = getVirtualRootUsbHub(); -// List usbDevices = null; -// byte firstInterface = 0; -// // get all connected devices -// usbDevices = getAllUsbDevices(virtualRootUsbHub); -// System.out.println("Found " + usbDevices.size() + " devices total."); -// -// // find an inactive interface -// for ( int i = 0; i > usbDevices.size(); i++ ) -// { -// UsbDevice device = (UsbDevice)usbDevices.get(i); -// List configurations = device.getUsbConfigurations(); -// for ( int j = 0; i - * Helper functions for IO tests - * - * @author Leslie Blair - */ -@SuppressWarnings("all") -public class IOMethods -{ - protected static void claimInterface(UsbInterface usbInterface) - { - Assert.assertFalse("Interface already claimed.", usbInterface.isClaimed()); - try - { - usbInterface.claim(); - Assert.assertTrue("usbInterface.isClaimed() returns false after interface is claimed.", usbInterface.isClaimed()); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - Assert.fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - Assert.fail("Exception claiming interface. " + e.toString()); - } - - }; - protected static void releaseInterface(UsbInterface usbInterface) - { - Assert.assertTrue("Attempting to release an interface that is not claimed.", usbInterface.isClaimed()); - try - { - usbInterface.release(); - Assert.assertFalse("usbInterface.isClaimed() returns true after interface is released.", usbInterface.isClaimed()); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - Assert.fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1A - { - Assert.fail("Exception releasing interface. " + e.toString()); - } - - }; - - protected static void openPipe(UsbPipe usbPipe) - { - Assert.assertTrue("Can't open pipe if it is not active.",usbPipe.isActive()); - - Assert.assertFalse("Pipe already claimed.", usbPipe.isOpen()); - try - { - usbPipe.open(); - Assert.assertTrue("usbPipe.isOpen() returns false after pipe is opened.", usbPipe.isOpen()); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - Assert.fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1A - { - Assert.fail("Exception opening pipe. " + e.toString()); - } - - }; - protected static void closePipe(UsbPipe usbPipe) - { - Assert.assertTrue("Trying to close a pipe that is not open.", usbPipe.isOpen()); - try - { - usbPipe.close(); - Assert.assertFalse("usbPipe.isOpen() returns true after pipe is closed.", usbPipe.isOpen()); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - Assert.fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } catch ( Exception e ) // @P1C - { - Assert.fail("Exception closing pipe. " + e.toString()); - } - - }; - - - protected static void createListofAllAvailablePipesOfSpecifiedEndpointType(UsbDevice usbDevice, byte endpointType, List usbPipeList) - { - //The following are the expected configuration, interface, and alternate setting location of the following types of pipes - if ( (endpointType == UsbConst.ENDPOINT_TYPE_INTERRUPT) || (endpointType == UsbConst.ENDPOINT_TYPE_BULK) ) - { - byte configurationNumber = 1; - byte interfaceNumber = 0; - byte alternateSetting = 0; // Now end point is on AS 0 @P2A - createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, configurationNumber, - interfaceNumber, alternateSetting, usbPipeList); - } else if ( endpointType == UsbConst.ENDPOINT_TYPE_ISOCHRONOUS ) - { - byte configurationNumber = 1; - byte interfaceNumber = 0; - byte alternateSetting = 0; - createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, configurationNumber, - interfaceNumber, alternateSetting, usbPipeList); - } - - }; - - protected static void createListofAllAvailablePipesOfSpecifiedEndpointType(UsbDevice usbDevice, byte endpointType, byte configurationNumber, - byte interfaceNumber, byte alternateSetting, List usbPipeList ) - { - // @P2D - selectAlternateSetting(usbDevice, configurationNumber, interfaceNumber, alternateSetting); - - UsbConfiguration usbConfiguration = usbDevice.getUsbConfiguration(configurationNumber); - UsbInterface usbInterface = usbConfiguration.getUsbInterface(interfaceNumber); - - List endpointList = new ArrayList(); - List endpointListFromImplementation = null; - endpointListFromImplementation = usbInterface.getUsbEndpoints(); - for ( int i = 0; i< endpointListFromImplementation.size(); i++ ) - { - endpointList.add(endpointListFromImplementation.get(i)); - } - - //get rid of all the endpoints that are not of the desired type - int numInList = 0; - while ( numInList != endpointList.size() ) - { - if ( (((UsbEndpoint)endpointList.get(numInList)).getType()) != endpointType ) - { - //it's not the right endpoint type, so remove it from list - endpointList.remove(numInList); - } else - { - //point to next entry in list - numInList++; - } - } - - //get pipes for all the endpoints - for ( int i = 0; i < endpointList.size(); i++ ) - { - usbPipeList.add(((UsbEndpoint)endpointList.get(i)).getUsbPipe()); - } - }; - - /** - * select alternate setting for the programmable board (AS0 or AS1) - */ - protected static void selectAlternateSetting(UsbDevice usbDevice, - byte requiredUsbConfigurationNumber, - byte requiredInterfaceNumber, - byte desiredAlternateSetting) - { - try - { - if ( usbDevice.isConfigured() ) - { - if ( debug ) - System.out.println("Active ConfigurationNumber: " + usbDevice.getActiveUsbConfigurationNumber() ); - // @P2D6 - //get UsbConfiguraion - UsbConfiguration usbConfiguration = usbDevice.getActiveUsbConfiguration(); - - //getUsbInterface - UsbInterface usbInterface = usbConfiguration.getUsbInterface(requiredInterfaceNumber); - if ( debug ) - System.out.println("Select Alternate Setting 1"); - // claim the interface: the interface has to be claimed to select an alternate setting. - if (!usbInterface.isClaimed()) - claimInterface(usbInterface); - // @P2D - } - } catch ( Exception e ) - { - Assert.fail("Error setting alternate setting. " + e.toString()); - } - - }; - - protected static void releaseListOfPipes(List pipeList ) - { - //all pipes in list are expected to be on the same interface - UsbInterface usbInterface = ((UsbPipe)pipeList.get(0)).getUsbEndpoint().getUsbInterface(); - while ( pipeList.size() != 0 ) - { - //make sure all pipes are closed (needed for error conditions) - if ( ((UsbPipe) pipeList.get(0)).isOpen() == true ) - { - closePipe((UsbPipe) pipeList.get(0)); - } - pipeList.remove(0); - } - releaseInterface(usbInterface); - }; - - protected static void findINandOUTPipesForTest(List pipeList, int endpointSize, int[] pipeIndexes, - int inPipeArrayIndex, int outPipeArrayIndex) - { - int i; - int j; - - int inPipeListIndex = 0; - int outPipeListIndex = 0; - - Assert.assertFalse("There are no pipes in list.",(0 == pipeList.size())); - - boolean pipeIndexesFound = false; - - for ( i = 0; i< pipeList.size(); i++ ) - { - - UsbPipe usbPipe1 = (UsbPipe) pipeList.get(i); - if ( usbPipe1.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize() == endpointSize ) - { - //it's the correct endpoint size, now get a matching pair - //For a pair to match, they must be an IN/OUT endpoint pair and their maxPacketSizes must be the same - byte endpointAddress1 = usbPipe1.getUsbEndpoint().getUsbEndpointDescriptor().bEndpointAddress(); - byte endpointAddress2; - if ( usbPipe1.getUsbEndpoint().getDirection() == UsbConst.ENDPOINT_DIRECTION_IN ) - { - endpointAddress2 = (byte)(endpointAddress1 & ~UsbConst.ENDPOINT_DIRECTION_MASK); - inPipeListIndex = i; - } else - { - endpointAddress2 = (byte) (endpointAddress1 | UsbConst.ENDPOINT_DIRECTION_MASK); - outPipeListIndex = i; - } - - //go through list looking for address 2 - for ( j = i+1; j< pipeList.size(); j++ ) - { - UsbPipe usbPipe2 = (UsbPipe) pipeList.get(j); - if ( (usbPipe2.getUsbEndpoint().getUsbEndpointDescriptor().bEndpointAddress() == endpointAddress2) - && (usbPipe2.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize() == endpointSize) - ) - { - //a pair of endpoints has been found - if ( usbPipe2.getUsbEndpoint().getDirection() == UsbConst.ENDPOINT_DIRECTION_IN ) - { - inPipeListIndex = j; - } else - { - outPipeListIndex = j; - } - pipeIndexesFound = true; - break; //break out of inner loop as a pair has been found - } - - } - } - - if ( pipeIndexesFound ) - { - pipeIndexes[inPipeArrayIndex] = inPipeListIndex; - pipeIndexes[outPipeArrayIndex] = outPipeListIndex; - break; - } - - } - - }; - protected static void verifyThePipes(UsbPipe inPipe, UsbPipe outPipe, int endpointSize) - { - Assert.assertNotNull("IN pipe should not be null.", inPipe); - Assert.assertNotNull("OUT pipe should not be null.",outPipe); - Assert.assertTrue("These pipes are not from matchine endpoint pairs.", - ((inPipe.getUsbEndpoint().getUsbEndpointDescriptor().bEndpointAddress()) - UsbConst.ENDPOINT_DIRECTION_MASK) - == (outPipe.getUsbEndpoint().getUsbEndpointDescriptor().bEndpointAddress())); - Assert.assertEquals("The IN pipe does not have the correct maxPacketSize.", - endpointSize,inPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize()); - Assert.assertEquals("The OUT pipe does not have the correct maxPacketSize.", - endpointSize,outPipe.getUsbEndpoint().getUsbEndpointDescriptor().wMaxPacketSize()); - - }; - - /** - * printDebug method will print the specified string if "debug" is true. - * Useful function for debugging - * @param infoString - */ - protected static void printDebug(String infoString) - { - if ( debug ) - { - System.out.println(infoString); - } - } - private static boolean debug = false; - //private static boolean debug = true; -} diff --git a/src/test/java/javax/usb/tck/IOShortPacketTest.java b/src/test/java/javax/usb/tck/IOShortPacketTest.java deleted file mode 100755 index d14c8a3..0000000 --- a/src/test/java/javax/usb/tck/IOShortPacketTest.java +++ /dev/null @@ -1,586 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ ------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040804 raulortz Support for UsbDisconnectedException - */ - -package javax.usb.tck; - -import java.util.*; - -import javax.usb.*; -import javax.usb.event.*; -import javax.usb.util.*; - - -import junit.framework.Assert; - -/** - * IOShortPacketTest -- Helper methods for Bulk, Interrupt, and Isochronous IO Tests - * UsbShortPacketException test. - *

- * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -public class IOShortPacketTest -{ - - protected void RoundTripIOTestShortPacket(byte testType, int syncOrAsync,int numIrps, int endpointmaxPacketSize, - boolean []acceptShortPacket, boolean []verifyAcceptShortPacket, - int[] OUTLength, int[] OUTOffset, int[] OUTExpectedLength, - Exception []OUTexpectedException, - - int[] INLength, int[]INOffset, int[]INExpectedLength, - Exception []INexpectedException, - byte [] transformType - ) - - { - - //Note that this code is based on IOTests.RounTripTest which handles IRP, IRPList, and Byte array. Since only IRPs - //are being sent in this test, some of the complexity has been removed; however, although the numIrps is always - //one for this test, the code has not been changed to get rid of the arrays. - - //ensure all values set up - Assert.assertEquals(numIrps,transformType.length); - Assert.assertEquals(numIrps,OUTLength.length); - Assert.assertEquals(numIrps,OUTOffset.length); - Assert.assertEquals(numIrps,acceptShortPacket.length); - Assert.assertEquals(numIrps,verifyAcceptShortPacket.length); - Assert.assertEquals(numIrps,OUTExpectedLength.length); - Assert.assertEquals(numIrps,OUTexpectedException.length); - Assert.assertEquals(numIrps,INLength.length); - Assert.assertEquals(numIrps,INOffset.length); - Assert.assertEquals(numIrps,INExpectedLength.length); - Assert.assertEquals(numIrps,INexpectedException.length); - - Assert.assertNotNull("usbDevice is null, but should not be null.", usbDevice); - Assert.assertEquals("For short packet test, number of IRPs should be 1.", 1, numIrps); - - - /* - * set up Pipes and add listeners - */ - UsbPipe inPipe = null; - UsbPipe outPipe = null; - - //we need two int values back from method call so we'll put them in the array - int [] pipeListIndexes = new int[2]; - int inPipeArrayIndex = 0; - int outPipeArrayIndex = 1; - - IOMethods.findINandOUTPipesForTest(usbPipeListGlobal, endpointmaxPacketSize, pipeListIndexes, inPipeArrayIndex, outPipeArrayIndex); - inPipe = (UsbPipe) usbPipeListGlobal.get(pipeListIndexes[inPipeArrayIndex]); - outPipe = (UsbPipe) usbPipeListGlobal.get(pipeListIndexes[outPipeArrayIndex]); - IOMethods.verifyThePipes(inPipe, outPipe, endpointmaxPacketSize); - - inPipe.addUsbPipeListener(inPipeListener); - outPipe.addUsbPipeListener(outPipeListener); - - IOMethods.openPipe(inPipe); - IOMethods.openPipe(outPipe); - - - - //define buffers to be used in IRPs or sent as byte[] - byte[] aggregateOUTbuffer = null; - byte[] aggregateINbuffer = null; - - - //for byte array and single IRP, the OUT and IN buffers are the length specified by the tests - aggregateOUTbuffer = new byte[OUTLength[0]]; - aggregateINbuffer = new byte[INLength[0]]; - - - printDebug("RoundTripTestShortPacket -- IRP " + transmitListStrings[syncOrAsync] +" " + endpointTypeStrings[endpointType]); - - - - - - - /* - * Create the OUT and IN IRPs or byte arrrays - */ - List transmitBuffers = new ArrayList(); - List listOfOUTIrps = new ArrayList(); - List listOfINIrps = new ArrayList(); - - for ( int k = 0 ; k < numIrps; k++ ) - { - //create transmit buffer for OUT and IN IRPs - TransmitBuffer currentTransmitBuffer = new TransmitBuffer(transformType[k], OUTLength[k]); - transmitBuffers.add(currentTransmitBuffer); - - - //create OUT IRP - UsbIrp currentOUTIrp = outPipe.createUsbIrp(); - listOfOUTIrps.add(currentOUTIrp); - - //set data in OUT IRP - currentOUTIrp.setData(aggregateOUTbuffer, OUTOffset[k], OUTLength[k]); - currentOUTIrp.setAcceptShortPacket(acceptShortPacket[k]); - - //OUT IRP is ready to go! - - - if ( endpointType == UsbConst.ENDPOINT_TYPE_ISOCHRONOUS ) - { - /* - * For isochronous transfers, all IN Irps will have an offset of zero and - * the same buffer length. - */ - //get the longest required buffer length for all of the IRPs. All of the IRPs in the list - //have the same length buffer. - int standardISOINBufferLength = INLength[0]; - for ( int l = 1; l standardISOINBufferLength ) - { - standardISOINBufferLength = INLength[l]; - } - } - //now that the largest has been found, set the length for each in IRP to the new length - for ( int l = 0; l=0; i-- ) - { - //all of the IRPs in which we are interested SHOULD have a non zero length - //amount of data returned. - //Once the zero length data IRP events are removed, only the IRP events that received the - //expected OUT data should be left in the list - - Assert.assertTrue("There should be no error events in the list.",((UsbPipeEvent) listOfPipeEvents.get(i)).getClass() == UsbPipeDataEvent.class); - if ( ((UsbPipeDataEvent) listOfPipeEvents.get(i)).getUsbIrp().getActualLength() == 0 ) - { - listOfPipeEvents.remove(i); - Assert.assertEquals("Original Irps and pipe event Irps should be zero actual length in the same position in the list.",0,((UsbIrp) listOfIrps.get(i)).getActualLength()); - listOfIrps.remove(i); - } - else - { - Assert.assertEquals("Original Irps and pipe event Irps actual length should be the same at the same position in the list.", - ((UsbPipeDataEvent) listOfPipeEvents.get(i)).getUsbIrp().getActualLength(), - ((UsbIrp) listOfIrps.get(i)).getActualLength()); - printDebug("Non-zero actual length pipe event found at index " + i); - } - } - Assert.assertFalse("None of the Isochronous IN IRPs received any data",0 == listOfPipeEvents.size()); - }; - - - - - //------------------------------------------------------------------------- - // Instance variables - // - - private UsbPipeListener inPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent updE) - { - Assert.assertNotNull(updE); - inPipeEvents.add(updE); - printDebug("IN Length: " + updE.getUsbIrp().getLength()); - printDebug("IN actualLength: " + updE.getUsbIrp().getActualLength()); - printDebug("IN acceptShortPackets: " + updE.getUsbIrp().getAcceptShortPacket()); - printDebug("IN data event."); - } - - public void errorEventOccurred(UsbPipeErrorEvent upeE) - { - Assert.assertNotNull(upeE); - inPipeEvents.add(upeE); - printDebug("IN error event."); - - } - }; - - private UsbPipeListener outPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent updE) - { - Assert.assertNotNull(updE); - outPipeEvents.add(updE); - printDebug("OUT actualLength: " + updE.getUsbIrp().getActualLength()); - printDebug("OUT data event."); - } - - public void errorEventOccurred(UsbPipeErrorEvent upeE) - { - Assert.assertNotNull(upeE); - //outPipeEvents.add(upeE); - printDebug("OUT error event."); - upeE.getUsbException().printStackTrace(); - Assert.fail("No OUT pipe error events expected during this test. Exception is " + upeE.getUsbException().getMessage()); - } - }; - - /** - * Constructor - */ - public IOShortPacketTest() - { - super(); - }; - - protected IOShortPacketTest(UsbDevice newUsbDevice, List newUsbPipeList, byte newEndpointType, byte newTestType) - { - usbPipeListGlobal = newUsbPipeList; - usbDevice = newUsbDevice; - endpointType = newEndpointType; - testType = newTestType; - }; - - private List inPipeEvents = new ArrayList(); - private List outPipeEvents = new ArrayList(); - - private List usbPipeListGlobal = new ArrayList(); - - private byte endpointType; - private static final int MAX_SIZE_IRP_BUFFER = 750; - - - protected static final byte TRANSFORM_TYPE_PASSTHROUGH = (byte)0x01; - protected static final byte TRANSFORM_TYPE_INVERT_BITS = (byte)0x02; - protected static final byte TRANSFORM_TYPE_INVERT_ALTERNATE_BITS = (byte)0x03; - - private UsbDevice usbDevice; - protected static int totalIterations = 10; - //private int totalIterations = 1; - private static final boolean SYNC_SUBMIT = true; - private static final boolean ASYNC_SUBMIT = false; - protected static final boolean [] transmitList= {SYNC_SUBMIT, ASYNC_SUBMIT}; - private static final String [] transmitListStrings = {"SYNC","ASYNC"}; - protected static final byte BYTE_ARRAY = 0; - protected static final byte IRP = 1; - protected static final byte IRPLIST = 2; - private static final String [] endpointTypeStrings = {"CONTROL","ISOCHRONOUS", "BULK", "INTERRUPT"}; - byte testType; - - protected static void printDebug(String infoString) - { - if ( printDebug ) - { - System.out.println(infoString); - } - } - private static boolean printDebug = false; - // private static boolean printDebug = true; -} diff --git a/src/test/java/javax/usb/tck/IOTests.java b/src/test/java/javax/usb/tck/IOTests.java deleted file mode 100755 index e1da886..0000000 --- a/src/test/java/javax/usb/tck/IOTests.java +++ /dev/null @@ -1,689 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ ------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040804 raulortz Support for UsbDisconnectedException - */ - -package javax.usb.tck; - -import java.util.*; - -import javax.usb.*; -import javax.usb.event.*; -import javax.usb.util.*; - - -import junit.framework.Assert; - -/** - * IOTests -- Helper methods for Bulk, Interrupt, and Isochronous IO Tests - *

- * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -public class IOTests -{ - - - - - protected void RoundTripIOTest(byte testType, int numIrps, int endpointmaxPacketSize, - boolean []acceptShortPacket, boolean []verifyAcceptShortPacket, - int[] OUTLength, int[] OUTOffset, int[] OUTExpectedLength, - Exception []OUTexpectedException, - - int[] INLength, int[]INOffset, int[]INExpectedLength, - Exception []INexpectedException, - byte [] transformType - ) - - { - - //ensure all values set up - Assert.assertEquals(numIrps,transformType.length); - Assert.assertEquals(numIrps,OUTLength.length); - Assert.assertEquals(numIrps,OUTOffset.length); - Assert.assertEquals(numIrps,acceptShortPacket.length); - Assert.assertEquals(numIrps,verifyAcceptShortPacket.length); - Assert.assertEquals(numIrps,OUTExpectedLength.length); - Assert.assertEquals(numIrps,OUTexpectedException.length); - Assert.assertEquals(numIrps,INLength.length); - Assert.assertEquals(numIrps,INOffset.length); - Assert.assertEquals(numIrps,INExpectedLength.length); - Assert.assertEquals(numIrps,INexpectedException.length); - - Assert.assertNotNull("usbDevice is null, but should not be null.", usbDevice); - - - /* - * set up Pipes and add listeners - */ - UsbPipe inPipe = null; - UsbPipe outPipe = null; - - //we need two int values back from method call so we'll put them in the array - int [] pipeListIndexes = new int[2]; - int inPipeArrayIndex = 0; - int outPipeArrayIndex = 1; - - IOMethods.findINandOUTPipesForTest(usbPipeListGlobal, endpointmaxPacketSize, pipeListIndexes, inPipeArrayIndex, outPipeArrayIndex); - inPipe = (UsbPipe) usbPipeListGlobal.get(pipeListIndexes[inPipeArrayIndex]); - outPipe = (UsbPipe) usbPipeListGlobal.get(pipeListIndexes[outPipeArrayIndex]); - IOMethods.verifyThePipes(inPipe, outPipe, endpointmaxPacketSize); - - inPipe.addUsbPipeListener(inPipeListener); - outPipe.addUsbPipeListener(outPipeListener); - - IOMethods.openPipe(inPipe); - IOMethods.openPipe(outPipe); - - if ( (inPipe instanceof UsbUtil.SynchronizedUsbPipe) && (outPipe instanceof UsbUtil.SynchronizedUsbPipe) ) - printDebug("SynchronizedUsbPipes under test."); - - /* - * set up the IRPs or byte arrays and send and verify the data - */ - for ( int iterations=0; (iterations < totalIterations); iterations++ ) - { - for ( int syncOrAsync=0; syncOrAsync standardISOINBufferLength ) - { - standardISOINBufferLength = INLength[l]; - } - } - //now that the largest has been found, set the length for each in IRP to the new length - for ( int l = 0; l=0; i-- ) - { - //all of the IRPs in which we are interested SHOULD have a non zero length - //amount of data returned. - //Once the zero length data IRP events are removed, only the IRP events that received the - //expected OUT data should be left in the list - - Assert.assertTrue("There should be no error events in the list.",((UsbPipeEvent) listOfPipeEvents.get(i)).getClass() == UsbPipeDataEvent.class); - if ( ((UsbPipeDataEvent) listOfPipeEvents.get(i)).getUsbIrp().getActualLength() == 0 ) - { - listOfPipeEvents.remove(i); - Assert.assertEquals("Original Irps and pipe event Irps should be zero actual length in the same position in the list.",0,((UsbIrp) listOfIrps.get(i)).getActualLength()); - listOfIrps.remove(i); - } - else - { - Assert.assertEquals("Original Irps and pipe event Irps actual length should be the same at the same position in the list.", - ((UsbPipeDataEvent) listOfPipeEvents.get(i)).getUsbIrp().getActualLength(), - ((UsbIrp) listOfIrps.get(i)).getActualLength()); - printDebug("Non-zero actual length pipe event found at index " + i); - } - } - Assert.assertFalse("None of the Isochronous IN IRPs received any data",0 == listOfPipeEvents.size()); - }; - - - - - //------------------------------------------------------------------------- - // Instance variables - // - - private UsbPipeListener inPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent updE) - { - Assert.assertNotNull(updE); - inPipeEvents.add(updE); - } - - public void errorEventOccurred(UsbPipeErrorEvent upeE) - { - Assert.assertNotNull(upeE); - //inPipeEvents.add(upeE); - Assert.fail("No IN pipe error events expected during this test. Exception is " + upeE.getUsbException().getMessage()); - } - }; - - private UsbPipeListener outPipeListener = new UsbPipeListener() - { - public void dataEventOccurred(UsbPipeDataEvent updE) - { - Assert.assertNotNull(updE); - outPipeEvents.add(updE); - } - - public void errorEventOccurred(UsbPipeErrorEvent upeE) - { - Assert.assertNotNull(upeE); - //outPipeEvents.add(upeE); - Assert.fail("No OUT pipe error events expected during this test. Exception is " + upeE.getUsbException().getMessage()); - } - }; - - /** - * Constructor - */ - public IOTests() - { - super(); - }; - - protected IOTests(UsbDevice newUsbDevice, List newUsbPipeList, byte newEndpointType, byte newTestType) - { - usbPipeListGlobal = newUsbPipeList; - usbDevice = newUsbDevice; - endpointType = newEndpointType; - testType = newTestType; - }; - - private List inPipeEvents = new ArrayList(); - private List outPipeEvents = new ArrayList(); - - private List usbPipeListGlobal = new ArrayList(); - - private byte endpointType; - private static final int MAX_SIZE_IRP_BUFFER = 750; - - - protected static final byte TRANSFORM_TYPE_PASSTHROUGH = (byte)0x01; - protected static final byte TRANSFORM_TYPE_INVERT_BITS = (byte)0x02; - protected static final byte TRANSFORM_TYPE_INVERT_ALTERNATE_BITS = (byte)0x03; - - private UsbDevice usbDevice; - private int totalIterations = 10; - //private int totalIterations = 1; - private static final boolean SYNC_SUBMIT = true; - private static final boolean ASYNC_SUBMIT = false; - private static final boolean [] transmitList= {SYNC_SUBMIT, ASYNC_SUBMIT}; - private static final String [] transmitListStrings = {"SYNC","ASYNC"}; - protected static final byte BYTE_ARRAY = 0; - protected static final byte IRP = 1; - protected static final byte IRPLIST = 2; - private static final String [] endpointTypeStrings = {"CONTROL","ISOCHRONOUS", "BULK", "INTERRUPT"}; - byte testType; - - protected static void printDebug(String infoString) - { - if ( printDebug ) - { - System.out.println(infoString); - } - } - private static boolean printDebug = false; - //private static boolean printDebug = true; -} diff --git a/src/test/java/javax/usb/tck/InterruptIOErrorConditionsTest.java b/src/test/java/javax/usb/tck/InterruptIOErrorConditionsTest.java deleted file mode 100755 index 4c32912..0000000 --- a/src/test/java/javax/usb/tck/InterruptIOErrorConditionsTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ ------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040804 raulortz Support for UsbDisconnectedException - */ - -//import java.util.*; -import javax.usb.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; -//import javax.usb.util.*; - -import junit.framework.TestCase; - -/** - * IO Error conditions - *

- * This test verifies that error conditions are generated and proper - * exceptions are thrown in the operation. - * - * @author Thanh Ngo - */ - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class InterruptIOErrorConditionsTest extends TestCase -{ - //------------------------------------------------------------------------- - // Ctor(s) - // - - - public InterruptIOErrorConditionsTest() - { - thisTest = new IOErrorConditionsTest(UsbConst.ENDPOINT_TYPE_INTERRUPT); - } - - //------------------------------------------------------------------------- - // Protected overridden methods - // - - protected void setUp() throws Exception { - thisTest.setUp(); - - } - - protected void tearDown() throws Exception { - thisTest.tearDown(); - } - - - - /** - * Null Data Buffer - */ - public void testNullDataBufferInIrp() - { - thisTest.testNullDataBufferInIrp(); - } - /** - * Null Data Buffer - */ - public void testNullDataBufferAsByteArray() - { - thisTest.testNullDataBufferAsByteArray(); - } - - /** - * Action against a closed pipe - */ - public void testActionAgainstClosePipeAbortAllSubmissions() - { - thisTest.testActionAgainstClosePipeAbortAllSubmissions(); - } - /** - * Action against a closed pipe - */ - public void testActionAgainstClosePipeSubmit() - { - thisTest.testActionAgainstClosePipeSubmit(); - } - - /** - * Close a pipe with pending operation - */ - public void testClosePipePendingAction() - { - thisTest.testClosePipePendingAction(); - } - - // Moved method testOpenPipeOnInactiveAlternateSetting into the optional setInterface tests @P1D7 - - /** - * Open a pipe on an unclaimed interface - */ - public void testOpenPipeOnUnclaimedInterface() - { - thisTest.testOpenPipeOnUnclaimedInterface(); - } - - /** - * Claim an already claimed interface - */ - public void testClaimAnAlreadyClaimedInterface() - { - thisTest.testClaimAnAlreadyClaimedInterface(); - - } - - - private IOErrorConditionsTest thisTest = null; -} diff --git a/src/test/java/javax/usb/tck/InterruptIOTests.java b/src/test/java/javax/usb/tck/InterruptIOTests.java deleted file mode 100755 index fe44e14..0000000 --- a/src/test/java/javax/usb/tck/InterruptIOTests.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -package javax.usb.tck; - -import java.util.*; - -import javax.usb.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - - - -import junit.framework.*; - -/** - * Interrupt IO Test -- Synchronous and asynchronous byte[], IRP, and IRP List submissions - *

- * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class InterruptIOTests extends TestCase -{ - public void setUp() throws Exception - { - endpointType = UsbConst.ENDPOINT_TYPE_INTERRUPT; - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - Assert.assertNotNull("Device required for test not found",usbDevice); - IOMethods.createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, usbPipeListGlobal); - super.setUp(); - } - public void tearDown() throws Exception - { - IOMethods.releaseListOfPipes(usbPipeListGlobal); - super.tearDown(); - } - - public void testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer8bytes_passthrough() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer8bytes_passthrough(); - }; - public void testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer16bytes_invertBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer16bytes_invertBits(); - }; - public void testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer24bytes_invertAltBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testByteArray_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer24bytes_invertAltBits(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer17bytes_passthrough() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer17bytes_passthrough(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer66bytes_invertBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer66bytes_invertBits(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer129bytes_invertAltBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testByteArray_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer129bytes_invertAltBits(); - }; - public void testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer8bytes_invertBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer8bytes_invertBits(); - }; - public void testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer16bytes_invertAltBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer16bytes_invertAltBits(); - }; - public void testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer64bytes_passthrough() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testSingleIRP_BuffersMultiplesOfMaxPacketSize_maxPacketSizeOf8bytes_buffer64bytes_passthrough(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer25bytes_invertBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer25bytes_invertBits(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer72bytes_invertAltBits() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer72bytes_invertAltBits(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer130bytes_passthrough() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testSingleIRP_BuffersNOTMultiplesOfMaxPacketSize_maxPacketSizeOf64bytes_buffer130bytes_passthrough(); - }; - public void testIRPListBuffersMultiplesOfMaxPacketSizeOf8bytes() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.testIRPListBuffersMultiplesOfMaxPacketSizeOf8bytes(); - }; - // TODO Disabled because 64 byte packet size not supported by test firmware - public void disabled_testIRPListBuffersNOTMultiplesOfMaxPacketSizeOf64bytes() - { - BulkIOTests thisInterruptTest = new BulkIOTests(usbDevice, usbPipeListGlobal, endpointType); - thisInterruptTest.disabled_testIRPListBuffersNOTMultiplesOfMaxPacketSizeOf64bytes(); - }; - - - - private List usbPipeListGlobal = new ArrayList(); - private byte endpointType; - private UsbDevice usbDevice; - - -} diff --git a/src/test/java/javax/usb/tck/InterruptIOTestwithSynchronizedUsbPipe.java b/src/test/java/javax/usb/tck/InterruptIOTestwithSynchronizedUsbPipe.java deleted file mode 100755 index a7f800d..0000000 --- a/src/test/java/javax/usb/tck/InterruptIOTestwithSynchronizedUsbPipe.java +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -package javax.usb.tck; - -import java.util.*; - -import javax.usb.*; -import javax.usb.util.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import junit.framework.*; - -/** - * Interrupt IO Test -- Synchronous and asynchronous byte[], IRP, and IRP List submissions - * with UsbUtil.synchronizedUsbPipe - *

- * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class InterruptIOTestwithSynchronizedUsbPipe extends TestCase -{ - public void setUp() throws Exception - { - endpointType = UsbConst.ENDPOINT_TYPE_INTERRUPT; - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - Assert.assertNotNull("Device required for test not found",usbDevice); - IOMethods.createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, usbPipeListNotSynchronized); - for ( int i=0; i - * The goal of the Bulk, Interrupt, and Isochronous IO test is to - * verify that IN and OUT pipes can be opened and closed, and verify - * that bulk, interrupt, and isochronous transfer operations work successfully, proper - * events are generated, and proper exceptions are thrown in the operation. - * - * This test verifies that UsbShortPacketException is received when expected. - * - * @author Leslie Blair - */ - - -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class InterruptShortPacketIOTests extends TestCase -{ - public void setUp() throws Exception - { - endpointType = UsbConst.ENDPOINT_TYPE_INTERRUPT; - usbDevice = FindProgrammableDevice.getInstance().getProgrammableDevice(); - Assert.assertNotNull("Device required for test not found",usbDevice); - IOMethods.createListofAllAvailablePipesOfSpecifiedEndpointType(usbDevice, endpointType, usbPipeListGlobal); - assertFalse("No pipes of specified endpoint were found.", (0 == usbPipeListGlobal.size())); - super.setUp(); - } - public void tearDown() throws Exception - { - IOMethods.releaseListOfPipes(usbPipeListGlobal); - super.tearDown(); - } - - - public void testShortPacketException() - { - //repeat the test for the number of iteration specified - for ( int iterations=0; (iterations < IOShortPacketTest.totalIterations); iterations++ ) - { - //first, do all transfers sync and then do async - for ( int syncOrAsync=0; syncOrAsync 6000 ) - { - fail("Timeout value exceeded"); - } - else - { - done = true; - } - } - private boolean done = false; - private long st, et, acttime; - private UsbIrp usbIrp; - } - } - -} diff --git a/src/test/java/javax/usb/tck/SignatureTest.java b/src/test/java/javax/usb/tck/SignatureTest.java deleted file mode 100755 index 67bd718..0000000 --- a/src/test/java/javax/usb/tck/SignatureTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -import javax.usb.tck.sigtest.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -import java.io.*; -import junit.framework.*; - -/** - * This is the API signature test for the entire javax.usb.* package. - * This test verifies the existence of all expected public classes and - * interfaces. In those public classes and interfaces it verifies the - * existence, correct modifiers, arguments, and throws clauses of - * public constructors and methods. It also verifies the existence and - * correct modifiers of public fields. - * - * @author Bob Rossi - */ -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class SignatureTest extends TestCase -{ - /** - * Test the signatures of all the classes and methods for compliance - * with the Javax.usb specification. - */ - public void testSignatures() throws IOException - { - String javaxusbtck_home = - System.getProperty("javaxusbtck_home", System.getProperty("user.dir")); - File dir = new File(javaxusbtck_home, "src/test/resources"); - File file = new File(dir, "javax.usb-1.0.sig"); - String result = ProjectDesc.compareProjectFile(file); - - Assert.assertNull(result, result); - } -} \ No newline at end of file diff --git a/src/test/java/javax/usb/tck/TransmitBuffer.java b/src/test/java/javax/usb/tck/TransmitBuffer.java deleted file mode 100755 index 93bfe44..0000000 --- a/src/test/java/javax/usb/tck/TransmitBuffer.java +++ /dev/null @@ -1,240 +0,0 @@ -package javax.usb.tck; - -/* - * Copyright (c) IBM Corporation, 2004 - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License. - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - * - */ - - -/** - * This is the TransmitBuffer class to create a OUT transmitt buffer based on - * parameters supply to the constructor. - * It will create an expected buffer to be received on an IN buffer also - * based on the parameters supplied to the constructor. - * @author Thanh Ngo - */ - -@SuppressWarnings("all") -public class TransmitBuffer extends Object -{ - - /** - * Constructor. - * @param ucTransformType The Data manipilation: - * 1 - Pass through - * 2 - Invert every bit starting with the second bit - * 3 - Invert every other bit (invert odd bits assuming bit numbering begins at 0) - * 4 - Drop every third byte (ex. OUT - b1, b2, b3, b4, b5, b6 IN - b1, b2, b4, b5) - * - * @param uilRPLength The length of the data byte in - * @exception IllegalArgumentException If the offset, length or data is invalid. - */ - protected TransmitBuffer(byte ucTransformType, int uilRPLength) - { - //System.out.println("type: " + ucTransformType + " length: " + uilRPLength); - if ( 0 > ucTransformType ) - throw new IllegalArgumentException("Type cannot be negative"); - if ( 0 == ucTransformType ) - throw new IllegalArgumentException("Type cannot be 0"); - if ( 5 < ucTransformType ) - throw new IllegalArgumentException("Valid value are 1 to 4"); - if ( 0 > uilRPLength ) - throw new IllegalArgumentException("Length cannot be negative"); - transformType = ucTransformType; - rpLength = uilRPLength; - outBuffer = new byte[rpLength]; - byte fill = 0; - for ( int i = 0; i < rpLength; i++ ) - outBuffer[i] = fill++; - outBuffer[0] = (byte)transformType; - outBuffer[1] = (byte)(rpLength / 256); - outBuffer[2] = (byte)(rpLength % 256); - outBuffer[3] = sequenceNumber; - int pos = 7; - while ( pos < rpLength ) - { - outBuffer[pos] = sequenceNumber; - pos += 8; - } - outBuffer[rpLength-1] = sequenceNumber; - if ( transformType_passthru == ucTransformType ) - { - inBuffer = new byte[rpLength]; - System.arraycopy(outBuffer, 0, inBuffer,0, inBuffer.length); - } - else if ( transformType_invert_every_bit == ucTransformType ) - { - inBuffer = new byte[rpLength]; - for ( int i = 0; i < inBuffer.length; i++ ) - inBuffer[i] = (byte)(outBuffer[i] ^ 0xff); - } - else if ( transformType_invert_every_other_bit == ucTransformType ) - { - inBuffer = new byte[rpLength]; - for ( int i = 0; i < inBuffer.length; i++ ) - inBuffer[i] = (byte)(outBuffer[i] ^ 0x55); - } - else if ( transformType_drop_every_third_byte == ucTransformType ) - { - int size = rpLength / 3; - size = rpLength - size; - inBuffer = new byte[size]; - int outIndex = 0; - int inIndex = 0; - while ( outIndex < rpLength ) - { - inBuffer[inIndex++] = outBuffer[outIndex++]; // 1st byte - if ( outIndex < rpLength ) - inBuffer[inIndex++] = outBuffer[outIndex++]; // 2nd byte - if ( outIndex < rpLength ) - outIndex++; // 3rd byte , skip - } - } - else - { - throw new IllegalArgumentException("Length exceed limit"); - } - mySequenceNumber = sequenceNumber; - sequenceNumber++; // next Transmitt buffer sequence - } - - //------------------------------------------------------------------------- - // Public methods - // - - /** compare the IN buffer expected to an IN buffer actually received - * @param in The Buffer to be compared with IN buffer - * @return true if the two buffers are the same, false otherwise. - */ - boolean compareBuffers(byte[] inData) - { - if ( inBuffer.length != inData.length ) - { - //System.out.println("-->length!!!"); - return false; - } - for ( int i = 0; i < inData.length; i++ ) - { - if ( inBuffer[i] != inData[i] ) - { - //System.out.println("-->False!!! i= " + i + " in: " + inBuffer[i] + " out: " + inData[i]); - return false; - } - } - return true; - } - - /** compare the OUT buffer to a buffer supplied as a parameter - * @param outData The buffer to compare with the OUT buffer - * @return true if the two buffers are the same, false otherwise - */ - protected boolean compareToOUTBuffer(byte[] outData) - { - if ( outBuffer.length != outData.length ) - return false; - for ( int i = 0; i < outData.length; i++ ) - { - if ( outBuffer[i] != outData[i] ) - { - return false; - } - } - return true; - - } - - /** compare two byte arrays supplied as a parameter. Length of byte arrays is expected to be equal. - * @param buffer1 First byte array. - * @param buffer2 Second byte array. - * @return true if the two byte arrays are the same, false otherwise - */ - protected static boolean compareTwoByteArrays(byte[] buffer1, byte[] buffer2) - { - if ( buffer1.length != buffer2.length ) - return false; - for ( int i = 0; i < buffer1.length; i++ ) - { - if ( buffer1[i] != buffer2[i] ) - { - return false; - } - } - return true; - - } - - /** Compares first "length" number of bytes of two arrays. - * The caller must ensure that the length does not exceed the - * length of either buffer1 or buffer2. - * @param buffer1 First byte array. - * @param buffer2 Second byte array. - * @param length Number of bytes to compare - * @return true if the two byte arrays are the same over the range specified, false otherwise - */ - protected static boolean compareTwoByteArraysForSpecifiedLength(byte[] buffer1, int offset1, byte[] buffer2, int offset2,int length) - { - - for ( int i = 0; i < length; i++ ) - { - if ( buffer1[i + offset1] != buffer2[i + offset2] ) - { - return false; - } - } - return true; - - } - - - - /** - * Get the IN buffer. - * @return The IN data buffer. - */ - protected byte[] getInBuffer() - { - return inBuffer; - } - - /** - * Get the OUT buffer. - * @return The OUT data buffer. - */ - protected byte[] getOutBuffer() - { - return outBuffer; - } - - /** - * Get the sequenceNumber. - * @return The sequenceNumber variable. - */ - protected int getsequenceNumber() - { - return mySequenceNumber; - } - - - - - //------------------------------------------------------------------------- - // Instance variables - // - private byte transformType; - private int rpLength; - private byte[] inBuffer = new byte[0]; - private byte[] outBuffer = new byte[0]; - private static byte sequenceNumber = 0; - private byte mySequenceNumber; - private static final byte transformType_passthru = 1; - private static final byte transformType_invert_every_bit = 2; - private static final byte transformType_invert_every_other_bit = 3; - private static final byte transformType_drop_every_third_byte = 4; - - -} diff --git a/src/test/java/javax/usb/tck/UsbInterfacePolicyTest.java b/src/test/java/javax/usb/tck/UsbInterfacePolicyTest.java deleted file mode 100755 index 8784f19..0000000 --- a/src/test/java/javax/usb/tck/UsbInterfacePolicyTest.java +++ /dev/null @@ -1,340 +0,0 @@ -package javax.usb.tck; - -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/* - * Change Activity: See below. - * - * FLAG REASON RELEASE DATE WHO DESCRIPTION - * ---- -------- -------- ------ -------- ------------------------------------ - * 0000 nnnnnnn yymmdd Initial Development - * $P1 tck.rel1 040804 raulortz Support for UsbDisconnectedException - * $P2 tck.rel1 041222 raulortz Redesign TCK to create base and optional - * tests. Separate setConfig, setInterface - * and isochronous transfers as optionals. - */ - -import junit.framework.TestCase; -import java.util.*; - -import javax.usb.*; - -import org.junit.runner.RunWith; - -import org.usb4java.test.TCKRunner; - -/** - * Usb Interface Policy Test - *

- * Goal: This test will use a new implementation of the UsbInterfacePolicy - * Interface to test the that the UsbInterfacePolicy is being used correctly. - * - * @author Dale Heeks - */ -@SuppressWarnings("all") -@RunWith(TCKRunner.class) -public class UsbInterfacePolicyTest extends TestCase -{ - - public UsbInterfacePolicyTest(String name) - { - - super(name); - } - - protected void setUp() throws Exception { - usbDevice = programmableDevice.getProgrammableDevice(); - assertTrue( "Find Programmable board Failed! Got a null instance", usbDevice != null ); - assertTrue("The usbDevice is not confuigured", usbDevice.isConfigured()); - usbConfiguration = usbDevice.getUsbConfiguration((byte)1); - policy1 = new InterfacePolicyImp(); - } - - protected void tearDown() throws Exception { - - } - - - /*ForceClaim policy test cases */ - /** - * Test forceClaim policy with a false return - *

- * This test case will set the ForceClaim policy - * to false and then call claim to ensure that the - * ForceClaim policy method is invoked inside - * the UsbInterfacePolicyImp class - *

- * NOTE: This will not check if the claim isn't forced - * because some implemetations - * will not be able to do a force claim and some will, - * - */ - - public void testIfaceForceClaimFalse() - { - - - policy1.setForceClaimPolicy(false); - - assertFalse("Force Claim tag isn't reset, this is probably a TCK defect", - policy1.getForceClaimTag() ); - - assertTrue("Can't claim Interface, this is probably a defect with your implementation", - claimIface(usbConfiguration.getUsbInterface((byte)0), policy1)); - // @P2D4 - //reset the claim tag - policy1.setForceClaimTag(false); - - releaseIface(usbConfiguration.getUsbInterface((byte)0), null); - - } - - /** - * Test forceClaim policy with a true return - *

- * This test case will set the ForceClaim policy - * to true and then call claim to ensure that the - * ForceClaim policy method is invoked inside - * the UsbInterfacePolicyImp class - *

- * NOTE: This will not check if the claim is forced - * because some implemetations - * will not be able to do a force claim and some will. - * - */ - public void testIfaceForceClaimTrue() - { - - policy1.setForceClaimPolicy(true); - - assertFalse("Force Claim tag isn't reset, this is probably a TCK defect", - policy1.getForceClaimTag() ); - - assertTrue("Can't claim Interface, this is probably a defect with your implementation", - claimIface(usbConfiguration.getUsbInterface((byte)0), policy1)); - // @P2D4 - //Reset the force claim tag - policy1.setForceClaimTag(false); - - releaseIface(usbConfiguration.getUsbInterface((byte)0), null); - - } - - - //This method will take an interface and policy and call the appropriate - //claim method, this method should only be used within this test - private boolean claimIface(UsbInterface iface, - UsbInterfacePolicy ifacePolicy) - { - try - { - if ( ifacePolicy == null ) - iface.claim(); - else - iface.claim(ifacePolicy); - } catch ( UsbClaimException uce ) - { - return false; - } catch ( UsbNotActiveException unae ) - { - fail("UsbNotActiveException: " + unae); - } catch ( UsbException ue ) - { - fail("UsbException: " + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - return true; - } - - - //This method takes a interface and key and make the appropriate - //interface method call - private int releaseIface(UsbInterface iface, - Object key) - { - try - { - iface.release(); - } catch ( UsbClaimException uce ) - { - return notClaimed; - } catch ( UsbNotActiveException unae ) - { - fail("UsbNotActiveException: " + unae); - } catch ( UsbException ue ) - { - fail("UsbException: " + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - return released; - } - - //Method that takes an interface and returns it's first pipe - private UsbPipe getUsbPipe(UsbInterface iface) - { - List endpoints = iface.getUsbEndpoints(); - UsbEndpoint e1 = (UsbEndpoint)endpoints.get(0); - return e1.getUsbPipe(); - } - - //Method that will call the appropriate open method given - //a pipe and a key - private int openPipe(UsbPipe pipe, Object key) - { - try - { - pipe.open(); - } catch ( UsbNotActiveException unae ) - { - fail("UsbNotActiveException: " + unae); - } catch ( UsbNotClaimedException unae ) - { - fail("UsbNotActiveException: " + unae); - } catch ( UsbException ue ) - { - fail("UsbException: " + ue); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - - return opened; - } - - //method to close a pipe, this is for test case clean up - private boolean closePipe(UsbPipe pipe) - { - try - { - pipe.close(); - } catch ( UsbException ue ) - { - fail("UsbException: " + ue); - } catch ( UsbNotActiveException unae ) - { - fail("UsbNotOpenedException: " + unae); - } catch ( UsbDisconnectedException uDE ) // @P1C - { // @P1A - fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A - } // @P1A - return true; - } - - - private FindProgrammableDevice programmableDevice = FindProgrammableDevice.getInstance(); - private InterfacePolicyImp policy1 = null; - private UsbConfiguration usbConfiguration = null; - private UsbDevice usbDevice = null; - private UsbInterface iface = null; - private UsbEndpoint Endpoint; - private static final boolean debug = true; - private static final int released = 1111; - private static final int opened = 2222; - private static final int notClaimed = 4444; - - - /* - ************************************************************************* - ********************Test Interface Policy Implemetation class************ - *************************************************************************/ - /** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - - /** - * Name of class -- Usb Interface Policy test implementation - *

- * This class is an implementation of the UsbInterfacePolicy, this - * should only be used for the Javax.usb tck. - * - * @author Dale Heeks - */ - - private class InterfacePolicyImp implements UsbInterfacePolicy - { - - /**Constuctor - * - *

- * Default constructor, sets everything in this policy to true, - * which is also the same as the default policy - * - * - */ - public InterfacePolicyImp () - { - forceClaimPolicy = true; - forceClaimTag = false; - } - - /**Method that should be called from a claim using - * the non default interface policy - * - *@param arg0 The current UsbInterface that is being claimed - * - *@return boolean Whether to allow an interface to attempt - *a force claim - */ - public boolean forceClaim(UsbInterface arg0) - { - forceClaimTag = true; - return forceClaimPolicy; - } - - /**Allows a user to dynamically set the force claim policy - * - * @param forceClaimIn The new force claim policy - */ - public void setForceClaimPolicy(boolean forceClaimIn) - { - forceClaimPolicy = forceClaimIn; - } - - /**Allows a user to dynamically set the force claim tag - * - *

- * The force claim tag checks to see if the force claim policy has been called - * - * @param forceClaimTagIn The new force claim tag - */ - public void setForceClaimTag(boolean forceClaimTagIn) - { - forceClaimTag = forceClaimTagIn; - } - - /**Allows a user to check the force claim tag - * - *

- * The force claim tag checks to see if the force claim policy has been called - * - * @return boolean The force claim tag - */ - public boolean getForceClaimTag() - { - return forceClaimTag; - } - - private boolean forceClaimPolicy; - private boolean forceClaimTag; - - - - } - /*************************************************************************/ -} diff --git a/src/test/java/javax/usb/tck/VerifyIrpMethods.java b/src/test/java/javax/usb/tck/VerifyIrpMethods.java deleted file mode 100755 index 48ca3f0..0000000 --- a/src/test/java/javax/usb/tck/VerifyIrpMethods.java +++ /dev/null @@ -1,413 +0,0 @@ -/** - * Copyright (c) 2004, International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ -package javax.usb.tck; - -import junit.framework.Assert; - -import java.util.*; - -import javax.usb.*; -import javax.usb.event.*; - -/** - * VerifyIrpMethods - *

- * Helper functions to verify IRPs and Events - * - * @author Leslie Blair - */ -@SuppressWarnings("all") -public class VerifyIrpMethods -{ - private static void verifyDataEventValuesAndUsbIrpValuesWithExpectedValues(UsbIrp usbIrpSubmitted, - EventObject usbEvent, - byte[] expectedData) - { - printDebug("Entering verifyDataEventValuesAndUsbIrpValuesWithExpectedValues"); - - UsbIrp usbEventIrp = null; - byte[] usbEventData = null; - - //Verify usbDataEvent is not null - Assert.assertNotNull("Event must not be null.", usbEvent); - - //Get the IRP from the Data event - if ( UsbDeviceDataEvent.class == usbEvent.getClass() ) - { - usbEventIrp = (((UsbDeviceDataEvent) usbEvent).getUsbControlIrp()); - usbEventData = (((UsbDeviceDataEvent) usbEvent).getData()); - Assert.assertNotNull("UsbDevice from Device event is unexpectedly null.",((UsbDeviceEvent)usbEvent).getUsbDevice()); - - } - else if ( UsbPipeDataEvent.class == usbEvent.getClass() ) - { - usbEventIrp = (((UsbPipeDataEvent) usbEvent).getUsbIrp()); - usbEventData = (((UsbPipeDataEvent) usbEvent).getData()); - } - - if ( usbIrpSubmitted != null ) - { - - /* - * Verify submitted IRP - */ - Assert.assertTrue("isComplete() not true.",usbIrpSubmitted.isComplete()); - - //Verify ActualLength as expected - Assert.assertEquals("ActualLength not expected value.", - expectedData.length, usbIrpSubmitted.getActualLength()); - - //Verify data in IRP - Assert.assertTrue("IRP data not as expected", TransmitBuffer.compareTwoByteArraysForSpecifiedLength( - usbIrpSubmitted.getData(),usbIrpSubmitted.getOffset(), - expectedData, 0, expectedData.length)); - - //Verify no exception - Assert.assertFalse("isUsbException() not false.", usbIrpSubmitted.isUsbException()); - Assert.assertNull("getUsbException() not null.", usbIrpSubmitted.getUsbException()); - - /* - * Verify data event IRP and data - */ - //Verify the IRP returned in data event is the same as IRP submitted - Assert.assertSame("The submitted Irp and the usbIrp returned " + - "in event are not the same object", - usbIrpSubmitted, usbEventIrp); - } - else - { - printDebug("No IRP submitted for verification. Test must by sync byte []."); - } - - //Verify data in the IRP from data event (This is really covered in assert that submitted IRP and event IRP are the same.) - Assert.assertTrue("Data from device data event IRP not expected data.", - TransmitBuffer.compareTwoByteArraysForSpecifiedLength(usbEventIrp.getData(), - usbEventIrp.getOffset(), - expectedData, 0, - expectedData.length)); - - //Note that the getData() from the DeviceDataEvent returns only the actual data transferred as opposed to the - //getData() for the DeviceDataEvent IRP which contains the entire byte[] originally set in the IRP. - //Therefore, the usbDeviceDataEvent.getData() should be an exact match for the expectedData. - Assert.assertTrue("Data from UsbDeviceDataEvent not expected data.", - TransmitBuffer.compareTwoByteArraysForSpecifiedLength(usbEventData, 0, - expectedData, 0, expectedData.length)); - - printDebug("Leaving verifyDataEventValuesAndUsbIrpValuesWithExpectedValues"); - }; - - - private static void verifyErrorEventValuesAndUsbIrpValuesWithExpectedValues(UsbIrp usbIrpSubmitted, - EventObject usbEvent, - Exception expectedException) - { - printDebug("Entering verifyErrorEventValuesAndUsbIrpValuesWithExpectedValues"); - - //Verify usbEvent is not null - Assert.assertNotNull("Event must not be null.", usbEvent); - - // Verify submitted IRP - Assert.assertTrue("isComplete() not true.",usbIrpSubmitted.isComplete()); - - //Verify exception - Assert.assertTrue("isUsbException() not true.", usbIrpSubmitted.isUsbException()); - Assert.assertNotNull("getUsbException() is null.", usbIrpSubmitted.getUsbException()); - - //Verify expected exception - if ( UsbDeviceErrorEvent.class == usbEvent.getClass() ) - { - if ( (((UsbDeviceErrorEvent)usbEvent).getUsbException()).getClass() != expectedException.getClass() ) - { - Assert.fail("\nExpected exception class is " + expectedException.getClass().toString() + - "\nReceived exception class is " + ((UsbDeviceErrorEvent)usbEvent).getUsbException().getClass().toString() ); - } - Assert.assertNotNull("UsbDevice from Device event is unexpectedly null.",((UsbDeviceEvent)usbEvent).getUsbDevice()); - } - else if ( UsbPipeErrorEvent.class == usbEvent.getClass() ) - { - if ( (((UsbPipeErrorEvent)usbEvent).getUsbException()).getClass() != expectedException.getClass() ) - { - Assert.fail("\nExpected exception class is " + expectedException.getClass().toString() + - "\nReceived exception class is " + ((UsbPipeErrorEvent)usbEvent).getUsbException().getClass().toString() ); - } - } - -/*Possible TODO -- if getUsb(Control)Irp method is added to DeviceErrorEvent and PipeErrorEvent classes - * then the following code needs to be added to this method. At that point you may consider combining this method with the - * "verifyDataEventValuesAndUsbIrpValuesWithExpectedValues" method because there will be more common code. - * - - UsbIrp usbEventIrp = null; - byte[] usbEventData = null; - //Get the IRP from the event - if ( UsbDeviceErrorEvent.class == usbEvent.getClass()) - { - usbEventIrp = (((UsbDeviceErrorEvent) usbEvent).getUsbControlIrp()); - usbEventData = (((UsbDeviceErrorEvent) usbEvent).getData()); - } - else if (UsbPipeErrorEvent.class == usbEvent.getClass()) - { - usbEventIrp = (((UsbPipeErrorEvent) usbEvent).getUsbIrp()); - usbEventData = (((UsbPipeErrorEvent) usbEvent).getData()); - } - - - - //Verify the IRP returned in event is the same as IRP submitted - Assert.assertSame("The submitted usbControlIrp and the usbControlIrp returned " + - "in event are not the same object", - usbIrpSubmitted, usbEventIrp); - //Assert.assertTrue("The submitted usbControlIrp and the usbControlIrp returned " + - // "in UsbDeviceDataEvent are not equal", - // usbIrpSubmitted.equals(usbEventIrp)); - -*/ - printDebug("Leaving verifyErrorEventValuesAndUsbIrpValuesWithExpectedValues"); - }; - - private static void validateExpectations(byte [] expectedData, Exception expectedException) throws IllegalArgumentException - { - printDebug("Entering validateExpectations"); - - /* - * The verification to be performed is based on which value, expectedData or expectedException, is set. - * One, and only one, of these values must be set. - */ - if ( (expectedData != null) && (expectedException != null) ) - { - throw new IllegalArgumentException("Both expectedData and expectedException are non-null. If a data event " + - "is expected, expectedData should be set. If an error event is expected, expectedError should be set. " + - "Both values should not be set"); - } - else if ( (expectedData == null) && (expectedException == null) ) - { - throw new IllegalArgumentException("Both expectedData and expectedException are null. If a data event " + - "is expected, expectedData should be set. If an error event is expected, expectedError should be set. " + - "One of the values must be set."); - } - - printDebug("Leaving validateExpectations"); - } - - /** - * verifyUsbIrpAfterEvent(..) verifies a UsbIrp against expected values - * @param usbIrpSubmitted IRP to verify - * @param usbEvent UsbDevice(or Pipe) Data or Error Event - * @param expectedData expected byte[] in IRP (must be null if expected exception not null) - * @param expectedActualLength actual length of data transmitted - * @param expectedException expected exception (must be null if expected data is not null) - * @param expectedAcceptShortPacket expected value of acceptShortPacket - * @param verifyAcceptShortPacket Specifies whether to verify acceptShortPacket - * @param expectedOffset expected offset for byte [] in IRP - * @param expectedLength expected length for byte [] in IRP - * @param expectedbmRequestType expected bmRequestType in control IRP - * @param expectedbRequest expected bRequest in control IRP - * @param expectedwValue expected wValue in control IRP - * @param expectedwIndex expected wIndex in control IRP - */ - protected static void verifyUsbControlIrpAfterEvent(UsbControlIrp usbControlIrpSubmitted, - EventObject usbEvent, - byte[] expectedData, - int expectedActualLength, - Exception expectedException, - boolean expectedAcceptShortPacket, - boolean verifyAcceptShortPacket, - int expectedOffset, - int expectedLength, - byte expectedbmRequestType, - byte expectedbRequest, - short expectedwValue, - short expectedwIndex) - { - printDebug("Entering verifyUsbControlIrpAfterEvent"); - - //Verify UsbControlIrp values - Assert.assertEquals("bmRequestType not expected value.", - expectedbmRequestType, usbControlIrpSubmitted.bmRequestType()); - Assert.assertEquals("bRequest not expected value.", - expectedbRequest, usbControlIrpSubmitted.bRequest()); - Assert.assertEquals("wValue not expected value.", - expectedwValue, usbControlIrpSubmitted.wValue()); - Assert.assertEquals("wIndex not expected value.", - expectedwIndex, usbControlIrpSubmitted.wIndex()); - - //verify UsbIrp values - VerifyIrpMethods.verifyUsbIrpAfterEvent(usbControlIrpSubmitted, - usbEvent, - expectedData, - expectedActualLength, - expectedException, - expectedAcceptShortPacket, - verifyAcceptShortPacket, - expectedOffset, - expectedLength); - - printDebug("Leaving verifyUsbControlIrpAfterEvent"); - }; - - /** - * verifyUsbIrpAfterEvent(..) verifies a UsbIrp against expected values - * @param usbIrpSubmitted IRP to verify - * @param usbEvent UsbDevice(or Pipe) Data or Error Event - * @param expectedData expected byte[] in IRP (must be null if expected exception not null) - * @param expectedActualLength actual length of data transmitted - * @param expectedException expected exception (must be null if expected data is not null) - * @param expectedAcceptShortPacket expected value of acceptShortPacket - * @param verifyAcceptShortPacket Specifies whether to verify acceptShortPacket - * @param expectedOffset expected offset for byte [] in IRP - * @param expectedLength expected length for byte [] in IRP - */ - protected static void verifyUsbIrpAfterEvent(UsbIrp usbIrpSubmitted, - EventObject usbEvent, - byte[] expectedData, - int expectedActualLength, - Exception expectedException, - boolean expectedAcceptShortPacket, - boolean verifyAcceptShortPacket, - int expectedOffset, - int expectedLength) - { - printDebug("Entering verifyUsbIrpAfterEvent"); - - try - { - validateExpectations(expectedData, expectedException); - } - catch ( IllegalArgumentException iaE ) - { - Assert.fail("Illegal Arguments supplied to verifyUsbIrpAfterEvent(...) method"); - } - - /* - * Verify values in UsbIrp that should be unchanged after submission. - * This verification is valid for a data event or error event - * - * Verify AcceptShortPacket, Offset, and Length not changed - */ - if ( usbIrpSubmitted != null ) - { - Assert.assertEquals("Offset changed after IRP submitted.", expectedOffset, usbIrpSubmitted.getOffset()); - Assert.assertEquals("Length changed after IRP submitted.", expectedLength, usbIrpSubmitted.getLength()); - - - - if ( verifyAcceptShortPacket ) - { - Assert.assertEquals("AcceptShortPacket changed after IRP submitted.", - expectedAcceptShortPacket, usbIrpSubmitted.getAcceptShortPacket()); - } - } - else - { - printDebug("No IRP submitted for verification. Test must by sync byte []."); - } - - - /* - * Data event verification - */ - if ( expectedData != null ) - { - //Verify expected values in UsbIrp after data event - VerifyIrpMethods.verifyDataEventValuesAndUsbIrpValuesWithExpectedValues(usbIrpSubmitted, - usbEvent, - expectedData); - } - /* - * Error event verification - */ - else - { - //Verify expected values in UsbIrp after error event - VerifyIrpMethods.verifyErrorEventValuesAndUsbIrpValuesWithExpectedValues(usbIrpSubmitted, - usbEvent, - expectedException); - } - printDebug("Leaving verifyUsbIrpAfterEvent"); - }; - - - /** - * verifyRequestTest(..) verifies a UsbIrp against expected values - * @param usbIrpSubmitted IRP to verify - * @param expectedbmRequestType expected bmRequestType in control IRP - * @param expectedbRequest expected bRequest in control IRP - * @param expectedwValue expected wValue in control IRP - * @param expectedwIndex expected wIndex in control IRP - */ - protected static void verifyRequestTest(UsbControlIrp usbControlIrpSubmitted, - byte expectedbmRequestType, - byte expectedbRequest, - short expectedwValue, - short expectedwIndex) - { - printDebug("Entering verifyRequestTest"); - - //Verify UsbControlIrp values - Assert.assertEquals("bmRequestType not expected value.", - expectedbmRequestType, usbControlIrpSubmitted.bmRequestType()); - Assert.assertEquals("bRequest not expected value.", - expectedbRequest, usbControlIrpSubmitted.bRequest()); - Assert.assertEquals("wValue not expected value.", - expectedwValue, usbControlIrpSubmitted.wValue()); - Assert.assertEquals("wIndex not expected value.", - expectedwIndex, usbControlIrpSubmitted.wIndex()); - - } - - /** - * verifyRequestTestData(..) verifies a UsbIrp against expected values - * @param usbIrpSubmitted IRP to verify - * @param expectedbmRequestType expected bmRequestType in control IRP - * @param expectedbRequest expected bRequest in control IRP - * @param expectedwValue expected wValue in control IRP - * @param expectedwIndex expected wIndex in control IRP - * @param expectedLength expected length for byte [] in IRP - * @param expectedData expected byte[] in IRP (must be null if expected exception not null) - */ - protected static void verifyRequestTestData(UsbControlIrp usbControlIrpSubmitted, - byte expectedbmRequestType, - byte expectedbRequest, - short expectedwValue, - short expectedwIndex, - int expectedLength) - { - byte[] buffer; - printDebug("Entering verifyRequestTestData"); - - //Verify UsbControlIrp values - Assert.assertEquals("bmRequestType not expected value.", - expectedbmRequestType, usbControlIrpSubmitted.bmRequestType()); - Assert.assertEquals("bRequest not expected value.", - expectedbRequest, usbControlIrpSubmitted.bRequest()); - Assert.assertEquals("wValue not expected value.", - expectedwValue, usbControlIrpSubmitted.wValue()); - Assert.assertEquals("wIndex not expected value.", - expectedwIndex, usbControlIrpSubmitted.wIndex()); - Assert.assertEquals("Length changed after IRP submitted.", - expectedLength, usbControlIrpSubmitted.getLength()); - - } - - - /** - * printDebug method will print the specified string if "debug" is true. - * Useful function for debugging - * @param infoString - */ - protected static void printDebug(String infoString) - { - if ( debug ) - { - System.out.println(infoString); - } - } - private static boolean debug = false; - //private static boolean debug = true; -} diff --git a/src/test/java/javax/usb/tck/sigtest/ClassDesc.java b/src/test/java/javax/usb/tck/sigtest/ClassDesc.java deleted file mode 100755 index 84db706..0000000 --- a/src/test/java/javax/usb/tck/sigtest/ClassDesc.java +++ /dev/null @@ -1,319 +0,0 @@ -package javax.usb.tck.sigtest; - -/** - * Copyright (c) 2003,2004 International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -import java.io.*; -import java.lang.reflect.*; -import java.util.*; - -/** - * This class stores all the information needed to compare the signature - * of one class to another. - * - * @author Matthew J. Duftler - */ -@SuppressWarnings("all") -public class ClassDesc extends MemberDesc -{ - private String superClassName = null; - private List interfaceNames = new Vector(); - private List constructorDescs = new Vector(); - private List methodDescs = new Vector(); - - public ClassDesc(String name, int modifiers) - { - super(name, modifiers); - } - - public void setSuperClassName(String superClassName) - { - this.superClassName = superClassName; - } - - public String getSuperClassName() - { - return superClassName; - } - - public void setInterfaceNames(List interfaceNames) - { - this.interfaceNames = interfaceNames; - } - - public List getInterfaceNames() - { - return interfaceNames; - } - - public void addConstructorDesc(MethodDesc constructorDesc) - { - constructorDescs.add(constructorDesc); - } - - public void setConstructorDescs(List constructorDescs) - { - this.constructorDescs = constructorDescs; - } - - public List getConstructorDescs() - { - return constructorDescs; - } - - public void addMethodDesc(MethodDesc methodDesc) - { - methodDescs.add(methodDesc); - } - - public void setMethodDescs(List methodDescs) - { - this.methodDescs = methodDescs; - } - - public List getMethodDescs() - { - return methodDescs; - } - - public static ClassDesc parseClassDesc(BufferedReader classDescReader) - throws IOException - { - String classDescStr = classDescReader.readLine(); - List tokens = SigTestUtils.stringToList(classDescStr, " "); - int size = tokens.size(); - int i = 0; - int modifiers = Integer.parseInt((String)tokens.get(i++)); - String className = (String)tokens.get(i++); - String superClassName = null; - String interfaceNamesListStr = null; - List interfaceNames = null; - - while (size > i) - { - String tempToken = (String)tokens.get(i++); - - if (tempToken.equals("extends")) - { - superClassName = (String)tokens.get(i++); - } - else if (tempToken.equals("implements")) - { - interfaceNamesListStr = (String)tokens.get(i++); - } - } - - if (interfaceNamesListStr != null) - { - interfaceNames = SigTestUtils.stringToList(interfaceNamesListStr, ","); - } - - ClassDesc classDesc = new ClassDesc(className, modifiers); - - classDesc.setSuperClassName(superClassName); - - if (interfaceNames != null) - { - classDesc.setInterfaceNames(interfaceNames); - } - - classDescReader.readLine(); - - String tempLine = null; - - while (!(tempLine = classDescReader.readLine()).equals("}")) - { - MethodDesc methodDesc = MethodDesc.parseMethodDesc(tempLine); - - if (methodDesc.getReturnTypeName() == null) - { - classDesc.addConstructorDesc(methodDesc); - } - else - { - classDesc.addMethodDesc(methodDesc); - } - } - - return classDesc; - } - - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - else if (obj == this) - { - return true; - } - else - { - ClassDesc that = (ClassDesc)obj; - - if (!SigTestUtils.objectsEqual(name, that.name)) - { - return false; - } - else if (modifiers != that.modifiers) - { - return false; - } - else if (!SigTestUtils.objectsEqual(superClassName, that.superClassName)) - { - return false; - } - else if (!SigTestUtils.collectionsMatch(interfaceNames, - that.interfaceNames)) - { - return false; - } - else if (!SigTestUtils.collectionsMatch(constructorDescs, - that.constructorDescs)) - { - return false; - } - else if (!SigTestUtils.collectionsMatch(methodDescs, that.methodDescs)) - { - return false; - } - else - { - return true; - } - } - } - - public String compare(ClassDesc that) - { - StringBuffer strBuf = new StringBuffer(); - - if (modifiers != that.modifiers) - { - strBuf.append("On class '" + name + "', the modifiers are '" + - Modifier.toString(that.modifiers) + - "', when they should be '" + - Modifier.toString(modifiers) + "'."); - } - - if (!SigTestUtils.objectsEqual(superClassName, that.superClassName)) - { - strBuf.append("\nClass '" + name + "' " + - (that.superClassName != null - ? "extends '" + that.superClassName + "'" - : "does not extend any class") + - ", when it should" + - (superClassName != null - ? " extend '" + superClassName + "'." - : "n't extend any class.")); - } - - if (!SigTestUtils.collectionsMatch(interfaceNames, that.interfaceNames)) - { - strBuf.append("\nClass '" + name + "' " + - (that.interfaceNames.size() > 0 - ? "implements '" + that.interfaceNames + "'" - : "does not implement any interfaces") + - ", when it should" + - (interfaceNames.size() > 0 - ? " implement '" + interfaceNames + "'." - : "n't implement any interfaces.")); - } - - List referenceExtras = new Vector(); - List candidateExtras = new Vector(); - - SigTestUtils.findExtras(constructorDescs, - that.constructorDescs, - referenceExtras, - candidateExtras); - - if (referenceExtras.size() > 0 || candidateExtras.size() > 0) - { - strBuf.append("\nClass '" + name + "'" + - (candidateExtras.size() > 0 - ? " has extraneous constructor" + - (candidateExtras.size() > 1 ? "s" : "") + " " + - SigTestUtils.getExpandedMethodList(candidateExtras) - : "") + - (referenceExtras.size() > 0 - ? (candidateExtras.size() > 0 ? " and" : "") + - " is missing constructor" + - (referenceExtras.size() > 1 ? "s" : "") + " " + - SigTestUtils.getExpandedMethodList(referenceExtras) - : "") + "."); - } - - referenceExtras = new Vector(); - candidateExtras = new Vector(); - - SigTestUtils.findExtras(methodDescs, - that.methodDescs, - referenceExtras, - candidateExtras); - - if (referenceExtras.size() > 0 || candidateExtras.size() > 0) - { - strBuf.append("\nClass '" + name + "'" + - (candidateExtras.size() > 0 - ? " has extraneous method" + - (candidateExtras.size() > 1 ? "s" : "") + " " + - SigTestUtils.getExpandedMethodList(candidateExtras) - : "") + - (referenceExtras.size() > 0 - ? (candidateExtras.size() > 0 ? " and" : "") + - " is missing method" + - (referenceExtras.size() > 1 ? "s" : "") + " " + - SigTestUtils.getExpandedMethodList(referenceExtras) - : "") + "."); - } - - return (strBuf.length() > 0) - ? strBuf.toString() - : null; - } - - public String toString() - { - StringBuffer strBuf = new StringBuffer(); - - strBuf.append(modifiers + " " + name + - (superClassName != null - ? " extends " + superClassName - : "") + - (interfaceNames.size() > 0 - ? " implements " + SigTestUtils.listToString(interfaceNames) - : "") + - "\n{\n"); - - Iterator constrIterator = constructorDescs.iterator(); - - while (constrIterator.hasNext()) - { - strBuf.append(" " + constrIterator.next() + "\n"); - } - - Iterator methodIterator = methodDescs.iterator(); - - while (methodIterator.hasNext()) - { - strBuf.append(" " + methodIterator.next() + "\n"); - } - - strBuf.append("}"); - - return strBuf.toString(); - } - - public int hashCode() - { - return toString().hashCode(); - } -} \ No newline at end of file diff --git a/src/test/java/javax/usb/tck/sigtest/MemberDesc.java b/src/test/java/javax/usb/tck/sigtest/MemberDesc.java deleted file mode 100755 index 0736943..0000000 --- a/src/test/java/javax/usb/tck/sigtest/MemberDesc.java +++ /dev/null @@ -1,49 +0,0 @@ -package javax.usb.tck.sigtest; - -/** - * Copyright (c) 2003,2004 International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -/** - * This class stores the name and modifiers for a given member (class or - * method). - * - * @author Matthew J. Duftler - */ -@SuppressWarnings("all") -public class MemberDesc -{ - protected String name = null; - protected int modifiers = 0; - - public MemberDesc(String name, int modifiers) - { - this.name = name; - this.modifiers = modifiers; - } - - public void setName(String name) - { - this.name = name; - } - - public String getName() - { - return name; - } - - public void setModifiers(int modifiers) - { - this.modifiers = modifiers; - } - - public int getModifiers() - { - return modifiers; - } -} \ No newline at end of file diff --git a/src/test/java/javax/usb/tck/sigtest/MethodDesc.java b/src/test/java/javax/usb/tck/sigtest/MethodDesc.java deleted file mode 100755 index 534da70..0000000 --- a/src/test/java/javax/usb/tck/sigtest/MethodDesc.java +++ /dev/null @@ -1,180 +0,0 @@ -package javax.usb.tck.sigtest; - -/** - * Copyright (c) 2003,2004 International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -import java.lang.reflect.*; -import java.util.*; - -/** - * This class stores all the information needed to identify a method - * signature. - * - * @author Matthew J. Duftler - */ -@SuppressWarnings("all") -public class MethodDesc extends MemberDesc -{ - private String returnTypeName = null; - private List paramTypeNames = new Vector(); - private List exceptionTypeNames = new Vector(); - - public MethodDesc(String name, - int modifiers, - String returnTypeName, - List paramTypeNames, - List exceptionTypeNames) - { - super(name, modifiers); - - this.returnTypeName = returnTypeName; - this.paramTypeNames = paramTypeNames; - this.exceptionTypeNames = exceptionTypeNames; - } - - public void setReturnTypeName(String returnTypeName) - { - this.returnTypeName = returnTypeName; - } - - public String getReturnTypeName() - { - return returnTypeName; - } - - public void setParameterTypeNames(List paramTypeNames) - { - this.paramTypeNames = paramTypeNames; - } - - public List getParameterTypeNames() - { - return paramTypeNames; - } - - public void setExceptionTypeNames(List exceptionTypeNames) - { - this.exceptionTypeNames = exceptionTypeNames; - } - - public List getExceptionTypeNames() - { - return exceptionTypeNames; - } - - public static MethodDesc parseMethodDesc(String methodDescStr) - { - String[] tokens = SigTestUtils.tokenize(methodDescStr, " "); - - int modifiers = Integer.parseInt(tokens[0]); - String returnTypeName = null; - int offset = 0; - - if (!tokens[2].startsWith("(")) - { - returnTypeName = tokens[1]; - offset = 1; - } - - String methodName = tokens[1 + offset]; - String parameterTypeNamesStr = tokens[2 + offset]; - - parameterTypeNamesStr = - parameterTypeNamesStr.substring(1, parameterTypeNamesStr.length() - 1); - - List parameterTypeNames = - SigTestUtils.stringToList(parameterTypeNamesStr, ","); - List exceptionTypeNames; - - if (tokens.length > (3 + offset)) - { - String exceptionTypeNamesStr = tokens[4 + offset]; - - exceptionTypeNames = - SigTestUtils.stringToList(exceptionTypeNamesStr, ","); - } - else - { - exceptionTypeNames = new Vector(); - } - - MethodDesc methodDesc = - new MethodDesc(methodName, - modifiers, - returnTypeName, - parameterTypeNames, - exceptionTypeNames); - - return methodDesc; - } - - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - else if (obj == this) - { - return true; - } - else - { - MethodDesc that = (MethodDesc)obj; - - if (!SigTestUtils.objectsEqual(name, that.name)) - { - return false; - } - else if (modifiers != that.modifiers) - { - return false; - } - else if (!SigTestUtils.objectsEqual(returnTypeName, that.returnTypeName)) - { - return false; - } - else if (!SigTestUtils.objectsEqual(paramTypeNames, that.paramTypeNames)) - { - return false; - } - else if (!SigTestUtils.collectionsMatch(exceptionTypeNames, - that.exceptionTypeNames)) - { - return false; - } - else - { - return true; - } - } - } - - public int hashCode() - { - return toString().hashCode(); - } - - public String toString(boolean expandModifiers) - { - return (expandModifiers - ? Modifier.toString(modifiers) - : modifiers + "") + " " + - (returnTypeName != null ? returnTypeName + " " : "") + - name + " (" + SigTestUtils.listToString(paramTypeNames) + ")" + - (exceptionTypeNames.size() > 0 - ? " throws " + SigTestUtils.listToString(exceptionTypeNames) - : ""); - } - - public String toString() - { - return toString(false); - } -} \ No newline at end of file diff --git a/src/test/java/javax/usb/tck/sigtest/ProjectDesc.java b/src/test/java/javax/usb/tck/sigtest/ProjectDesc.java deleted file mode 100755 index 721b2bc..0000000 --- a/src/test/java/javax/usb/tck/sigtest/ProjectDesc.java +++ /dev/null @@ -1,179 +0,0 @@ -package javax.usb.tck.sigtest; - -/** - * Copyright (c) 2003,2004 International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -import java.io.*; -import java.util.*; - -/** - * This class stores a name and a collection of class descriptions, - * to form a project. - * - * @author Matthew J. Duftler - */ -@SuppressWarnings("all") -public class ProjectDesc -{ - private String name; - private List classDescs = new Vector(); - - public ProjectDesc(String name) - { - this.name = name; - } - - public void addClassDesc(ClassDesc classDesc) - { - classDescs.add(classDesc); - } - - public ClassDesc getClassDesc(String className) - { - Iterator iterator = classDescs.iterator(); - - while (iterator.hasNext()) - { - ClassDesc classDesc = (ClassDesc)iterator.next(); - - if (SigTestUtils.objectsEqual(classDesc.getName(), className)) - { - return classDesc; - } - } - - return null; - } - - public void setClassDescs(List classDescs) - { - this.classDescs = classDescs; - } - - public List getClassDescs() - { - return classDescs; - } - - /** - * This method compares this project description to the specified one. - * - * @param that the project description to compare this one to - * - * @return a description of the differences, or null if they match perfectly - */ - public String compare(ProjectDesc that) - { - StringBuffer strBuf = new StringBuffer(); - Iterator iterator = classDescs.iterator(); - - while (iterator.hasNext()) - { - ClassDesc thisCD = (ClassDesc)iterator.next(); - ClassDesc thatCD = that.getClassDesc(thisCD.getName()); - - if (thatCD != null) - { - String result = thisCD.compare(thatCD); - - if (result != null) - { - strBuf.append("\n" + result); - } - } - } - - List referenceExtras = new Vector(); - List candidateExtras = new Vector(); - - SigTestUtils.findExtraClasses(this, - that, - referenceExtras, - candidateExtras); - - if (referenceExtras.size() > 0 || candidateExtras.size() > 0) - { - strBuf.append("\nProject '" + that.name + "'" + - (candidateExtras.size() > 0 - ? " has extraneous class" + - (candidateExtras.size() > 1 ? "es" : "") + " " + - SigTestUtils.getCondensedClassList(candidateExtras) - : "") + - (referenceExtras.size() > 0 - ? (candidateExtras.size() > 0 ? " and" : "") + - " is missing class" + - (referenceExtras.size() > 1 ? "es" : "") + " " + - SigTestUtils.getCondensedClassList(referenceExtras) - : "") + "."); - } - - return (strBuf.length() > 0) - ? strBuf.toString() - : null; - } - - /** - * This method compares the specified project file to the classes - * currently available on the classpath. - * - * @param file the project file to read from - * - * @return a description of the differences, or null if they match perfectly - */ - public static String compareProjectFile(File projectFile) - throws IOException - { - ProjectDesc riPD = readProjectFile("ReferenceImpl", projectFile); - ProjectDesc cdPD = SigTestUtils.getProjectDesc(riPD); - - return riPD.compare(cdPD); - } - - public String toString() - { - StringBuffer strBuf = new StringBuffer("Project '" + name + "': "); - int size = classDescs.size(); - - for (int i = 0; i < size; i++) - { - strBuf.append((i > 0 ? ", " : "") + - ((ClassDesc)classDescs.get(i)).getName()); - } - - return strBuf.toString(); - } - - /** - * This method reads the specified project file into memory. - * - * @param projectName the name to be used when referring to the project in - * error messages - * @param file the project file to read from - * - * @return a model of the project - */ - public static ProjectDesc readProjectFile(String projectName, - File file) - throws IOException - { - ProjectDesc pd = new ProjectDesc(projectName); - FileReader fileReader = new FileReader(file); - BufferedReader buf = new BufferedReader(fileReader); - - while (buf.ready()) - { - pd.addClassDesc(ClassDesc.parseClassDesc(buf)); - } - - buf.close(); - fileReader.close(); - - return pd; - } -} diff --git a/src/test/java/javax/usb/tck/sigtest/SigTestUtils.java b/src/test/java/javax/usb/tck/sigtest/SigTestUtils.java deleted file mode 100755 index ec194a3..0000000 --- a/src/test/java/javax/usb/tck/sigtest/SigTestUtils.java +++ /dev/null @@ -1,441 +0,0 @@ -package javax.usb.tck.sigtest; - -/** - * Copyright (c) 2003,2004 International Business Machines Corporation. - * All Rights Reserved. - * - * This software is provided and licensed under the terms and conditions - * of the Common Public License: - * http://oss.software.ibm.com/developerworks/opensource/license-cpl.html - */ - -import java.lang.reflect.*; -import java.io.*; -import java.util.*; - -/** - * This class implements static utility methods for use by the signature - * test tool. - * - * @author Matthew J. Duftler - */ -@SuppressWarnings("all") -public class SigTestUtils -{ - /** - * This method builds a new project description by using an existing one - * as a reference. The new project description is built by resolving each - * class specified in the reference description, and adding their signatures - * to the newly built project. - * - * @param referencePD the reference project description - * - * @return the new project description - */ - public static ProjectDesc getProjectDesc(ProjectDesc referencePD) - { - ProjectDesc candidatePD = new ProjectDesc("CandidateImpl"); - Iterator iterator = referencePD.getClassDescs().iterator(); - - while (iterator.hasNext()) - { - ClassDesc referenceCD = (ClassDesc)iterator.next(); - String className = referenceCD.getName(); - ClassDesc candidateCD = null; - - try - { - Class candidateClass = Class.forName(className); - - candidateCD = getClassDesc(candidateClass); - } - catch (ClassNotFoundException e) - { - } - - if (candidateCD != null) - { - candidatePD.addClassDesc(candidateCD); - } - } - - return candidatePD; - } - - public static ClassDesc getClassDesc(Class theClass) - { - String className = getClassName(theClass); - ClassDesc classDesc = new ClassDesc(className, - theClass.getModifiers()); - Class superClass = theClass.getSuperclass(); - - if (superClass != null) - { - classDesc.setSuperClassName(getClassName(superClass)); - } - - List interfaceNames = getTypeNames(theClass.getInterfaces()); - - classDesc.setInterfaceNames(interfaceNames); - - List constructorDescs = - getConstructorDescs(className, theClass.getDeclaredConstructors()); - - classDesc.setConstructorDescs(constructorDescs); - - List methodDescs = - getMethodDescs(theClass.getDeclaredMethods()); - - classDesc.setMethodDescs(methodDescs); - - return classDesc; - } - - public static List getConstructorDescs(String className, - Constructor[] constructors) - { - List constructorDescs = new Vector(); - - for (int i = 0; i < constructors.length; i++) - { - MethodDesc constructorDesc = - new MethodDesc(className, - constructors[i].getModifiers(), - null, - getTypeNames(constructors[i].getParameterTypes()), - getTypeNames(constructors[i].getExceptionTypes())); - - constructorDescs.add(constructorDesc); - } - - return constructorDescs; - } - - public static List getMethodDescs(Method[] methods) - { - List methodDescs = new Vector(); - - for (int i = 0; i < methods.length; i++) - { - MethodDesc methodDesc = - new MethodDesc(methods[i].getName(), - methods[i].getModifiers(), - getClassName(methods[i].getReturnType()), - getTypeNames(methods[i].getParameterTypes()), - getTypeNames(methods[i].getExceptionTypes())); - - methodDescs.add(methodDesc); - } - - return methodDescs; - } - - public static List getTypeNames(Class[] types) - { - List typeNames = new Vector(); - - for (int i = 0; i < types.length; i++) - { - typeNames.add(getClassName(types[i])); - } - - return typeNames; - } - - public static String listToString(List list) - { - StringBuffer strBuf = new StringBuffer(); - int size = list.size(); - - for (int i = 0; i < size; i++) - { - strBuf.append((i > 0 ? "," : "") + - list.get(i)); - } - - return strBuf.toString(); - } - - public static List stringToList(String str, String delim) - { - return Arrays.asList(tokenize(str, delim)); - } - - public static String[] tokenize(String tokenStr, String delim) - { - StringTokenizer strTok = new StringTokenizer(tokenStr, delim); - String[] tokens = new String[strTok.countTokens()]; - - for (int i = 0; i < tokens.length; i++) - { - tokens[i] = strTok.nextToken(); - } - - return tokens; - } - - public static boolean objectsEqual(Object obj1, Object obj2) - { - if (obj1 == null) - { - return (obj2 == null); - } - else - { - return obj1.equals(obj2); - } - } - - public static boolean collectionsMatch(Collection c1, Collection c2) - { - if (c1 == null) - { - return (c2 == null); - } - else - { - return c1.containsAll(c2) && c2.containsAll(c1); - } - } - - public static String getExpandedMethodList(List list) - { - StringBuffer strBuf = new StringBuffer("["); - int size = list.size(); - - for (int i = 0; i < size; i++) - { - strBuf.append((i > 0 ? ", " : "") + - ((MethodDesc)list.get(i)).toString(true)); - } - - strBuf.append("]"); - - return strBuf.toString(); - } - - public static String getCondensedClassList(List list) - { - StringBuffer strBuf = new StringBuffer("["); - int size = list.size(); - - for (int i = 0; i < size; i++) - { - strBuf.append((i > 0 ? ", " : "") + - ((ClassDesc)list.get(i)).getName()); - } - - strBuf.append("]"); - - return strBuf.toString(); - } - - public static void findExtras(Collection reference, - Collection candidate, - List referenceExtras, - List candidateExtras) - { - referenceExtras.addAll(reference); - referenceExtras.removeAll(candidate); - candidateExtras.addAll(candidate); - candidateExtras.removeAll(reference); - - if (candidateExtras.size() > 0) - { - Iterator memberDescs = candidateExtras.iterator(); - - while (memberDescs.hasNext()) - { - MemberDesc memberDesc = (MemberDesc)memberDescs.next(); - int modifiers = memberDesc.getModifiers(); - - if (Modifier.isPrivate(modifiers) - || !(Modifier.isProtected(modifiers) - || Modifier.isPublic(modifiers))) - { - memberDescs.remove(); - } - } - } - } - - public static void findExtraClasses(ProjectDesc referencePD, - ProjectDesc candidatePD, - List referenceExtras, - List candidateExtras) - { - referenceExtras.addAll(referencePD.getClassDescs()); - candidateExtras.addAll(candidatePD.getClassDescs()); - - Iterator iterator = referenceExtras.iterator(); - - while (iterator.hasNext()) - { - ClassDesc referenceCD = (ClassDesc)iterator.next(); - ClassDesc candidateCD = - candidatePD.getClassDesc(referenceCD.getName()); - - if (candidateCD != null) - { - iterator.remove(); - } - } - - iterator = candidateExtras.iterator(); - - while (iterator.hasNext()) - { - ClassDesc candidateCD = (ClassDesc)iterator.next(); - ClassDesc referenceCD = - referencePD.getClassDesc(candidateCD.getName()); - - if (referenceCD != null) - { - iterator.remove(); - } - } - } - - /* - This method will return the correct name for a class object representing - a primitive, a single instance of a class, as well as n-dimensional arrays - of primitives or instances. This logic is needed to handle the string returned - from Class.getName(). If the class object represents a single instance (or - a primitive), Class.getName() returns the fully-qualified name of the class - and no further work is needed. However, if the class object represents an - array (of n dimensions), Class.getName() returns a Descriptor (the Descriptor - grammar is defined in section 4.3 of the Java VM Spec). This method will - parse the Descriptor if necessary. - */ - public static String getClassName(Class targetClass) - { - String className = targetClass.getName(); - - return targetClass.isArray() ? parseDescriptor(className) : className; - } - - /* - See the comment above for getClassName(targetClass)... - */ - private static String parseDescriptor(String className) - { - char[] classNameChars = className.toCharArray(); - int arrayDim = 0; - int i = 0; - - while (classNameChars[i] == '[') - { - arrayDim++; - i++; - } - - StringBuffer classNameBuf = new StringBuffer(); - - switch (classNameChars[i++]) - { - case 'B' : classNameBuf.append("byte"); - break; - case 'C' : classNameBuf.append("char"); - break; - case 'D' : classNameBuf.append("double"); - break; - case 'F' : classNameBuf.append("float"); - break; - case 'I' : classNameBuf.append("int"); - break; - case 'J' : classNameBuf.append("long"); - break; - case 'S' : classNameBuf.append("short"); - break; - case 'Z' : classNameBuf.append("boolean"); - break; - case 'L' : classNameBuf.append(classNameChars, - i, classNameChars.length - i - 1); - break; - } - - for (i = 0; i < arrayDim; i++) - classNameBuf.append("[]"); - - return classNameBuf.toString(); - } - - private static OutputStream getOutputStream(String root, - String name, - boolean overwrite, - boolean verbose) - throws IOException - { - if (root != null) - { - File directory = new File(root); - - if (!directory.exists()) - { - if (!directory.mkdirs()) - { - throw new IOException("Failed to create directory '" + root + "'."); - } - else if (verbose) - { - System.out.println("Created directory '" + - directory.getAbsolutePath() + "'."); - } - } - } - - File file = new File(root, name); - String absolutePath = file.getAbsolutePath(); - - if (file.exists()) - { - if (!overwrite) - { - throw new IOException("File '" + absolutePath + "' already exists. " + - "Please remove it or enable the " + - "overwrite option."); - } - else - { - file.delete(); - - if (verbose) - { - System.out.println("Deleted file '" + absolutePath + "'."); - } - } - } - - FileOutputStream fos = new FileOutputStream(absolutePath); - - if (verbose) - { - System.out.println("Created file '" + absolutePath + "'."); - } - - return fos; - } - - public static void generateProjectFile(String classListFile, - String projectFile, - boolean overwrite) - throws IOException, - ClassNotFoundException - { - FileReader in = new FileReader(classListFile); - BufferedReader buf = new BufferedReader(in); - OutputStream out = getOutputStream(null, projectFile, overwrite, true); - PrintWriter pw = new PrintWriter(out); - String tempLine; - - while ((tempLine = buf.readLine()) != null) - { - pw.println(getClassDesc(Class.forName(tempLine))); - } - - pw.flush(); - pw.close(); - buf.close(); - in.close(); - } -} diff --git a/src/test/java/org/libusb4java/BosDescriptorTest.java b/src/test/java/org/usb4java/BosDescriptorTest.java similarity index 96% rename from src/test/java/org/libusb4java/BosDescriptorTest.java rename to src/test/java/org/usb4java/BosDescriptorTest.java index f7de17d..6f736cd 100644 --- a/src/test/java/org/libusb4java/BosDescriptorTest.java +++ b/src/test/java/org/usb4java/BosDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.BosDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link BosDescriptor} class. diff --git a/src/test/java/org/libusb4java/BosDevCapabilityDescriptorTest.java b/src/test/java/org/usb4java/BosDevCapabilityDescriptorTest.java similarity index 95% rename from src/test/java/org/libusb4java/BosDevCapabilityDescriptorTest.java rename to src/test/java/org/usb4java/BosDevCapabilityDescriptorTest.java index e879928..3f5fd73 100644 --- a/src/test/java/org/libusb4java/BosDevCapabilityDescriptorTest.java +++ b/src/test/java/org/usb4java/BosDevCapabilityDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.BosDevCapabilityDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link BosDevCapabilityDescriptor} class. diff --git a/src/test/java/org/libusb4java/ConfigDescriptorTest.java b/src/test/java/org/usb4java/ConfigDescriptorTest.java similarity index 97% rename from src/test/java/org/libusb4java/ConfigDescriptorTest.java rename to src/test/java/org/usb4java/ConfigDescriptorTest.java index b2d9571..fbac11d 100644 --- a/src/test/java/org/libusb4java/ConfigDescriptorTest.java +++ b/src/test/java/org/usb4java/ConfigDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.ConfigDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link ConfigDescriptor} class. diff --git a/src/test/java/org/usb4java/ConfigTest.java b/src/test/java/org/usb4java/ConfigTest.java deleted file mode 100644 index dfaa4ee..0000000 --- a/src/test/java/org/usb4java/ConfigTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertEquals; - -import java.util.Properties; - -import org.junit.Test; - -/** - * Tests the {@link Config} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class ConfigTest -{ - /** - * Tests the default configuration - */ - @Test - public void testDefaultConfiguration() - { - final Properties properties = new Properties(); - final Config config = new Config(properties); - assertEquals(2500, config.getTimeout()); - assertEquals(500, config.getScanInterval()); - } - - /** - * Tests the scan interval configuration. - */ - @Test - public void testScanIntervalConfiguration() - { - final Properties properties = new Properties(); - properties.put("org.usb4java.scanInterval", "123"); - final Config config = new Config(properties); - assertEquals(123, config.getScanInterval()); - } - - /** - * Tests the timeout configuration. - */ - @Test - public void testTimeoutConfiguration() - { - final Properties properties = new Properties(); - properties.put("org.usb4java.timeout", "1234"); - final Config config = new Config(properties); - assertEquals(1234, config.getTimeout()); - } -} diff --git a/src/test/java/org/libusb4java/ContainerIdDescriptorTest.java b/src/test/java/org/usb4java/ContainerIdDescriptorTest.java similarity index 95% rename from src/test/java/org/libusb4java/ContainerIdDescriptorTest.java rename to src/test/java/org/usb4java/ContainerIdDescriptorTest.java index 19ba2cc..63976a0 100644 --- a/src/test/java/org/libusb4java/ContainerIdDescriptorTest.java +++ b/src/test/java/org/usb4java/ContainerIdDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.ContainerIdDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link ContainerIdDescriptor} class. diff --git a/src/test/java/org/libusb4java/DeviceDescriptorTest.java b/src/test/java/org/usb4java/DeviceDescriptorTest.java similarity index 98% rename from src/test/java/org/libusb4java/DeviceDescriptorTest.java rename to src/test/java/org/usb4java/DeviceDescriptorTest.java index 6d4df81..35023dd 100644 --- a/src/test/java/org/libusb4java/DeviceDescriptorTest.java +++ b/src/test/java/org/usb4java/DeviceDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.DeviceDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link DeviceDescriptor} class. diff --git a/src/test/java/org/usb4java/DeviceIdTest.java b/src/test/java/org/usb4java/DeviceIdTest.java deleted file mode 100644 index 4603e6b..0000000 --- a/src/test/java/org/usb4java/DeviceIdTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import org.usb4java.descriptors.SimpleUsbDeviceDescriptor; - -/** - * Tests the {@link DeviceId} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class DeviceIdTest -{ - /** A zero byte used in the dummy descriptor. */ - private static final byte ZERO = 0; - - /** A dummy device descriptor. */ - private static final SimpleUsbDeviceDescriptor descriptor = - new SimpleUsbDeviceDescriptor(ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, - ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO); - - /** - * Tests the constructor without a descriptor. - */ - @Test(expected = IllegalArgumentException.class) - public void testConstructorWithoutDescriptor() - { - assertNotNull(new DeviceId(0, 1, 2, null)); - } - - /** - * Tests the {@link DeviceId#getBusNumber()} method. - */ - @Test - public void testGetBusNumber() - { - assertEquals(1, new DeviceId(1, 2, 3, descriptor).getBusNumber()); - } - - /** - * Tests the {@link DeviceId#getDeviceAddress()} method. - */ - @Test - public void testGetDeviceAddress() - { - assertEquals(2, new DeviceId(1, 2, 3, descriptor).getDeviceAddress()); - } - - /** - * Tests the {@link DeviceId#getPortNumber()} method. - */ - @Test - public void testGetPortNumber() - { - assertEquals(3, new DeviceId(1, 2, 3, descriptor).getPortNumber()); - } - - /** - * Tests the {@link DeviceId#getDeviceDescriptor()} method. - */ - @Test - public void testGetDeviceDescriptor() - { - assertSame(descriptor, - new DeviceId(1, 2, 3, descriptor).getDeviceDescriptor()); - } - - /** - * Tests the {@link DeviceId#hashCode()} method. - */ - @Test - public void testHashCode() - { - final int code = new DeviceId(1, 2, 3, descriptor).hashCode(); - assertEquals(code, new DeviceId(1, 2, 3, descriptor).hashCode()); - } - - /** - * Tests the {@link DeviceId#equals(Object)} method. - */ - @Test - public void testEquals() - { - final DeviceId subject = new DeviceId(1, 2, 3, descriptor); - final DeviceId equal = new DeviceId(1, 2, 3, descriptor); - final DeviceId other = new DeviceId(2, 3, 4, descriptor); - assertFalse(subject.equals(null)); - assertFalse(subject.equals(new Object())); - assertTrue(subject.equals(subject)); - assertTrue(subject.equals(equal)); - assertFalse(subject.equals(other)); - } -} diff --git a/src/test/java/org/usb4java/DeviceListenerListTest.java b/src/test/java/org/usb4java/DeviceListenerListTest.java deleted file mode 100644 index 7abe427..0000000 --- a/src/test/java/org/usb4java/DeviceListenerListTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import javax.usb.UsbControlIrp; -import javax.usb.UsbDevice; -import javax.usb.event.UsbDeviceDataEvent; -import javax.usb.event.UsbDeviceErrorEvent; -import javax.usb.event.UsbDeviceListener; - -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the {@link DeviceListenerList} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class DeviceListenerListTest -{ - /** The test subject. */ - private DeviceListenerList list; - - /** - * Set up the test. - */ - @Before - public void setUp() - { - this.list = new DeviceListenerList(); - } - - /** - * Tests the list functionality. - */ - @Test - public void testList() - { - // Must be initially empty - assertEquals(0, this.list.getListeners().size()); - - // Add first listener - final UsbDeviceListener a = mock(UsbDeviceListener.class); - this.list.add(a); - assertEquals(1, this.list.getListeners().size()); - assertSame(a, this.list.getListeners().get(0)); - - // Add same listener again - this.list.add(a); - assertEquals(1, this.list.getListeners().size()); - - // Add second listener - final UsbDeviceListener b = mock(UsbDeviceListener.class); - this.list.add(b); - assertEquals(2, this.list.getListeners().size()); - - // Remove first listener - this.list.remove(a); - assertEquals(1, this.list.getListeners().size()); - assertSame(b, this.list.getListeners().get(0)); - - // Add first listener again and check array conversion - this.list.add(a); - assertArrayEquals(new UsbDeviceListener[] { b, a }, this.list.toArray()); - - // Clear the list - this.list.clear(); - assertSame(0, this.list.getListeners().size()); - } - - /** - * Tests the data event. - */ - @Test - public void testDataEvent() - { - final UsbDeviceDataEvent event = new UsbDeviceDataEvent( - mock(UsbDevice.class), mock(UsbControlIrp.class)); - final UsbDeviceListener a = mock(UsbDeviceListener.class); - final UsbDeviceListener b = mock(UsbDeviceListener.class); - this.list.add(a); - this.list.add(b); - this.list.dataEventOccurred(event); - verify(a).dataEventOccurred(event); - verify(b).dataEventOccurred(event); - } - - /** - * Tests the error event. - */ - @Test - public void testErrorEvent() - { - final UsbDeviceErrorEvent event = new UsbDeviceErrorEvent( - mock(UsbDevice.class), mock(UsbControlIrp.class)); - final UsbDeviceListener a = mock(UsbDeviceListener.class); - final UsbDeviceListener b = mock(UsbDeviceListener.class); - this.list.add(a); - this.list.add(b); - this.list.errorEventOccurred(event); - verify(a).errorEventOccurred(event); - verify(b).errorEventOccurred(event); - } - - /** - * Tests the detached event. - */ - @Test - public void testDetachedEvent() - { - final UsbDeviceErrorEvent event = new UsbDeviceErrorEvent( - mock(UsbDevice.class), mock(UsbControlIrp.class)); - final UsbDeviceListener a = mock(UsbDeviceListener.class); - final UsbDeviceListener b = mock(UsbDeviceListener.class); - this.list.add(a); - this.list.add(b); - this.list.usbDeviceDetached(event); - verify(a).usbDeviceDetached(event); - verify(b).usbDeviceDetached(event); - } -} diff --git a/src/test/java/org/usb4java/DeviceNotFoundExceptionTest.java b/src/test/java/org/usb4java/DeviceNotFoundExceptionTest.java deleted file mode 100644 index 93cc692..0000000 --- a/src/test/java/org/usb4java/DeviceNotFoundExceptionTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ -package org.usb4java; - -import static org.junit.Assert.assertSame; - -import org.junit.Test; - -import org.usb4java.descriptors.SimpleUsbDeviceDescriptor; - -/** - * Tests the {@link DeviceNotFoundException} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class DeviceNotFoundExceptionTest -{ - /** - * Tests the {@link DeviceNotFoundException#getId() method}. - */ - @Test - public void testGetId() - { - final byte d = 0; - final DeviceId id = new DeviceId(0, 1, 2, - new SimpleUsbDeviceDescriptor(d, d, d, d, d, d, d, d, d, d, d, d, - d, d)); - assertSame(id, new DeviceNotFoundException(id).getId()); - } -} diff --git a/src/test/java/org/libusb4java/EndpointDescriptorTest.java b/src/test/java/org/usb4java/EndpointDescriptorTest.java similarity index 97% rename from src/test/java/org/libusb4java/EndpointDescriptorTest.java rename to src/test/java/org/usb4java/EndpointDescriptorTest.java index 1216ce3..f3d3c1e 100644 --- a/src/test/java/org/libusb4java/EndpointDescriptorTest.java +++ b/src/test/java/org/usb4java/EndpointDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.EndpointDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link EndpointDescriptor} class. diff --git a/src/test/java/org/libusb4java/InterfaceDescriptorTest.java b/src/test/java/org/usb4java/InterfaceDescriptorTest.java similarity index 97% rename from src/test/java/org/libusb4java/InterfaceDescriptorTest.java rename to src/test/java/org/usb4java/InterfaceDescriptorTest.java index 1c6f057..e570958 100644 --- a/src/test/java/org/libusb4java/InterfaceDescriptorTest.java +++ b/src/test/java/org/usb4java/InterfaceDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.InterfaceDescriptor; +import org.usb4java.LibUsb; /** * Tests the {@link InterfaceDescriptor} class. diff --git a/src/test/java/org/libusb4java/InterfaceTest.java b/src/test/java/org/usb4java/InterfaceTest.java similarity index 93% rename from src/test/java/org/libusb4java/InterfaceTest.java rename to src/test/java/org/usb4java/InterfaceTest.java index baff051..03fb7f7 100644 --- a/src/test/java/org/libusb4java/InterfaceTest.java +++ b/src/test/java/org/usb4java/InterfaceTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.Interface; +import org.usb4java.LibUsb; /** * Tests the {@link Interface} class. diff --git a/src/test/java/org/libusb4java/LibUSBDeviceTest.java b/src/test/java/org/usb4java/LibUSBDeviceTest.java similarity index 98% rename from src/test/java/org/libusb4java/LibUSBDeviceTest.java rename to src/test/java/org/usb4java/LibUSBDeviceTest.java index ecdc048..29710cd 100644 --- a/src/test/java/org/libusb4java/LibUSBDeviceTest.java +++ b/src/test/java/org/usb4java/LibUSBDeviceTest.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import static org.junit.Assert.assertEquals; @@ -18,8 +18,17 @@ import java.nio.IntBuffer; import org.junit.After; import org.junit.Before; import org.junit.Test; - -import org.libusb4java.utils.BufferUtils; +import org.usb4java.ConfigDescriptor; +import org.usb4java.Context; +import org.usb4java.Device; +import org.usb4java.DeviceDescriptor; +import org.usb4java.DeviceHandle; +import org.usb4java.DeviceList; +import org.usb4java.EndpointDescriptor; +import org.usb4java.Interface; +import org.usb4java.InterfaceDescriptor; +import org.usb4java.LibUsb; +import org.usb4java.utils.BufferUtils; /** * Tests the device-scope methods of the {@link LibUsb} class which need a open diff --git a/src/test/java/org/libusb4java/LibUSBGlobalTest.java b/src/test/java/org/usb4java/LibUSBGlobalTest.java similarity index 96% rename from src/test/java/org/libusb4java/LibUSBGlobalTest.java rename to src/test/java/org/usb4java/LibUSBGlobalTest.java index 115b16d..228ad45 100644 --- a/src/test/java/org/libusb4java/LibUSBGlobalTest.java +++ b/src/test/java/org/usb4java/LibUSBGlobalTest.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import static org.junit.Assert.assertEquals; @@ -14,6 +14,10 @@ import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.Context; +import org.usb4java.Device; +import org.usb4java.DeviceList; +import org.usb4java.LibUsb; /** * Tests the global-scope methods of the {@link LibUsb} class which need a diff --git a/src/test/java/org/libusb4java/LibUSBTest.java b/src/test/java/org/usb4java/LibUSBTest.java similarity index 98% rename from src/test/java/org/libusb4java/LibUSBTest.java rename to src/test/java/org/usb4java/LibUSBTest.java index 2b4342a..311537c 100644 --- a/src/test/java/org/libusb4java/LibUSBTest.java +++ b/src/test/java/org/usb4java/LibUSBTest.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import static org.junit.Assert.assertEquals; @@ -19,9 +19,25 @@ import java.nio.IntBuffer; import java.nio.LongBuffer; import org.junit.Test; - -import org.libusb4java.mocks.PollfdListenerMock; -import org.libusb4java.utils.BufferUtils; +import org.usb4java.BosDescriptor; +import org.usb4java.BosDevCapabilityDescriptor; +import org.usb4java.ConfigDescriptor; +import org.usb4java.ContainerIdDescriptor; +import org.usb4java.Context; +import org.usb4java.Device; +import org.usb4java.DeviceDescriptor; +import org.usb4java.DeviceHandle; +import org.usb4java.DeviceList; +import org.usb4java.EndpointDescriptor; +import org.usb4java.LibUsb; +import org.usb4java.PollfdListener; +import org.usb4java.SsEndpointCompanionDescriptor; +import org.usb4java.SsUsbDeviceCapabilityDescriptor; +import org.usb4java.Transfer; +import org.usb4java.Usb20ExtensionDescriptor; +import org.usb4java.Version; +import org.usb4java.mocks.PollfdListenerMock; +import org.usb4java.utils.BufferUtils; /** * Tests the {@link LibUsb} class. diff --git a/src/test/java/org/usb4java/PipeListenerListTest.java b/src/test/java/org/usb4java/PipeListenerListTest.java deleted file mode 100644 index 1ef553c..0000000 --- a/src/test/java/org/usb4java/PipeListenerListTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import javax.usb.UsbException; -import javax.usb.UsbPipe; -import javax.usb.event.UsbPipeDataEvent; -import javax.usb.event.UsbPipeErrorEvent; -import javax.usb.event.UsbPipeListener; - -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the {@link PipeListenerList} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class PipeListenerListTest -{ - /** The test subject. */ - private PipeListenerList list; - - /** - * Set up the test. - */ - @Before - public void setUp() - { - this.list = new PipeListenerList(); - } - - /** - * Tests the list functionality. - */ - @Test - public void testList() - { - // Must be initially empty - assertEquals(0, this.list.getListeners().size()); - - // Add first listener - final UsbPipeListener a = mock(UsbPipeListener.class); - this.list.add(a); - assertEquals(1, this.list.getListeners().size()); - assertSame(a, this.list.getListeners().get(0)); - - // Add same listener again - this.list.add(a); - assertEquals(1, this.list.getListeners().size()); - - // Add second listener - final UsbPipeListener b = mock(UsbPipeListener.class); - this.list.add(b); - assertEquals(2, this.list.getListeners().size()); - - // Remove first listener - this.list.remove(a); - assertEquals(1, this.list.getListeners().size()); - assertSame(b, this.list.getListeners().get(0)); - - // Add first listener again and check array conversion - this.list.add(a); - assertArrayEquals(new UsbPipeListener[] { b, a }, this.list.toArray()); - - // Clear the list - this.list.clear(); - assertSame(0, this.list.getListeners().size()); - } - - /** - * Tests the data event. - */ - @Test - public void testDataEvent() - { - final UsbPipeDataEvent event = - new UsbPipeDataEvent(mock(UsbPipe.class), null); - final UsbPipeListener a = mock(UsbPipeListener.class); - final UsbPipeListener b = mock(UsbPipeListener.class); - this.list.add(a); - this.list.add(b); - this.list.dataEventOccurred(event); - verify(a).dataEventOccurred(event); - verify(b).dataEventOccurred(event); - } - - /** - * Tests the error event. - */ - @Test - public void testErrorEvent() - { - final UsbPipeErrorEvent event = - new UsbPipeErrorEvent(mock(UsbPipe.class), new UsbException()); - final UsbPipeListener a = mock(UsbPipeListener.class); - final UsbPipeListener b = mock(UsbPipeListener.class); - this.list.add(a); - this.list.add(b); - this.list.errorEventOccurred(event); - verify(a).errorEventOccurred(event); - verify(b).errorEventOccurred(event); - } -} diff --git a/src/test/java/org/usb4java/RootHubConfigurationTest.java b/src/test/java/org/usb4java/RootHubConfigurationTest.java deleted file mode 100644 index bf87846..0000000 --- a/src/test/java/org/usb4java/RootHubConfigurationTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.List; - -import javax.usb.UsbDevice; -import javax.usb.UsbInterface; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -/** - * Tests the {@link RootHubConfiguration} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class RootHubConfigurationTest -{ - /** The test subject. */ - private RootHubConfiguration config; - - /** - * Initialize the test. - */ - @Before - public void init() - { - this.config = new RootHubConfiguration(Mockito.mock(UsbDevice.class)); - } - - /** - * Tests the {@link RootHubConfiguration#isActive()} method. - */ - @Test - public void testIsActive() - { - assertTrue(this.config.isActive()); - } - - /** - * Tests the {@link RootHubConfiguration#getUsbInterfaces()} method. - */ - @Test - public void testGetUsbInterfaces() - { - final List ifaces = this.config.getUsbInterfaces(); - assertEquals(1, ifaces.size()); - assertNotNull(ifaces.get(0)); - } - - /** - * Tests the {@link RootHubConfiguration#getUsbInterface(byte)} method. - */ - @Test - public void testGetUsbInterface() - { - assertNotNull(this.config.getUsbInterface((byte) 0)); - assertNull(this.config.getUsbInterface((byte) 1)); - } - - /** - * Tests the {@link RootHubConfiguration#containsUsbInterface(byte)} method. - */ - @Test - public void testContainsUsbInterface() - { - assertTrue(this.config.containsUsbInterface((byte) 0)); - assertFalse(this.config.containsUsbInterface((byte) 1)); - } - - /** - * Tests the {@link RootHubConfiguration#getUsbDevice()} method. - */ - @Test - public void testGetUsbDevice() - { - assertNotNull(this.config.getUsbDevice()); - } - - /** - * Tests the {@link RootHubConfiguration#getUsbConfigurationDescriptor()} - * method. - */ - @Test - public void testGetUsbConfigurationDescriptor() - { - assertNotNull(this.config.getUsbConfigurationDescriptor()); - } - - /** - * Tests the {@link RootHubConfiguration#getConfigurationString()} - * method. - */ - @Test - public void testGetConfigurationString() - { - assertNull(this.config.getConfigurationString()); - } -} diff --git a/src/test/java/org/usb4java/ScanExceptionTest.java b/src/test/java/org/usb4java/ScanExceptionTest.java deleted file mode 100644 index 8e61f0a..0000000 --- a/src/test/java/org/usb4java/ScanExceptionTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -/** - * Tests the {@link ScanException} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class ScanExceptionTest -{ - /** - * Tests the constructor. - */ - @Test - public void testConstructor() - { - final Throwable cause = new RuntimeException(""); - final String message = "Bang"; - final ScanException exception = new ScanException(message, cause); - assertEquals(message, exception.getMessage()); - assertEquals(cause, exception.getCause()); - } -} diff --git a/src/test/java/org/usb4java/ServicesExceptionTest.java b/src/test/java/org/usb4java/ServicesExceptionTest.java deleted file mode 100644 index 77bc5eb..0000000 --- a/src/test/java/org/usb4java/ServicesExceptionTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -/** - * Tests the {@link ServicesException} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class ServicesExceptionTest -{ - /** - * Tests the constructor. - */ - @Test - public void testConstructor() - { - final Throwable cause = new RuntimeException(""); - final String message = "Bang"; - final ServicesException exception = - new ServicesException(message, cause); - assertEquals(message, exception.getMessage()); - assertEquals(cause, exception.getCause()); - } -} diff --git a/src/test/java/org/usb4java/ServicesListenerListTest.java b/src/test/java/org/usb4java/ServicesListenerListTest.java deleted file mode 100644 index b4f5daf..0000000 --- a/src/test/java/org/usb4java/ServicesListenerListTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import javax.usb.UsbDevice; -import javax.usb.UsbServices; -import javax.usb.event.UsbServicesEvent; -import javax.usb.event.UsbServicesListener; - -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the {@link ServicesListenerList} class. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class ServicesListenerListTest -{ - /** The test subject. */ - private ServicesListenerList list; - - /** - * Set up the test. - */ - @Before - public void setUp() - { - this.list = new ServicesListenerList(); - } - - /** - * Tests the list functionality. - */ - @Test - public void testList() - { - // Must be initially empty - assertEquals(0, this.list.getListeners().size()); - - // Add first listener - final UsbServicesListener a = mock(UsbServicesListener.class); - this.list.add(a); - assertEquals(1, this.list.getListeners().size()); - assertSame(a, this.list.getListeners().get(0)); - - // Add same listener again - this.list.add(a); - assertEquals(1, this.list.getListeners().size()); - - // Add second listener - final UsbServicesListener b = mock(UsbServicesListener.class); - this.list.add(b); - assertEquals(2, this.list.getListeners().size()); - - // Remove first listener - this.list.remove(a); - assertEquals(1, this.list.getListeners().size()); - assertSame(b, this.list.getListeners().get(0)); - - // Add first listener again and check array conversion - this.list.add(a); - assertArrayEquals(new UsbServicesListener[] { b, a }, this.list.toArray()); - - // Clear the list - this.list.clear(); - assertSame(0, this.list.getListeners().size()); - } - - /** - * Tests the detached event. - */ - @Test - public void testDetachedEvent() - { - final UsbServicesEvent event = new UsbServicesEvent( - mock(UsbServices.class), mock(UsbDevice.class)); - final UsbServicesListener a = mock(UsbServicesListener.class); - final UsbServicesListener b = mock(UsbServicesListener.class); - this.list.add(a); - this.list.add(b); - this.list.usbDeviceDetached(event); - verify(a).usbDeviceDetached(event); - verify(b).usbDeviceDetached(event); - } - - /** - * Tests the attached event. - */ - @Test - public void testAttachedEvent() - { - final UsbServicesEvent event = new UsbServicesEvent( - mock(UsbServices.class), mock(UsbDevice.class)); - final UsbServicesListener a = mock(UsbServicesListener.class); - final UsbServicesListener b = mock(UsbServicesListener.class); - this.list.add(a); - this.list.add(b); - this.list.usbDeviceAttached(event); - verify(a).usbDeviceAttached(event); - verify(b).usbDeviceAttached(event); - } -} diff --git a/src/test/java/org/libusb4java/SsEndpointCompanionDescriptorTest.java b/src/test/java/org/usb4java/SsEndpointCompanionDescriptorTest.java similarity index 95% rename from src/test/java/org/libusb4java/SsEndpointCompanionDescriptorTest.java rename to src/test/java/org/usb4java/SsEndpointCompanionDescriptorTest.java index 7915b41..654a8b5 100644 --- a/src/test/java/org/libusb4java/SsEndpointCompanionDescriptorTest.java +++ b/src/test/java/org/usb4java/SsEndpointCompanionDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.LibUsb; +import org.usb4java.SsEndpointCompanionDescriptor; /** * Tests the {@link SsEndpointCompanionDescriptor} class. diff --git a/src/test/java/org/libusb4java/SsUsbDeviceCapabilityDescriptorTest.java b/src/test/java/org/usb4java/SsUsbDeviceCapabilityDescriptorTest.java similarity index 96% rename from src/test/java/org/libusb4java/SsUsbDeviceCapabilityDescriptorTest.java rename to src/test/java/org/usb4java/SsUsbDeviceCapabilityDescriptorTest.java index d38f48d..f523a9b 100644 --- a/src/test/java/org/libusb4java/SsUsbDeviceCapabilityDescriptorTest.java +++ b/src/test/java/org/usb4java/SsUsbDeviceCapabilityDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.LibUsb; +import org.usb4java.SsUsbDeviceCapabilityDescriptor; /** * Tests the {@link SsUsbDeviceCapabilityDescriptor} class. diff --git a/src/test/java/org/libusb4java/TransferTest.java b/src/test/java/org/usb4java/TransferTest.java similarity index 97% rename from src/test/java/org/libusb4java/TransferTest.java rename to src/test/java/org/usb4java/TransferTest.java index 3b0b284..facb0e8 100644 --- a/src/test/java/org/libusb4java/TransferTest.java +++ b/src/test/java/org/usb4java/TransferTest.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import static org.junit.Assert.assertEquals; @@ -18,6 +18,10 @@ import java.lang.reflect.Field; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.Context; +import org.usb4java.DeviceHandle; +import org.usb4java.LibUsb; +import org.usb4java.Transfer; /** * Tests the {@link Transfer} class. diff --git a/src/test/java/org/libusb4java/Usb20ExtensionDescriptorTest.java b/src/test/java/org/usb4java/Usb20ExtensionDescriptorTest.java similarity index 95% rename from src/test/java/org/libusb4java/Usb20ExtensionDescriptorTest.java rename to src/test/java/org/usb4java/Usb20ExtensionDescriptorTest.java index 39bd795..b7dc479 100644 --- a/src/test/java/org/libusb4java/Usb20ExtensionDescriptorTest.java +++ b/src/test/java/org/usb4java/Usb20ExtensionDescriptorTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.LibUsb; +import org.usb4java.Usb20ExtensionDescriptor; /** * Tests the {@link Usb20ExtensionDescriptor} class. diff --git a/src/test/java/org/libusb4java/VersionTest.java b/src/test/java/org/usb4java/VersionTest.java similarity index 95% rename from src/test/java/org/libusb4java/VersionTest.java rename to src/test/java/org/usb4java/VersionTest.java index 32aa945..16779ed 100644 --- a/src/test/java/org/libusb4java/VersionTest.java +++ b/src/test/java/org/usb4java/VersionTest.java @@ -3,13 +3,15 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java; +package org.usb4java; import static org.usb4java.test.UsbAssume.assumeUsbTestsEnabled; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.usb4java.LibUsb; +import org.usb4java.Version; /** * Tests the {@link Version} class. diff --git a/src/test/java/org/usb4java/adapter/UsbDeviceAdapterTest.java b/src/test/java/org/usb4java/adapter/UsbDeviceAdapterTest.java deleted file mode 100644 index 791716d..0000000 --- a/src/test/java/org/usb4java/adapter/UsbDeviceAdapterTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ -package org.usb4java.adapter; - -import javax.usb.event.UsbDeviceDataEvent; -import javax.usb.event.UsbDeviceErrorEvent; -import javax.usb.event.UsbDeviceEvent; -import javax.usb.event.UsbDeviceListener; - -import org.junit.Test; - -/** - * Test the {@link UsbDeviceAdapter} class. There is not really anything to - * test there. This class just ensures that the class exists and provides - * the needed methods. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class UsbDeviceAdapterTest -{ - /** - * Ensure the existence of the needed methods. - */ - @Test - public void testAbstractMethods() - { - final UsbDeviceListener adapter = new UsbDeviceAdapter() - { - // Empty - }; - adapter.usbDeviceDetached((UsbDeviceEvent) null); - adapter.dataEventOccurred((UsbDeviceDataEvent) null); - adapter.errorEventOccurred((UsbDeviceErrorEvent) null); - } -} diff --git a/src/test/java/org/usb4java/adapter/UsbPipeAdapterTest.java b/src/test/java/org/usb4java/adapter/UsbPipeAdapterTest.java deleted file mode 100644 index 5b7e961..0000000 --- a/src/test/java/org/usb4java/adapter/UsbPipeAdapterTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ -package org.usb4java.adapter; - -import javax.usb.event.UsbPipeDataEvent; -import javax.usb.event.UsbPipeErrorEvent; -import javax.usb.event.UsbPipeListener; - -import org.junit.Test; - -/** - * Test the {@link UsbPipeAdapter} class. There is not really anything to - * test there. This class just ensures that the class exists and provides - * the needed methods. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class UsbPipeAdapterTest -{ - /** - * Ensure the existence of the needed methods. - */ - @Test - public void testAbstractMethods() - { - final UsbPipeListener adapter = new UsbPipeAdapter() - { - // Empty - }; - adapter.dataEventOccurred((UsbPipeDataEvent) null); - adapter.errorEventOccurred((UsbPipeErrorEvent) null); - } -} diff --git a/src/test/java/org/usb4java/adapter/UsbServicesAdapterTest.java b/src/test/java/org/usb4java/adapter/UsbServicesAdapterTest.java deleted file mode 100644 index a958c5d..0000000 --- a/src/test/java/org/usb4java/adapter/UsbServicesAdapterTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ -package org.usb4java.adapter; - -import javax.usb.event.UsbServicesEvent; -import javax.usb.event.UsbServicesListener; - -import org.junit.Test; - -/** - * Test the {@link UsbServicesAdapter} class. There is not really anything to - * test there. This class just ensures that the class exists and provides - * the needed methods. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class UsbServicesAdapterTest -{ - /** - * Ensure the existence of the needed methods. - */ - @Test - public void testAbstractMethods() - { - final UsbServicesListener adapter = new UsbServicesAdapter() - { - // Empty - }; - adapter.usbDeviceAttached((UsbServicesEvent) null); - adapter.usbDeviceDetached((UsbServicesEvent) null); - } -} diff --git a/src/test/java/org/usb4java/descriptors/SimpleUsbConfigurationDescriptorTest.java b/src/test/java/org/usb4java/descriptors/SimpleUsbConfigurationDescriptorTest.java deleted file mode 100644 index e45159c..0000000 --- a/src/test/java/org/usb4java/descriptors/SimpleUsbConfigurationDescriptorTest.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests the {@link SimpleUsbConfigurationDescriptor}. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class SimpleUsbConfigurationDescriptorTest -{ - /** The test subject. */ - private static SimpleUsbConfigurationDescriptor descriptor; - - /** Value for {@link SimpleUsbConfigurationDescriptor#bLength()}. */ - private static final byte LENGTH = 1; - - /** Value for {@link SimpleUsbConfigurationDescriptor#bDescriptorType()}. */ - private static final byte DESCRIPTOR_TYPE = 2; - - /** Value for {@link SimpleUsbConfigurationDescriptor#wTotalLength()}. */ - private static final short TOTAL_LENGTH = 3; - - /** Value for {@link SimpleUsbConfigurationDescriptor#bNumInterfaces()}. */ - private static final byte NUM_INTERFACES = 4; - - /** - * Value for {@link SimpleUsbConfigurationDescriptor#bConfigurationValue()}. - */ - private static final byte CONFIGURATION_VALUE = 5; - - /** Value for {@link SimpleUsbConfigurationDescriptor#iConfiguration()}. */ - private static final byte CONFIGURATION = 6; - - /** Value for {@link SimpleUsbConfigurationDescriptor#bmAttributes()}. */ - private static final byte ATTRIBUTES = 7; - - /** Value for {@link SimpleUsbConfigurationDescriptor#bMaxPower()}. */ - private static final byte MAX_POWER = 8; - - /** A wrong value for equality test. */ - private static final byte WRONG = 0; - - /** - * Setup the test subject. - */ - @BeforeClass - public static void setUp() - { - descriptor = new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#bLength()} method. - */ - @Test - public void testLength() - { - assertEquals(LENGTH, descriptor.bLength()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#bDescriptorType()} - * method. - */ - @Test - public void testDescriptorType() - { - assertEquals(DESCRIPTOR_TYPE, descriptor.bDescriptorType()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#wTotalLength()} method. - */ - @Test - public void testTotalLength() - { - assertEquals(TOTAL_LENGTH, descriptor.wTotalLength()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#bNumInterfaces()} - * method. - */ - @Test - public void testNumInterfaces() - { - assertEquals(NUM_INTERFACES, descriptor.bNumInterfaces()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#bConfigurationValue()} - * method. - */ - @Test - public void testConfigurationValue() - { - assertEquals(CONFIGURATION_VALUE, descriptor.bConfigurationValue()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#iConfiguration()} - * method. - */ - @Test - public void testConfiguration() - { - assertEquals(CONFIGURATION, descriptor.iConfiguration()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#bmAttributes()} method. - */ - @Test - public void testAttributes() - { - assertEquals(ATTRIBUTES, descriptor.bmAttributes()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#bMaxPower()} method. - */ - @Test - public void testMaxPower() - { - assertEquals(MAX_POWER, descriptor.bMaxPower()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#hashCode()} method. - */ - @Test - public void testHashCode() - { - final int code = descriptor.hashCode(); - assertEquals(code, descriptor.hashCode()); - assertEquals(code, new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, - MAX_POWER).hashCode()); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#equals(Object)} method. - */ - @Test - public void testEquals() - { - assertFalse(descriptor.equals(null)); - assertFalse(descriptor.equals(new Object())); - assertTrue(descriptor.equals(descriptor)); - assertTrue(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - WRONG, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, WRONG, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, WRONG, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - WRONG, CONFIGURATION, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, WRONG, ATTRIBUTES, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, WRONG, MAX_POWER))); - assertFalse(descriptor.equals(new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, WRONG))); - } - - /** - * Tests the {@link SimpleUsbConfigurationDescriptor#toString()} method. - */ - @Test - public void testToString() - { - assertEquals(descriptor.toString(), descriptor.toString()); - assertEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, - MAX_POWER).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - WRONG, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER) - .toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, WRONG, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER) - .toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER) - .toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, WRONG, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, MAX_POWER) - .toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - WRONG, CONFIGURATION, ATTRIBUTES, MAX_POWER).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, WRONG, ATTRIBUTES, MAX_POWER) - .toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, WRONG, MAX_POWER) - .toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbConfigurationDescriptor( - LENGTH, DESCRIPTOR_TYPE, TOTAL_LENGTH, NUM_INTERFACES, - CONFIGURATION_VALUE, CONFIGURATION, ATTRIBUTES, WRONG) - .toString()); - } -} diff --git a/src/test/java/org/usb4java/descriptors/SimpleUsbDeviceDescriptorTest.java b/src/test/java/org/usb4java/descriptors/SimpleUsbDeviceDescriptorTest.java deleted file mode 100644 index 354ea2e..0000000 --- a/src/test/java/org/usb4java/descriptors/SimpleUsbDeviceDescriptorTest.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests the {@link SimpleUsbDeviceDescriptor}. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class SimpleUsbDeviceDescriptorTest -{ - /** The test subject. */ - private static SimpleUsbDeviceDescriptor descriptor; - - /** Value for {@link SimpleUsbDeviceDescriptor#bLength()}. */ - private static final byte LENGTH = 1; - - /** Value for {@link SimpleUsbDeviceDescriptor#bDescriptorType()}. */ - private static final byte DESCRIPTOR_TYPE = 2; - - /** Value for {@link SimpleUsbDeviceDescriptor#bcdUSB()}. */ - private static final short USB = 3; - - /** Value for {@link SimpleUsbDeviceDescriptor#bDeviceClass()}. */ - private static final byte DEVICE_CLASS = 4; - - /** Value for {@link SimpleUsbDeviceDescriptor#bDeviceSubClass()}. */ - private static final byte DEVICE_SUB_CLASS = 5; - - /** Value for {@link SimpleUsbDeviceDescriptor#bDeviceProtocol()}. */ - private static final byte DEVICE_PROTOCOL = 6; - - /** Value for {@link SimpleUsbDeviceDescriptor#bMaxPacketSize0()}. */ - private static final byte MAX_PACKET_SIZE0 = 7; - - /** Value for {@link SimpleUsbDeviceDescriptor#idVendor()}. */ - private static final short ID_VENDOR = 8; - - /** Value for {@link SimpleUsbDeviceDescriptor#idProduct()}. */ - private static final short ID_PRODUCT = 9; - - /** Value for {@link SimpleUsbDeviceDescriptor#bcdDevice()}. */ - private static final short DEVICE = 10; - - /** Value for {@link SimpleUsbDeviceDescriptor#iManufacturer()}. */ - private static final byte MANUFACTURER = 11; - - /** Value for {@link SimpleUsbDeviceDescriptor#iProduct()}. */ - private static final byte PRODUCT = 12; - - /** Value for {@link SimpleUsbDeviceDescriptor#iSerialNumber()}. */ - private static final byte SERIAL_NUMBER = 13; - - /** Value for {@link SimpleUsbDeviceDescriptor#bNumConfigurations()}. */ - private static final byte NUM_CONFIGURATIONS = 14; - - /** A wrong value for equality test. */ - private static final byte WRONG = 0; - - /** - * Setup the test subject. - */ - @BeforeClass - public static void setUp() - { - descriptor = new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bLength()} method. - */ - @Test - public void testLength() - { - assertEquals(LENGTH, descriptor.bLength()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bDescriptorType()} method. - */ - @Test - public void testDescriptorType() - { - assertEquals(DESCRIPTOR_TYPE, descriptor.bDescriptorType()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bcdUSB()} method. - */ - @Test - public void testUSB() - { - assertEquals(USB, descriptor.bcdUSB()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bDeviceClass()} method. - */ - @Test - public void testDeviceClass() - { - assertEquals(DEVICE_CLASS, descriptor.bDeviceClass()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bDeviceSubClass()} method. - */ - @Test - public void testDeviceSubClass() - { - assertEquals(DEVICE_SUB_CLASS, descriptor.bDeviceSubClass()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bMaxPacketSize0()} method. - */ - @Test - public void testMaxPacketSize0() - { - assertEquals(MAX_PACKET_SIZE0, descriptor.bMaxPacketSize0()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#idVendor()} method. - */ - @Test - public void testIdVendor() - { - assertEquals(ID_VENDOR, descriptor.idVendor()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#idProduct()} method. - */ - @Test - public void testIdProduct() - { - assertEquals(ID_PRODUCT, descriptor.idProduct()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bcdDevice()} method. - */ - @Test - public void testDevice() - { - assertEquals(DEVICE, descriptor.bcdDevice()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#iManufacturer()} method. - */ - @Test - public void testManufacturer() - { - assertEquals(MANUFACTURER, descriptor.iManufacturer()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#iProduct()} method. - */ - @Test - public void testProduct() - { - assertEquals(PRODUCT, descriptor.iProduct()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#iSerialNumber()} method. - */ - @Test - public void testSerialNumber() - { - assertEquals(SERIAL_NUMBER, descriptor.iSerialNumber()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#bNumConfigurations()} method. - */ - @Test - public void testNumConfigurations() - { - assertEquals(NUM_CONFIGURATIONS, descriptor.bNumConfigurations()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#hashCode()} method. - */ - @Test - public void testHashCode() - { - final int code = descriptor.hashCode(); - assertEquals(code, descriptor.hashCode()); - assertEquals(code,new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, - NUM_CONFIGURATIONS).hashCode()); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#equals(Object)} method. - */ - @Test - public void testEquals() - { - assertFalse(descriptor.equals(null)); - assertFalse(descriptor.equals(new Object())); - assertTrue(descriptor.equals(descriptor)); - assertTrue(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - WRONG, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, WRONG, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, WRONG, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, WRONG, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - WRONG, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, WRONG, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, WRONG, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, WRONG, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, WRONG, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - WRONG, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, WRONG, SERIAL_NUMBER, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, WRONG, NUM_CONFIGURATIONS))); - assertFalse(descriptor.equals(new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, WRONG))); - } - - /** - * Tests the {@link SimpleUsbDeviceDescriptor#toString()} method. - */ - @Test - public void testToString() - { - assertEquals(descriptor.toString(), descriptor.toString()); - assertEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, - NUM_CONFIGURATIONS).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - WRONG, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, WRONG, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, WRONG, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, WRONG, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - WRONG, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, WRONG, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, WRONG, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, WRONG, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, WRONG, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - WRONG, PRODUCT, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, WRONG, SERIAL_NUMBER, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, WRONG, NUM_CONFIGURATIONS) - .toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbDeviceDescriptor( - LENGTH, DESCRIPTOR_TYPE, USB, DEVICE_CLASS, DEVICE_SUB_CLASS, - DEVICE_PROTOCOL, MAX_PACKET_SIZE0, ID_VENDOR, ID_PRODUCT, DEVICE, - MANUFACTURER, PRODUCT, SERIAL_NUMBER, WRONG) - .toString()); - } -} diff --git a/src/test/java/org/usb4java/descriptors/SimpleUsbEndpointDescriptorTest.java b/src/test/java/org/usb4java/descriptors/SimpleUsbEndpointDescriptorTest.java deleted file mode 100644 index 0e8b50a..0000000 --- a/src/test/java/org/usb4java/descriptors/SimpleUsbEndpointDescriptorTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests the {@link SimpleUsbEndpointDescriptor}. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class SimpleUsbEndpointDescriptorTest -{ - /** The test subject. */ - private static SimpleUsbEndpointDescriptor descriptor; - - /** Value for {@link SimpleUsbEndpointDescriptor#bLength()}. */ - private static final byte LENGTH = 1; - - /** Value for {@link SimpleUsbEndpointDescriptor#bDescriptorType()}. */ - private static final byte DESCRIPTOR_TYPE = 2; - - /** Value for {@link SimpleUsbEndpointDescriptor#bEndpointAddress()}. */ - private static final byte ENDPOINT_ADDRESS = 3; - - /** Value for {@link SimpleUsbEndpointDescriptor#bmAttributes()}. */ - private static final byte ATTRIBUTES = 4; - - /** Value for {@link SimpleUsbEndpointDescriptor#wMaxPacketSize()}. */ - private static final short MAX_PACKET_SIZE = 5; - - /** Value for {@link SimpleUsbEndpointDescriptor#bInterval()}. */ - private static final byte INTERVAL = 6; - - /** A wrong value for equality test. */ - private static final byte WRONG = 0; - - /** - * Setup the test subject. - */ - @BeforeClass - public static void setUp() - { - descriptor = new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#bLength()} method. - */ - @Test - public void testLength() - { - assertEquals(LENGTH, descriptor.bLength()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#bDescriptorType()} method. - */ - @Test - public void testDescriptorType() - { - assertEquals(DESCRIPTOR_TYPE, descriptor.bDescriptorType()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#bEndpointAddress()} method. - */ - @Test - public void testEndpontAddress() - { - assertEquals(ENDPOINT_ADDRESS, descriptor.bEndpointAddress()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#bmAttributes()} method. - */ - @Test - public void testAttributes() - { - assertEquals(ATTRIBUTES, descriptor.bmAttributes()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#wMaxPacketSize()} method. - */ - @Test - public void testMaxPacketSize() - { - assertEquals(MAX_PACKET_SIZE, descriptor.wMaxPacketSize()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#bInterval()} method. - */ - @Test - public void testInterval() - { - assertEquals(INTERVAL, descriptor.bInterval()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#hashCode()} method. - */ - @Test - public void testHashCode() - { - final int code = descriptor.hashCode(); - assertEquals(code, descriptor.hashCode()); - assertEquals(code, new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL).hashCode()); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#equals(Object)} method. - */ - @Test - public void testEquals() - { - assertFalse(descriptor.equals(null)); - assertFalse(descriptor.equals(new Object())); - assertTrue(descriptor.equals(descriptor)); - assertTrue(descriptor.equals(new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL))); - assertFalse(descriptor.equals(new SimpleUsbEndpointDescriptor( - WRONG, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL))); - assertFalse(descriptor.equals(new SimpleUsbEndpointDescriptor( - LENGTH, WRONG, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL))); - assertFalse(descriptor.equals(new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL))); - assertFalse(descriptor.equals(new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, WRONG, - MAX_PACKET_SIZE, INTERVAL))); - assertFalse(descriptor.equals(new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - WRONG, INTERVAL))); - assertFalse(descriptor.equals(new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, WRONG))); - } - - /** - * Tests the {@link SimpleUsbEndpointDescriptor#toString()} method. - */ - @Test - public void testToString() - { - assertEquals(descriptor.toString(), descriptor.toString()); - assertEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - WRONG, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - LENGTH, WRONG, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, ATTRIBUTES, - MAX_PACKET_SIZE, INTERVAL).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, WRONG, - MAX_PACKET_SIZE, INTERVAL).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - WRONG, INTERVAL).toString()); - assertNotEquals(descriptor.toString(), new SimpleUsbEndpointDescriptor( - LENGTH, DESCRIPTOR_TYPE, ENDPOINT_ADDRESS, ATTRIBUTES, - MAX_PACKET_SIZE, WRONG).toString()); - } -} diff --git a/src/test/java/org/usb4java/descriptors/SimpleUsbInterfaceDescriptorTest.java b/src/test/java/org/usb4java/descriptors/SimpleUsbInterfaceDescriptorTest.java deleted file mode 100644 index 92ec0b9..0000000 --- a/src/test/java/org/usb4java/descriptors/SimpleUsbInterfaceDescriptorTest.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests the {@link SimpleUsbInterfaceDescriptor}. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class SimpleUsbInterfaceDescriptorTest -{ - /** The test subject. */ - private static SimpleUsbInterfaceDescriptor descriptor; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bLength()}. */ - private static final byte LENGTH = 1; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bDescriptorType()}. */ - private static final byte DESCRIPTOR_TYPE = 2; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bInterfaceNumber()}. */ - private static final byte INTERFACE_NUMBER = 3; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bAlternateSetting()}. */ - private static final byte ALTERNATE_SETTING = 4; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bNumEndpoints()}. */ - private static final byte NUM_ENDPOINTS = 5; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bInterfaceClass()}. */ - private static final byte INTERFACE_CLASS = 6; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bInterfaceSubClass()}. */ - private static final byte INTERFACE_SUB_CLASS = 7; - - /** Value for {@link SimpleUsbInterfaceDescriptor#bInterfaceProtocol()}. */ - private static final byte INTERFACE_PROTOCOL = 8; - - /** Value for {@link SimpleUsbInterfaceDescriptor#iInterface()}. */ - private static final byte INTERFACE = 9; - - /** A wrong value for equality test. */ - private static final byte WRONG = 0; - - /** - * Setup the test subject. - */ - @BeforeClass - public static void setUp() - { - descriptor = new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bLength()} method. - */ - @Test - public void testLength() - { - assertEquals(LENGTH, descriptor.bLength()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bDescriptorType()} method. - */ - @Test - public void testDescriptorType() - { - assertEquals(DESCRIPTOR_TYPE, descriptor.bDescriptorType()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bInterfaceNumber()} method. - */ - @Test - public void testInterfaceNumber() - { - assertEquals(INTERFACE_NUMBER, descriptor.bInterfaceNumber()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bAlternateSetting()} - * method. - */ - @Test - public void testAlternateSetting() - { - assertEquals(ALTERNATE_SETTING, descriptor.bAlternateSetting()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bNumEndpoints()} method. - */ - @Test - public void testNumEndpoints() - { - assertEquals(NUM_ENDPOINTS, descriptor.bNumEndpoints()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bInterfaceClass()} method. - */ - @Test - public void testInterfaceClass() - { - assertEquals(INTERFACE_CLASS, descriptor.bInterfaceClass()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bInterfaceSubClass()} - * method. - */ - @Test - public void testInterfaceSubClass() - { - assertEquals(INTERFACE_SUB_CLASS, descriptor.bInterfaceSubClass()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#bInterfaceProtocol()} - * method. - */ - @Test - public void testInterfaceProtocol() - { - assertEquals(INTERFACE_PROTOCOL, descriptor.bInterfaceProtocol()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#iInterface()} method. - */ - @Test - public void testInterface() - { - assertEquals(INTERFACE, descriptor.iInterface()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#hashCode()} method. - */ - @Test - public void testHashCode() - { - final int code = descriptor.hashCode(); - assertEquals(code, descriptor.hashCode()); - assertEquals(code, new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).hashCode()); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#equals(Object)} method. - */ - @Test - public void testEquals() - { - assertFalse(descriptor.equals(null)); - assertFalse(descriptor.equals(new Object())); - assertTrue(descriptor.equals(descriptor)); - assertTrue(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - WRONG, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, WRONG, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, WRONG, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - WRONG, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, WRONG, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, WRONG, - INTERFACE_PROTOCOL, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - WRONG, INTERFACE))); - assertFalse(descriptor.equals(new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, WRONG))); - } - - /** - * Tests the {@link SimpleUsbInterfaceDescriptor#toString()} method. - */ - @Test - public void testToString() - { - assertEquals(descriptor.toString(), descriptor.toString()); - assertEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - WRONG, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, WRONG, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, WRONG, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, WRONG, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - WRONG, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, WRONG, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, WRONG, - INTERFACE_PROTOCOL, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - WRONG, INTERFACE).toString()); - assertNotEquals(descriptor.toString(), - new SimpleUsbInterfaceDescriptor( - LENGTH, DESCRIPTOR_TYPE, INTERFACE_NUMBER, ALTERNATE_SETTING, - NUM_ENDPOINTS, INTERFACE_CLASS, INTERFACE_SUB_CLASS, - INTERFACE_PROTOCOL, WRONG).toString()); - } -} diff --git a/src/test/java/org/usb4java/descriptors/SimpleUsbStringDescriptorTest.java b/src/test/java/org/usb4java/descriptors/SimpleUsbStringDescriptorTest.java deleted file mode 100644 index 14df542..0000000 --- a/src/test/java/org/usb4java/descriptors/SimpleUsbStringDescriptorTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.descriptors; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; - -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests the {@link SimpleUsbStringDescriptor}. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class SimpleUsbStringDescriptorTest -{ - /** The test subject. */ - private static SimpleUsbStringDescriptor descriptor; - - /** Value for {@link SimpleUsbStringDescriptor#bLength()}. */ - private static final byte LENGTH = 1; - - /** Value for {@link SimpleUsbStringDescriptor#bDescriptorType()}. */ - private static final byte DESCRIPTOR_TYPE = 2; - - /** Value for {@link SimpleUsbStringDescriptor#bString()}. */ - private static final String STRING = "usb4java"; - - /** A wrong value for equality test. */ - private static final byte WRONG = 0; - - /** - * Setup the test subject. - * - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - @BeforeClass - public static void setUp() throws UnsupportedEncodingException - { - descriptor = new SimpleUsbStringDescriptor( - LENGTH, DESCRIPTOR_TYPE, STRING); - } - - /** - * Tests the copy constructor. - */ - @Test - public void testCopyConstructor() - { - final SimpleUsbStringDescriptor copy = - new SimpleUsbStringDescriptor(descriptor); - assertNotSame(copy, descriptor); - assertEquals(copy, descriptor); - } - - /** - * Tests the byte buffer constructor. - * - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - @Test - public void testByteBufferConstructor() throws UnsupportedEncodingException - { - ByteBuffer buffer = ByteBuffer.allocate(STRING.length() * 2 + 2); - buffer.put((byte) (STRING.length() * 2 + 2)); - buffer.put(DESCRIPTOR_TYPE); - buffer.put(STRING.getBytes("UTF-16LE")); - final SimpleUsbStringDescriptor descriptor = - new SimpleUsbStringDescriptor(buffer); - assertEquals((byte) (STRING.length() * 2 + 2), descriptor.bLength()); - assertEquals(DESCRIPTOR_TYPE, descriptor.bDescriptorType()); - assertEquals(STRING, descriptor.getString()); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#bLength()} method. - */ - @Test - public void testLength() - { - assertEquals(LENGTH, descriptor.bLength()); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#bDescriptorType()} method. - */ - @Test - public void testDescriptorType() - { - assertEquals(DESCRIPTOR_TYPE, descriptor.bDescriptorType()); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#bString()} method. - * - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - @Test - public void testString() throws UnsupportedEncodingException - { - assertArrayEquals(STRING.getBytes("UTF-16LE"), descriptor.bString()); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#getString()} method. - * - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - @Test - public void testGetString() throws UnsupportedEncodingException - { - assertEquals(STRING, descriptor.getString()); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#hashCode()} method. - */ - @Test - public void testHashCode() - { - final int code = descriptor.hashCode(); - assertEquals(code, descriptor.hashCode()); - assertEquals(code, - new SimpleUsbStringDescriptor(descriptor).hashCode()); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#equals(Object)} method. - * - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - @Test - public void testEquals() throws UnsupportedEncodingException - { - assertFalse(descriptor.equals(null)); - assertFalse(descriptor.equals(new Object())); - assertTrue(descriptor.equals(descriptor)); - assertTrue(descriptor.equals(new SimpleUsbStringDescriptor( - descriptor))); - assertFalse(descriptor.equals(new SimpleUsbStringDescriptor( - WRONG, DESCRIPTOR_TYPE, STRING))); - assertFalse(descriptor.equals(new SimpleUsbStringDescriptor( - LENGTH, WRONG, STRING))); - assertFalse(descriptor.equals(new SimpleUsbStringDescriptor( - LENGTH, DESCRIPTOR_TYPE, "wrong"))); - } - - /** - * Tests the {@link SimpleUsbStringDescriptor#toString()} method. - * - * @throws UnsupportedEncodingException - * When system does not support UTF-16LE encoding. - */ - @Test - public void testToString() throws UnsupportedEncodingException - { - assertEquals(descriptor.getString(), descriptor.toString()); - } -} diff --git a/src/test/java/org/libusb4java/mocks/PollfdListenerMock.java b/src/test/java/org/usb4java/mocks/PollfdListenerMock.java similarity index 95% rename from src/test/java/org/libusb4java/mocks/PollfdListenerMock.java rename to src/test/java/org/usb4java/mocks/PollfdListenerMock.java index 2e042ab..ce438dd 100644 --- a/src/test/java/org/libusb4java/mocks/PollfdListenerMock.java +++ b/src/test/java/org/usb4java/mocks/PollfdListenerMock.java @@ -2,11 +2,11 @@ * Copyright (C) 2013 Klaus Reimer * See LICENSE.md for licensing information. */ -package org.libusb4java.mocks; +package org.usb4java.mocks; import java.io.FileDescriptor; -import org.libusb4java.PollfdListener; +import org.usb4java.PollfdListener; /** * A mocked pollfd listener implementation. diff --git a/src/test/java/org/usb4java/test/TCKRunner.java b/src/test/java/org/usb4java/test/TCKRunner.java deleted file mode 100644 index a89e934..0000000 --- a/src/test/java/org/usb4java/test/TCKRunner.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2013 Klaus Reimer - * See LICENSE.md for licensing information. - */ - -package org.usb4java.test; - -import org.junit.internal.AssumptionViolatedException; -import org.junit.internal.runners.JUnit38ClassRunner; -import org.junit.runner.Description; -import org.junit.runner.manipulation.Filter; -import org.junit.runner.manipulation.NoTestsRemainException; - -/** - * Runner for TCK tests. TCK tests are only run when the property TCK_TESTS - * is set. - * - * @author Klaus Reimer (k@ailis.de) - */ -public class TCKRunner extends JUnit38ClassRunner -{ - /** - * Constructor. - * - * @param testClass - * The test class. - * @throws NoTestsRemainException - * When no tests are to be run in this test class. - */ - public TCKRunner(final Class testClass) throws NoTestsRemainException - { - super(testClass); - filter(new Filter() - { - @Override - public boolean shouldRun(Description description) - { - try - { - UsbAssume.assumeTckTestsEnabled(); - return true; - } - catch (AssumptionViolatedException e) - { - return false; - } - } - - @Override - public String describe() - { - return "TCK tests only when enabled"; - } - }); - } -} diff --git a/src/test/java/org/libusb4java/utils/DescriptorUtilsTest.java b/src/test/java/org/usb4java/utils/DescriptorUtilsTest.java similarity index 97% rename from src/test/java/org/libusb4java/utils/DescriptorUtilsTest.java rename to src/test/java/org/usb4java/utils/DescriptorUtilsTest.java index 8cea540..55b50bd 100644 --- a/src/test/java/org/libusb4java/utils/DescriptorUtilsTest.java +++ b/src/test/java/org/usb4java/utils/DescriptorUtilsTest.java @@ -3,7 +3,7 @@ * See LICENSE.md for licensing information. */ -package org.libusb4java.utils; +package org.usb4java.utils; import static org.junit.Assert.assertEquals; @@ -11,7 +11,8 @@ import java.lang.reflect.Constructor; import java.nio.ByteBuffer; import org.junit.Test; -import org.libusb4java.LibUsb; +import org.usb4java.LibUsb; +import org.usb4java.utils.DescriptorUtils; /** * Tests the {@link DescriptorUtils} class. diff --git a/src/test/resources/javax.usb-1.0.sig b/src/test/resources/javax.usb-1.0.sig deleted file mode 100755 index 0218c0c..0000000 --- a/src/test/resources/javax.usb-1.0.sig +++ /dev/null @@ -1,497 +0,0 @@ -1 javax.usb.UsbAbortException extends javax.usb.UsbException -{ - 1 javax.usb.UsbAbortException (java.lang.String) - 1 javax.usb.UsbAbortException () -} -1 javax.usb.UsbBabbleException extends javax.usb.UsbException -{ - 1 javax.usb.UsbBabbleException (java.lang.String) - 1 javax.usb.UsbBabbleException () -} -1 javax.usb.UsbBitStuffException extends javax.usb.UsbException -{ - 1 javax.usb.UsbBitStuffException (java.lang.String) - 1 javax.usb.UsbBitStuffException () -} -1 javax.usb.UsbClaimException extends javax.usb.UsbException -{ - 1 javax.usb.UsbClaimException (java.lang.String) - 1 javax.usb.UsbClaimException () -} -1537 javax.usb.UsbConfiguration -{ - 1025 boolean isActive () - 1025 java.util.List getUsbInterfaces () - 1025 javax.usb.UsbInterface getUsbInterface (byte) - 1025 boolean containsUsbInterface (byte) - 1025 javax.usb.UsbDevice getUsbDevice () - 1025 javax.usb.UsbConfigurationDescriptor getUsbConfigurationDescriptor () - 1025 java.lang.String getConfigurationString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException,javax.usb.UsbDisconnectedException -} -1537 javax.usb.UsbConfigurationDescriptor implements javax.usb.UsbDescriptor -{ - 1025 short wTotalLength () - 1025 byte bNumInterfaces () - 1025 byte bConfigurationValue () - 1025 byte iConfiguration () - 1025 byte bmAttributes () - 1025 byte bMaxPower () -} -1537 javax.usb.UsbConst -{ -} -1537 javax.usb.UsbControlIrp implements javax.usb.UsbIrp -{ - 1025 byte bmRequestType () - 1025 byte bRequest () - 1025 short wValue () - 1025 short wIndex () -} -1 javax.usb.UsbCRCException extends javax.usb.UsbException -{ - 1 javax.usb.UsbCRCException (java.lang.String) - 1 javax.usb.UsbCRCException () -} -1537 javax.usb.UsbDescriptor -{ - 1025 byte bLength () - 1025 byte bDescriptorType () -} -1537 javax.usb.UsbDevice -{ - 1025 javax.usb.UsbPort getParentUsbPort () throws javax.usb.UsbDisconnectedException - 1025 boolean isUsbHub () - 1025 java.lang.String getManufacturerString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException,javax.usb.UsbDisconnectedException - 1025 java.lang.String getSerialNumberString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException,javax.usb.UsbDisconnectedException - 1025 java.lang.String getProductString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException,javax.usb.UsbDisconnectedException - 1025 java.lang.Object getSpeed () - 1025 java.util.List getUsbConfigurations () - 1025 javax.usb.UsbConfiguration getUsbConfiguration (byte) - 1025 boolean containsUsbConfiguration (byte) - 1025 byte getActiveUsbConfigurationNumber () - 1025 javax.usb.UsbConfiguration getActiveUsbConfiguration () - 1025 boolean isConfigured () - 1025 javax.usb.UsbDeviceDescriptor getUsbDeviceDescriptor () - 1025 javax.usb.UsbStringDescriptor getUsbStringDescriptor (byte) throws javax.usb.UsbException,javax.usb.UsbDisconnectedException - 1025 java.lang.String getString (byte) throws javax.usb.UsbException,java.io.UnsupportedEncodingException,javax.usb.UsbDisconnectedException - 1025 void syncSubmit (javax.usb.UsbControlIrp) throws javax.usb.UsbException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void asyncSubmit (javax.usb.UsbControlIrp) throws javax.usb.UsbException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void syncSubmit (java.util.List) throws javax.usb.UsbException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void asyncSubmit (java.util.List) throws javax.usb.UsbException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 javax.usb.UsbControlIrp createUsbControlIrp (byte,byte,short,short) - 1025 void addUsbDeviceListener (javax.usb.event.UsbDeviceListener) - 1025 void removeUsbDeviceListener (javax.usb.event.UsbDeviceListener) -} -1537 javax.usb.UsbDeviceDescriptor implements javax.usb.UsbDescriptor -{ - 1025 short bcdUSB () - 1025 byte bDeviceClass () - 1025 byte bDeviceSubClass () - 1025 byte bDeviceProtocol () - 1025 byte bMaxPacketSize0 () - 1025 short idVendor () - 1025 short idProduct () - 1025 short bcdDevice () - 1025 byte iManufacturer () - 1025 byte iProduct () - 1025 byte iSerialNumber () - 1025 byte bNumConfigurations () -} -1 javax.usb.UsbDisconnectedException extends java.lang.RuntimeException -{ - 1 javax.usb.UsbDisconnectedException (java.lang.String) - 1 javax.usb.UsbDisconnectedException () -} -1537 javax.usb.UsbEndpoint -{ - 1025 javax.usb.UsbInterface getUsbInterface () - 1025 javax.usb.UsbEndpointDescriptor getUsbEndpointDescriptor () - 1025 byte getDirection () - 1025 byte getType () - 1025 javax.usb.UsbPipe getUsbPipe () -} -1537 javax.usb.UsbEndpointDescriptor implements javax.usb.UsbDescriptor -{ - 1025 byte bEndpointAddress () - 1025 byte bmAttributes () - 1025 short wMaxPacketSize () - 1025 byte bInterval () -} -1 javax.usb.UsbException extends java.lang.Exception -{ - 1 javax.usb.UsbException (java.lang.String) - 1 javax.usb.UsbException () -} -17 javax.usb.UsbHostManager extends java.lang.Object -{ - 2 javax.usb.UsbHostManager () - 9 javax.usb.UsbServices getUsbServices () throws javax.usb.UsbException,java.lang.SecurityException - 9 java.util.Properties getProperties () throws javax.usb.UsbException,java.lang.SecurityException - 10 javax.usb.UsbServices createUsbServices () throws javax.usb.UsbException,java.lang.SecurityException - 10 void setupProperties () throws javax.usb.UsbException,java.lang.SecurityException - 26 java.lang.String USBSERVICES_PROPERTY_NOT_DEFINED () - 26 java.lang.String USBSERVICES_CLASSNOTFOUNDEXCEPTION (java.lang.String) - 26 java.lang.String USBSERVICES_EXCEPTIONININITIALIZERERROR (java.lang.String) - 26 java.lang.String USBSERVICES_INSTANTIATIONEXCEPTION (java.lang.String) - 26 java.lang.String USBSERVICES_ILLEGALACCESSEXCEPTION (java.lang.String) - 26 java.lang.String USBSERVICES_CLASSCASTEXCEPTION (java.lang.String) -} -1537 javax.usb.UsbHub implements javax.usb.UsbDevice -{ - 1025 byte getNumberOfPorts () - 1025 java.util.List getUsbPorts () - 1025 javax.usb.UsbPort getUsbPort (byte) - 1025 java.util.List getAttachedUsbDevices () - 1025 boolean isRootUsbHub () -} -1537 javax.usb.UsbInterface -{ - 1025 void claim () throws javax.usb.UsbClaimException,javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbDisconnectedException - 1025 void claim (javax.usb.UsbInterfacePolicy) throws javax.usb.UsbClaimException,javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbDisconnectedException - 1025 void release () throws javax.usb.UsbClaimException,javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbDisconnectedException - 1025 boolean isClaimed () - 1025 boolean isActive () - 1025 int getNumSettings () - 1025 byte getActiveSettingNumber () throws javax.usb.UsbNotActiveException - 1025 javax.usb.UsbInterface getActiveSetting () throws javax.usb.UsbNotActiveException - 1025 javax.usb.UsbInterface getSetting (byte) - 1025 boolean containsSetting (byte) - 1025 java.util.List getSettings () - 1025 java.util.List getUsbEndpoints () - 1025 javax.usb.UsbEndpoint getUsbEndpoint (byte) - 1025 boolean containsUsbEndpoint (byte) - 1025 javax.usb.UsbConfiguration getUsbConfiguration () - 1025 javax.usb.UsbInterfaceDescriptor getUsbInterfaceDescriptor () - 1025 java.lang.String getInterfaceString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException,javax.usb.UsbDisconnectedException -} -1537 javax.usb.UsbInterfaceDescriptor implements javax.usb.UsbDescriptor -{ - 1025 byte bInterfaceNumber () - 1025 byte bAlternateSetting () - 1025 byte bNumEndpoints () - 1025 byte bInterfaceClass () - 1025 byte bInterfaceSubClass () - 1025 byte bInterfaceProtocol () - 1025 byte iInterface () -} -1537 javax.usb.UsbInterfacePolicy -{ - 1025 boolean forceClaim (javax.usb.UsbInterface) -} -1537 javax.usb.UsbIrp -{ - 1025 byte[] getData () - 1025 int getOffset () - 1025 int getLength () - 1025 int getActualLength () - 1025 void setData (byte[]) - 1025 void setData (byte[],int,int) - 1025 void setOffset (int) - 1025 void setLength (int) - 1025 void setActualLength (int) - 1025 boolean isUsbException () - 1025 javax.usb.UsbException getUsbException () - 1025 void setUsbException (javax.usb.UsbException) - 1025 boolean getAcceptShortPacket () - 1025 void setAcceptShortPacket (boolean) - 1025 boolean isComplete () - 1025 void setComplete (boolean) - 1025 void complete () - 1025 void waitUntilComplete () - 1025 void waitUntilComplete (long) -} -1 javax.usb.UsbNativeClaimException extends javax.usb.UsbClaimException -{ - 1 javax.usb.UsbNativeClaimException (java.lang.String) - 1 javax.usb.UsbNativeClaimException () -} -1 javax.usb.UsbNotActiveException extends java.lang.RuntimeException -{ - 1 javax.usb.UsbNotActiveException (java.lang.String) - 1 javax.usb.UsbNotActiveException () -} -1 javax.usb.UsbNotClaimedException extends java.lang.RuntimeException -{ - 1 javax.usb.UsbNotClaimedException (java.lang.String) - 1 javax.usb.UsbNotClaimedException () -} -1 javax.usb.UsbNotOpenException extends java.lang.RuntimeException -{ - 1 javax.usb.UsbNotOpenException (java.lang.String) - 1 javax.usb.UsbNotOpenException () -} -1 javax.usb.UsbPIDException extends javax.usb.UsbException -{ - 1 javax.usb.UsbPIDException (java.lang.String) - 1 javax.usb.UsbPIDException () -} -1537 javax.usb.UsbPipe -{ - 1025 void open () throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotClaimedException,javax.usb.UsbDisconnectedException - 1025 void close () throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,javax.usb.UsbDisconnectedException - 1025 boolean isActive () - 1025 boolean isOpen () - 1025 javax.usb.UsbEndpoint getUsbEndpoint () - 1025 int syncSubmit (byte[]) throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 javax.usb.UsbIrp asyncSubmit (byte[]) throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void syncSubmit (javax.usb.UsbIrp) throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void asyncSubmit (javax.usb.UsbIrp) throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void syncSubmit (java.util.List) throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void asyncSubmit (java.util.List) throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,java.lang.IllegalArgumentException,javax.usb.UsbDisconnectedException - 1025 void abortAllSubmissions () throws javax.usb.UsbNotActiveException,javax.usb.UsbNotOpenException,javax.usb.UsbDisconnectedException - 1025 javax.usb.UsbIrp createUsbIrp () - 1025 javax.usb.UsbControlIrp createUsbControlIrp (byte,byte,short,short) - 1025 void addUsbPipeListener (javax.usb.event.UsbPipeListener) - 1025 void removeUsbPipeListener (javax.usb.event.UsbPipeListener) -} -1 javax.usb.UsbPlatformException extends javax.usb.UsbException -{ - 1 javax.usb.UsbPlatformException (java.lang.String,int,java.lang.Exception) - 1 javax.usb.UsbPlatformException (int,java.lang.Exception) - 1 javax.usb.UsbPlatformException (java.lang.String,java.lang.Exception) - 1 javax.usb.UsbPlatformException (java.lang.String,int) - 1 javax.usb.UsbPlatformException (java.lang.Exception) - 1 javax.usb.UsbPlatformException (int) - 1 javax.usb.UsbPlatformException (java.lang.String) - 1 javax.usb.UsbPlatformException () - 1 java.lang.Exception getPlatformException () - 1 int getErrorCode () -} -1537 javax.usb.UsbPort -{ - 1025 byte getPortNumber () - 1025 javax.usb.UsbHub getUsbHub () - 1025 javax.usb.UsbDevice getUsbDevice () - 1025 boolean isUsbDeviceAttached () -} -1537 javax.usb.UsbServices -{ - 1025 javax.usb.UsbHub getRootUsbHub () throws javax.usb.UsbException,java.lang.SecurityException - 1025 void addUsbServicesListener (javax.usb.event.UsbServicesListener) - 1025 void removeUsbServicesListener (javax.usb.event.UsbServicesListener) - 1025 java.lang.String getApiVersion () - 1025 java.lang.String getImpVersion () - 1025 java.lang.String getImpDescription () -} -1 javax.usb.UsbShortPacketException extends javax.usb.UsbException -{ - 1 javax.usb.UsbShortPacketException (java.lang.String) - 1 javax.usb.UsbShortPacketException () -} -1 javax.usb.UsbStallException extends javax.usb.UsbException -{ - 1 javax.usb.UsbStallException (java.lang.String) - 1 javax.usb.UsbStallException () -} -1537 javax.usb.UsbStringDescriptor implements javax.usb.UsbDescriptor -{ - 1025 byte[] bString () - 1025 java.lang.String getString () throws java.io.UnsupportedEncodingException -} -1 javax.usb.Version extends java.lang.Object -{ - 1 javax.usb.Version () - 9 void main (java.lang.String[]) - 9 java.lang.String getApiVersion () - 9 java.lang.String getUsbVersion () -} -1 javax.usb.event.UsbDeviceDataEvent extends javax.usb.event.UsbDeviceEvent -{ - 1 javax.usb.event.UsbDeviceDataEvent (javax.usb.UsbDevice,javax.usb.UsbControlIrp) - 1 byte[] getData () - 1 javax.usb.UsbControlIrp getUsbControlIrp () -} -1 javax.usb.event.UsbDeviceErrorEvent extends javax.usb.event.UsbDeviceEvent -{ - 1 javax.usb.event.UsbDeviceErrorEvent (javax.usb.UsbDevice,javax.usb.UsbControlIrp) - 1 javax.usb.UsbException getUsbException () - 1 javax.usb.UsbControlIrp getUsbControlIrp () -} -1 javax.usb.event.UsbDeviceEvent extends java.util.EventObject -{ - 1 javax.usb.event.UsbDeviceEvent (javax.usb.UsbDevice) - 1 javax.usb.UsbDevice getUsbDevice () -} -1537 javax.usb.event.UsbDeviceListener implements java.util.EventListener -{ - 1025 void usbDeviceDetached (javax.usb.event.UsbDeviceEvent) - 1025 void errorEventOccurred (javax.usb.event.UsbDeviceErrorEvent) - 1025 void dataEventOccurred (javax.usb.event.UsbDeviceDataEvent) -} -1 javax.usb.event.UsbPipeDataEvent extends javax.usb.event.UsbPipeEvent -{ - 1 javax.usb.event.UsbPipeDataEvent (javax.usb.UsbPipe,javax.usb.UsbIrp) - 1 javax.usb.event.UsbPipeDataEvent (javax.usb.UsbPipe,byte[],int) - 1 byte[] getData () - 1 int getActualLength () -} -1 javax.usb.event.UsbPipeErrorEvent extends javax.usb.event.UsbPipeEvent -{ - 1 javax.usb.event.UsbPipeErrorEvent (javax.usb.UsbPipe,javax.usb.UsbIrp) - 1 javax.usb.event.UsbPipeErrorEvent (javax.usb.UsbPipe,javax.usb.UsbException) - 1 javax.usb.UsbException getUsbException () -} -1 javax.usb.event.UsbPipeEvent extends java.util.EventObject -{ - 1 javax.usb.event.UsbPipeEvent (javax.usb.UsbPipe,javax.usb.UsbIrp) - 1 javax.usb.event.UsbPipeEvent (javax.usb.UsbPipe) - 1 javax.usb.UsbPipe getUsbPipe () - 1 boolean hasUsbIrp () - 1 javax.usb.UsbIrp getUsbIrp () -} -1537 javax.usb.event.UsbPipeListener implements java.util.EventListener -{ - 1025 void errorEventOccurred (javax.usb.event.UsbPipeErrorEvent) - 1025 void dataEventOccurred (javax.usb.event.UsbPipeDataEvent) -} -1 javax.usb.event.UsbServicesEvent extends java.util.EventObject -{ - 1 javax.usb.event.UsbServicesEvent (javax.usb.UsbServices,javax.usb.UsbDevice) - 1 javax.usb.UsbServices getUsbServices () - 1 javax.usb.UsbDevice getUsbDevice () -} -1537 javax.usb.event.UsbServicesListener implements java.util.EventListener -{ - 1025 void usbDeviceAttached (javax.usb.event.UsbServicesEvent) - 1025 void usbDeviceDetached (javax.usb.event.UsbServicesEvent) -} -1 javax.usb.util.DefaultUsbControlIrp extends javax.usb.util.DefaultUsbIrp implements javax.usb.UsbControlIrp -{ - 1 javax.usb.util.DefaultUsbControlIrp (byte[],int,int,boolean,byte,byte,short,short) - 1 javax.usb.util.DefaultUsbControlIrp (byte,byte,short,short) - 1 byte bmRequestType () - 1 byte bRequest () - 1 short wValue () - 1 short wIndex () - 1 short wLength () -} -1 javax.usb.util.DefaultUsbIrp extends java.lang.Object implements javax.usb.UsbIrp -{ - 1 javax.usb.util.DefaultUsbIrp (byte[],int,int,boolean) - 1 javax.usb.util.DefaultUsbIrp (byte[]) - 1 javax.usb.util.DefaultUsbIrp () - 1 byte[] getData () - 1 int getOffset () - 1 int getLength () - 1 int getActualLength () - 1 void setData (byte[],int,int) throws java.lang.IllegalArgumentException - 1 void setData (byte[]) throws java.lang.IllegalArgumentException - 1 void setOffset (int) throws java.lang.IllegalArgumentException - 1 void setLength (int) throws java.lang.IllegalArgumentException - 1 void setActualLength (int) throws java.lang.IllegalArgumentException - 1 boolean isUsbException () - 1 javax.usb.UsbException getUsbException () - 1 void setUsbException (javax.usb.UsbException) - 1 boolean getAcceptShortPacket () - 1 void setAcceptShortPacket (boolean) - 1 boolean isComplete () - 1 void setComplete (boolean) - 1 void complete () - 1 void waitUntilComplete () - 1 void waitUntilComplete (long) -} -1 javax.usb.util.StandardRequest extends java.lang.Object -{ - 1 javax.usb.util.StandardRequest (javax.usb.UsbDevice) - 1 void clearFeature (byte,short,short) throws javax.usb.UsbException,java.lang.IllegalArgumentException - 1 byte getConfiguration () throws javax.usb.UsbException - 1 int getDescriptor (byte,byte,short,byte[]) throws javax.usb.UsbException - 1 byte getInterface (short) throws javax.usb.UsbException - 1 short getStatus (byte,short) throws javax.usb.UsbException,java.lang.IllegalArgumentException - 1 void setAddress (short) throws javax.usb.UsbException - 1 void setConfiguration (short) throws javax.usb.UsbException - 1 int setDescriptor (byte,byte,short,byte[]) throws javax.usb.UsbException - 1 void setFeature (byte,short,short) throws javax.usb.UsbException,java.lang.IllegalArgumentException - 1 void setInterface (short,short) throws javax.usb.UsbException - 1 short synchFrame (short) throws javax.usb.UsbException - 9 void clearFeature (javax.usb.UsbDevice,byte,short,short) throws javax.usb.UsbException,java.lang.IllegalArgumentException - 9 byte getConfiguration (javax.usb.UsbDevice) throws javax.usb.UsbException - 9 int getDescriptor (javax.usb.UsbDevice,byte,byte,short,byte[]) throws javax.usb.UsbException - 9 byte getInterface (javax.usb.UsbDevice,short) throws javax.usb.UsbException - 9 short getStatus (javax.usb.UsbDevice,byte,short) throws javax.usb.UsbException,java.lang.IllegalArgumentException - 9 void setAddress (javax.usb.UsbDevice,short) throws javax.usb.UsbException - 9 void setConfiguration (javax.usb.UsbDevice,short) throws javax.usb.UsbException - 9 int setDescriptor (javax.usb.UsbDevice,byte,byte,short,byte[]) throws javax.usb.UsbException - 9 void setFeature (javax.usb.UsbDevice,byte,short,short) throws javax.usb.UsbException,java.lang.IllegalArgumentException - 9 void setInterface (javax.usb.UsbDevice,short,short) throws javax.usb.UsbException - 9 short synchFrame (javax.usb.UsbDevice,short) throws javax.usb.UsbException - 12 void checkRecipient (byte) throws java.lang.IllegalArgumentException -} -1 javax.usb.util.UsbUtil extends java.lang.Object -{ - 1 javax.usb.util.UsbUtil () - 9 short unsignedShort (byte) - 9 int unsignedInt (byte) - 9 int unsignedInt (short) - 9 long unsignedLong (byte) - 9 long unsignedLong (short) - 9 long unsignedLong (int) - 9 short toShort (byte,byte) - 9 int toInt (byte,byte,byte,byte) - 9 long toLong (byte,byte,byte,byte,byte,byte,byte,byte) - 9 int toInt (short,short) - 9 long toLong (short,short,short,short) - 9 long toLong (int,int) - 9 java.lang.String toHexString (byte) - 9 java.lang.String toHexString (short) - 9 java.lang.String toHexString (int) - 9 java.lang.String toHexString (long) - 9 java.lang.String toHexString (long,char,int,int) - 9 java.lang.String toHexString (java.lang.String,byte[],int) - 9 java.lang.String toHexString (java.lang.String,short[],int) - 9 java.lang.String toHexString (java.lang.String,int[],int) - 9 java.lang.String toHexString (java.lang.String,long[],int) - 9 java.lang.String toHexString (java.lang.String,byte[]) - 9 java.lang.String toHexString (java.lang.String,short[]) - 9 java.lang.String toHexString (java.lang.String,int[]) - 9 java.lang.String toHexString (java.lang.String,long[]) - 9 java.lang.String getSpeedString (java.lang.Object) - 9 javax.usb.UsbDevice synchronizedUsbDevice (javax.usb.UsbDevice) - 9 javax.usb.UsbPipe synchronizedUsbPipe (javax.usb.UsbPipe) -} -9 javax.usb.util.UsbUtil$SynchronizedUsbDevice extends java.lang.Object implements javax.usb.UsbDevice -{ - 1 javax.usb.util.UsbUtil$SynchronizedUsbDevice (javax.usb.UsbDevice) - 1 javax.usb.UsbPort getParentUsbPort () - 1 boolean isUsbHub () - 1 java.lang.String getManufacturerString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException - 1 java.lang.String getSerialNumberString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException - 1 java.lang.String getProductString () throws javax.usb.UsbException,java.io.UnsupportedEncodingException - 1 java.lang.Object getSpeed () - 1 java.util.List getUsbConfigurations () - 1 javax.usb.UsbConfiguration getUsbConfiguration (byte) - 1 boolean containsUsbConfiguration (byte) - 1 byte getActiveUsbConfigurationNumber () - 1 javax.usb.UsbConfiguration getActiveUsbConfiguration () - 1 boolean isConfigured () - 1 javax.usb.UsbDeviceDescriptor getUsbDeviceDescriptor () - 1 javax.usb.UsbStringDescriptor getUsbStringDescriptor (byte) throws javax.usb.UsbException - 1 java.lang.String getString (byte) throws javax.usb.UsbException,java.io.UnsupportedEncodingException - 1 void syncSubmit (javax.usb.UsbControlIrp) throws javax.usb.UsbException - 1 void asyncSubmit (javax.usb.UsbControlIrp) throws javax.usb.UsbException - 1 void syncSubmit (java.util.List) throws javax.usb.UsbException - 1 void asyncSubmit (java.util.List) throws javax.usb.UsbException - 1 javax.usb.UsbControlIrp createUsbControlIrp (byte,byte,short,short) - 1 void addUsbDeviceListener (javax.usb.event.UsbDeviceListener) - 1 void removeUsbDeviceListener (javax.usb.event.UsbDeviceListener) -} -9 javax.usb.util.UsbUtil$SynchronizedUsbPipe extends java.lang.Object implements javax.usb.UsbPipe -{ - 1 javax.usb.util.UsbUtil$SynchronizedUsbPipe (javax.usb.UsbPipe) - 1 void open () throws javax.usb.UsbException,javax.usb.UsbNotActiveException,javax.usb.UsbNotClaimedException - 1 void close () throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 boolean isActive () - 1 boolean isOpen () - 1 javax.usb.UsbEndpoint getUsbEndpoint () - 1 int syncSubmit (byte[]) throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 javax.usb.UsbIrp asyncSubmit (byte[]) throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 void syncSubmit (javax.usb.UsbIrp) throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 void asyncSubmit (javax.usb.UsbIrp) throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 void syncSubmit (java.util.List) throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 void asyncSubmit (java.util.List) throws javax.usb.UsbException,javax.usb.UsbNotOpenException - 1 void abortAllSubmissions () throws javax.usb.UsbNotOpenException - 1 javax.usb.UsbIrp createUsbIrp () - 1 javax.usb.UsbControlIrp createUsbControlIrp (byte,byte,short,short) - 1 void addUsbPipeListener (javax.usb.event.UsbPipeListener) - 1 void removeUsbPipeListener (javax.usb.event.UsbPipeListener) -} diff --git a/src/test/resources/javax.usb.properties b/src/test/resources/javax.usb.properties deleted file mode 100644 index d34a60b..0000000 --- a/src/test/resources/javax.usb.properties +++ /dev/null @@ -1 +0,0 @@ -javax.usb.services = org.usb4java.Services