diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0c0b5c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.gradle +.settings +.project +.classpath +.project +.maven +bin +build diff --git a/java/LGPL.txt b/LGPL.txt similarity index 98% rename from java/LGPL.txt rename to LGPL.txt index 5faba9d..5ab7695 100644 --- a/java/LGPL.txt +++ b/LGPL.txt @@ -1,504 +1,504 @@ - 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! - - + 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/build.gradle b/build.gradle new file mode 100644 index 0000000..136db4b --- /dev/null +++ b/build.gradle @@ -0,0 +1,22 @@ +apply plugin: 'java' +apply plugin: 'cpp' +apply plugin: 'maven' +apply plugin: 'eclipse' + +group = 'com.github.boukefalos' +archivesBaseName = 'jlibusb' +version = '0.5.7' + +repositories { + mavenCentral() +} + +dependencies { + testCompile 'junit:junit:4.11' +} + +uploadArchives { + repositories.mavenDeployer { + repository(url: uri('.maven')) + } +} \ No newline at end of file diff --git a/java/.settings/org.eclipse.jdt.ui.prefs b/java/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 1b61afb..0000000 --- a/java/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Thu Oct 06 09:12:32 CEST 2005 -eclipse.preferences.version=1 -internal.default.compliance=default diff --git a/java/META-INF/MANIFEST.MF b/java/META-INF/MANIFEST.MF deleted file mode 100644 index 67ec8ca..0000000 --- a/java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,13 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Java libusb-1.0 wrapper -Bundle-SymbolicName: ch.ntb.inf.libusbJava -Bundle-Version: 1.0.2 -Bundle-Vendor: libusbjava.sourceforge.net -Require-Bundle: org.junit4 -Export-Package: ch.ntb.inf.libusbJava, - ch.ntb.inf.libusbJava.logger, - ch.ntb.inf.libusbJava.testApp, - ch.ntb.inf.libusbJava.usbView -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Import-Package: ch.ntb.inf.libusbJava diff --git a/java/src/.configure b/java/src/.configure deleted file mode 100644 index ddcfdbe..0000000 --- a/java/src/.configure +++ /dev/null @@ -1,6 +0,0 @@ -# enable or disable logging -ch.ntb.inf.libusbJava/debug = true -# set and configure individual loggers here -# the format is: projectName/debug/ = / -ch.ntb.inf.libusbJava/debug/logger0 = ch.ntb.inf.libusbJava/OFF -ch.ntb.inf.libusbJava/debug/logger1 = ch.ntb.inf.libusbJava.test/INFO diff --git a/LibusbJava/libusb/MinGW32/dll/libusb-1.0.dll b/lib/MinGW32/dll/libusb-1.0.dll similarity index 100% rename from LibusbJava/libusb/MinGW32/dll/libusb-1.0.dll rename to lib/MinGW32/dll/libusb-1.0.dll diff --git a/LibusbJava/libusb/MinGW32/dll/libusb-1.0.dll.a b/lib/MinGW32/dll/libusb-1.0.dll.a similarity index 100% rename from LibusbJava/libusb/MinGW32/dll/libusb-1.0.dll.a rename to lib/MinGW32/dll/libusb-1.0.dll.a diff --git a/LibusbJava/libusb/MinGW32/static/libusb-1.0.a b/lib/MinGW32/static/libusb-1.0.a similarity index 100% rename from LibusbJava/libusb/MinGW32/static/libusb-1.0.a rename to lib/MinGW32/static/libusb-1.0.a diff --git a/LibusbJava/libusb/MinGW64/dll/libusb-1.0.dll b/lib/MinGW64/dll/libusb-1.0.dll similarity index 100% rename from LibusbJava/libusb/MinGW64/dll/libusb-1.0.dll rename to lib/MinGW64/dll/libusb-1.0.dll diff --git a/LibusbJava/libusb/MinGW64/dll/libusb-1.0.dll.a b/lib/MinGW64/dll/libusb-1.0.dll.a similarity index 100% rename from LibusbJava/libusb/MinGW64/dll/libusb-1.0.dll.a rename to lib/MinGW64/dll/libusb-1.0.dll.a diff --git a/LibusbJava/libusb/MinGW64/static/libusb-1.0.a b/lib/MinGW64/static/libusb-1.0.a similarity index 100% rename from LibusbJava/libusb/MinGW64/static/libusb-1.0.a rename to lib/MinGW64/static/libusb-1.0.a diff --git a/LibusbJava/libusb/libusb-1.0.def b/lib/libusb-1.0.def similarity index 97% rename from LibusbJava/libusb/libusb-1.0.def rename to lib/libusb-1.0.def index 6ce2111..3aba343 100644 --- a/LibusbJava/libusb/libusb-1.0.def +++ b/lib/libusb-1.0.def @@ -1,126 +1,126 @@ -LIBRARY "libusb-1.0.dll" -EXPORTS - libusb_alloc_transfer - libusb_alloc_transfer@4 = libusb_alloc_transfer - libusb_attach_kernel_driver - libusb_attach_kernel_driver@8 = libusb_attach_kernel_driver - libusb_bulk_transfer - libusb_bulk_transfer@24 = libusb_bulk_transfer - libusb_cancel_transfer - libusb_cancel_transfer@4 = libusb_cancel_transfer - libusb_claim_interface - libusb_claim_interface@8 = libusb_claim_interface - libusb_clear_halt - libusb_clear_halt@8 = libusb_clear_halt - libusb_close - libusb_close@4 = libusb_close - libusb_control_transfer - libusb_control_transfer@32 = libusb_control_transfer - libusb_detach_kernel_driver - libusb_detach_kernel_driver@8 = libusb_detach_kernel_driver - libusb_error_name - libusb_error_name@4 = libusb_error_name - libusb_event_handler_active - libusb_event_handler_active@4 = libusb_event_handler_active - libusb_event_handling_ok - libusb_event_handling_ok@4 = libusb_event_handling_ok - libusb_exit - libusb_exit@4 = libusb_exit - libusb_free_config_descriptor - libusb_free_config_descriptor@4 = libusb_free_config_descriptor - libusb_free_device_list - libusb_free_device_list@8 = libusb_free_device_list - libusb_free_transfer - libusb_free_transfer@4 = libusb_free_transfer - libusb_get_active_config_descriptor - libusb_get_active_config_descriptor@8 = libusb_get_active_config_descriptor - libusb_get_bus_number - libusb_get_bus_number@4 = libusb_get_bus_number - libusb_get_config_descriptor - libusb_get_config_descriptor@12 = libusb_get_config_descriptor - libusb_get_config_descriptor_by_value - libusb_get_config_descriptor_by_value@12 = libusb_get_config_descriptor_by_value - libusb_get_configuration - libusb_get_configuration@8 = libusb_get_configuration - libusb_get_device - libusb_get_device@4 = libusb_get_device - libusb_get_device_address - libusb_get_device_address@4 = libusb_get_device_address - libusb_get_device_descriptor - libusb_get_device_descriptor@8 = libusb_get_device_descriptor - libusb_get_device_list - libusb_get_device_list@8 = libusb_get_device_list - libusb_get_device_speed - libusb_get_device_speed@4 = libusb_get_device_speed - libusb_get_max_iso_packet_size - libusb_get_max_iso_packet_size@8 = libusb_get_max_iso_packet_size - libusb_get_max_packet_size - libusb_get_max_packet_size@8 = libusb_get_max_packet_size - libusb_get_next_timeout - libusb_get_next_timeout@8 = libusb_get_next_timeout - libusb_get_parent - libusb_get_parent@4 = libusb_get_parent - libusb_get_pollfds - libusb_get_pollfds@4 = libusb_get_pollfds - libusb_get_port_number - libusb_get_port_number@4 = libusb_get_port_number - libusb_get_port_path - libusb_get_port_path@16 = libusb_get_port_path - libusb_get_string_descriptor_ascii - libusb_get_string_descriptor_ascii@16 = libusb_get_string_descriptor_ascii - libusb_get_version - libusb_get_version@0 = libusb_get_version - libusb_handle_events - libusb_handle_events@4 = libusb_handle_events - libusb_handle_events_completed - libusb_handle_events_completed@8 = libusb_handle_events_completed - libusb_handle_events_locked - libusb_handle_events_locked@8 = libusb_handle_events_locked - libusb_handle_events_timeout - libusb_handle_events_timeout@8 = libusb_handle_events_timeout - libusb_handle_events_timeout_completed - libusb_handle_events_timeout_completed@12 = libusb_handle_events_timeout_completed - libusb_has_capability - libusb_has_capability@4 = libusb_has_capability - libusb_init - libusb_init@4 = libusb_init - libusb_interrupt_transfer - libusb_interrupt_transfer@24 = libusb_interrupt_transfer - libusb_kernel_driver_active - libusb_kernel_driver_active@8 = libusb_kernel_driver_active - libusb_lock_event_waiters - libusb_lock_event_waiters@4 = libusb_lock_event_waiters - libusb_lock_events - libusb_lock_events@4 = libusb_lock_events - libusb_open - libusb_open@8 = libusb_open - libusb_open_device_with_vid_pid - libusb_open_device_with_vid_pid@12 = libusb_open_device_with_vid_pid - libusb_pollfds_handle_timeouts - libusb_pollfds_handle_timeouts@4 = libusb_pollfds_handle_timeouts - libusb_ref_device - libusb_ref_device@4 = libusb_ref_device - libusb_release_interface - libusb_release_interface@8 = libusb_release_interface - libusb_reset_device - libusb_reset_device@4 = libusb_reset_device - libusb_set_configuration - libusb_set_configuration@8 = libusb_set_configuration - libusb_set_debug - libusb_set_debug@8 = libusb_set_debug - libusb_set_interface_alt_setting - libusb_set_interface_alt_setting@12 = libusb_set_interface_alt_setting - libusb_set_pollfd_notifiers - libusb_set_pollfd_notifiers@16 = libusb_set_pollfd_notifiers - libusb_submit_transfer - libusb_submit_transfer@4 = libusb_submit_transfer - libusb_try_lock_events - libusb_try_lock_events@4 = libusb_try_lock_events - libusb_unlock_event_waiters - libusb_unlock_event_waiters@4 = libusb_unlock_event_waiters - libusb_unlock_events - libusb_unlock_events@4 = libusb_unlock_events - libusb_unref_device - libusb_unref_device@4 = libusb_unref_device - libusb_wait_for_event - libusb_wait_for_event@8 = libusb_wait_for_event +LIBRARY "libusb-1.0.dll" +EXPORTS + libusb_alloc_transfer + libusb_alloc_transfer@4 = libusb_alloc_transfer + libusb_attach_kernel_driver + libusb_attach_kernel_driver@8 = libusb_attach_kernel_driver + libusb_bulk_transfer + libusb_bulk_transfer@24 = libusb_bulk_transfer + libusb_cancel_transfer + libusb_cancel_transfer@4 = libusb_cancel_transfer + libusb_claim_interface + libusb_claim_interface@8 = libusb_claim_interface + libusb_clear_halt + libusb_clear_halt@8 = libusb_clear_halt + libusb_close + libusb_close@4 = libusb_close + libusb_control_transfer + libusb_control_transfer@32 = libusb_control_transfer + libusb_detach_kernel_driver + libusb_detach_kernel_driver@8 = libusb_detach_kernel_driver + libusb_error_name + libusb_error_name@4 = libusb_error_name + libusb_event_handler_active + libusb_event_handler_active@4 = libusb_event_handler_active + libusb_event_handling_ok + libusb_event_handling_ok@4 = libusb_event_handling_ok + libusb_exit + libusb_exit@4 = libusb_exit + libusb_free_config_descriptor + libusb_free_config_descriptor@4 = libusb_free_config_descriptor + libusb_free_device_list + libusb_free_device_list@8 = libusb_free_device_list + libusb_free_transfer + libusb_free_transfer@4 = libusb_free_transfer + libusb_get_active_config_descriptor + libusb_get_active_config_descriptor@8 = libusb_get_active_config_descriptor + libusb_get_bus_number + libusb_get_bus_number@4 = libusb_get_bus_number + libusb_get_config_descriptor + libusb_get_config_descriptor@12 = libusb_get_config_descriptor + libusb_get_config_descriptor_by_value + libusb_get_config_descriptor_by_value@12 = libusb_get_config_descriptor_by_value + libusb_get_configuration + libusb_get_configuration@8 = libusb_get_configuration + libusb_get_device + libusb_get_device@4 = libusb_get_device + libusb_get_device_address + libusb_get_device_address@4 = libusb_get_device_address + libusb_get_device_descriptor + libusb_get_device_descriptor@8 = libusb_get_device_descriptor + libusb_get_device_list + libusb_get_device_list@8 = libusb_get_device_list + libusb_get_device_speed + libusb_get_device_speed@4 = libusb_get_device_speed + libusb_get_max_iso_packet_size + libusb_get_max_iso_packet_size@8 = libusb_get_max_iso_packet_size + libusb_get_max_packet_size + libusb_get_max_packet_size@8 = libusb_get_max_packet_size + libusb_get_next_timeout + libusb_get_next_timeout@8 = libusb_get_next_timeout + libusb_get_parent + libusb_get_parent@4 = libusb_get_parent + libusb_get_pollfds + libusb_get_pollfds@4 = libusb_get_pollfds + libusb_get_port_number + libusb_get_port_number@4 = libusb_get_port_number + libusb_get_port_path + libusb_get_port_path@16 = libusb_get_port_path + libusb_get_string_descriptor_ascii + libusb_get_string_descriptor_ascii@16 = libusb_get_string_descriptor_ascii + libusb_get_version + libusb_get_version@0 = libusb_get_version + libusb_handle_events + libusb_handle_events@4 = libusb_handle_events + libusb_handle_events_completed + libusb_handle_events_completed@8 = libusb_handle_events_completed + libusb_handle_events_locked + libusb_handle_events_locked@8 = libusb_handle_events_locked + libusb_handle_events_timeout + libusb_handle_events_timeout@8 = libusb_handle_events_timeout + libusb_handle_events_timeout_completed + libusb_handle_events_timeout_completed@12 = libusb_handle_events_timeout_completed + libusb_has_capability + libusb_has_capability@4 = libusb_has_capability + libusb_init + libusb_init@4 = libusb_init + libusb_interrupt_transfer + libusb_interrupt_transfer@24 = libusb_interrupt_transfer + libusb_kernel_driver_active + libusb_kernel_driver_active@8 = libusb_kernel_driver_active + libusb_lock_event_waiters + libusb_lock_event_waiters@4 = libusb_lock_event_waiters + libusb_lock_events + libusb_lock_events@4 = libusb_lock_events + libusb_open + libusb_open@8 = libusb_open + libusb_open_device_with_vid_pid + libusb_open_device_with_vid_pid@12 = libusb_open_device_with_vid_pid + libusb_pollfds_handle_timeouts + libusb_pollfds_handle_timeouts@4 = libusb_pollfds_handle_timeouts + libusb_ref_device + libusb_ref_device@4 = libusb_ref_device + libusb_release_interface + libusb_release_interface@8 = libusb_release_interface + libusb_reset_device + libusb_reset_device@4 = libusb_reset_device + libusb_set_configuration + libusb_set_configuration@8 = libusb_set_configuration + libusb_set_debug + libusb_set_debug@8 = libusb_set_debug + libusb_set_interface_alt_setting + libusb_set_interface_alt_setting@12 = libusb_set_interface_alt_setting + libusb_set_pollfd_notifiers + libusb_set_pollfd_notifiers@16 = libusb_set_pollfd_notifiers + libusb_submit_transfer + libusb_submit_transfer@4 = libusb_submit_transfer + libusb_try_lock_events + libusb_try_lock_events@4 = libusb_try_lock_events + libusb_unlock_event_waiters + libusb_unlock_event_waiters@4 = libusb_unlock_event_waiters + libusb_unlock_events + libusb_unlock_events@4 = libusb_unlock_events + libusb_unref_device + libusb_unref_device@4 = libusb_unref_device + libusb_wait_for_event + libusb_wait_for_event@8 = libusb_wait_for_event diff --git a/LibusbJava/LibusbJava.cpp b/src/main/cpp/LibusbJava.cpp similarity index 97% rename from LibusbJava/LibusbJava.cpp rename to src/main/cpp/LibusbJava.cpp index 0403a5f..61ee3fb 100644 --- a/LibusbJava/LibusbJava.cpp +++ b/src/main/cpp/LibusbJava.cpp @@ -1,2560 +1,2560 @@ -/*! \file - * \brief Java libusb1.0 wrapper - * - * \copyright 2010-2012 NTB Interstate University of Applied Sciences of Technology Buchs - * This libary is covered by the LGPL, read LGPL.txt for details - * - * \author Roger Millischer (original author) - * \author Ueli Niederer (modifications and enhancements) - * - * \todo Currently all the pointers and handles passed to and received from libusb are coded - * in long values to get them in JVM. - * Clebert Suconic ( http://planet.jboss.org/post/pointers_in_jni_c ) suggests a - * possibly more elegant way to deal with this issue: - * Make use of the ByteBuffer-Class delivered by with the native IO package. - * (java.nio). As this class is made to store the start pointer to native buffers - * we could create a "ByteBuffer" of length 0 where the start address represents - * e.g. the handle. This can be done using the following JNI Call: - * env->NewDirectByteBuffer(myPointer, 0); // size = 0, you don't want anyone to - * // change the data you are pointing to... - */ - -/******************************************************************************************** - * - * Includes - * - *******************************************************************************************/ -#include -#include -#include -#include -#include - -#ifdef DO_UNIT_TEST -# include - -# define TEST_CASE(name) static void name(CuTest *tc) -#endif - -#include - -#include - -#include "LibusbJava.h" -#include "objects/Usb_Device.h" - -//#define DEBUGON - -typedef struct JNIObject { - int (*connect)(JNIEnv *env); - void (*disconnect)(JNIEnv *env); -}tJNIObject; - -#define ERROR_JAVA_REFERENCES_NOT_LOADED -100 -#define ERROR_JAVA_WRONG_ENVIRONMENT -101 -#define ERROR_JAVA_ILEGAL_DEVICE_HANDLE -102 - -#define OBJ(name) { name ## _connect, name ## _disconnect } - -/*! \brief Structure holding all the global information needed. */ -typedef struct LUJ_Instance { - struct JNI{ -#ifdef DO_UNIT_TEST - int onLoadCalled; /*!< Set after OnLoad is called, reset after OnUnload was called. Only - used for unit tests */ -#endif - int refs_loaded; /*!< 0 if references are NOT loaded. */ - const tJNIObject * objects; /*!< Points to the table of connect/disconnect calls - that are perfomed while loading/unloading */ - }jni; -}tLUJ_Instance; - -/******************************************************************************************** - * - * Globals - * - *******************************************************************************************/ -/* if > 0 an LibusbJava specific error string is set*/ -static char *libusbJavaError = NULL; - -static const tJNIObject jniObjects[] = { - OBJ(Usb_Device), - { NULL, NULL} -}; -/******************************************************************************************** - * - * Macros - * - *******************************************************************************************/ -/* to set and clear LibusbJava specific errors*/ -#define setLibusbJavaError(error) libusbJavaError = error -#define clearLibusbJavaError() libusbJavaError = NULL - -/******************************************************************************************** - * - * Prototyp and define for callback-function - * - *******************************************************************************************/ -static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer); - -static void - LIBUSB_CALL fd_added_callback(int fd, short events, void *user_data); - -static void LIBUSB_CALL fd_removed_callback(int fd, void *user_data); - -/******************************************************************************************** - * - * Local helper functions - * - *******************************************************************************************/ -static __inline int ReferencesCheck(tLUJ_Instance *instance, JNIEnv *env); -static __inline int ReferencesLoad(tLUJ_Instance *instance, JNIEnv *env, const tJNIObject *objects); -static __inline void ReferencesUnload(tLUJ_Instance *instance, JNIEnv *env); -static __inline jbyteArray JNICALL to_byteArray(JNIEnv *env, const void *data, size_t len); -static __inline void JNICALL ThrowIfUnsuccessful(JNIEnv *env, int libusb_result); -static __inline void JNICALL ThrowLibusbError(JNIEnv *env, jint code); - -/******************************************************************************************** - * - * References - * - *******************************************************************************************/ -/* class references*/ -static jclass usb_devDescClazz, usb_confDescClazz, usb_intClazz, - usb_intDescClazz, usb_epDescClazz, usb_cb_clazz, usb_pollfd_clazz; - -/* method ID references*/ -static jmethodID usb_devDescMid, usb_confDescMid, usb_intMid, - usb_intDescMid, usb_epDescMid, usb_transfer_cb_Mid, - usb_fd_added_cb_Mid, usb_fd_removed_cb_Mid, usb_pollfd_Mid; - -/* field ID references*/ -/* usb_deviceDescriptor */ -static jfieldID usb_devDescFID_bLength, usb_devDescFID_bDescriptorType, - usb_devDescFID_bcdUSB, usb_devDescFID_bDeviceClass, - usb_devDescFID_bDeviceSubClass, usb_devDescFID_bDeviceProtocol, - usb_devDescFID_bMaxPacketSize0, usb_devDescFID_idVendor, - usb_devDescFID_idProduct, usb_devDescFID_bcdDevice, - usb_devDescFID_iManufacturer, usb_devDescFID_iProduct, - usb_devDescFID_iSerialNumber, usb_devDescFID_bNumConfigurations; -/* usb_configurationDescriptor*/ -static jfieldID usb_confDescFID_bLength, usb_confDescFID_bDescriptorType, - usb_confDescFID_wTotalLength, usb_confDescFID_bNumInterfaces, - usb_confDescFID_bConfigurationValue, usb_confDescFID_iConfiguration, - usb_confDescFID_bmAttributes, usb_confDescFID_MaxPower, - usb_confDescFID_interface_, usb_confDescFID_extra, - usb_confDescFID_extralen; -/* usb_interface*/ -static jfieldID usb_intFID_altsetting, usb_intFID_num_altsetting; -/* usb_intDesc*/ -static jfieldID usb_intDescFID_bLength, usb_intDescFID_bDescriptorType, - usb_intDescFID_bInterfaceNumber, usb_intDescFID_bAlternateSetting, - usb_intDescFID_bNumEndpoints, usb_intDescFID_bInterfaceClass, - usb_intDescFID_bInterfaceSubClass, usb_intDescFID_bInterfaceProtocol, - usb_intDescFID_iInterface, usb_intDescFID_endpoint, - usb_intDescFID_extra, usb_intDescFID_extralen; -/* usb_endpointDescriptor*/ -static jfieldID usb_epDescFID_bLength, usb_epDescFID_bDescriptorType, - usb_epDescFID_bEndpointAddress, usb_epDescFID_bmAttributes, - usb_epDescFID_wMaxPacketSize, usb_epDescFID_bInterval, - usb_epDescFID_bRefresh, usb_epDescFID_bSynchAddress, - usb_epDescFID_extra, usb_epDescFID_extralen; -/*Libusb_pollfd*/ -static jfieldID usb_pollfdFID_fd, usb_pollfdFID_events; - -#ifdef DO_UNIT_TEST - static struct TestContext - { - JNIEnv *env; - }test_context = { NULL }; - - # define TEST_CONTEXT() JNIEnv *env = test_context.env -#endif - -static tLUJ_Instance info = {{0}}; - -/******************************************************************************************** - * - * Library Events - * - *******************************************************************************************/ - -/*! \brief The VM calls JNI_OnLoad when the native library is loaded (for example, through - * System.loadLibrary). - * - * \see http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#JNI_OnLoad - * - * \return The JNI version needed by the native library (use constants as JNI_VERSION_X_Y). - */ -jint JNI_OnLoad(JavaVM *vm, void *reserved) -{ - JNIEnv* env = NULL; - -#ifdef DO_UNIT_TEST - info.jni.onLoadCalled = -1; -#endif - - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_1) != JNI_OK) { - return -1; - } - - ReferencesLoad(&info, env, jniObjects); - - return JNI_VERSION_1_1; -} - -#if defined(DO_UNIT_TEST) - TEST_CASE(JNI_OnLoad_test) - { - TEST_CONTEXT(); - - CuAssert(tc, "correct initialization", info.jni.onLoadCalled == 0); - info.jni.onLoadCalled=10; - - /* Load the LibusbJava1 class to force the initialization of the library */ - jclass clazz = env->FindClass("ch/ntb/inf/libusbJava/LibusbJava1"); - CuAssert(tc, "ch/ntb/inf/libusbJava/LibusbJava1 loaded", clazz != NULL); - - CuAssert(tc, "JNI_OnLoad was executed", info.jni.onLoadCalled != 0); - env->DeleteLocalRef(clazz); - - /* As garbage collection is not necessarily run after freeing a reference - * and there is no way to force the run of GC, we can't test this here. */ -// CuAssert(tc, "JNI_OnUnload was executed", info.jni.onLoadCalled == 0); - } -#endif - -/*! \brief The VM calls JNI_OnUnload when the class loader containing the native library is - * garbage collected. - * - * This function can be used to perform cleanup operations. Because this function is - * called in an unknown context (such as from a finalizer), the programmer should be - * conservative on using Java VM services, and refrain from arbitrary Java call-backs. - * - * \see http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#JNI_OnUnload - */ -void JNI_OnUnload(JavaVM *vm, void *reserved) -{ - JNIEnv* env = NULL; - - if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_1) == JNI_OK) { - ReferencesUnload(&info, env); - } - -#ifdef DO_UNIT_TEST - info.jni.onLoadCalled = 0; -#endif -} - -/******************************************************************************************** - * - * Methods - * - *******************************************************************************************/ - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_debug - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1debug( JNIEnv *env, jclass obj, jlong ctx, jint level) { - clearLibusbJavaError(); - libusb_context *context = NULL; - if (ctx) { - context = (libusb_context*) ((unsigned long) ctx); - } - libusb_set_debug(context, level); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_init - * Signature: ()J - ********************************************************************************************/ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1init( JNIEnv *env, jclass obj) { - int res; - libusb_context *context; - clearLibusbJavaError(); - - res = libusb_init(&context); - - #ifdef DEBUGON - printf("res = %i \n", res); - printf("env = %p\n", env); - printf("context = %p\n", &context); - #endif - - if (res != 0) - { - ThrowLibusbError(env, res); - return 0; - } - else - { - return (jlong) context; - } -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_exit - * Signature: (J)V - *******************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1exit(JNIEnv *env, jclass obj, jlong ctx) { - libusb_context *context = NULL; - clearLibusbJavaError(); - if (ctx) { - context = (libusb_context*) ((unsigned long) ctx); - } - libusb_exit(context); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_device_list - * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; - ********************************************************************************************/ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device_1list( JNIEnv *env, jclass obj, jlong ctx) { - libusb_device **devs; - libusb_context *context = (ctx != 0) ? (libusb_context*)ctx : NULL; - ssize_t cnt; - int res, a, i; - uint8_t c, h, e; - - if (ReferencesCheck(&info, env) != 0) return NULL; - - /* objects*/ - jobject root_usb_devObj, usb_devObj, usb_devObj_next, usb_devObj_prev, - usb_devDescObj, usb_confDescObj, usb_intObj, usb_intDescObj, - usb_epDescObj; - - jobjectArray usb_confDescObjArray, usb_intObjArray, usb_intDescObjArray, - usb_epDescObjArray; - clearLibusbJavaError(); - - libusb_config_descriptor *conf_desc; - - cnt = libusb_get_device_list(context, &devs); - if (cnt < 0) { - setLibusbJavaError("libusb_get_device_list: Error on Memory allocation"); - libusb_free_device_list(devs, 1); - return NULL; - } - else if (cnt == 0) { - libusb_free_device_list(devs, 1); - return NULL; - } - - usb_devObj = NULL; - usb_devObj_next = NULL; - usb_devObj_prev = NULL; - - /* create a new object for every device */ - for (i = 0; i < cnt; i++) { -#ifdef DEBUGON - printf("libusb_get_device_list: dev %u \n", i); -#endif - libusb_device_descriptor dev_desc; - res = libusb_get_device_descriptor(devs[i], &dev_desc); - - if (res) { - /* this shouldn't happen*/ - printf("\t libusb_get _device_list: dev %u coudn't read Devicedescriptor\n",i); - continue; - } - - if (dev_desc.bLength != 18) { - printf("Corrupt Devicedescriptor dev %d\n", i); - continue; - } - - usb_devObj = Usb_Device_create(env, devs[i], libusb_get_device_address(devs[i])); - if (usb_devObj == NULL) { - setLibusbJavaError("shared library error: Error NewObject (usb_devObj)"); - return NULL; - } - - /* If it's the root element (no previous elements available) we set the root value */ - if (usb_devObj_prev == NULL) { - root_usb_devObj = usb_devObj; - } - else { - /* If it's not the root element, simply enqueue the newly created device */ - Usb_Device_NextSet(env, usb_devObj_prev, usb_devObj); - } - - /* Fill the fields of the object */ - Usb_Device_NextSet(env, usb_devObj, usb_devObj_next); - Usb_Device_PrevSet(env, usb_devObj, usb_devObj_prev); - - /*device Descriptor*/ - usb_devDescObj = env->NewObject(usb_devDescClazz, usb_devDescMid); - if (!usb_devDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_devDescObj)"); - return NULL; - } - env->SetByteField(usb_devDescObj, usb_devDescFID_bLength, dev_desc.bLength); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDescriptorType, dev_desc.bDescriptorType); - env->SetShortField(usb_devDescObj, usb_devDescFID_bcdUSB, dev_desc.bcdUSB); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceClass, dev_desc.bDeviceClass); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceSubClass, dev_desc.bDeviceSubClass); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceProtocol, dev_desc.bDeviceProtocol); - env->SetByteField(usb_devDescObj, usb_devDescFID_bMaxPacketSize0, dev_desc.bMaxPacketSize0); - env->SetShortField(usb_devDescObj, usb_devDescFID_idVendor, dev_desc.idVendor); - env->SetShortField(usb_devDescObj, usb_devDescFID_idProduct, dev_desc.idProduct); - env->SetShortField(usb_devDescObj, usb_devDescFID_bcdDevice, dev_desc.bcdDevice); - env->SetByteField(usb_devDescObj, usb_devDescFID_iManufacturer, dev_desc.iManufacturer); - env->SetByteField(usb_devDescObj, usb_devDescFID_iProduct, dev_desc.iProduct); - env->SetByteField(usb_devDescObj, usb_devDescFID_iSerialNumber, dev_desc.iSerialNumber); - env->SetByteField(usb_devDescObj, usb_devDescFID_bNumConfigurations, dev_desc.bNumConfigurations); - // TODO @NIUE: Why a reference on itself?! And why should we use a field ID from the Usb_Device class - // for an instance of the Descriptor object? - // env->SetObjectField(usb_devDescObj, usb_devFID_descriptor, usb_devDescObj); - Usb_Device_DescriptorSet(env, usb_devObj, usb_devDescObj); - - /*configuration descriptor*/ - /*Loop through all of the configurations*/ - usb_confDescObjArray = (jobjectArray) env->NewObjectArray(dev_desc.bNumConfigurations, usb_confDescClazz, NULL); - if (!usb_confDescObjArray) { - setLibusbJavaError("shared library error: Error NewOjectArray"); - return NULL; - } - for (c = 0; c < dev_desc.bNumConfigurations; c++) { -#ifdef DEBUGON - printf("\t\tlibusb_get_device_list: configuration %u, Dev: %d \n", c, i); -#endif - res = libusb_get_config_descriptor(devs[i], c, &conf_desc); - if (res) { - continue; - } - usb_confDescObj = env->NewObject(usb_confDescClazz, usb_confDescMid); - if (!usb_confDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_confDescObjArray, c, usb_confDescObj);/*add it to the Array*/ - /*fill the fields*/ - env->SetByteField(usb_confDescObj, usb_confDescFID_bLength, conf_desc->bLength); - env->SetByteField(usb_confDescObj, usb_confDescFID_bDescriptorType, conf_desc->bDescriptorType); - env->SetShortField(usb_confDescObj, usb_confDescFID_wTotalLength, conf_desc->wTotalLength); - env->SetByteField(usb_confDescObj, usb_confDescFID_bNumInterfaces, conf_desc->bNumInterfaces); - env->SetByteField(usb_confDescObj, usb_confDescFID_bConfigurationValue, conf_desc->bConfigurationValue); - env->SetByteField(usb_confDescObj, usb_confDescFID_iConfiguration, conf_desc->iConfiguration); - env->SetByteField(usb_confDescObj, usb_confDescFID_bmAttributes, conf_desc->bmAttributes); - env->SetByteField(usb_confDescObj, usb_confDescFID_MaxPower, conf_desc->MaxPower); - env->SetIntField(usb_confDescObj, usb_confDescFID_extralen, conf_desc->extra_length); - if (conf_desc->extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->extra, conf_desc->extra_length); - env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, NULL); - } - /*interface*/ - usb_intObjArray = (jobjectArray) env->NewObjectArray(conf_desc->bNumInterfaces, usb_intClazz, NULL); - if (!usb_intObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_intObjArray)"); - return NULL; - } - for (h = 0; h < conf_desc->bNumInterfaces; h++) { -#ifdef DEBUGON - printf("\t\t\tlibusb_get_device_list: interface %u \n", h); -#endif - - if (conf_desc->interface == NULL) { - /* this shouldn't happen*/ - printf("(*conf_desc)->usb_interface == NULL"); - continue; - } - usb_intObj = env->NewObject(usb_intClazz, usb_intMid); - if (!usb_intObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_intObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_intObjArray, h, usb_intObj); - env->SetIntField(usb_intObj, usb_intFID_num_altsetting, conf_desc->interface[h].num_altsetting); - // interface descriptor - usb_intDescObjArray = (jobjectArray) env->NewObjectArray( conf_desc->interface[h].num_altsetting, usb_intDescClazz, NULL); - if (!usb_intDescObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_intDescObjArray)"); - return NULL; - } - for (a = 0; a < conf_desc->interface[h].num_altsetting; a++) { -#ifdef DEBUGON - printf("\t\t\t\tlibusb_get_device_list: interface descriptor %u \n", a); -#endif - if (conf_desc->interface[h].altsetting == NULL) { - // this shouldn't happen - printf("LibusbJava: libusb_get_device_list: (*conf_desc)->interface->altsetting == NULL\n"); - continue; - } - usb_intDescObj = env->NewObject(usb_intDescClazz, usb_intDescMid); - if (!usb_intDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_intDescObjArray, a, usb_intDescObj); - /*fill fields*/ - env->SetByteField(usb_intDescObj, usb_intDescFID_bLength, conf_desc->interface[h].altsetting[a].bLength); - env->SetByteField(usb_intDescObj, usb_intDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].bDescriptorType); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceNumber, conf_desc->interface[h].altsetting[a].bInterfaceNumber); - env->SetByteField(usb_intDescObj, usb_intDescFID_bAlternateSetting, conf_desc->interface[h].altsetting[a].bAlternateSetting); - env->SetByteField(usb_intDescObj, usb_intDescFID_bNumEndpoints, conf_desc->interface[h].altsetting[a].bNumEndpoints); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceClass, conf_desc->interface[h].altsetting[a].bInterfaceClass); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceSubClass, conf_desc->interface[h].altsetting[a].bInterfaceSubClass); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceProtocol, conf_desc->interface[h].altsetting[a].bInterfaceProtocol); - env->SetByteField(usb_intDescObj, usb_intDescFID_iInterface, conf_desc->interface[h].altsetting[a].iInterface); - env->SetIntField(usb_intDescObj, usb_intDescFID_extralen, conf_desc->interface[h].altsetting[a].extra_length); - if (conf_desc->interface[h].altsetting[a].extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].extra, conf_desc->interface[h].altsetting[a].extra_length); - env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, NULL); - } - /*endpoint descriptor*/ - usb_epDescObjArray = (jobjectArray) env->NewObjectArray( conf_desc->interface[h].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL); - if (!usb_epDescObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_epDescObjArray)"); - return NULL; - } - for (e = 0; e < conf_desc->interface[h].altsetting[a].bNumEndpoints; e++) { -#ifdef DEBUGON - printf("\t\t\t\t\tLibusb_get_device_list: endpoint descriptor %u \n",e); -#endif - - - if (conf_desc->interface[h].altsetting[a].endpoint == NULL) { - printf( "LibusbJava: usb_get_busses: (*conf_desc)->interface->altsetting->endpoint == NULL\n"); - return root_usb_devObj; - } - usb_epDescObj = env->NewObject(usb_epDescClazz, usb_epDescMid); - if (!usb_epDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_epDescObjArray, e, usb_epDescObj); - env->SetByteField(usb_epDescObj, usb_epDescFID_bLength, conf_desc->interface[h].altsetting[a].endpoint[e].bLength); - env->SetByteField(usb_epDescObj, usb_epDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].endpoint[e].bDescriptorType); - env->SetByteField(usb_epDescObj, usb_epDescFID_bEndpointAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bEndpointAddress); - env->SetByteField(usb_epDescObj, usb_epDescFID_bmAttributes, conf_desc->interface[h].altsetting[a].endpoint[e].bmAttributes); - env->SetShortField(usb_epDescObj, usb_epDescFID_wMaxPacketSize, conf_desc->interface[h].altsetting[a].endpoint[e].wMaxPacketSize); - env->SetByteField(usb_epDescObj, usb_epDescFID_bInterval, conf_desc->interface[h].altsetting[a].endpoint[e].bInterval); - env->SetByteField(usb_epDescObj, usb_epDescFID_bRefresh, conf_desc->interface[h].altsetting[a].endpoint[e].bRefresh); - env->SetByteField(usb_epDescObj, usb_epDescFID_bSynchAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bSynchAddress); - env->SetIntField(usb_epDescObj, usb_epDescFID_extralen, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); - if (conf_desc->interface[h].altsetting[a].endpoint[e].extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].endpoint[e].extra, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); - env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, NULL); - } - } - env->SetObjectField(usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray); - } - env->SetObjectField(usb_intObj, usb_intFID_altsetting, usb_intDescObjArray); - } - env->SetObjectField(usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray); - libusb_free_config_descriptor(conf_desc); - } - - if (res) { - Usb_Device_HandleSet(env, usb_devObj, NULL); - continue; - } - Usb_Device_ConfigSet(env, usb_devObj, usb_confDescObjArray); - usb_devObj_prev = usb_devObj; - } - - //Eliminate empty last device - Usb_Device_NextSet(env, usb_devObj_prev, NULL); - -// free(dev_desc); - libusb_free_device_list(devs, 0); -#ifdef DEBUGON - printf("libusb_get_device_list: done\n"); -#endif - return root_usb_devObj; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_bus_number - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)S - ********************************************************************************************/ -JNIEXPORT jshort JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1bus_1number( JNIEnv *env, jclass obj, jobject dev) { - clearLibusbJavaError(); - - if (ReferencesCheck(&info, env) != 0) return 0; - - libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); - if (libusb_dev == NULL) { - ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); - return 0; - } - - return libusb_get_bus_number(libusb_dev); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_max_iso_packet_size - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;S)I - ********************************************************************************************/ -JNIEXPORT jint -JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1max_1iso_1packet_1size( JNIEnv *env, jclass obj, jobject dev, jshort epAddr) { - clearLibusbJavaError(); - - if (ReferencesCheck(&info, env) != 0) return 0; - - libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); - if (libusb_dev == NULL) { - ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); - return 0; - } - - return libusb_get_max_iso_packet_size(libusb_dev, epAddr); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_ref_device - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Device; - ********************************************************************************************/ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1ref_1device(JNIEnv *env, jclass obj, jobject dev) { - clearLibusbJavaError(); - - if (ReferencesCheck(&info, env) != 0) return NULL; - - libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); - if (libusb_dev == NULL) { - ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); - return NULL; - } - - libusb_ref_device(libusb_dev); - return dev; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_unref_device - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unref_1device(JNIEnv *env, jclass obj, jobject dev) { - clearLibusbJavaError(); - if (ReferencesCheck(&info, env) != 0) return; - libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); - if (libusb_dev == NULL) { - ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); - return; - } - - libusb_unref_device(libusb_dev); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_open - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)J - ********************************************************************************************/ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open( JNIEnv *env, jclass obj, jobject dev) { - clearLibusbJavaError(); - libusb_device_handle *handle = NULL; - if (ReferencesCheck(&info, env) != 0) return 0; - libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); - if (libusb_dev == NULL) { - ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); - return 0; - } - - int res = libusb_open(libusb_dev, &handle); - - if(res != 0) - { - ThrowLibusbError(env, res); - handle = NULL; - } - - return (jlong)handle; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_open_device_with_vid_pid - * Signature: (JII)J - ********************************************************************************************/ -JNIEXPORT jlong -JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open_1device_1with_1vid_1pid(JNIEnv *env, jclass obj, jlong ctx, jint vendor_id, jint product_id) { - clearLibusbJavaError(); - return (jlong) libusb_open_device_with_vid_pid((libusb_context*) (unsigned long) ctx, vendor_id, product_id); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_close - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1close(JNIEnv *env, jclass obj, jlong dev_handle) { - clearLibusbJavaError(); - libusb_close((libusb_device_handle*) (unsigned long) dev_handle); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_device - * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; - ********************************************************************************************/ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device(JNIEnv *env, jclass obj, jlong handle) { - int res, a; - uint8_t c, h, e; - clearLibusbJavaError(); - if (ReferencesCheck(&info, env) != 0) return NULL; - - libusb_config_descriptor *conf_desc; - struct libusb_device_descriptor dev_desc; - - libusb_device *lib_dev = libusb_get_device((libusb_device_handle*) (unsigned long) handle); - - /* objects*/ - jobject usb_devObj, usb_devDescObj, usb_confDescObj, usb_intObj, usb_intDescObj, usb_epDescObj; - jobjectArray usb_confDescObjArray, usb_intObjArray, usb_intDescObjArray, usb_epDescObjArray; - - /* create a new object for device*/ - usb_devObj = Usb_Device_create(env, lib_dev, libusb_get_device_address(lib_dev)); - if (usb_devObj == NULL) { - setLibusbJavaError("shared library error: Could not create new Usb_Device!"); - return NULL; - } - - /*fill the fields of the object*/ - Usb_Device_NextSet(env, usb_devObj, NULL); - Usb_Device_PrevSet(env, usb_devObj, NULL); - - /*device Descriptor*/ - libusb_get_device_descriptor(lib_dev, &dev_desc); - usb_devDescObj = env->NewObject(usb_devDescClazz, usb_devDescMid); - if (!usb_devDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_devDescObj)"); - return NULL; - } - - env->SetByteField(usb_devDescObj, usb_devDescFID_bLength, dev_desc.bLength); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDescriptorType, dev_desc.bDescriptorType); - env->SetShortField(usb_devDescObj, usb_devDescFID_bcdUSB, dev_desc.bcdUSB); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceClass, dev_desc.bDeviceClass); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceSubClass, dev_desc.bDeviceSubClass); - env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceProtocol, dev_desc.bDeviceProtocol); - env->SetByteField(usb_devDescObj, usb_devDescFID_bMaxPacketSize0, dev_desc.bMaxPacketSize0); - env->SetShortField(usb_devDescObj, usb_devDescFID_idVendor, dev_desc.idVendor); - env->SetShortField(usb_devDescObj, usb_devDescFID_idProduct, dev_desc.idProduct); - env->SetShortField(usb_devDescObj, usb_devDescFID_bcdDevice, dev_desc.bcdDevice); - env->SetByteField(usb_devDescObj, usb_devDescFID_iManufacturer, dev_desc.iManufacturer); - env->SetByteField(usb_devDescObj, usb_devDescFID_iProduct, dev_desc.iProduct); - env->SetByteField(usb_devDescObj, usb_devDescFID_iSerialNumber, dev_desc.iSerialNumber); - env->SetByteField(usb_devDescObj, usb_devDescFID_bNumConfigurations, dev_desc.bNumConfigurations); - // TODO @NIUE: Why a reference on itself?! And why should we use a field ID from the Usb_Device class - // for an instance of the Descriptor object? - // env->SetObjectField(usb_devDescObj, usb_devFID_descriptor, usb_devDescObj); - Usb_Device_DescriptorSet(env, usb_devObj, usb_devDescObj); - - /*configuration descriptor*/ - /*Loop through all of the configurations*/ - usb_confDescObjArray = (jobjectArray) env->NewObjectArray( - dev_desc.bNumConfigurations, usb_confDescClazz, NULL); - if (!usb_confDescObjArray) { - setLibusbJavaError("shared library error: Error NewOjectArray"); - return NULL; - } - for (c = 0; c < dev_desc.bNumConfigurations; c++) { -#ifdef DEBUGON - printf("\t\tlibusb_get_device: configuration %u \n", c); -#endif - res = libusb_get_config_descriptor(lib_dev, c, &conf_desc); - if (res) { - setLibusbJavaError("shared library error: read conf_desc failed"); - return usb_devObj; - } - - usb_confDescObj = env->NewObject(usb_confDescClazz, usb_confDescMid); - if (!usb_confDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_confDescObjArray, c, usb_confDescObj);/*add it to the Array*/ - /*fill the fields*/ - env->SetByteField(usb_confDescObj, usb_confDescFID_bLength, conf_desc->bLength); - env->SetByteField(usb_confDescObj, usb_confDescFID_bDescriptorType, conf_desc->bDescriptorType); - env->SetShortField(usb_confDescObj, usb_confDescFID_wTotalLength, conf_desc->wTotalLength); - env->SetByteField(usb_confDescObj, usb_confDescFID_bNumInterfaces, conf_desc->bNumInterfaces); - env->SetByteField(usb_confDescObj, usb_confDescFID_bConfigurationValue, conf_desc->bConfigurationValue); - env->SetByteField(usb_confDescObj, usb_confDescFID_iConfiguration, conf_desc->iConfiguration); - env->SetByteField(usb_confDescObj, usb_confDescFID_bmAttributes, conf_desc->bmAttributes); - env->SetByteField(usb_confDescObj, usb_confDescFID_MaxPower, conf_desc->MaxPower); - env->SetIntField(usb_confDescObj, usb_confDescFID_extralen, conf_desc->extra_length); - if (conf_desc->extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->extra, conf_desc->extra_length); - env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, NULL); - } - /*interface*/ - usb_intObjArray = (jobjectArray) env->NewObjectArray(conf_desc->bNumInterfaces, usb_intClazz, NULL); - if (!usb_intObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_intObjArray)"); - return NULL; - } - for (h = 0; h < conf_desc->bNumInterfaces; h++) { -#ifdef DEBUGON - printf("\t\t\tlibusb_get_device: interface %u \n", h); -#endif - - if (conf_desc->interface == NULL) { - // this shouldn't happen - printf("(*conf_desc)->usb_interface == NULL"); - continue; - } - usb_intObj = env->NewObject(usb_intClazz, usb_intMid); - if (!usb_intObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_intObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_intObjArray, h, usb_intObj); - env->SetIntField(usb_intObj, usb_intFID_num_altsetting, conf_desc->interface[h].num_altsetting); - // interface descriptor - usb_intDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[h].num_altsetting, usb_intDescClazz, NULL); - if (!usb_intDescObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_intDescObjArray)"); - return NULL; - } - for (a = 0; a < conf_desc->interface[h].num_altsetting; a++) { -#ifdef DEBUGON - printf("\t\t\t\tlibusb_get_device: interface descriptor %u \n", a); -#endif - - if (conf_desc->interface[h].altsetting == NULL) { - // this shouldn't happen - printf("LibusbJava: libusb_get_device_list: altsetting == NULL\n"); - continue; - } - usb_intDescObj = env->NewObject(usb_intDescClazz, usb_intDescMid); - if (!usb_intDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_intDescObjArray, a, usb_intDescObj); - /*fill fields*/ - env->SetByteField(usb_intDescObj, usb_intDescFID_bLength, conf_desc->interface[h].altsetting[a].bLength); - env->SetByteField(usb_intDescObj, usb_intDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].bDescriptorType); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceNumber, conf_desc->interface[h].altsetting[a].bInterfaceNumber); - env->SetByteField(usb_intDescObj, usb_intDescFID_bAlternateSetting, conf_desc->interface[h].altsetting[a].bAlternateSetting); - env->SetByteField(usb_intDescObj, usb_intDescFID_bNumEndpoints, conf_desc->interface[h].altsetting[a].bNumEndpoints); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceClass, conf_desc->interface[h].altsetting[a].bInterfaceClass); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceSubClass, conf_desc->interface[h].altsetting[a].bInterfaceSubClass); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceProtocol, conf_desc->interface[h].altsetting[a].bInterfaceProtocol); - env->SetByteField(usb_intDescObj, usb_intDescFID_iInterface, conf_desc->interface[h].altsetting[a].iInterface); - env->SetIntField(usb_intDescObj, usb_intDescFID_extralen, conf_desc->interface[h].altsetting[a].extra_length); - if (conf_desc->interface[h].altsetting[a].extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].extra, conf_desc->interface[h].altsetting[a].extra_length); - env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, NULL); - } - /*endpoint descriptor*/ - usb_epDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[h].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL); - if (!usb_epDescObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_epDescObjArray)"); - return NULL; - } - for (e = 0; e < conf_desc->interface[h].altsetting[a].bNumEndpoints; e++) { -#ifdef DEBUGON - printf("\t\t\t\t\tLibusb_get_device: endpoint descriptor %u \n", e); -#endif - - if (conf_desc->interface[h].altsetting[a].endpoint == NULL) { - printf("LibusbJava: usb_get_busses: endpoint == NULL\n"); - return usb_devObj; - } - usb_epDescObj = env->NewObject(usb_epDescClazz, usb_epDescMid); - if (!usb_epDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_epDescObjArray, e, usb_epDescObj); - env->SetByteField(usb_epDescObj, usb_epDescFID_bLength, conf_desc->interface[h].altsetting[a].endpoint[e].bLength); - env->SetByteField(usb_epDescObj, usb_epDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].endpoint[e].bDescriptorType); - env->SetByteField(usb_epDescObj, usb_epDescFID_bEndpointAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bEndpointAddress); - env->SetByteField(usb_epDescObj, usb_epDescFID_bmAttributes, conf_desc->interface[h].altsetting[a].endpoint[e].bmAttributes); - env->SetShortField(usb_epDescObj, usb_epDescFID_wMaxPacketSize, conf_desc->interface[h].altsetting[a].endpoint[e].wMaxPacketSize); - env->SetByteField(usb_epDescObj, usb_epDescFID_bInterval, conf_desc->interface[h].altsetting[a].endpoint[e].bInterval); - env->SetByteField(usb_epDescObj, usb_epDescFID_bRefresh, conf_desc->interface[h].altsetting[a].endpoint[e].bRefresh); - env->SetByteField(usb_epDescObj, usb_epDescFID_bSynchAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bSynchAddress); - env->SetIntField(usb_epDescObj, usb_epDescFID_extralen, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); - if (conf_desc->interface[h].altsetting[a].endpoint[e].extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].endpoint[e].extra, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); - env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, NULL); - } - } - env->SetObjectField(usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray); - } - env->SetObjectField(usb_intObj, usb_intFID_altsetting, usb_intDescObjArray); - } - env->SetObjectField(usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray); - libusb_free_config_descriptor(conf_desc); - } - Usb_Device_ConfigSet(env, usb_devObj, usb_confDescObjArray); - -#ifdef DEBUGON - printf("libusb_get_device: done\n"); -#endif - return usb_devObj; -} -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_configuration - * Signature: (J)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1configuration(JNIEnv *env, jclass obj, jlong handle) { - int config = 0; - int libusb_result = 0; - - clearLibusbJavaError(); - libusb_result = libusb_get_configuration((libusb_device_handle*) (unsigned long) handle, &config); - - if (libusb_result != 0) { - setLibusbJavaError("shared library error: get_configuration failed"); - ThrowLibusbError(env, libusb_result); - config = 0; - } - - return config; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_configuration - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1configuration(JNIEnv *env, jclass obj, jlong handle, jint config) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_set_configuration((libusb_device_handle*) (unsigned long) handle, config)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_claim_interface - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1claim_1interface(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_claim_interface((libusb_device_handle*) (unsigned long) handle, iNumber)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_release_interface - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1release_1interface(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_release_interface((libusb_device_handle*) (unsigned long) handle, iNumber)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_interface_alt_setting - * Signature: (JII)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1interface_1alt_1setting(JNIEnv *env, jclass obj, jlong handle, jint iNumber, jint altSet) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_set_interface_alt_setting((libusb_device_handle*) (unsigned long) handle, iNumber, altSet)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_clear_halt - * Signature: (JS)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1clear_1halt(JNIEnv *env, jclass obj, jlong handle, jshort ep) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_clear_halt((libusb_device_handle*) (unsigned long) handle, ep)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_reset_device - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1reset_1device(JNIEnv *env, jclass obj, jlong handle) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_reset_device((libusb_device_handle*) (unsigned long) handle)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_kernel_driver_active - * Signature: (JI)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1kernel_1driver_1active(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { - int libusb_result = 0; - - clearLibusbJavaError(); - libusb_result = libusb_kernel_driver_active((libusb_device_handle*) (unsigned long) handle, iNumber); - - if (libusb_result < 0) - { - ThrowLibusbError(env, libusb_result); - libusb_result = 0; - } - - return libusb_result; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_detach_kernel_driver - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1detach_1kernel_1driver(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_detach_kernel_driver((libusb_device_handle*) (unsigned long) handle, iNumber)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_attach_kernel_driver - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1attach_1kernel_1driver(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_attach_kernel_driver((libusb_device_handle*) (unsigned long) handle, iNumber)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_active_config_descriptor - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Config_Descriptor; - ********************************************************************************************/ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1active_1config_1descriptor(JNIEnv *env, jclass obj, jobject dev) { - uint8_t a, e; - clearLibusbJavaError(); - if (ReferencesCheck(&info, env) != 0) return NULL; - libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); - if (libusb_dev == NULL) { - ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); - return NULL; - } - - libusb_config_descriptor *conf_desc; - jobject usb_confDescObj, usb_intObj, usb_intDescObj, usb_epDescObj; - jobjectArray usb_intObjArray, usb_intDescObjArray, usb_epDescObjArray; - - libusb_device *lib_dev = Usb_Device_HandleGet(env, dev); - if (lib_dev == NULL) return NULL; - - if (libusb_get_active_config_descriptor(lib_dev, &conf_desc)) { - setLibusbJavaError("shared library error: get_configuration failed"); - return NULL; - } - usb_confDescObj = env->NewObject(usb_confDescClazz, usb_confDescMid); - if (!usb_confDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)"); - return NULL; - } - /*fill the fields*/ - env->SetByteField(usb_confDescObj, usb_confDescFID_bLength, conf_desc->bLength); - env->SetByteField(usb_confDescObj, usb_confDescFID_bDescriptorType, conf_desc->bDescriptorType); - env->SetShortField(usb_confDescObj, usb_confDescFID_wTotalLength, conf_desc->wTotalLength); - env->SetByteField(usb_confDescObj, usb_confDescFID_bNumInterfaces, conf_desc->bNumInterfaces); - env->SetByteField(usb_confDescObj, usb_confDescFID_bConfigurationValue, conf_desc->bConfigurationValue); - env->SetByteField(usb_confDescObj, usb_confDescFID_iConfiguration, conf_desc->iConfiguration); - env->SetByteField(usb_confDescObj, usb_confDescFID_bmAttributes, conf_desc->bmAttributes); - env->SetByteField(usb_confDescObj, usb_confDescFID_MaxPower, conf_desc->MaxPower); - env->SetIntField(usb_confDescObj, usb_confDescFID_extralen, conf_desc->extra_length); - if (conf_desc->extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->extra, conf_desc->extra_length); - env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, NULL); - } - /*interface*/ - usb_intObjArray = (jobjectArray) env->NewObjectArray(conf_desc->bNumInterfaces, usb_intClazz, NULL); - if (!usb_intObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_intObjArray)"); - return NULL; - } - for (int i = 0; i < conf_desc->bNumInterfaces; i++) { -#ifdef DEBUGON - printf("\t\t\tlibusb_get_activ_config_descriptor: interface %u \n", i); -#endif - if (conf_desc->interface == NULL) { - // this shouldn't happen - printf("conf_des->interface == NULL"); - continue; - } - usb_intObj = env->NewObject(usb_intClazz, usb_intMid); - if (!usb_intObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_intObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_intObjArray, i, usb_intObj); - env->SetIntField(usb_intObj, usb_intFID_num_altsetting, conf_desc->interface[i].num_altsetting); - // interface descriptor - usb_intDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[i].num_altsetting, usb_intDescClazz, NULL); - if (!usb_intDescObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_intDescObjArray)"); - return NULL; - } - for (a = 0; a < conf_desc->interface[i].num_altsetting; a++) { -#ifdef DEBUGON - printf("\t\t\t\tlibusb_get__activ_config_descriptor: interface descriptor %u \n", a); -#endif - - if (conf_desc->interface[i].altsetting == NULL) { - // this shouldn't happen - printf("LibusbJava: libusb_get__activ_config_descriptor: altsetting == NULL\n"); - continue; - } - usb_intDescObj = env->NewObject(usb_intDescClazz, usb_intDescMid); - if (!usb_intDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_intDescObjArray, a, usb_intDescObj); - /*fill fields*/ - env->SetByteField(usb_intDescObj, usb_intDescFID_bLength, conf_desc->interface[i].altsetting[a].bLength); - env->SetByteField(usb_intDescObj, usb_intDescFID_bDescriptorType, conf_desc->interface[i].altsetting[a].bDescriptorType); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceNumber, conf_desc->interface[i].altsetting[a].bInterfaceNumber); - env->SetByteField(usb_intDescObj, usb_intDescFID_bAlternateSetting, conf_desc->interface[i].altsetting[a].bAlternateSetting); - env->SetByteField(usb_intDescObj, usb_intDescFID_bNumEndpoints, conf_desc->interface[i].altsetting[a].bNumEndpoints); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceClass, conf_desc->interface[i].altsetting[a].bInterfaceClass); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceSubClass, conf_desc->interface[i].altsetting[a].bInterfaceSubClass); - env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceProtocol, conf_desc->interface[i].altsetting[a].bInterfaceProtocol); - env->SetByteField(usb_intDescObj, usb_intDescFID_iInterface, conf_desc->interface[i].altsetting[a].iInterface); - env->SetIntField(usb_intDescObj, usb_intDescFID_extralen, conf_desc->interface[i].altsetting[a].extra_length); - if (conf_desc->interface[i].altsetting[a].extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[i].altsetting[a].extra, conf_desc->interface[i].altsetting[a].extra_length); - env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, NULL); - } - /*endpoint descriptor*/ - usb_epDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[i].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL); - if (!usb_epDescObjArray) { - setLibusbJavaError("shared library error: Error NewObjectArray (usb_epDescObjArray)"); - return NULL; - } - for (e = 0; e < conf_desc->interface[i].altsetting[a].bNumEndpoints; e++) { -#ifdef DEBUGON - printf("\t\t\t\t\tLibusb_get__activ_config_descriptor: endpoint descriptor %u \n", e); -#endif - if (conf_desc->interface[i].altsetting[a].endpoint == NULL) { - printf("LibusbJava: usb_get__activ_config_descriptor: endpoint == NULL\n"); - return usb_confDescObj; - } - usb_epDescObj = env->NewObject(usb_epDescClazz, usb_epDescMid); - if (!usb_epDescObj) { - setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)"); - return NULL; - } - env->SetObjectArrayElement(usb_epDescObjArray, e, usb_epDescObj); - env->SetByteField(usb_epDescObj, usb_epDescFID_bLength, conf_desc->interface[i].altsetting[a].endpoint[e].bLength); - env->SetByteField(usb_epDescObj, usb_epDescFID_bDescriptorType, conf_desc->interface[i].altsetting[a].endpoint[e].bDescriptorType); - env->SetByteField(usb_epDescObj, usb_epDescFID_bEndpointAddress, conf_desc->interface[i].altsetting[a].endpoint[e].bEndpointAddress); - env->SetByteField(usb_epDescObj, usb_epDescFID_bmAttributes, conf_desc->interface[i].altsetting[a].endpoint[e].bmAttributes); - env->SetShortField(usb_epDescObj, usb_epDescFID_wMaxPacketSize, conf_desc->interface[i].altsetting[a].endpoint[e].wMaxPacketSize); - env->SetByteField(usb_epDescObj, usb_epDescFID_bInterval, conf_desc->interface[i].altsetting[a].endpoint[e].bInterval); - env->SetByteField(usb_epDescObj, usb_epDescFID_bRefresh, conf_desc->interface[i].altsetting[a].endpoint[e].bRefresh); - env->SetByteField(usb_epDescObj, usb_epDescFID_bSynchAddress, conf_desc->interface[i].altsetting[a].endpoint[e].bSynchAddress); - env->SetIntField(usb_epDescObj, usb_epDescFID_extralen, conf_desc->interface[i].altsetting[a].endpoint[e].extra_length); - if (conf_desc->interface[i].altsetting[a].endpoint[e].extra) { - jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[i].altsetting[a].endpoint[e].extra, conf_desc->interface[i].altsetting[a].endpoint[e].extra_length); - env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, jbExtraDesc); - } else { - env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, NULL); - } - } - env->SetObjectField(usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray); - } - env->SetObjectField(usb_intObj, usb_intFID_altsetting, usb_intDescObjArray); - } - env->SetObjectField(usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray); - libusb_free_config_descriptor(conf_desc); - - return usb_confDescObj; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_string_descriptor_ascii - * Signature: (JSI)Ljava/lang/String; - ********************************************************************************************/ -JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor_1ascii( JNIEnv *env, jclass obj, jlong handle, jshort desc_index, jint length) { - jstring string; - int res = 0; - clearLibusbJavaError(); - unsigned char data[(int)length + 1]; - - res = libusb_get_string_descriptor_ascii((libusb_device_handle*) (unsigned long) handle, desc_index, data, (int)length); - - if (res >= 0) - { - data[res] = '\0'; - string = env->NewStringUTF((const char*)data); - } - else - { - setLibusbJavaError("get_string_descriptor_ascii: retrieve String failed"); - string = NULL; - ThrowLibusbError(env, res); - } - return string; -} -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_descriptor - * Signature: (JISI)[B - ********************************************************************************************/ - -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1descriptor( - JNIEnv *env, jclass obj, jlong handle, jint desc_type, - jshort desc_index, jint size) { - - clearLibusbJavaError(); - int res; - unsigned char data[255]; - - res = libusb_get_descriptor((libusb_device_handle*) (unsigned long) handle, desc_type, desc_index, data, size); - if (res < 0) { - setLibusbJavaError("libusb_get_descriptor: retrieve data failed"); - ThrowLibusbError(env, res); - return NULL; - } - - return to_byteArray(env, data, res); -} -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_string_descriptor - * Signature: (JSII)Ljava/lang/String; - ********************************************************************************************/ -JNIEXPORT jstring -JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor(JNIEnv *env, jclass obj, jlong handle, jshort desc_index, jint langid, jint size) { - clearLibusbJavaError(); - int res; - jstring string; - unsigned char data[(int)size + 1]; - - res = libusb_get_string_descriptor((libusb_device_handle*) (unsigned long) handle, desc_index, langid, data, size); - - if (res >= 0) { - data[res] = '\0'; - string = env->NewStringUTF((const char*) data); - } else { - setLibusbJavaError("get_string_descriptor: retrieve String failed"); - string = NULL; - ThrowLibusbError(env, res); - } - - return string; - -} -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_alloc_transfer - * Signature: (I)J - ********************************************************************************************/ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1alloc_1transfer( JNIEnv *env, jclass obj, jint iso_packets) { - clearLibusbJavaError(); - return (jlong) libusb_alloc_transfer(iso_packets); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_free_transfer - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1free_1transfer( JNIEnv *env, jclass obj, jlong transfernumber) { - clearLibusbJavaError(); - libusb_free_transfer((libusb_transfer*) (unsigned long) transfernumber); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_submit_transfer - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1submit_1transfer(JNIEnv *env, jclass obj, jlong transfernumber) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_submit_transfer((libusb_transfer*) (unsigned long) transfernumber)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_cancel_transfer - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1cancel_1transfer(JNIEnv *env, jclass obj, jlong transfernumber) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_cancel_transfer((libusb_transfer*) (unsigned long) transfernumber)); -} -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_control_transfer_get_data - * Signature: (J)[B - ********************************************************************************************/ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1data(JNIEnv *env, jclass obj, jlong transfernumber) { - clearLibusbJavaError(); - unsigned char *data; - libusb_transfer* trans = (libusb_transfer*) (unsigned long) transfernumber; - - if (trans == NULL) - return NULL; - - data = libusb_control_transfer_get_data(trans); - return to_byteArray(env, data, trans->actual_length - LIBUSB_CONTROL_SETUP_SIZE ); -} - -/********************************************************************************************* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_control_transfer_get_setup - * Signature: (J)[B - ********************************************************************************************/ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1setup(JNIEnv *env, jclass obj, jlong transfernumber) { - clearLibusbJavaError(); - unsigned char *data; - libusb_transfer* trans = (libusb_transfer*) (unsigned long) transfernumber; - - if (trans == NULL) { - return NULL; - } - - data = (unsigned char*)libusb_control_transfer_get_setup(trans); - - return to_byteArray(env, data, 8); -} -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_control_setup - * Signature: (IIIII)[B - ********************************************************************************************/ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1setup(JNIEnv *env, jclass obj, jint bmRequestType, jint bRequest, jint wValue, jint wIndex, jint wLength) { - clearLibusbJavaError(); - unsigned char setup[8]; - - libusb_fill_control_setup(setup, bmRequestType, bRequest, wValue, wIndex, wLength); - - return to_byteArray(env, setup, 8); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_control_transfer - * Signature: (JJ[BI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle, jbyteArray buffer, jint timeout) { - clearLibusbJavaError(); - jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); - libusb_fill_control_transfer((libusb_transfer*) (unsigned long) transfernumber,(libusb_device_handle*) (unsigned long) handle,(unsigned char*) byteArrayElements, transfer_callback, env,(unsigned int) timeout); - env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_bulk_transfer - * Signature: (JJB[BII)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1bulk_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { - clearLibusbJavaError(); - jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); - libusb_fill_bulk_transfer((libusb_transfer*) (unsigned long) transfernumber,(libusb_device_handle*) (unsigned long) handle, endpoint,(unsigned char*) byteArrayElements, length, transfer_callback, env,(unsigned int) timeout); - env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_interrupt_transfer - * Signature: (JJB[BII)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1interrupt_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle,jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { - clearLibusbJavaError(); - jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); - libusb_fill_interrupt_transfer((libusb_transfer*) (unsigned long) transfernumber,(libusb_device_handle*) (unsigned long) handle, endpoint,(unsigned char*) byteArrayElements, length, transfer_callback, env, timeout); - env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_iso_transfer - * Signature: (JJB[BIII)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1iso_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint num_iso_packets, jint timeout) { - clearLibusbJavaError(); - jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); - libusb_fill_iso_transfer((libusb_transfer*) (unsigned long) transfernumber, (libusb_device_handle*) (unsigned long) handle, endpoint, (unsigned char*) byteArrayElements, length, num_iso_packets, transfer_callback, env, timeout); - env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_iso_packet_lengths - * Signature: (JI)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1iso_1packet_1lengths(JNIEnv *env, jclass obj, jlong transfernumber, jint length) { - clearLibusbJavaError(); - libusb_set_iso_packet_lengths((libusb_transfer*) (unsigned long) transfernumber, length); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_iso_packet_buffer - * Signature: (JI)[B - ********************************************************************************************/ - -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer(JNIEnv *env, jclass obj, jlong transfernumber, jint packet) { - clearLibusbJavaError(); - int size = 0; - unsigned char *data = NULL; - libusb_transfer* transfer = (libusb_transfer*) (unsigned long) transfernumber; - - if (transfer == NULL) { - setLibusbJavaError("libusb_get_iso_packet_buffer: ilegal transfernumber"); - return NULL; - } - - if (packet < transfer->num_iso_packets) { - size = transfer->iso_packet_desc[packet].actual_length; - } - - data = libusb_get_iso_packet_buffer((libusb_transfer*) (unsigned long) transfernumber, packet); - if (data == NULL) { - setLibusbJavaError("libusb_get_iso_packet_buffer: packet does not exist"); - return NULL; - } - - return to_byteArray(env, data, size); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_iso_packet_buffer_simple - * Signature: (JI)[B - ********************************************************************************************/ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer_1simple(JNIEnv *env, jclass obj, jlong transfernumber, jint packet) { - clearLibusbJavaError(); - int size = 0; - unsigned char *data = NULL; - libusb_transfer* transfer = (libusb_transfer*) (unsigned long) transfernumber; - - if (transfer == NULL) { - setLibusbJavaError("libusb_get_iso_packet_buffer_simple: ilegal transfernumber"); - return NULL; - } - - if (packet < transfer->num_iso_packets) { - size = transfer->iso_packet_desc[packet].actual_length; - } - - data = libusb_get_iso_packet_buffer_simple((libusb_transfer*) (unsigned long) transfernumber, packet); - - if (data == NULL) { - setLibusbJavaError("libusb_get_iso_packet_buffer_simple: packet does not exist"); - return NULL; - } - - return to_byteArray(env, data, size); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_try_lock_events - * Signature: (J)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1try_1lock_1events(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - return libusb_try_lock_events((libusb_context*) (unsigned long) ctx); -// return libusb_try_lock_events(NULL); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_lock_events - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1events(JNIEnv *env, jclass obj, jlong ctx) { - libusb_lock_events((libusb_context*) (unsigned long) ctx); -// libusb_lock_events(NULL); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_unlock_events - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1events(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - libusb_unlock_events((libusb_context*) (unsigned long) ctx); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_event_handling_ok - * Signature: (J)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handling_1ok(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - return libusb_event_handling_ok((libusb_context*) (unsigned long) ctx); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_event_handler_active - * Signature: (J)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handler_1active(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - return libusb_event_handler_active((libusb_context*) (unsigned long) ctx); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_lock_event_waiters - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1event_1waiters(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - libusb_lock_event_waiters((libusb_context*) (unsigned long) ctx); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_unlock_event_waiters - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1event_1waiters(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - libusb_unlock_event_waiters((libusb_context*) (unsigned long) ctx); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_wait_for_event - * Signature: (JJ)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1wait_1for_1event(JNIEnv *env, jclass obj, jlong ctx, jlong timevalue) { - clearLibusbJavaError(); - if (timevalue) { - timeval tv; - tv.tv_sec = timevalue; - tv.tv_usec = 0; - return libusb_wait_for_event((libusb_context*) (unsigned long) ctx, &tv); - } - return libusb_wait_for_event((libusb_context*) (unsigned long) ctx, NULL); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_handle_events_timeout - * Signature: (JJ)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1timeout(JNIEnv *env, jclass obj, jlong ctx, jlong timevalue) { - clearLibusbJavaError(); - if (timevalue != 0) - { - timeval tv; - tv.tv_sec = timevalue; - tv.tv_usec = 0; - ThrowIfUnsuccessful(env, libusb_handle_events_timeout((libusb_context*) (unsigned long) ctx, &tv)); - } - else - { - ThrowIfUnsuccessful(env, libusb_handle_events_timeout((libusb_context*) (unsigned long) ctx, NULL)); - } -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_handle_events - * Signature: (J)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - ThrowIfUnsuccessful(env, libusb_handle_events((libusb_context*) (unsigned long) ctx)); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_handle_events_locked - * Signature: (JJ)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1locked(JNIEnv *env, jclass obj, jlong ctx, jlong timevalue) { - clearLibusbJavaError(); - if (timevalue) { - timeval tv; - tv.tv_sec = timevalue; - tv.tv_usec = 0; - ThrowIfUnsuccessful(env, libusb_handle_events_locked((libusb_context*) (unsigned long) ctx, &tv)); - } - else - { - ThrowIfUnsuccessful(env, libusb_handle_events_locked((libusb_context*) (unsigned long) ctx, NULL)); - } -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_pollfds_handle_timeouts - * Signature: (J)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1pollfds_1handle_1timeouts(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - return libusb_pollfds_handle_timeouts((libusb_context*) (unsigned long) ctx); -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_next_timeout - * Signature: (J)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1next_1timeout(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - int res; - timeval tv; - - /*! \todo Is this code working correctly if we use it in a 64-Bit environment? Actually - * it's unlikely to have a timeout of more than 2^(31)-1 seconds. But still it is a - * possible value. */ - res = libusb_get_next_timeout((libusb_context*) (unsigned long) ctx, &tv); - - if (res > 0) - { - res = tv.tv_sec; - } - else if (res == 0) { - res = -1; - } - else - { - ThrowLibusbError(env, res); - res = -2; - } - - return res; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_pollfd_notifiers - * Signature: (JZ)V - ********************************************************************************************/ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1pollfd_1notifiers(JNIEnv *env, jclass obj, jlong ctx, jboolean remove) { - clearLibusbJavaError(); - if (remove) - { - libusb_set_pollfd_notifiers((libusb_context*) (unsigned long) ctx, NULL, NULL, env); - } - else - { - libusb_set_pollfd_notifiers((libusb_context*) (unsigned long) ctx, fd_added_callback, fd_removed_callback, env); - } -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_pollfds - * Signature: (J)[Lch/ntb/inf/libusbJava/Libusb_pollfd; - ********************************************************************************************/ -JNIEXPORT jobjectArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1pollfds(JNIEnv *env, jclass obj, jlong ctx) { - clearLibusbJavaError(); - int count = 0; - jobjectArray pollfdArray; - jobject pollfdObj; - const libusb_pollfd **fdList; - - fdList = libusb_get_pollfds((libusb_context*) (unsigned long) ctx); - if (fdList == NULL) { - return NULL; - } - /*determine the length of the list*/ - while (fdList[count]) { - count++; - } - pollfdArray = (jobjectArray) env->NewObjectArray(count, usb_pollfd_clazz, NULL); - if (!pollfdArray) { - setLibusbJavaError("libusb_get_pollfds: error NewObjectArry (pollfdArray"); - return NULL; - } - - for (int i = 0; i < count; i++) { - pollfdObj = env->NewObject(usb_pollfd_clazz, usb_pollfd_Mid); - if (!pollfdObj) { - setLibusbJavaError("libusb_get_pollfds: Error NewObject (pollfdObj)"); - return NULL; - } - env->SetObjectArrayElement(pollfdArray, i, pollfdObj); - env->SetIntField(pollfdObj, usb_pollfdFID_fd, fdList[i]->fd); - env->SetShortField(pollfdObj, usb_pollfdFID_events, fdList[i]->events); - } - return pollfdArray; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_control_transfer - * Signature: (JIIII[BII)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer(JNIEnv *env, jclass obj, jlong handle, jint bmRequestType, jint bRequest, jint wValue, jint wIndex, jbyteArray buffer, jint wLength, jint timeout) { - clearLibusbJavaError(); - int res; - unsigned char* data; - data = (unsigned char*) env->GetByteArrayElements(buffer, NULL); - res = libusb_control_transfer((libusb_device_handle*) (unsigned long) handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); - env->ReleaseByteArrayElements(buffer, (jbyte*) data, 0); - - return res; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_bulk_transfer - * Signature: (JB[BII)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1bulk_1transfer(JNIEnv *env, jclass obj, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { - clearLibusbJavaError(); - int libusb_result = 0; - int bytes_transferred = 0; - unsigned char* data = (unsigned char*) env->GetByteArrayElements(buffer, NULL); - - libusb_result = libusb_bulk_transfer((libusb_device_handle*) (unsigned long) handle, endpoint, data, length, &bytes_transferred, timeout); - env->ReleaseByteArrayElements(buffer, (jbyte*) data, 0); - - if (libusb_result != 0) - { - ThrowLibusbError(env, libusb_result); - bytes_transferred = 0; - } - - return bytes_transferred; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_interrupt_transfer - * Signature: (JB[BII)I - ********************************************************************************************/ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1interrupt_1transfer(JNIEnv *env, jclass obj, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { - clearLibusbJavaError(); - int libusb_result; - int bytes_transferred = 0; - unsigned char* data = (unsigned char*) env->GetByteArrayElements(buffer, NULL); - libusb_result = libusb_interrupt_transfer((libusb_device_handle*) (unsigned long) handle, endpoint, data, length, &bytes_transferred, timeout); - env->ReleaseByteArrayElements(buffer, (jbyte*) data, 0); - - if (libusb_result != 0) - { - ThrowLibusbError(env, libusb_result); - bytes_transferred = 0; - } - - return bytes_transferred; -} - -/******************************************************************************************** - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_strerror - * Signature: ()Ljava/lang/String; - ********************************************************************************************/ -JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1strerror(JNIEnv *env, jclass obj) { - char *str = "Libusb-1.0 Error"; - - /* check for LibusbJava specific errors first*/ - if (libusbJavaError != NULL) { - str = libusbJavaError; - clearLibusbJavaError(); - } - - return env->NewStringUTF(str); -} - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: setup - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_setup(JNIEnv *env, jclass obj) -{ - return ReferencesLoad(&info, env, jniObjects); -} - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: teardown - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_teardown(JNIEnv *env, jclass obj) -{ - ReferencesUnload(&info, env); -} - -/******************************************************************************************** - * Class: LibusbJava_1_0.cpp - * Method: transfer_callback - * - ********************************************************************************************/ -static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer) { - - ((JNIEnv*) transfer->user_data)->CallVoidMethod(usb_cb_clazz, - usb_transfer_cb_Mid); -} - -/******************************************************************************************** - * Class: LibusbJava_1_0.cpp - * Method: fd_added_callback - * - ********************************************************************************************/ -static void LIBUSB_CALL fd_added_callback(int fd, short events, void *user_data) { - - ((JNIEnv*) user_data)->CallVoidMethod(usb_cb_clazz, usb_fd_added_cb_Mid, - (jint) fd); -} - -/******************************************************************************************** - * Class: LibusbJava_1_0.cpp - * Method: fd_removed_callback - * - ********************************************************************************************/ -static void LIBUSB_CALL fd_removed_callback(int fd, void *user_data) { - - ((JNIEnv*) user_data)->CallVoidMethod(usb_cb_clazz, usb_fd_removed_cb_Mid, - (jint) fd); -} - -/*! \brief Turns a memory section into a java byte array that can be returned to the java - * environment. - * - * \param env Environment to create the array for - * \param data Pointer to the data to be put in the array - * \param len [bytes] Length of the data to be put into the array - * - * \return The pointer to the newly created byte array. NULL if an error occured - * - * \note If NULL is returned, #libusbJavaError is set to a matching error string. - * - * \test Tested through the unit-test of the java part of this dll by passing a string - * with length 5 and checking the result. - * \test Tested through the Unit-Test of the java part of this dll by passing a string - * with length 0 and checking the result. - */ -static __inline jbyteArray JNICALL to_byteArray(JNIEnv *env, const void *data, size_t len) -{ - jbyteArray result = env->NewByteArray(len); - - if (result != NULL) { - /* By using SetByteArrayRegion, we avoid that the JNI layer first copies the data of - * the array in our space just to overwrite them. As we just allocated the - * byte array with a length of "len", the set operation can never fail. The check for an - * exception can therefore be omitted. */ - env->SetByteArrayRegion(result, 0, len, (const signed char *)data); -#if 0 /* No need to check for exceptions here... */ - if (env->ExceptionOccurred()){ - setLibusbJavaError("to_byteArray: unable to copy data to array"); - env->DeleteLocalRef(result); - result = NULL; - } -#endif - } - else { - setLibusbJavaError("to_byteArray: out of memory"); - } - - return result; -} - -/*! \brief Convenience function that throws an exception in the callers environment if - * the given result is not "success" - * - * This function can be used to wrap calls to the libusb if no further reaction - * on a unsuccessful result is needed, than throwing an exception in the java - * environment. - * - * \param env Java environment of the caller - * \param libusb_result Result code of the libusb call. If the result is != 0, a - * LibusbError is thrown. - * - * \test Code-Review - */ -static __inline void JNICALL ThrowIfUnsuccessful(JNIEnv *env, int libusb_result) -{ - if (libusb_result != 0) - { - ThrowLibusbError(env, libusb_result); - } -} - -#ifdef DO_UNIT_TEST - TEST_CASE(ThrowIfUnsuccessfulTest) - { - TEST_CONTEXT(); - - CuAssert(tc, "Pre-Condition: No exception pending", env->ExceptionCheck() == JNI_FALSE); - - ThrowIfUnsuccessful(env, 0); - CuAssert(tc, "No exception pending", env->ExceptionCheck() == JNI_FALSE); - - ThrowIfUnsuccessful(env, -1); - CuAssert(tc, "Exception pending < 0", env->ExceptionCheck() == JNI_TRUE); - env->ExceptionClear(); - - ThrowIfUnsuccessful(env, 1); - CuAssert(tc, "Exception pending > 0", env->ExceptionCheck() == JNI_TRUE); - env->ExceptionClear(); - } -#endif - -/*! \brief Throws an exception of type LibusbError in the calling Java environment. - * - * \param env Environment to throw the exception in - * \param code Error code that represents the cause of the exception - * - * \test Tested through the unit-test of the java part of this dll - */ -static __inline void JNICALL ThrowLibusbError(JNIEnv *env, jint code) -{ - jmethodID constructor = NULL; - jthrowable exception = NULL; - - jclass clazz = env->FindClass("ch/ntb/inf/libusbJava/exceptions/LibusbError"); - if (clazz == NULL) - { - goto no_class; - } - - constructor = env->GetMethodID(clazz, "", "(I)V"); - if (constructor == NULL) - { - goto no_constructor; - } - - exception = (jthrowable)env->NewObject(clazz, constructor, code); - if (exception == NULL) - { - goto no_object; - } - - if (env->Throw(exception) != 0) - { - goto throw_failed; - } - - env->DeleteLocalRef(exception); - env->DeleteLocalRef(clazz); - - return; - -/* Error Handling. All errors covered here are caused by JNI callbacks and have - * therefore already thrown appropriate exceptions in the Java environment. - * Therefore we only have to cleanup what we constructed. */ -throw_failed: - env->DeleteLocalRef(exception); - -no_object: - -no_constructor: - env->DeleteLocalRef(clazz); - -no_class: - - return; -} - -#ifdef DO_UNIT_TEST - static void ThrowLibusbErrorTestEvaluate(CuTest *tc, JNIEnv *env, int code) { - /* Prepare the needed environment */ - jclass clazz = env->FindClass("ch/ntb/inf/libusbJava/exceptions/LibusbError"); - CuAssert(tc, "LibusbError class not found!", clazz != NULL); - jfieldID f_code = env->GetFieldID(clazz, "code", "I"); - CuAssert(tc, "LibusbError has a field \"code\"", f_code != NULL); - - /* Evaluate the effect of the call */ - jthrowable e = env->ExceptionOccurred(); - CuAssert(tc, "An exception occured", e != NULL); - CuAssert(tc, "The exception is of type LibusbError", env->IsInstanceOf(e, clazz) == JNI_TRUE); - CuAssertIntEquals_Msg(tc, "The exception error code is correct", code, env->GetIntField(e, f_code)); - env->ExceptionClear(); - } - - TEST_CASE(ThrowLibusbErrorTest) - { - TEST_CONTEXT(); - - /* Test borders and run through a range of values including 0 */ - int code = 0; - for (code = -5;code < 5;code++) { - ThrowLibusbError(env, code); - ThrowLibusbErrorTestEvaluate(tc, env, code); - } - - ThrowLibusbError(env, 0x80000000); - ThrowLibusbErrorTestEvaluate(tc, env, 0x80000000); - ThrowLibusbError(env, 0x7FFFFFFF); - ThrowLibusbErrorTestEvaluate(tc, env, 0x7FFFFFFF); - } -#endif - -/*! \brief Checks if the references are loaded correctly and throws an exception if not - * - * This function serves as a "paranoia" function to make sure, there are no calls - * to the library without loading the references first. - * - * \param instance Reference-Instance to be checked - * \param env JNI Environment the function can work with in case of an error - * - * \return - * - 0 if everything is ok - * - <0 in case the references are not loaded - */ -static __inline int ReferencesCheck(tLUJ_Instance *instance, JNIEnv *env) -{ - int result = -1; - - if (instance->jni.refs_loaded == 0){ - ThrowLibusbError(env, ERROR_JAVA_REFERENCES_NOT_LOADED); - } - else { - result = 0; - } - - return result; -} - -/*! \brief Loads all class References from the environment. - * - * \param instance Pointer to an instance of a status data struct the action should be performed with - * \param env Pointer to an environment enabling access to the jvm - * \param objects An array of function calls for connecting / disconnecting - * the objects to the JNI layer. The array is expected to be - * NULL terminated. (tJNIObject::connect set to NULL). - * - * \return - * - 0 if the references could be loaded successfully - * - <0 if an error occured - * - * \note For every valid row it is expected that neither connect nor disconnect is NULL - */ -static __inline int ReferencesLoad(tLUJ_Instance *instance, JNIEnv *env, const tJNIObject *objects) -{ - int result = -1; - - /* If the references are not (yet) loaded, we start loading - * the references for the classes used by this wrapper. */ - if (instance->jni.refs_loaded == 0) - { - int i = 0; - - result = 0; - - /* Walk through all registered objects and try to connect - * them. */ - while (objects[i].connect != NULL) { - if (objects[i].connect(env) != 0) { - result = -1; - break; - } - - ++i; - } - - /* If an error occured, we roll back all the previously - * connected elements. */ - if (result != 0) { - while (i > 0) { - --i; - objects[i].disconnect(env); - } - - instance->jni.refs_loaded = 0; - } - else - { -#ifndef DO_UNIT_TEST - { - /* find classes and field ids*/ - #ifdef DEBUGON - printf("load references starts\n"); - #endif - - #ifdef DEBUGON - printf("usb_device references loaded\n"); - #endif - /* usb_device_descriptor*/ - jobject devDescClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Device_Descriptor");//returns a local reference - usb_devDescClazz = (jclass)env->NewGlobalRef(devDescClazz);//make it global - if (usb_devDescClazz == NULL) { - return -1; /* exception thrown */ - } - usb_devDescMid = env->GetMethodID(usb_devDescClazz, "", "()V"); - if (usb_devDescMid == NULL) { - return -1; - } - usb_devDescFID_bLength = env->GetFieldID(usb_devDescClazz, "bLength", "B"); - usb_devDescFID_bDescriptorType = env->GetFieldID(usb_devDescClazz, "bDescriptorType", "B"); - usb_devDescFID_bcdUSB = env->GetFieldID(usb_devDescClazz, "bcdUSB", "S"); - usb_devDescFID_bDeviceClass = env->GetFieldID(usb_devDescClazz, "bDeviceClass", "B"); - usb_devDescFID_bDeviceSubClass = env->GetFieldID(usb_devDescClazz, "bDeviceSubClass", "B"); - usb_devDescFID_bDeviceProtocol = env->GetFieldID(usb_devDescClazz, "bDeviceProtocol", "B"); - usb_devDescFID_bMaxPacketSize0 = env->GetFieldID(usb_devDescClazz, "bMaxPacketSize0", "B"); - usb_devDescFID_idVendor = env->GetFieldID(usb_devDescClazz, "idVendor", "S"); - usb_devDescFID_idProduct = env->GetFieldID(usb_devDescClazz, "idProduct", "S"); - usb_devDescFID_bcdDevice = env->GetFieldID(usb_devDescClazz, "bcdDevice", "S"); - usb_devDescFID_iManufacturer = env->GetFieldID(usb_devDescClazz, "iManufacturer", "B"); - usb_devDescFID_iProduct = env->GetFieldID(usb_devDescClazz, "iProduct", "B"); - usb_devDescFID_iSerialNumber = env->GetFieldID(usb_devDescClazz, "iSerialNumber", "B"); - usb_devDescFID_bNumConfigurations = env->GetFieldID(usb_devDescClazz, "bNumConfigurations", "B"); - - - #ifdef DEBUGON - printf("usb_device_descriptor references loaded\n"); - #endif - /* usb_configuration_descriptor*/ - jobject confDescClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Config_Descriptor");//returns a local reference - usb_confDescClazz = (jclass)env->NewGlobalRef(confDescClazz);//make it global - if (usb_confDescClazz == NULL) { - return -1; /* exception thrown */ - } - usb_confDescMid = env->GetMethodID(usb_confDescClazz, "", "()V"); - if (usb_confDescMid == NULL) { - return -1; - } - - usb_confDescFID_bLength = env->GetFieldID(usb_confDescClazz, "bLength", "B"); - usb_confDescFID_bDescriptorType = env->GetFieldID(usb_confDescClazz, "bDescriptorType", "B"); - usb_confDescFID_wTotalLength = env->GetFieldID(usb_confDescClazz, "wTotalLength", "S"); - usb_confDescFID_bNumInterfaces = env->GetFieldID(usb_confDescClazz, "bNumInterfaces", "B"); - usb_confDescFID_bConfigurationValue = env->GetFieldID(usb_confDescClazz, "bConfigurationValue", "B"); - usb_confDescFID_iConfiguration = env->GetFieldID(usb_confDescClazz, "iConfiguration", "B"); - usb_confDescFID_bmAttributes = env->GetFieldID(usb_confDescClazz, "bmAttributes", "B"); - usb_confDescFID_MaxPower = env->GetFieldID(usb_confDescClazz, "MaxPower", "B"); - usb_confDescFID_interface_ = env->GetFieldID(usb_confDescClazz, "interface_", "[Lch/ntb/inf/libusbJava/Usb_Interface;"); - usb_confDescFID_extra = env->GetFieldID(usb_confDescClazz, "extra", "[B"); - usb_confDescFID_extralen = env->GetFieldID(usb_confDescClazz, "extralen", "I"); - #ifdef DEBUGON - printf("usb_configuration_descriptor references loaded\n"); - #endif - /* usb_interface*/ - jobject intClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Interface");//returns a local reference - usb_intClazz = (jclass)env->NewGlobalRef(intClazz);//make it global - if (usb_intClazz == NULL) { - return -1; /* exception thrown */ - } - usb_intMid = env->GetMethodID(usb_intClazz, "", "()V"); - if (usb_intMid == NULL) { - return -1; - } - usb_intFID_altsetting = env->GetFieldID(usb_intClazz, "altsetting", "[Lch/ntb/inf/libusbJava/Usb_Interface_Descriptor;"); - usb_intFID_num_altsetting = env->GetFieldID(usb_intClazz, "num_altsetting", "I"); - #ifdef DEBUGON - printf("usb_interface references loaded\n"); - #endif - /* usb_interface_descriptor*/ - jobject intDescClazz = env->FindClass( "ch/ntb/inf/libusbJava/Usb_Interface_Descriptor");//returns a local reference - usb_intDescClazz = (jclass)env->NewGlobalRef(intDescClazz);//make it global - if (usb_intDescClazz == NULL) { - return -1; /* exception thrown */ - } - usb_intDescMid = env->GetMethodID(usb_intDescClazz, "", "()V"); - if (usb_intDescMid == NULL) { - return -1; - } - usb_intDescFID_bLength = env->GetFieldID(usb_intDescClazz, "bLength", "B"); - usb_intDescFID_bDescriptorType = env->GetFieldID(usb_intDescClazz, "bDescriptorType", "B"); - usb_intDescFID_bInterfaceNumber = env->GetFieldID(usb_intDescClazz, "bInterfaceNumber", "B"); - usb_intDescFID_bAlternateSetting = env->GetFieldID(usb_intDescClazz, "bAlternateSetting", "B"); - usb_intDescFID_bNumEndpoints = env->GetFieldID(usb_intDescClazz, "bNumEndpoints", "B"); - usb_intDescFID_bInterfaceClass = env->GetFieldID(usb_intDescClazz, "bInterfaceClass", "B"); - usb_intDescFID_bInterfaceSubClass = env->GetFieldID(usb_intDescClazz, "bInterfaceSubClass", "B"); - usb_intDescFID_bInterfaceProtocol = env->GetFieldID(usb_intDescClazz, "bInterfaceProtocol", "B"); - usb_intDescFID_iInterface = env->GetFieldID(usb_intDescClazz, "iInterface", "B"); - usb_intDescFID_endpoint = env->GetFieldID(usb_intDescClazz, "endpoint", "[Lch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor;"); - usb_intDescFID_extra = env->GetFieldID(usb_intDescClazz, "extra", "[B"); - usb_intDescFID_extralen = env->GetFieldID(usb_intDescClazz, "extralen", "I"); - #ifdef DEBUGON - printf("usb_interface_descriptor references loaded\n"); - #endif - /* usb_endpoint_descriptor*/ - jobject epDescClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor");//returns a local reference - usb_epDescClazz = (jclass)env->NewGlobalRef(epDescClazz);//make it global - if (usb_epDescClazz == NULL) { - return -1; /* exception thrown */ - } - usb_epDescMid = env->GetMethodID(usb_epDescClazz, "", "()V"); - if (usb_epDescMid == NULL) { - return -1; - } - usb_epDescFID_bLength = env->GetFieldID(usb_epDescClazz, "bLength", "B"); - usb_epDescFID_bDescriptorType = env->GetFieldID(usb_epDescClazz, "bDescriptorType", "B"); - usb_epDescFID_bEndpointAddress = env->GetFieldID(usb_epDescClazz, "bEndpointAddress", "B"); - usb_epDescFID_bmAttributes = env->GetFieldID(usb_epDescClazz, "bmAttributes", "B"); - usb_epDescFID_wMaxPacketSize = env->GetFieldID(usb_epDescClazz, "wMaxPacketSize", "S"); - usb_epDescFID_bInterval = env->GetFieldID(usb_epDescClazz, "bInterval", "B"); - usb_epDescFID_bRefresh = env->GetFieldID(usb_epDescClazz, "bRefresh", "B"); - usb_epDescFID_bSynchAddress = env->GetFieldID(usb_epDescClazz, "bSynchAddress", "B"); - usb_epDescFID_extra = env->GetFieldID(usb_epDescClazz, "extra", "[B"); - usb_epDescFID_extralen = env->GetFieldID(usb_epDescClazz, "extralen", "I"); - #ifdef DEBUGON - printf("usb_endpoint_descriptor references loaded\n"); - #endif - /*libusb_event*/ - jobject cb_clazz = env->FindClass("ch/ntb/inf/libusbJava/Libusb_event");//returns a local reference - usb_cb_clazz = (jclass)env->NewGlobalRef(cb_clazz);//make it global - if (usb_cb_clazz == NULL) { - printf("load Clazz failed\n"); - return -1; /*exception thrown*/ - } - usb_transfer_cb_Mid = env->GetMethodID(usb_cb_clazz, "transferCallback", "()V"); - if (usb_transfer_cb_Mid == NULL) { - printf("load method transferCallback failed\n"); - return -1; /* exception thrown */ - } - usb_fd_added_cb_Mid = env->GetMethodID(usb_cb_clazz, "fdAddedCallback", "(I)V"); - if (usb_fd_added_cb_Mid == NULL) { - printf("load method fdAddedCallback failed\n"); - return -1;/* exception thrown */ - } - usb_fd_removed_cb_Mid = env->GetMethodID(usb_cb_clazz, "fdRemovedCallback", "(I)V"); - if (usb_fd_removed_cb_Mid == NULL) { - printf("load method fdRemovedCallback failed\n"); - return -1;/* exception thrown */ - } - #ifdef DEBUGON - printf("usb_event_descriptor references loaded\n"); - #endif - /*Libusb_pollfd*/ - jobject pollfd_clazz = env->FindClass("ch/ntb/inf/libusbJava/Libusb_pollfd");//returns a local reference - usb_pollfd_clazz = (jclass)env->NewGlobalRef(pollfd_clazz);//make it global - if (usb_pollfd_clazz == NULL) { - return -1; /*exception thrown*/ - } - usb_pollfd_Mid = env->GetMethodID(usb_pollfd_clazz, "", "()V"); - // Bugfix: if (usb_devMid == NULL) @ Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device_1list - Copy-paste error - if (usb_pollfd_Mid == NULL) { - return -1; /*exception thrown*/ - } - usb_pollfdFID_fd = env->GetFieldID(usb_pollfd_clazz, "fd", "I"); - usb_pollfdFID_events = env->GetFieldID(usb_pollfd_clazz, "events", "B"); - #ifdef DEBUGON - printf("Libusb_pollfd_descriptor references loaded\n"); - #endif - - #ifdef DEBUGON - printf("libusb_init: Field initialization done \n"); - #endif - } -#endif - - instance->jni.objects = objects; - instance->jni.refs_loaded = -1; - } - } - else - { - result = 0; - } - - return result; -} - -/*! \brief Unloads all cached references - * - * \param instance Pointer to an instance of a status data struct containing necessary information. - * \param env Pointer to the JVM-Environment, where actions can be performed with */ -static __inline void ReferencesUnload(tLUJ_Instance *instance, JNIEnv *env) -{ - if (instance->jni.refs_loaded == 0) - return; - - int i = 0; - const JNIObject *objects = instance->jni.objects; - - /* Walk through all registered objects and try to - * disconnect them. */ - while (objects[i].disconnect != NULL) { - objects[i].disconnect(env); - ++i; - } - - instance->jni.refs_loaded = 0; -} - -/* Unit-Tests for References*-Functions */ -#ifdef DO_UNIT_TEST - enum { - TEST_RESULT_TEST1 = 0, - TEST_RESULT_TEST2, - TEST_RESULT_TEST3, - TEST_RESULT_TEST_FAILS, - TEST_RESULT_PARAM_FORWARDING, - - TEST_RESULT_COUNT - }; - - enum { - TEST_OBJECTS_NORMAL = 0, - TEST_OBJECTS_FAILING, - TEST_OBJECTS_EMPTY, - TEST_OBJECTS_PARAM_FORWARDING, - }; - - static struct ReferencesXTestsData { - tLUJ_Instance instance; - - struct { - int connect; - int disconnect; - }executed[TEST_RESULT_COUNT]; - }ReferencesXTestsData; - - static int Test1_connect(JNIEnv *env); - static void Test1_disconnect(JNIEnv *env); - static int Test2_connect(JNIEnv *env); - static void Test2_disconnect(JNIEnv *env); - static int Test3_connect(JNIEnv *env); - static void Test3_disconnect(JNIEnv *env); - static int TestFails_connect(JNIEnv *env); - static void TestFails_disconnect(JNIEnv *env); - static int TestParamForwarding_connect(JNIEnv *env); - static void TestParamForwarding_disconnect(JNIEnv *env); - - static const tJNIObject ReferencesXTestsObjects[][5] = { - { /* TEST_OBJECTS_NORMAL */ - OBJ(Test1), - OBJ(Test2), - { NULL, NULL}, - OBJ(Test3), - { NULL, NULL}, - }, - { /* TEST_OBJECTS_FAILING */ - OBJ(Test1), - OBJ(Test2), - OBJ(TestFails), - { NULL, NULL}, - { NULL, NULL}, - }, - { /* TEST_OBJECTS_EMPTY */ - { NULL, NULL}, - { NULL, NULL}, - { NULL, NULL}, - { NULL, NULL}, - { NULL, NULL}, - }, - { /* TEST_OBJECTS_PARAM_FORWARDING */ - OBJ(TestParamForwarding), - { NULL, NULL }, - { NULL, NULL }, - { NULL, NULL }, - { NULL, NULL }, - } - }; - - TEST_CASE(ReferencesCheckTest) { - TEST_CONTEXT(); - memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); - CuAssert(tc, "Return value", ReferencesCheck(&ReferencesXTestsData.instance, env) < 0); - CuAssert(tc, "Exception Thrown", env->ExceptionCheck() == JNI_TRUE); - - ThrowLibusbErrorTestEvaluate(tc, env, ERROR_JAVA_REFERENCES_NOT_LOADED); - - ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[2]); - CuAssert(tc, "Return value", ReferencesCheck(&ReferencesXTestsData.instance, env) == 0); - CuAssert(tc, "No exception Thrown", env->ExceptionCheck() == JNI_FALSE); - } - - TEST_CASE(ReferencesLoadTest) { - TEST_CONTEXT(); - - /* Check initial loading of modules */ - memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); - CuAssert(tc, "References loaded return value", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); - CuAssert(tc, "1st module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect != 0); - CuAssert(tc, "1st module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); - CuAssert(tc, "2nd module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect != 0); - CuAssert(tc, "2nd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); - CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); - - /* Check repeated load call */ - memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); - CuAssert(tc, "References loaded return value", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); - CuAssert(tc, "1st module NOT loaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); - CuAssert(tc, "1st module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); - CuAssert(tc, "2nd module NOT loaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); - CuAssert(tc, "2nd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); - CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); - - memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); - CuAssert(tc, "References loaded empty list", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_EMPTY]) >= 0); - CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); - CuAssert(tc, "1st module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); - CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); - CuAssert(tc, "2nd module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); - CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); - } - - TEST_CASE(ReferencesUnloadTest) { - TEST_CONTEXT(); - - memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); - CuAssert(tc, "References loaded", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); - - /* Check initial unloading of modules */ - memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); - ReferencesUnload(&ReferencesXTestsData.instance, env); - CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); - CuAssert(tc, "1st module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect != 0); - CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); - CuAssert(tc, "2nd module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect != 0); - CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); - - /* Check repeated unload call */ - memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); - ReferencesUnload(&ReferencesXTestsData.instance, env); - CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); - CuAssert(tc, "1st module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); - CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); - CuAssert(tc, "2nd module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); - CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); - - memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); - CuAssert(tc, "References loaded", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); - - memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); - CuAssert(tc, "References loaded empty list", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_EMPTY]) >= 0); - CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); - CuAssert(tc, "1st module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); - CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); - CuAssert(tc, "2nd module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); - CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); - } - - TEST_CASE(ReferencesLoadRollbackTest) { - TEST_CONTEXT(); - - memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); - CuAssert(tc, "References load rollback", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_FAILING]) < 0); - CuAssert(tc, "1st module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect != 0); - CuAssert(tc, "1st module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect != 0); - CuAssert(tc, "2nd module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect != 0); - CuAssert(tc, "2nd module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect != 0); - CuAssert(tc, "3rd module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].connect != 0); - CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].disconnect == 0); - } - - TEST_CASE(ReferencesParameterForwardTest) { - memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); - CuAssert(tc, "References load", ReferencesLoad(&ReferencesXTestsData.instance, (JNIEnv *)0x06051982, ReferencesXTestsObjects[TEST_OBJECTS_PARAM_FORWARDING]) >= 0); - ReferencesUnload(&ReferencesXTestsData.instance, (JNIEnv *)0x06051982); - CuAssert(tc, "Connect parameter arrived.", ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].connect != 0); - CuAssert(tc, "Disconnect parameter arrived.", ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].disconnect != 0); - } - - static int Test1_connect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect = -1; - return 0; - } - - static void Test1_disconnect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect = -1; - } - - static int Test2_connect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect = -1; - return 0; - } - - static void Test2_disconnect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect = -1; - } - - static int Test3_connect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect = -1; - return 0; - } - - static void Test3_disconnect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect = -1; - } - - static int TestFails_connect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].connect = -1; - return -1; - } - - static void TestFails_disconnect(JNIEnv *env) { - ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].disconnect = -1; - } - - static int TestParamForwarding_connect(JNIEnv *env) { - if (env != ((JNIEnv *)0x06051982)) - { - ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].connect = 0; - return -1; - } - - ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].connect = -1; - return 0; - } - - static void TestParamForwarding_disconnect(JNIEnv *env) { - if (env != ((JNIEnv *)0x06051982)) - { - ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].disconnect = 0; - return; - } - - ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].disconnect = -1; - } -#endif - -#ifdef DO_UNIT_TEST - typedef CuSuite* (*tSuiteNew)(void); - - extern "C" JNIEXPORT CuSuite* GetLibusbJavaSuite(tSuiteNew SuiteNew, JNIEnv *env); - - TEST_CASE(Usb_Device_Tests) { -// TEST_CONTEXT(); - - CuAssert(tc, "TODO", 0); - } - -/*! \brief Exports the test suite for the libraries helper functions - * - * \param SuiteNew Pointer to an allocator function for a CuTest instance - * \param env JNI Environment for the test - * - * \return A fully setup test suite. */ -JNIEXPORT CuSuite* GetLibusbJavaSuite(tSuiteNew SuiteNew, JNIEnv *env) -{ - CuSuite* suite = SuiteNew(); - - SUITE_ADD_TEST(suite, JNI_OnLoad_test); - - SUITE_ADD_TEST(suite, ReferencesLoadTest); - SUITE_ADD_TEST(suite, ReferencesUnloadTest); - SUITE_ADD_TEST(suite, ReferencesLoadRollbackTest); - SUITE_ADD_TEST(suite, ReferencesCheckTest); - SUITE_ADD_TEST(suite, ReferencesParameterForwardTest); - - - SUITE_ADD_TEST(suite, ThrowLibusbErrorTest); - SUITE_ADD_TEST(suite, ThrowIfUnsuccessfulTest); - - SUITE_ADD_TEST(suite, Usb_Device_Tests); - - test_context.env = env; - return suite; -} -#endif +/*! \file + * \brief Java libusb1.0 wrapper + * + * \copyright 2010-2012 NTB Interstate University of Applied Sciences of Technology Buchs + * This libary is covered by the LGPL, read LGPL.txt for details + * + * \author Roger Millischer (original author) + * \author Ueli Niederer (modifications and enhancements) + * + * \todo Currently all the pointers and handles passed to and received from libusb are coded + * in long values to get them in JVM. + * Clebert Suconic ( http://planet.jboss.org/post/pointers_in_jni_c ) suggests a + * possibly more elegant way to deal with this issue: + * Make use of the ByteBuffer-Class delivered by with the native IO package. + * (java.nio). As this class is made to store the start pointer to native buffers + * we could create a "ByteBuffer" of length 0 where the start address represents + * e.g. the handle. This can be done using the following JNI Call: + * env->NewDirectByteBuffer(myPointer, 0); // size = 0, you don't want anyone to + * // change the data you are pointing to... + */ + +/******************************************************************************************** + * + * Includes + * + *******************************************************************************************/ +#include +#include +#include +#include +#include + +#ifdef DO_UNIT_TEST +# include + +# define TEST_CASE(name) static void name(CuTest *tc) +#endif + +#include + +#include + +#include "LibusbJava.h" +#include "objects/Usb_Device.h" + +//#define DEBUGON + +typedef struct JNIObject { + int (*connect)(JNIEnv *env); + void (*disconnect)(JNIEnv *env); +}tJNIObject; + +#define ERROR_JAVA_REFERENCES_NOT_LOADED -100 +#define ERROR_JAVA_WRONG_ENVIRONMENT -101 +#define ERROR_JAVA_ILEGAL_DEVICE_HANDLE -102 + +#define OBJ(name) { name ## _connect, name ## _disconnect } + +/*! \brief Structure holding all the global information needed. */ +typedef struct LUJ_Instance { + struct JNI{ +#ifdef DO_UNIT_TEST + int onLoadCalled; /*!< Set after OnLoad is called, reset after OnUnload was called. Only + used for unit tests */ +#endif + int refs_loaded; /*!< 0 if references are NOT loaded. */ + const tJNIObject * objects; /*!< Points to the table of connect/disconnect calls + that are perfomed while loading/unloading */ + }jni; +}tLUJ_Instance; + +/******************************************************************************************** + * + * Globals + * + *******************************************************************************************/ +/* if > 0 an LibusbJava specific error string is set*/ +static char *libusbJavaError = NULL; + +static const tJNIObject jniObjects[] = { + OBJ(Usb_Device), + { NULL, NULL} +}; +/******************************************************************************************** + * + * Macros + * + *******************************************************************************************/ +/* to set and clear LibusbJava specific errors*/ +#define setLibusbJavaError(error) libusbJavaError = error +#define clearLibusbJavaError() libusbJavaError = NULL + +/******************************************************************************************** + * + * Prototyp and define for callback-function + * + *******************************************************************************************/ +static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer); + +static void + LIBUSB_CALL fd_added_callback(int fd, short events, void *user_data); + +static void LIBUSB_CALL fd_removed_callback(int fd, void *user_data); + +/******************************************************************************************** + * + * Local helper functions + * + *******************************************************************************************/ +static __inline int ReferencesCheck(tLUJ_Instance *instance, JNIEnv *env); +static __inline int ReferencesLoad(tLUJ_Instance *instance, JNIEnv *env, const tJNIObject *objects); +static __inline void ReferencesUnload(tLUJ_Instance *instance, JNIEnv *env); +static __inline jbyteArray JNICALL to_byteArray(JNIEnv *env, const void *data, size_t len); +static __inline void JNICALL ThrowIfUnsuccessful(JNIEnv *env, int libusb_result); +static __inline void JNICALL ThrowLibusbError(JNIEnv *env, jint code); + +/******************************************************************************************** + * + * References + * + *******************************************************************************************/ +/* class references*/ +static jclass usb_devDescClazz, usb_confDescClazz, usb_intClazz, + usb_intDescClazz, usb_epDescClazz, usb_cb_clazz, usb_pollfd_clazz; + +/* method ID references*/ +static jmethodID usb_devDescMid, usb_confDescMid, usb_intMid, + usb_intDescMid, usb_epDescMid, usb_transfer_cb_Mid, + usb_fd_added_cb_Mid, usb_fd_removed_cb_Mid, usb_pollfd_Mid; + +/* field ID references*/ +/* usb_deviceDescriptor */ +static jfieldID usb_devDescFID_bLength, usb_devDescFID_bDescriptorType, + usb_devDescFID_bcdUSB, usb_devDescFID_bDeviceClass, + usb_devDescFID_bDeviceSubClass, usb_devDescFID_bDeviceProtocol, + usb_devDescFID_bMaxPacketSize0, usb_devDescFID_idVendor, + usb_devDescFID_idProduct, usb_devDescFID_bcdDevice, + usb_devDescFID_iManufacturer, usb_devDescFID_iProduct, + usb_devDescFID_iSerialNumber, usb_devDescFID_bNumConfigurations; +/* usb_configurationDescriptor*/ +static jfieldID usb_confDescFID_bLength, usb_confDescFID_bDescriptorType, + usb_confDescFID_wTotalLength, usb_confDescFID_bNumInterfaces, + usb_confDescFID_bConfigurationValue, usb_confDescFID_iConfiguration, + usb_confDescFID_bmAttributes, usb_confDescFID_MaxPower, + usb_confDescFID_interface_, usb_confDescFID_extra, + usb_confDescFID_extralen; +/* usb_interface*/ +static jfieldID usb_intFID_altsetting, usb_intFID_num_altsetting; +/* usb_intDesc*/ +static jfieldID usb_intDescFID_bLength, usb_intDescFID_bDescriptorType, + usb_intDescFID_bInterfaceNumber, usb_intDescFID_bAlternateSetting, + usb_intDescFID_bNumEndpoints, usb_intDescFID_bInterfaceClass, + usb_intDescFID_bInterfaceSubClass, usb_intDescFID_bInterfaceProtocol, + usb_intDescFID_iInterface, usb_intDescFID_endpoint, + usb_intDescFID_extra, usb_intDescFID_extralen; +/* usb_endpointDescriptor*/ +static jfieldID usb_epDescFID_bLength, usb_epDescFID_bDescriptorType, + usb_epDescFID_bEndpointAddress, usb_epDescFID_bmAttributes, + usb_epDescFID_wMaxPacketSize, usb_epDescFID_bInterval, + usb_epDescFID_bRefresh, usb_epDescFID_bSynchAddress, + usb_epDescFID_extra, usb_epDescFID_extralen; +/*Libusb_pollfd*/ +static jfieldID usb_pollfdFID_fd, usb_pollfdFID_events; + +#ifdef DO_UNIT_TEST + static struct TestContext + { + JNIEnv *env; + }test_context = { NULL }; + + # define TEST_CONTEXT() JNIEnv *env = test_context.env +#endif + +static tLUJ_Instance info = {{0}}; + +/******************************************************************************************** + * + * Library Events + * + *******************************************************************************************/ + +/*! \brief The VM calls JNI_OnLoad when the native library is loaded (for example, through + * System.loadLibrary). + * + * \see http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#JNI_OnLoad + * + * \return The JNI version needed by the native library (use constants as JNI_VERSION_X_Y). + */ +jint JNI_OnLoad(JavaVM *vm, void *reserved) +{ + JNIEnv* env = NULL; + +#ifdef DO_UNIT_TEST + info.jni.onLoadCalled = -1; +#endif + + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_1) != JNI_OK) { + return -1; + } + + ReferencesLoad(&info, env, jniObjects); + + return JNI_VERSION_1_1; +} + +#if defined(DO_UNIT_TEST) + TEST_CASE(JNI_OnLoad_test) + { + TEST_CONTEXT(); + + CuAssert(tc, "correct initialization", info.jni.onLoadCalled == 0); + info.jni.onLoadCalled=10; + + /* Load the LibusbJava1 class to force the initialization of the library */ + jclass clazz = env->FindClass("ch/ntb/inf/libusbJava/LibusbJava1"); + CuAssert(tc, "ch/ntb/inf/libusbJava/LibusbJava1 loaded", clazz != NULL); + + CuAssert(tc, "JNI_OnLoad was executed", info.jni.onLoadCalled != 0); + env->DeleteLocalRef(clazz); + + /* As garbage collection is not necessarily run after freeing a reference + * and there is no way to force the run of GC, we can't test this here. */ +// CuAssert(tc, "JNI_OnUnload was executed", info.jni.onLoadCalled == 0); + } +#endif + +/*! \brief The VM calls JNI_OnUnload when the class loader containing the native library is + * garbage collected. + * + * This function can be used to perform cleanup operations. Because this function is + * called in an unknown context (such as from a finalizer), the programmer should be + * conservative on using Java VM services, and refrain from arbitrary Java call-backs. + * + * \see http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#JNI_OnUnload + */ +void JNI_OnUnload(JavaVM *vm, void *reserved) +{ + JNIEnv* env = NULL; + + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_1) == JNI_OK) { + ReferencesUnload(&info, env); + } + +#ifdef DO_UNIT_TEST + info.jni.onLoadCalled = 0; +#endif +} + +/******************************************************************************************** + * + * Methods + * + *******************************************************************************************/ + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_debug + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1debug( JNIEnv *env, jclass obj, jlong ctx, jint level) { + clearLibusbJavaError(); + libusb_context *context = NULL; + if (ctx) { + context = (libusb_context*) ((unsigned long) ctx); + } + libusb_set_debug(context, level); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_init + * Signature: ()J + ********************************************************************************************/ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1init( JNIEnv *env, jclass obj) { + int res; + libusb_context *context; + clearLibusbJavaError(); + + res = libusb_init(&context); + + #ifdef DEBUGON + printf("res = %i \n", res); + printf("env = %p\n", env); + printf("context = %p\n", &context); + #endif + + if (res != 0) + { + ThrowLibusbError(env, res); + return 0; + } + else + { + return (jlong) context; + } +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_exit + * Signature: (J)V + *******************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1exit(JNIEnv *env, jclass obj, jlong ctx) { + libusb_context *context = NULL; + clearLibusbJavaError(); + if (ctx) { + context = (libusb_context*) ((unsigned long) ctx); + } + libusb_exit(context); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_device_list + * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; + ********************************************************************************************/ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device_1list( JNIEnv *env, jclass obj, jlong ctx) { + libusb_device **devs; + libusb_context *context = (ctx != 0) ? (libusb_context*)ctx : NULL; + ssize_t cnt; + int res, a, i; + uint8_t c, h, e; + + if (ReferencesCheck(&info, env) != 0) return NULL; + + /* objects*/ + jobject root_usb_devObj, usb_devObj, usb_devObj_next, usb_devObj_prev, + usb_devDescObj, usb_confDescObj, usb_intObj, usb_intDescObj, + usb_epDescObj; + + jobjectArray usb_confDescObjArray, usb_intObjArray, usb_intDescObjArray, + usb_epDescObjArray; + clearLibusbJavaError(); + + libusb_config_descriptor *conf_desc; + + cnt = libusb_get_device_list(context, &devs); + if (cnt < 0) { + setLibusbJavaError("libusb_get_device_list: Error on Memory allocation"); + libusb_free_device_list(devs, 1); + return NULL; + } + else if (cnt == 0) { + libusb_free_device_list(devs, 1); + return NULL; + } + + usb_devObj = NULL; + usb_devObj_next = NULL; + usb_devObj_prev = NULL; + + /* create a new object for every device */ + for (i = 0; i < cnt; i++) { +#ifdef DEBUGON + printf("libusb_get_device_list: dev %u \n", i); +#endif + libusb_device_descriptor dev_desc; + res = libusb_get_device_descriptor(devs[i], &dev_desc); + + if (res) { + /* this shouldn't happen*/ + printf("\t libusb_get _device_list: dev %u coudn't read Devicedescriptor\n",i); + continue; + } + + if (dev_desc.bLength != 18) { + printf("Corrupt Devicedescriptor dev %d\n", i); + continue; + } + + usb_devObj = Usb_Device_create(env, devs[i], libusb_get_device_address(devs[i])); + if (usb_devObj == NULL) { + setLibusbJavaError("shared library error: Error NewObject (usb_devObj)"); + return NULL; + } + + /* If it's the root element (no previous elements available) we set the root value */ + if (usb_devObj_prev == NULL) { + root_usb_devObj = usb_devObj; + } + else { + /* If it's not the root element, simply enqueue the newly created device */ + Usb_Device_NextSet(env, usb_devObj_prev, usb_devObj); + } + + /* Fill the fields of the object */ + Usb_Device_NextSet(env, usb_devObj, usb_devObj_next); + Usb_Device_PrevSet(env, usb_devObj, usb_devObj_prev); + + /*device Descriptor*/ + usb_devDescObj = env->NewObject(usb_devDescClazz, usb_devDescMid); + if (!usb_devDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_devDescObj)"); + return NULL; + } + env->SetByteField(usb_devDescObj, usb_devDescFID_bLength, dev_desc.bLength); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDescriptorType, dev_desc.bDescriptorType); + env->SetShortField(usb_devDescObj, usb_devDescFID_bcdUSB, dev_desc.bcdUSB); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceClass, dev_desc.bDeviceClass); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceSubClass, dev_desc.bDeviceSubClass); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceProtocol, dev_desc.bDeviceProtocol); + env->SetByteField(usb_devDescObj, usb_devDescFID_bMaxPacketSize0, dev_desc.bMaxPacketSize0); + env->SetShortField(usb_devDescObj, usb_devDescFID_idVendor, dev_desc.idVendor); + env->SetShortField(usb_devDescObj, usb_devDescFID_idProduct, dev_desc.idProduct); + env->SetShortField(usb_devDescObj, usb_devDescFID_bcdDevice, dev_desc.bcdDevice); + env->SetByteField(usb_devDescObj, usb_devDescFID_iManufacturer, dev_desc.iManufacturer); + env->SetByteField(usb_devDescObj, usb_devDescFID_iProduct, dev_desc.iProduct); + env->SetByteField(usb_devDescObj, usb_devDescFID_iSerialNumber, dev_desc.iSerialNumber); + env->SetByteField(usb_devDescObj, usb_devDescFID_bNumConfigurations, dev_desc.bNumConfigurations); + // TODO @NIUE: Why a reference on itself?! And why should we use a field ID from the Usb_Device class + // for an instance of the Descriptor object? + // env->SetObjectField(usb_devDescObj, usb_devFID_descriptor, usb_devDescObj); + Usb_Device_DescriptorSet(env, usb_devObj, usb_devDescObj); + + /*configuration descriptor*/ + /*Loop through all of the configurations*/ + usb_confDescObjArray = (jobjectArray) env->NewObjectArray(dev_desc.bNumConfigurations, usb_confDescClazz, NULL); + if (!usb_confDescObjArray) { + setLibusbJavaError("shared library error: Error NewOjectArray"); + return NULL; + } + for (c = 0; c < dev_desc.bNumConfigurations; c++) { +#ifdef DEBUGON + printf("\t\tlibusb_get_device_list: configuration %u, Dev: %d \n", c, i); +#endif + res = libusb_get_config_descriptor(devs[i], c, &conf_desc); + if (res) { + continue; + } + usb_confDescObj = env->NewObject(usb_confDescClazz, usb_confDescMid); + if (!usb_confDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_confDescObjArray, c, usb_confDescObj);/*add it to the Array*/ + /*fill the fields*/ + env->SetByteField(usb_confDescObj, usb_confDescFID_bLength, conf_desc->bLength); + env->SetByteField(usb_confDescObj, usb_confDescFID_bDescriptorType, conf_desc->bDescriptorType); + env->SetShortField(usb_confDescObj, usb_confDescFID_wTotalLength, conf_desc->wTotalLength); + env->SetByteField(usb_confDescObj, usb_confDescFID_bNumInterfaces, conf_desc->bNumInterfaces); + env->SetByteField(usb_confDescObj, usb_confDescFID_bConfigurationValue, conf_desc->bConfigurationValue); + env->SetByteField(usb_confDescObj, usb_confDescFID_iConfiguration, conf_desc->iConfiguration); + env->SetByteField(usb_confDescObj, usb_confDescFID_bmAttributes, conf_desc->bmAttributes); + env->SetByteField(usb_confDescObj, usb_confDescFID_MaxPower, conf_desc->MaxPower); + env->SetIntField(usb_confDescObj, usb_confDescFID_extralen, conf_desc->extra_length); + if (conf_desc->extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->extra, conf_desc->extra_length); + env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, NULL); + } + /*interface*/ + usb_intObjArray = (jobjectArray) env->NewObjectArray(conf_desc->bNumInterfaces, usb_intClazz, NULL); + if (!usb_intObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_intObjArray)"); + return NULL; + } + for (h = 0; h < conf_desc->bNumInterfaces; h++) { +#ifdef DEBUGON + printf("\t\t\tlibusb_get_device_list: interface %u \n", h); +#endif + + if (conf_desc->interface == NULL) { + /* this shouldn't happen*/ + printf("(*conf_desc)->usb_interface == NULL"); + continue; + } + usb_intObj = env->NewObject(usb_intClazz, usb_intMid); + if (!usb_intObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_intObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_intObjArray, h, usb_intObj); + env->SetIntField(usb_intObj, usb_intFID_num_altsetting, conf_desc->interface[h].num_altsetting); + // interface descriptor + usb_intDescObjArray = (jobjectArray) env->NewObjectArray( conf_desc->interface[h].num_altsetting, usb_intDescClazz, NULL); + if (!usb_intDescObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_intDescObjArray)"); + return NULL; + } + for (a = 0; a < conf_desc->interface[h].num_altsetting; a++) { +#ifdef DEBUGON + printf("\t\t\t\tlibusb_get_device_list: interface descriptor %u \n", a); +#endif + if (conf_desc->interface[h].altsetting == NULL) { + // this shouldn't happen + printf("LibusbJava: libusb_get_device_list: (*conf_desc)->interface->altsetting == NULL\n"); + continue; + } + usb_intDescObj = env->NewObject(usb_intDescClazz, usb_intDescMid); + if (!usb_intDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_intDescObjArray, a, usb_intDescObj); + /*fill fields*/ + env->SetByteField(usb_intDescObj, usb_intDescFID_bLength, conf_desc->interface[h].altsetting[a].bLength); + env->SetByteField(usb_intDescObj, usb_intDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].bDescriptorType); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceNumber, conf_desc->interface[h].altsetting[a].bInterfaceNumber); + env->SetByteField(usb_intDescObj, usb_intDescFID_bAlternateSetting, conf_desc->interface[h].altsetting[a].bAlternateSetting); + env->SetByteField(usb_intDescObj, usb_intDescFID_bNumEndpoints, conf_desc->interface[h].altsetting[a].bNumEndpoints); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceClass, conf_desc->interface[h].altsetting[a].bInterfaceClass); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceSubClass, conf_desc->interface[h].altsetting[a].bInterfaceSubClass); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceProtocol, conf_desc->interface[h].altsetting[a].bInterfaceProtocol); + env->SetByteField(usb_intDescObj, usb_intDescFID_iInterface, conf_desc->interface[h].altsetting[a].iInterface); + env->SetIntField(usb_intDescObj, usb_intDescFID_extralen, conf_desc->interface[h].altsetting[a].extra_length); + if (conf_desc->interface[h].altsetting[a].extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].extra, conf_desc->interface[h].altsetting[a].extra_length); + env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, NULL); + } + /*endpoint descriptor*/ + usb_epDescObjArray = (jobjectArray) env->NewObjectArray( conf_desc->interface[h].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL); + if (!usb_epDescObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_epDescObjArray)"); + return NULL; + } + for (e = 0; e < conf_desc->interface[h].altsetting[a].bNumEndpoints; e++) { +#ifdef DEBUGON + printf("\t\t\t\t\tLibusb_get_device_list: endpoint descriptor %u \n",e); +#endif + + + if (conf_desc->interface[h].altsetting[a].endpoint == NULL) { + printf( "LibusbJava: usb_get_busses: (*conf_desc)->interface->altsetting->endpoint == NULL\n"); + return root_usb_devObj; + } + usb_epDescObj = env->NewObject(usb_epDescClazz, usb_epDescMid); + if (!usb_epDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_epDescObjArray, e, usb_epDescObj); + env->SetByteField(usb_epDescObj, usb_epDescFID_bLength, conf_desc->interface[h].altsetting[a].endpoint[e].bLength); + env->SetByteField(usb_epDescObj, usb_epDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].endpoint[e].bDescriptorType); + env->SetByteField(usb_epDescObj, usb_epDescFID_bEndpointAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bEndpointAddress); + env->SetByteField(usb_epDescObj, usb_epDescFID_bmAttributes, conf_desc->interface[h].altsetting[a].endpoint[e].bmAttributes); + env->SetShortField(usb_epDescObj, usb_epDescFID_wMaxPacketSize, conf_desc->interface[h].altsetting[a].endpoint[e].wMaxPacketSize); + env->SetByteField(usb_epDescObj, usb_epDescFID_bInterval, conf_desc->interface[h].altsetting[a].endpoint[e].bInterval); + env->SetByteField(usb_epDescObj, usb_epDescFID_bRefresh, conf_desc->interface[h].altsetting[a].endpoint[e].bRefresh); + env->SetByteField(usb_epDescObj, usb_epDescFID_bSynchAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bSynchAddress); + env->SetIntField(usb_epDescObj, usb_epDescFID_extralen, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); + if (conf_desc->interface[h].altsetting[a].endpoint[e].extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].endpoint[e].extra, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); + env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, NULL); + } + } + env->SetObjectField(usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray); + } + env->SetObjectField(usb_intObj, usb_intFID_altsetting, usb_intDescObjArray); + } + env->SetObjectField(usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray); + libusb_free_config_descriptor(conf_desc); + } + + if (res) { + Usb_Device_HandleSet(env, usb_devObj, NULL); + continue; + } + Usb_Device_ConfigSet(env, usb_devObj, usb_confDescObjArray); + usb_devObj_prev = usb_devObj; + } + + //Eliminate empty last device + Usb_Device_NextSet(env, usb_devObj_prev, NULL); + +// free(dev_desc); + libusb_free_device_list(devs, 0); +#ifdef DEBUGON + printf("libusb_get_device_list: done\n"); +#endif + return root_usb_devObj; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_bus_number + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)S + ********************************************************************************************/ +JNIEXPORT jshort JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1bus_1number( JNIEnv *env, jclass obj, jobject dev) { + clearLibusbJavaError(); + + if (ReferencesCheck(&info, env) != 0) return 0; + + libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); + if (libusb_dev == NULL) { + ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); + return 0; + } + + return libusb_get_bus_number(libusb_dev); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_max_iso_packet_size + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;S)I + ********************************************************************************************/ +JNIEXPORT jint +JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1max_1iso_1packet_1size( JNIEnv *env, jclass obj, jobject dev, jshort epAddr) { + clearLibusbJavaError(); + + if (ReferencesCheck(&info, env) != 0) return 0; + + libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); + if (libusb_dev == NULL) { + ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); + return 0; + } + + return libusb_get_max_iso_packet_size(libusb_dev, epAddr); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_ref_device + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Device; + ********************************************************************************************/ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1ref_1device(JNIEnv *env, jclass obj, jobject dev) { + clearLibusbJavaError(); + + if (ReferencesCheck(&info, env) != 0) return NULL; + + libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); + if (libusb_dev == NULL) { + ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); + return NULL; + } + + libusb_ref_device(libusb_dev); + return dev; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_unref_device + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unref_1device(JNIEnv *env, jclass obj, jobject dev) { + clearLibusbJavaError(); + if (ReferencesCheck(&info, env) != 0) return; + libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); + if (libusb_dev == NULL) { + ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); + return; + } + + libusb_unref_device(libusb_dev); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_open + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)J + ********************************************************************************************/ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open( JNIEnv *env, jclass obj, jobject dev) { + clearLibusbJavaError(); + libusb_device_handle *handle = NULL; + if (ReferencesCheck(&info, env) != 0) return 0; + libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); + if (libusb_dev == NULL) { + ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); + return 0; + } + + int res = libusb_open(libusb_dev, &handle); + + if(res != 0) + { + ThrowLibusbError(env, res); + handle = NULL; + } + + return (jlong)handle; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_open_device_with_vid_pid + * Signature: (JII)J + ********************************************************************************************/ +JNIEXPORT jlong +JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open_1device_1with_1vid_1pid(JNIEnv *env, jclass obj, jlong ctx, jint vendor_id, jint product_id) { + clearLibusbJavaError(); + return (jlong) libusb_open_device_with_vid_pid((libusb_context*) (unsigned long) ctx, vendor_id, product_id); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_close + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1close(JNIEnv *env, jclass obj, jlong dev_handle) { + clearLibusbJavaError(); + libusb_close((libusb_device_handle*) (unsigned long) dev_handle); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_device + * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; + ********************************************************************************************/ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device(JNIEnv *env, jclass obj, jlong handle) { + int res, a; + uint8_t c, h, e; + clearLibusbJavaError(); + if (ReferencesCheck(&info, env) != 0) return NULL; + + libusb_config_descriptor *conf_desc; + struct libusb_device_descriptor dev_desc; + + libusb_device *lib_dev = libusb_get_device((libusb_device_handle*) (unsigned long) handle); + + /* objects*/ + jobject usb_devObj, usb_devDescObj, usb_confDescObj, usb_intObj, usb_intDescObj, usb_epDescObj; + jobjectArray usb_confDescObjArray, usb_intObjArray, usb_intDescObjArray, usb_epDescObjArray; + + /* create a new object for device*/ + usb_devObj = Usb_Device_create(env, lib_dev, libusb_get_device_address(lib_dev)); + if (usb_devObj == NULL) { + setLibusbJavaError("shared library error: Could not create new Usb_Device!"); + return NULL; + } + + /*fill the fields of the object*/ + Usb_Device_NextSet(env, usb_devObj, NULL); + Usb_Device_PrevSet(env, usb_devObj, NULL); + + /*device Descriptor*/ + libusb_get_device_descriptor(lib_dev, &dev_desc); + usb_devDescObj = env->NewObject(usb_devDescClazz, usb_devDescMid); + if (!usb_devDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_devDescObj)"); + return NULL; + } + + env->SetByteField(usb_devDescObj, usb_devDescFID_bLength, dev_desc.bLength); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDescriptorType, dev_desc.bDescriptorType); + env->SetShortField(usb_devDescObj, usb_devDescFID_bcdUSB, dev_desc.bcdUSB); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceClass, dev_desc.bDeviceClass); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceSubClass, dev_desc.bDeviceSubClass); + env->SetByteField(usb_devDescObj, usb_devDescFID_bDeviceProtocol, dev_desc.bDeviceProtocol); + env->SetByteField(usb_devDescObj, usb_devDescFID_bMaxPacketSize0, dev_desc.bMaxPacketSize0); + env->SetShortField(usb_devDescObj, usb_devDescFID_idVendor, dev_desc.idVendor); + env->SetShortField(usb_devDescObj, usb_devDescFID_idProduct, dev_desc.idProduct); + env->SetShortField(usb_devDescObj, usb_devDescFID_bcdDevice, dev_desc.bcdDevice); + env->SetByteField(usb_devDescObj, usb_devDescFID_iManufacturer, dev_desc.iManufacturer); + env->SetByteField(usb_devDescObj, usb_devDescFID_iProduct, dev_desc.iProduct); + env->SetByteField(usb_devDescObj, usb_devDescFID_iSerialNumber, dev_desc.iSerialNumber); + env->SetByteField(usb_devDescObj, usb_devDescFID_bNumConfigurations, dev_desc.bNumConfigurations); + // TODO @NIUE: Why a reference on itself?! And why should we use a field ID from the Usb_Device class + // for an instance of the Descriptor object? + // env->SetObjectField(usb_devDescObj, usb_devFID_descriptor, usb_devDescObj); + Usb_Device_DescriptorSet(env, usb_devObj, usb_devDescObj); + + /*configuration descriptor*/ + /*Loop through all of the configurations*/ + usb_confDescObjArray = (jobjectArray) env->NewObjectArray( + dev_desc.bNumConfigurations, usb_confDescClazz, NULL); + if (!usb_confDescObjArray) { + setLibusbJavaError("shared library error: Error NewOjectArray"); + return NULL; + } + for (c = 0; c < dev_desc.bNumConfigurations; c++) { +#ifdef DEBUGON + printf("\t\tlibusb_get_device: configuration %u \n", c); +#endif + res = libusb_get_config_descriptor(lib_dev, c, &conf_desc); + if (res) { + setLibusbJavaError("shared library error: read conf_desc failed"); + return usb_devObj; + } + + usb_confDescObj = env->NewObject(usb_confDescClazz, usb_confDescMid); + if (!usb_confDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_confDescObjArray, c, usb_confDescObj);/*add it to the Array*/ + /*fill the fields*/ + env->SetByteField(usb_confDescObj, usb_confDescFID_bLength, conf_desc->bLength); + env->SetByteField(usb_confDescObj, usb_confDescFID_bDescriptorType, conf_desc->bDescriptorType); + env->SetShortField(usb_confDescObj, usb_confDescFID_wTotalLength, conf_desc->wTotalLength); + env->SetByteField(usb_confDescObj, usb_confDescFID_bNumInterfaces, conf_desc->bNumInterfaces); + env->SetByteField(usb_confDescObj, usb_confDescFID_bConfigurationValue, conf_desc->bConfigurationValue); + env->SetByteField(usb_confDescObj, usb_confDescFID_iConfiguration, conf_desc->iConfiguration); + env->SetByteField(usb_confDescObj, usb_confDescFID_bmAttributes, conf_desc->bmAttributes); + env->SetByteField(usb_confDescObj, usb_confDescFID_MaxPower, conf_desc->MaxPower); + env->SetIntField(usb_confDescObj, usb_confDescFID_extralen, conf_desc->extra_length); + if (conf_desc->extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->extra, conf_desc->extra_length); + env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, NULL); + } + /*interface*/ + usb_intObjArray = (jobjectArray) env->NewObjectArray(conf_desc->bNumInterfaces, usb_intClazz, NULL); + if (!usb_intObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_intObjArray)"); + return NULL; + } + for (h = 0; h < conf_desc->bNumInterfaces; h++) { +#ifdef DEBUGON + printf("\t\t\tlibusb_get_device: interface %u \n", h); +#endif + + if (conf_desc->interface == NULL) { + // this shouldn't happen + printf("(*conf_desc)->usb_interface == NULL"); + continue; + } + usb_intObj = env->NewObject(usb_intClazz, usb_intMid); + if (!usb_intObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_intObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_intObjArray, h, usb_intObj); + env->SetIntField(usb_intObj, usb_intFID_num_altsetting, conf_desc->interface[h].num_altsetting); + // interface descriptor + usb_intDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[h].num_altsetting, usb_intDescClazz, NULL); + if (!usb_intDescObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_intDescObjArray)"); + return NULL; + } + for (a = 0; a < conf_desc->interface[h].num_altsetting; a++) { +#ifdef DEBUGON + printf("\t\t\t\tlibusb_get_device: interface descriptor %u \n", a); +#endif + + if (conf_desc->interface[h].altsetting == NULL) { + // this shouldn't happen + printf("LibusbJava: libusb_get_device_list: altsetting == NULL\n"); + continue; + } + usb_intDescObj = env->NewObject(usb_intDescClazz, usb_intDescMid); + if (!usb_intDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_intDescObjArray, a, usb_intDescObj); + /*fill fields*/ + env->SetByteField(usb_intDescObj, usb_intDescFID_bLength, conf_desc->interface[h].altsetting[a].bLength); + env->SetByteField(usb_intDescObj, usb_intDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].bDescriptorType); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceNumber, conf_desc->interface[h].altsetting[a].bInterfaceNumber); + env->SetByteField(usb_intDescObj, usb_intDescFID_bAlternateSetting, conf_desc->interface[h].altsetting[a].bAlternateSetting); + env->SetByteField(usb_intDescObj, usb_intDescFID_bNumEndpoints, conf_desc->interface[h].altsetting[a].bNumEndpoints); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceClass, conf_desc->interface[h].altsetting[a].bInterfaceClass); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceSubClass, conf_desc->interface[h].altsetting[a].bInterfaceSubClass); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceProtocol, conf_desc->interface[h].altsetting[a].bInterfaceProtocol); + env->SetByteField(usb_intDescObj, usb_intDescFID_iInterface, conf_desc->interface[h].altsetting[a].iInterface); + env->SetIntField(usb_intDescObj, usb_intDescFID_extralen, conf_desc->interface[h].altsetting[a].extra_length); + if (conf_desc->interface[h].altsetting[a].extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].extra, conf_desc->interface[h].altsetting[a].extra_length); + env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, NULL); + } + /*endpoint descriptor*/ + usb_epDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[h].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL); + if (!usb_epDescObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_epDescObjArray)"); + return NULL; + } + for (e = 0; e < conf_desc->interface[h].altsetting[a].bNumEndpoints; e++) { +#ifdef DEBUGON + printf("\t\t\t\t\tLibusb_get_device: endpoint descriptor %u \n", e); +#endif + + if (conf_desc->interface[h].altsetting[a].endpoint == NULL) { + printf("LibusbJava: usb_get_busses: endpoint == NULL\n"); + return usb_devObj; + } + usb_epDescObj = env->NewObject(usb_epDescClazz, usb_epDescMid); + if (!usb_epDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_epDescObjArray, e, usb_epDescObj); + env->SetByteField(usb_epDescObj, usb_epDescFID_bLength, conf_desc->interface[h].altsetting[a].endpoint[e].bLength); + env->SetByteField(usb_epDescObj, usb_epDescFID_bDescriptorType, conf_desc->interface[h].altsetting[a].endpoint[e].bDescriptorType); + env->SetByteField(usb_epDescObj, usb_epDescFID_bEndpointAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bEndpointAddress); + env->SetByteField(usb_epDescObj, usb_epDescFID_bmAttributes, conf_desc->interface[h].altsetting[a].endpoint[e].bmAttributes); + env->SetShortField(usb_epDescObj, usb_epDescFID_wMaxPacketSize, conf_desc->interface[h].altsetting[a].endpoint[e].wMaxPacketSize); + env->SetByteField(usb_epDescObj, usb_epDescFID_bInterval, conf_desc->interface[h].altsetting[a].endpoint[e].bInterval); + env->SetByteField(usb_epDescObj, usb_epDescFID_bRefresh, conf_desc->interface[h].altsetting[a].endpoint[e].bRefresh); + env->SetByteField(usb_epDescObj, usb_epDescFID_bSynchAddress, conf_desc->interface[h].altsetting[a].endpoint[e].bSynchAddress); + env->SetIntField(usb_epDescObj, usb_epDescFID_extralen, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); + if (conf_desc->interface[h].altsetting[a].endpoint[e].extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[h].altsetting[a].endpoint[e].extra, conf_desc->interface[h].altsetting[a].endpoint[e].extra_length); + env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, NULL); + } + } + env->SetObjectField(usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray); + } + env->SetObjectField(usb_intObj, usb_intFID_altsetting, usb_intDescObjArray); + } + env->SetObjectField(usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray); + libusb_free_config_descriptor(conf_desc); + } + Usb_Device_ConfigSet(env, usb_devObj, usb_confDescObjArray); + +#ifdef DEBUGON + printf("libusb_get_device: done\n"); +#endif + return usb_devObj; +} +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_configuration + * Signature: (J)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1configuration(JNIEnv *env, jclass obj, jlong handle) { + int config = 0; + int libusb_result = 0; + + clearLibusbJavaError(); + libusb_result = libusb_get_configuration((libusb_device_handle*) (unsigned long) handle, &config); + + if (libusb_result != 0) { + setLibusbJavaError("shared library error: get_configuration failed"); + ThrowLibusbError(env, libusb_result); + config = 0; + } + + return config; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_configuration + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1configuration(JNIEnv *env, jclass obj, jlong handle, jint config) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_set_configuration((libusb_device_handle*) (unsigned long) handle, config)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_claim_interface + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1claim_1interface(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_claim_interface((libusb_device_handle*) (unsigned long) handle, iNumber)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_release_interface + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1release_1interface(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_release_interface((libusb_device_handle*) (unsigned long) handle, iNumber)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_interface_alt_setting + * Signature: (JII)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1interface_1alt_1setting(JNIEnv *env, jclass obj, jlong handle, jint iNumber, jint altSet) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_set_interface_alt_setting((libusb_device_handle*) (unsigned long) handle, iNumber, altSet)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_clear_halt + * Signature: (JS)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1clear_1halt(JNIEnv *env, jclass obj, jlong handle, jshort ep) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_clear_halt((libusb_device_handle*) (unsigned long) handle, ep)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_reset_device + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1reset_1device(JNIEnv *env, jclass obj, jlong handle) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_reset_device((libusb_device_handle*) (unsigned long) handle)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_kernel_driver_active + * Signature: (JI)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1kernel_1driver_1active(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { + int libusb_result = 0; + + clearLibusbJavaError(); + libusb_result = libusb_kernel_driver_active((libusb_device_handle*) (unsigned long) handle, iNumber); + + if (libusb_result < 0) + { + ThrowLibusbError(env, libusb_result); + libusb_result = 0; + } + + return libusb_result; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_detach_kernel_driver + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1detach_1kernel_1driver(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_detach_kernel_driver((libusb_device_handle*) (unsigned long) handle, iNumber)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_attach_kernel_driver + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1attach_1kernel_1driver(JNIEnv *env, jclass obj, jlong handle, jint iNumber) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_attach_kernel_driver((libusb_device_handle*) (unsigned long) handle, iNumber)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_active_config_descriptor + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Config_Descriptor; + ********************************************************************************************/ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1active_1config_1descriptor(JNIEnv *env, jclass obj, jobject dev) { + uint8_t a, e; + clearLibusbJavaError(); + if (ReferencesCheck(&info, env) != 0) return NULL; + libusb_device *libusb_dev = Usb_Device_HandleGet(env, dev); + if (libusb_dev == NULL) { + ThrowLibusbError(env, ERROR_JAVA_ILEGAL_DEVICE_HANDLE); + return NULL; + } + + libusb_config_descriptor *conf_desc; + jobject usb_confDescObj, usb_intObj, usb_intDescObj, usb_epDescObj; + jobjectArray usb_intObjArray, usb_intDescObjArray, usb_epDescObjArray; + + libusb_device *lib_dev = Usb_Device_HandleGet(env, dev); + if (lib_dev == NULL) return NULL; + + if (libusb_get_active_config_descriptor(lib_dev, &conf_desc)) { + setLibusbJavaError("shared library error: get_configuration failed"); + return NULL; + } + usb_confDescObj = env->NewObject(usb_confDescClazz, usb_confDescMid); + if (!usb_confDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_confDescObj)"); + return NULL; + } + /*fill the fields*/ + env->SetByteField(usb_confDescObj, usb_confDescFID_bLength, conf_desc->bLength); + env->SetByteField(usb_confDescObj, usb_confDescFID_bDescriptorType, conf_desc->bDescriptorType); + env->SetShortField(usb_confDescObj, usb_confDescFID_wTotalLength, conf_desc->wTotalLength); + env->SetByteField(usb_confDescObj, usb_confDescFID_bNumInterfaces, conf_desc->bNumInterfaces); + env->SetByteField(usb_confDescObj, usb_confDescFID_bConfigurationValue, conf_desc->bConfigurationValue); + env->SetByteField(usb_confDescObj, usb_confDescFID_iConfiguration, conf_desc->iConfiguration); + env->SetByteField(usb_confDescObj, usb_confDescFID_bmAttributes, conf_desc->bmAttributes); + env->SetByteField(usb_confDescObj, usb_confDescFID_MaxPower, conf_desc->MaxPower); + env->SetIntField(usb_confDescObj, usb_confDescFID_extralen, conf_desc->extra_length); + if (conf_desc->extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->extra, conf_desc->extra_length); + env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_confDescObj, usb_confDescFID_extra, NULL); + } + /*interface*/ + usb_intObjArray = (jobjectArray) env->NewObjectArray(conf_desc->bNumInterfaces, usb_intClazz, NULL); + if (!usb_intObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_intObjArray)"); + return NULL; + } + for (int i = 0; i < conf_desc->bNumInterfaces; i++) { +#ifdef DEBUGON + printf("\t\t\tlibusb_get_activ_config_descriptor: interface %u \n", i); +#endif + if (conf_desc->interface == NULL) { + // this shouldn't happen + printf("conf_des->interface == NULL"); + continue; + } + usb_intObj = env->NewObject(usb_intClazz, usb_intMid); + if (!usb_intObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_intObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_intObjArray, i, usb_intObj); + env->SetIntField(usb_intObj, usb_intFID_num_altsetting, conf_desc->interface[i].num_altsetting); + // interface descriptor + usb_intDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[i].num_altsetting, usb_intDescClazz, NULL); + if (!usb_intDescObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_intDescObjArray)"); + return NULL; + } + for (a = 0; a < conf_desc->interface[i].num_altsetting; a++) { +#ifdef DEBUGON + printf("\t\t\t\tlibusb_get__activ_config_descriptor: interface descriptor %u \n", a); +#endif + + if (conf_desc->interface[i].altsetting == NULL) { + // this shouldn't happen + printf("LibusbJava: libusb_get__activ_config_descriptor: altsetting == NULL\n"); + continue; + } + usb_intDescObj = env->NewObject(usb_intDescClazz, usb_intDescMid); + if (!usb_intDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_intDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_intDescObjArray, a, usb_intDescObj); + /*fill fields*/ + env->SetByteField(usb_intDescObj, usb_intDescFID_bLength, conf_desc->interface[i].altsetting[a].bLength); + env->SetByteField(usb_intDescObj, usb_intDescFID_bDescriptorType, conf_desc->interface[i].altsetting[a].bDescriptorType); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceNumber, conf_desc->interface[i].altsetting[a].bInterfaceNumber); + env->SetByteField(usb_intDescObj, usb_intDescFID_bAlternateSetting, conf_desc->interface[i].altsetting[a].bAlternateSetting); + env->SetByteField(usb_intDescObj, usb_intDescFID_bNumEndpoints, conf_desc->interface[i].altsetting[a].bNumEndpoints); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceClass, conf_desc->interface[i].altsetting[a].bInterfaceClass); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceSubClass, conf_desc->interface[i].altsetting[a].bInterfaceSubClass); + env->SetByteField(usb_intDescObj, usb_intDescFID_bInterfaceProtocol, conf_desc->interface[i].altsetting[a].bInterfaceProtocol); + env->SetByteField(usb_intDescObj, usb_intDescFID_iInterface, conf_desc->interface[i].altsetting[a].iInterface); + env->SetIntField(usb_intDescObj, usb_intDescFID_extralen, conf_desc->interface[i].altsetting[a].extra_length); + if (conf_desc->interface[i].altsetting[a].extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[i].altsetting[a].extra, conf_desc->interface[i].altsetting[a].extra_length); + env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_intDescObj, usb_intDescFID_extra, NULL); + } + /*endpoint descriptor*/ + usb_epDescObjArray = (jobjectArray) env->NewObjectArray(conf_desc->interface[i].altsetting[a].bNumEndpoints, usb_epDescClazz, NULL); + if (!usb_epDescObjArray) { + setLibusbJavaError("shared library error: Error NewObjectArray (usb_epDescObjArray)"); + return NULL; + } + for (e = 0; e < conf_desc->interface[i].altsetting[a].bNumEndpoints; e++) { +#ifdef DEBUGON + printf("\t\t\t\t\tLibusb_get__activ_config_descriptor: endpoint descriptor %u \n", e); +#endif + if (conf_desc->interface[i].altsetting[a].endpoint == NULL) { + printf("LibusbJava: usb_get__activ_config_descriptor: endpoint == NULL\n"); + return usb_confDescObj; + } + usb_epDescObj = env->NewObject(usb_epDescClazz, usb_epDescMid); + if (!usb_epDescObj) { + setLibusbJavaError("shared library error: Error NewObject (usb_epDescObj)"); + return NULL; + } + env->SetObjectArrayElement(usb_epDescObjArray, e, usb_epDescObj); + env->SetByteField(usb_epDescObj, usb_epDescFID_bLength, conf_desc->interface[i].altsetting[a].endpoint[e].bLength); + env->SetByteField(usb_epDescObj, usb_epDescFID_bDescriptorType, conf_desc->interface[i].altsetting[a].endpoint[e].bDescriptorType); + env->SetByteField(usb_epDescObj, usb_epDescFID_bEndpointAddress, conf_desc->interface[i].altsetting[a].endpoint[e].bEndpointAddress); + env->SetByteField(usb_epDescObj, usb_epDescFID_bmAttributes, conf_desc->interface[i].altsetting[a].endpoint[e].bmAttributes); + env->SetShortField(usb_epDescObj, usb_epDescFID_wMaxPacketSize, conf_desc->interface[i].altsetting[a].endpoint[e].wMaxPacketSize); + env->SetByteField(usb_epDescObj, usb_epDescFID_bInterval, conf_desc->interface[i].altsetting[a].endpoint[e].bInterval); + env->SetByteField(usb_epDescObj, usb_epDescFID_bRefresh, conf_desc->interface[i].altsetting[a].endpoint[e].bRefresh); + env->SetByteField(usb_epDescObj, usb_epDescFID_bSynchAddress, conf_desc->interface[i].altsetting[a].endpoint[e].bSynchAddress); + env->SetIntField(usb_epDescObj, usb_epDescFID_extralen, conf_desc->interface[i].altsetting[a].endpoint[e].extra_length); + if (conf_desc->interface[i].altsetting[a].endpoint[e].extra) { + jbyteArray jbExtraDesc = to_byteArray(env, conf_desc->interface[i].altsetting[a].endpoint[e].extra, conf_desc->interface[i].altsetting[a].endpoint[e].extra_length); + env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, jbExtraDesc); + } else { + env->SetObjectField(usb_epDescObj, usb_epDescFID_extra, NULL); + } + } + env->SetObjectField(usb_intDescObj, usb_intDescFID_endpoint, usb_epDescObjArray); + } + env->SetObjectField(usb_intObj, usb_intFID_altsetting, usb_intDescObjArray); + } + env->SetObjectField(usb_confDescObj, usb_confDescFID_interface_, usb_intObjArray); + libusb_free_config_descriptor(conf_desc); + + return usb_confDescObj; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_string_descriptor_ascii + * Signature: (JSI)Ljava/lang/String; + ********************************************************************************************/ +JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor_1ascii( JNIEnv *env, jclass obj, jlong handle, jshort desc_index, jint length) { + jstring string; + int res = 0; + clearLibusbJavaError(); + unsigned char data[(int)length + 1]; + + res = libusb_get_string_descriptor_ascii((libusb_device_handle*) (unsigned long) handle, desc_index, data, (int)length); + + if (res >= 0) + { + data[res] = '\0'; + string = env->NewStringUTF((const char*)data); + } + else + { + setLibusbJavaError("get_string_descriptor_ascii: retrieve String failed"); + string = NULL; + ThrowLibusbError(env, res); + } + return string; +} +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_descriptor + * Signature: (JISI)[B + ********************************************************************************************/ + +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1descriptor( + JNIEnv *env, jclass obj, jlong handle, jint desc_type, + jshort desc_index, jint size) { + + clearLibusbJavaError(); + int res; + unsigned char data[255]; + + res = libusb_get_descriptor((libusb_device_handle*) (unsigned long) handle, desc_type, desc_index, data, size); + if (res < 0) { + setLibusbJavaError("libusb_get_descriptor: retrieve data failed"); + ThrowLibusbError(env, res); + return NULL; + } + + return to_byteArray(env, data, res); +} +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_string_descriptor + * Signature: (JSII)Ljava/lang/String; + ********************************************************************************************/ +JNIEXPORT jstring +JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor(JNIEnv *env, jclass obj, jlong handle, jshort desc_index, jint langid, jint size) { + clearLibusbJavaError(); + int res; + jstring string; + unsigned char data[(int)size + 1]; + + res = libusb_get_string_descriptor((libusb_device_handle*) (unsigned long) handle, desc_index, langid, data, size); + + if (res >= 0) { + data[res] = '\0'; + string = env->NewStringUTF((const char*) data); + } else { + setLibusbJavaError("get_string_descriptor: retrieve String failed"); + string = NULL; + ThrowLibusbError(env, res); + } + + return string; + +} +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_alloc_transfer + * Signature: (I)J + ********************************************************************************************/ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1alloc_1transfer( JNIEnv *env, jclass obj, jint iso_packets) { + clearLibusbJavaError(); + return (jlong) libusb_alloc_transfer(iso_packets); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_free_transfer + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1free_1transfer( JNIEnv *env, jclass obj, jlong transfernumber) { + clearLibusbJavaError(); + libusb_free_transfer((libusb_transfer*) (unsigned long) transfernumber); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_submit_transfer + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1submit_1transfer(JNIEnv *env, jclass obj, jlong transfernumber) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_submit_transfer((libusb_transfer*) (unsigned long) transfernumber)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_cancel_transfer + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1cancel_1transfer(JNIEnv *env, jclass obj, jlong transfernumber) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_cancel_transfer((libusb_transfer*) (unsigned long) transfernumber)); +} +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_control_transfer_get_data + * Signature: (J)[B + ********************************************************************************************/ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1data(JNIEnv *env, jclass obj, jlong transfernumber) { + clearLibusbJavaError(); + unsigned char *data; + libusb_transfer* trans = (libusb_transfer*) (unsigned long) transfernumber; + + if (trans == NULL) + return NULL; + + data = libusb_control_transfer_get_data(trans); + return to_byteArray(env, data, trans->actual_length - LIBUSB_CONTROL_SETUP_SIZE ); +} + +/********************************************************************************************* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_control_transfer_get_setup + * Signature: (J)[B + ********************************************************************************************/ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1setup(JNIEnv *env, jclass obj, jlong transfernumber) { + clearLibusbJavaError(); + unsigned char *data; + libusb_transfer* trans = (libusb_transfer*) (unsigned long) transfernumber; + + if (trans == NULL) { + return NULL; + } + + data = (unsigned char*)libusb_control_transfer_get_setup(trans); + + return to_byteArray(env, data, 8); +} +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_control_setup + * Signature: (IIIII)[B + ********************************************************************************************/ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1setup(JNIEnv *env, jclass obj, jint bmRequestType, jint bRequest, jint wValue, jint wIndex, jint wLength) { + clearLibusbJavaError(); + unsigned char setup[8]; + + libusb_fill_control_setup(setup, bmRequestType, bRequest, wValue, wIndex, wLength); + + return to_byteArray(env, setup, 8); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_control_transfer + * Signature: (JJ[BI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle, jbyteArray buffer, jint timeout) { + clearLibusbJavaError(); + jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); + libusb_fill_control_transfer((libusb_transfer*) (unsigned long) transfernumber,(libusb_device_handle*) (unsigned long) handle,(unsigned char*) byteArrayElements, transfer_callback, env,(unsigned int) timeout); + env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_bulk_transfer + * Signature: (JJB[BII)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1bulk_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { + clearLibusbJavaError(); + jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); + libusb_fill_bulk_transfer((libusb_transfer*) (unsigned long) transfernumber,(libusb_device_handle*) (unsigned long) handle, endpoint,(unsigned char*) byteArrayElements, length, transfer_callback, env,(unsigned int) timeout); + env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_interrupt_transfer + * Signature: (JJB[BII)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1interrupt_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle,jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { + clearLibusbJavaError(); + jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); + libusb_fill_interrupt_transfer((libusb_transfer*) (unsigned long) transfernumber,(libusb_device_handle*) (unsigned long) handle, endpoint,(unsigned char*) byteArrayElements, length, transfer_callback, env, timeout); + env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_iso_transfer + * Signature: (JJB[BIII)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1iso_1transfer(JNIEnv *env, jclass obj, jlong transfernumber, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint num_iso_packets, jint timeout) { + clearLibusbJavaError(); + jbyte *byteArrayElements = env->GetByteArrayElements(buffer, NULL); + libusb_fill_iso_transfer((libusb_transfer*) (unsigned long) transfernumber, (libusb_device_handle*) (unsigned long) handle, endpoint, (unsigned char*) byteArrayElements, length, num_iso_packets, transfer_callback, env, timeout); + env->ReleaseByteArrayElements(buffer, byteArrayElements, 0); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_iso_packet_lengths + * Signature: (JI)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1iso_1packet_1lengths(JNIEnv *env, jclass obj, jlong transfernumber, jint length) { + clearLibusbJavaError(); + libusb_set_iso_packet_lengths((libusb_transfer*) (unsigned long) transfernumber, length); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_iso_packet_buffer + * Signature: (JI)[B + ********************************************************************************************/ + +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer(JNIEnv *env, jclass obj, jlong transfernumber, jint packet) { + clearLibusbJavaError(); + int size = 0; + unsigned char *data = NULL; + libusb_transfer* transfer = (libusb_transfer*) (unsigned long) transfernumber; + + if (transfer == NULL) { + setLibusbJavaError("libusb_get_iso_packet_buffer: ilegal transfernumber"); + return NULL; + } + + if (packet < transfer->num_iso_packets) { + size = transfer->iso_packet_desc[packet].actual_length; + } + + data = libusb_get_iso_packet_buffer((libusb_transfer*) (unsigned long) transfernumber, packet); + if (data == NULL) { + setLibusbJavaError("libusb_get_iso_packet_buffer: packet does not exist"); + return NULL; + } + + return to_byteArray(env, data, size); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_iso_packet_buffer_simple + * Signature: (JI)[B + ********************************************************************************************/ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer_1simple(JNIEnv *env, jclass obj, jlong transfernumber, jint packet) { + clearLibusbJavaError(); + int size = 0; + unsigned char *data = NULL; + libusb_transfer* transfer = (libusb_transfer*) (unsigned long) transfernumber; + + if (transfer == NULL) { + setLibusbJavaError("libusb_get_iso_packet_buffer_simple: ilegal transfernumber"); + return NULL; + } + + if (packet < transfer->num_iso_packets) { + size = transfer->iso_packet_desc[packet].actual_length; + } + + data = libusb_get_iso_packet_buffer_simple((libusb_transfer*) (unsigned long) transfernumber, packet); + + if (data == NULL) { + setLibusbJavaError("libusb_get_iso_packet_buffer_simple: packet does not exist"); + return NULL; + } + + return to_byteArray(env, data, size); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_try_lock_events + * Signature: (J)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1try_1lock_1events(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + return libusb_try_lock_events((libusb_context*) (unsigned long) ctx); +// return libusb_try_lock_events(NULL); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_lock_events + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1events(JNIEnv *env, jclass obj, jlong ctx) { + libusb_lock_events((libusb_context*) (unsigned long) ctx); +// libusb_lock_events(NULL); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_unlock_events + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1events(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + libusb_unlock_events((libusb_context*) (unsigned long) ctx); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_event_handling_ok + * Signature: (J)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handling_1ok(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + return libusb_event_handling_ok((libusb_context*) (unsigned long) ctx); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_event_handler_active + * Signature: (J)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handler_1active(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + return libusb_event_handler_active((libusb_context*) (unsigned long) ctx); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_lock_event_waiters + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1event_1waiters(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + libusb_lock_event_waiters((libusb_context*) (unsigned long) ctx); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_unlock_event_waiters + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1event_1waiters(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + libusb_unlock_event_waiters((libusb_context*) (unsigned long) ctx); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_wait_for_event + * Signature: (JJ)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1wait_1for_1event(JNIEnv *env, jclass obj, jlong ctx, jlong timevalue) { + clearLibusbJavaError(); + if (timevalue) { + timeval tv; + tv.tv_sec = timevalue; + tv.tv_usec = 0; + return libusb_wait_for_event((libusb_context*) (unsigned long) ctx, &tv); + } + return libusb_wait_for_event((libusb_context*) (unsigned long) ctx, NULL); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_handle_events_timeout + * Signature: (JJ)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1timeout(JNIEnv *env, jclass obj, jlong ctx, jlong timevalue) { + clearLibusbJavaError(); + if (timevalue != 0) + { + timeval tv; + tv.tv_sec = timevalue; + tv.tv_usec = 0; + ThrowIfUnsuccessful(env, libusb_handle_events_timeout((libusb_context*) (unsigned long) ctx, &tv)); + } + else + { + ThrowIfUnsuccessful(env, libusb_handle_events_timeout((libusb_context*) (unsigned long) ctx, NULL)); + } +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_handle_events + * Signature: (J)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + ThrowIfUnsuccessful(env, libusb_handle_events((libusb_context*) (unsigned long) ctx)); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_handle_events_locked + * Signature: (JJ)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1locked(JNIEnv *env, jclass obj, jlong ctx, jlong timevalue) { + clearLibusbJavaError(); + if (timevalue) { + timeval tv; + tv.tv_sec = timevalue; + tv.tv_usec = 0; + ThrowIfUnsuccessful(env, libusb_handle_events_locked((libusb_context*) (unsigned long) ctx, &tv)); + } + else + { + ThrowIfUnsuccessful(env, libusb_handle_events_locked((libusb_context*) (unsigned long) ctx, NULL)); + } +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_pollfds_handle_timeouts + * Signature: (J)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1pollfds_1handle_1timeouts(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + return libusb_pollfds_handle_timeouts((libusb_context*) (unsigned long) ctx); +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_next_timeout + * Signature: (J)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1next_1timeout(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + int res; + timeval tv; + + /*! \todo Is this code working correctly if we use it in a 64-Bit environment? Actually + * it's unlikely to have a timeout of more than 2^(31)-1 seconds. But still it is a + * possible value. */ + res = libusb_get_next_timeout((libusb_context*) (unsigned long) ctx, &tv); + + if (res > 0) + { + res = tv.tv_sec; + } + else if (res == 0) { + res = -1; + } + else + { + ThrowLibusbError(env, res); + res = -2; + } + + return res; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_pollfd_notifiers + * Signature: (JZ)V + ********************************************************************************************/ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1pollfd_1notifiers(JNIEnv *env, jclass obj, jlong ctx, jboolean remove) { + clearLibusbJavaError(); + if (remove) + { + libusb_set_pollfd_notifiers((libusb_context*) (unsigned long) ctx, NULL, NULL, env); + } + else + { + libusb_set_pollfd_notifiers((libusb_context*) (unsigned long) ctx, fd_added_callback, fd_removed_callback, env); + } +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_pollfds + * Signature: (J)[Lch/ntb/inf/libusbJava/Libusb_pollfd; + ********************************************************************************************/ +JNIEXPORT jobjectArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1pollfds(JNIEnv *env, jclass obj, jlong ctx) { + clearLibusbJavaError(); + int count = 0; + jobjectArray pollfdArray; + jobject pollfdObj; + const libusb_pollfd **fdList; + + fdList = libusb_get_pollfds((libusb_context*) (unsigned long) ctx); + if (fdList == NULL) { + return NULL; + } + /*determine the length of the list*/ + while (fdList[count]) { + count++; + } + pollfdArray = (jobjectArray) env->NewObjectArray(count, usb_pollfd_clazz, NULL); + if (!pollfdArray) { + setLibusbJavaError("libusb_get_pollfds: error NewObjectArry (pollfdArray"); + return NULL; + } + + for (int i = 0; i < count; i++) { + pollfdObj = env->NewObject(usb_pollfd_clazz, usb_pollfd_Mid); + if (!pollfdObj) { + setLibusbJavaError("libusb_get_pollfds: Error NewObject (pollfdObj)"); + return NULL; + } + env->SetObjectArrayElement(pollfdArray, i, pollfdObj); + env->SetIntField(pollfdObj, usb_pollfdFID_fd, fdList[i]->fd); + env->SetShortField(pollfdObj, usb_pollfdFID_events, fdList[i]->events); + } + return pollfdArray; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_control_transfer + * Signature: (JIIII[BII)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer(JNIEnv *env, jclass obj, jlong handle, jint bmRequestType, jint bRequest, jint wValue, jint wIndex, jbyteArray buffer, jint wLength, jint timeout) { + clearLibusbJavaError(); + int res; + unsigned char* data; + data = (unsigned char*) env->GetByteArrayElements(buffer, NULL); + res = libusb_control_transfer((libusb_device_handle*) (unsigned long) handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); + env->ReleaseByteArrayElements(buffer, (jbyte*) data, 0); + + return res; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_bulk_transfer + * Signature: (JB[BII)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1bulk_1transfer(JNIEnv *env, jclass obj, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { + clearLibusbJavaError(); + int libusb_result = 0; + int bytes_transferred = 0; + unsigned char* data = (unsigned char*) env->GetByteArrayElements(buffer, NULL); + + libusb_result = libusb_bulk_transfer((libusb_device_handle*) (unsigned long) handle, endpoint, data, length, &bytes_transferred, timeout); + env->ReleaseByteArrayElements(buffer, (jbyte*) data, 0); + + if (libusb_result != 0) + { + ThrowLibusbError(env, libusb_result); + bytes_transferred = 0; + } + + return bytes_transferred; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_interrupt_transfer + * Signature: (JB[BII)I + ********************************************************************************************/ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1interrupt_1transfer(JNIEnv *env, jclass obj, jlong handle, jbyte endpoint, jbyteArray buffer, jint length, jint timeout) { + clearLibusbJavaError(); + int libusb_result; + int bytes_transferred = 0; + unsigned char* data = (unsigned char*) env->GetByteArrayElements(buffer, NULL); + libusb_result = libusb_interrupt_transfer((libusb_device_handle*) (unsigned long) handle, endpoint, data, length, &bytes_transferred, timeout); + env->ReleaseByteArrayElements(buffer, (jbyte*) data, 0); + + if (libusb_result != 0) + { + ThrowLibusbError(env, libusb_result); + bytes_transferred = 0; + } + + return bytes_transferred; +} + +/******************************************************************************************** + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_strerror + * Signature: ()Ljava/lang/String; + ********************************************************************************************/ +JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1strerror(JNIEnv *env, jclass obj) { + char *str = "Libusb-1.0 Error"; + + /* check for LibusbJava specific errors first*/ + if (libusbJavaError != NULL) { + str = libusbJavaError; + clearLibusbJavaError(); + } + + return env->NewStringUTF(str); +} + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: setup + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_setup(JNIEnv *env, jclass obj) +{ + return ReferencesLoad(&info, env, jniObjects); +} + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: teardown + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_teardown(JNIEnv *env, jclass obj) +{ + ReferencesUnload(&info, env); +} + +/******************************************************************************************** + * Class: LibusbJava_1_0.cpp + * Method: transfer_callback + * + ********************************************************************************************/ +static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer) { + + ((JNIEnv*) transfer->user_data)->CallVoidMethod(usb_cb_clazz, + usb_transfer_cb_Mid); +} + +/******************************************************************************************** + * Class: LibusbJava_1_0.cpp + * Method: fd_added_callback + * + ********************************************************************************************/ +static void LIBUSB_CALL fd_added_callback(int fd, short events, void *user_data) { + + ((JNIEnv*) user_data)->CallVoidMethod(usb_cb_clazz, usb_fd_added_cb_Mid, + (jint) fd); +} + +/******************************************************************************************** + * Class: LibusbJava_1_0.cpp + * Method: fd_removed_callback + * + ********************************************************************************************/ +static void LIBUSB_CALL fd_removed_callback(int fd, void *user_data) { + + ((JNIEnv*) user_data)->CallVoidMethod(usb_cb_clazz, usb_fd_removed_cb_Mid, + (jint) fd); +} + +/*! \brief Turns a memory section into a java byte array that can be returned to the java + * environment. + * + * \param env Environment to create the array for + * \param data Pointer to the data to be put in the array + * \param len [bytes] Length of the data to be put into the array + * + * \return The pointer to the newly created byte array. NULL if an error occured + * + * \note If NULL is returned, #libusbJavaError is set to a matching error string. + * + * \test Tested through the unit-test of the java part of this dll by passing a string + * with length 5 and checking the result. + * \test Tested through the Unit-Test of the java part of this dll by passing a string + * with length 0 and checking the result. + */ +static __inline jbyteArray JNICALL to_byteArray(JNIEnv *env, const void *data, size_t len) +{ + jbyteArray result = env->NewByteArray(len); + + if (result != NULL) { + /* By using SetByteArrayRegion, we avoid that the JNI layer first copies the data of + * the array in our space just to overwrite them. As we just allocated the + * byte array with a length of "len", the set operation can never fail. The check for an + * exception can therefore be omitted. */ + env->SetByteArrayRegion(result, 0, len, (const signed char *)data); +#if 0 /* No need to check for exceptions here... */ + if (env->ExceptionOccurred()){ + setLibusbJavaError("to_byteArray: unable to copy data to array"); + env->DeleteLocalRef(result); + result = NULL; + } +#endif + } + else { + setLibusbJavaError("to_byteArray: out of memory"); + } + + return result; +} + +/*! \brief Convenience function that throws an exception in the callers environment if + * the given result is not "success" + * + * This function can be used to wrap calls to the libusb if no further reaction + * on a unsuccessful result is needed, than throwing an exception in the java + * environment. + * + * \param env Java environment of the caller + * \param libusb_result Result code of the libusb call. If the result is != 0, a + * LibusbError is thrown. + * + * \test Code-Review + */ +static __inline void JNICALL ThrowIfUnsuccessful(JNIEnv *env, int libusb_result) +{ + if (libusb_result != 0) + { + ThrowLibusbError(env, libusb_result); + } +} + +#ifdef DO_UNIT_TEST + TEST_CASE(ThrowIfUnsuccessfulTest) + { + TEST_CONTEXT(); + + CuAssert(tc, "Pre-Condition: No exception pending", env->ExceptionCheck() == JNI_FALSE); + + ThrowIfUnsuccessful(env, 0); + CuAssert(tc, "No exception pending", env->ExceptionCheck() == JNI_FALSE); + + ThrowIfUnsuccessful(env, -1); + CuAssert(tc, "Exception pending < 0", env->ExceptionCheck() == JNI_TRUE); + env->ExceptionClear(); + + ThrowIfUnsuccessful(env, 1); + CuAssert(tc, "Exception pending > 0", env->ExceptionCheck() == JNI_TRUE); + env->ExceptionClear(); + } +#endif + +/*! \brief Throws an exception of type LibusbError in the calling Java environment. + * + * \param env Environment to throw the exception in + * \param code Error code that represents the cause of the exception + * + * \test Tested through the unit-test of the java part of this dll + */ +static __inline void JNICALL ThrowLibusbError(JNIEnv *env, jint code) +{ + jmethodID constructor = NULL; + jthrowable exception = NULL; + + jclass clazz = env->FindClass("ch/ntb/inf/libusbJava/exceptions/LibusbError"); + if (clazz == NULL) + { + goto no_class; + } + + constructor = env->GetMethodID(clazz, "", "(I)V"); + if (constructor == NULL) + { + goto no_constructor; + } + + exception = (jthrowable)env->NewObject(clazz, constructor, code); + if (exception == NULL) + { + goto no_object; + } + + if (env->Throw(exception) != 0) + { + goto throw_failed; + } + + env->DeleteLocalRef(exception); + env->DeleteLocalRef(clazz); + + return; + +/* Error Handling. All errors covered here are caused by JNI callbacks and have + * therefore already thrown appropriate exceptions in the Java environment. + * Therefore we only have to cleanup what we constructed. */ +throw_failed: + env->DeleteLocalRef(exception); + +no_object: + +no_constructor: + env->DeleteLocalRef(clazz); + +no_class: + + return; +} + +#ifdef DO_UNIT_TEST + static void ThrowLibusbErrorTestEvaluate(CuTest *tc, JNIEnv *env, int code) { + /* Prepare the needed environment */ + jclass clazz = env->FindClass("ch/ntb/inf/libusbJava/exceptions/LibusbError"); + CuAssert(tc, "LibusbError class not found!", clazz != NULL); + jfieldID f_code = env->GetFieldID(clazz, "code", "I"); + CuAssert(tc, "LibusbError has a field \"code\"", f_code != NULL); + + /* Evaluate the effect of the call */ + jthrowable e = env->ExceptionOccurred(); + CuAssert(tc, "An exception occured", e != NULL); + CuAssert(tc, "The exception is of type LibusbError", env->IsInstanceOf(e, clazz) == JNI_TRUE); + CuAssertIntEquals_Msg(tc, "The exception error code is correct", code, env->GetIntField(e, f_code)); + env->ExceptionClear(); + } + + TEST_CASE(ThrowLibusbErrorTest) + { + TEST_CONTEXT(); + + /* Test borders and run through a range of values including 0 */ + int code = 0; + for (code = -5;code < 5;code++) { + ThrowLibusbError(env, code); + ThrowLibusbErrorTestEvaluate(tc, env, code); + } + + ThrowLibusbError(env, 0x80000000); + ThrowLibusbErrorTestEvaluate(tc, env, 0x80000000); + ThrowLibusbError(env, 0x7FFFFFFF); + ThrowLibusbErrorTestEvaluate(tc, env, 0x7FFFFFFF); + } +#endif + +/*! \brief Checks if the references are loaded correctly and throws an exception if not + * + * This function serves as a "paranoia" function to make sure, there are no calls + * to the library without loading the references first. + * + * \param instance Reference-Instance to be checked + * \param env JNI Environment the function can work with in case of an error + * + * \return + * - 0 if everything is ok + * - <0 in case the references are not loaded + */ +static __inline int ReferencesCheck(tLUJ_Instance *instance, JNIEnv *env) +{ + int result = -1; + + if (instance->jni.refs_loaded == 0){ + ThrowLibusbError(env, ERROR_JAVA_REFERENCES_NOT_LOADED); + } + else { + result = 0; + } + + return result; +} + +/*! \brief Loads all class References from the environment. + * + * \param instance Pointer to an instance of a status data struct the action should be performed with + * \param env Pointer to an environment enabling access to the jvm + * \param objects An array of function calls for connecting / disconnecting + * the objects to the JNI layer. The array is expected to be + * NULL terminated. (tJNIObject::connect set to NULL). + * + * \return + * - 0 if the references could be loaded successfully + * - <0 if an error occured + * + * \note For every valid row it is expected that neither connect nor disconnect is NULL + */ +static __inline int ReferencesLoad(tLUJ_Instance *instance, JNIEnv *env, const tJNIObject *objects) +{ + int result = -1; + + /* If the references are not (yet) loaded, we start loading + * the references for the classes used by this wrapper. */ + if (instance->jni.refs_loaded == 0) + { + int i = 0; + + result = 0; + + /* Walk through all registered objects and try to connect + * them. */ + while (objects[i].connect != NULL) { + if (objects[i].connect(env) != 0) { + result = -1; + break; + } + + ++i; + } + + /* If an error occured, we roll back all the previously + * connected elements. */ + if (result != 0) { + while (i > 0) { + --i; + objects[i].disconnect(env); + } + + instance->jni.refs_loaded = 0; + } + else + { +#ifndef DO_UNIT_TEST + { + /* find classes and field ids*/ + #ifdef DEBUGON + printf("load references starts\n"); + #endif + + #ifdef DEBUGON + printf("usb_device references loaded\n"); + #endif + /* usb_device_descriptor*/ + jobject devDescClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Device_Descriptor");//returns a local reference + usb_devDescClazz = (jclass)env->NewGlobalRef(devDescClazz);//make it global + if (usb_devDescClazz == NULL) { + return -1; /* exception thrown */ + } + usb_devDescMid = env->GetMethodID(usb_devDescClazz, "", "()V"); + if (usb_devDescMid == NULL) { + return -1; + } + usb_devDescFID_bLength = env->GetFieldID(usb_devDescClazz, "bLength", "B"); + usb_devDescFID_bDescriptorType = env->GetFieldID(usb_devDescClazz, "bDescriptorType", "B"); + usb_devDescFID_bcdUSB = env->GetFieldID(usb_devDescClazz, "bcdUSB", "S"); + usb_devDescFID_bDeviceClass = env->GetFieldID(usb_devDescClazz, "bDeviceClass", "B"); + usb_devDescFID_bDeviceSubClass = env->GetFieldID(usb_devDescClazz, "bDeviceSubClass", "B"); + usb_devDescFID_bDeviceProtocol = env->GetFieldID(usb_devDescClazz, "bDeviceProtocol", "B"); + usb_devDescFID_bMaxPacketSize0 = env->GetFieldID(usb_devDescClazz, "bMaxPacketSize0", "B"); + usb_devDescFID_idVendor = env->GetFieldID(usb_devDescClazz, "idVendor", "S"); + usb_devDescFID_idProduct = env->GetFieldID(usb_devDescClazz, "idProduct", "S"); + usb_devDescFID_bcdDevice = env->GetFieldID(usb_devDescClazz, "bcdDevice", "S"); + usb_devDescFID_iManufacturer = env->GetFieldID(usb_devDescClazz, "iManufacturer", "B"); + usb_devDescFID_iProduct = env->GetFieldID(usb_devDescClazz, "iProduct", "B"); + usb_devDescFID_iSerialNumber = env->GetFieldID(usb_devDescClazz, "iSerialNumber", "B"); + usb_devDescFID_bNumConfigurations = env->GetFieldID(usb_devDescClazz, "bNumConfigurations", "B"); + + + #ifdef DEBUGON + printf("usb_device_descriptor references loaded\n"); + #endif + /* usb_configuration_descriptor*/ + jobject confDescClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Config_Descriptor");//returns a local reference + usb_confDescClazz = (jclass)env->NewGlobalRef(confDescClazz);//make it global + if (usb_confDescClazz == NULL) { + return -1; /* exception thrown */ + } + usb_confDescMid = env->GetMethodID(usb_confDescClazz, "", "()V"); + if (usb_confDescMid == NULL) { + return -1; + } + + usb_confDescFID_bLength = env->GetFieldID(usb_confDescClazz, "bLength", "B"); + usb_confDescFID_bDescriptorType = env->GetFieldID(usb_confDescClazz, "bDescriptorType", "B"); + usb_confDescFID_wTotalLength = env->GetFieldID(usb_confDescClazz, "wTotalLength", "S"); + usb_confDescFID_bNumInterfaces = env->GetFieldID(usb_confDescClazz, "bNumInterfaces", "B"); + usb_confDescFID_bConfigurationValue = env->GetFieldID(usb_confDescClazz, "bConfigurationValue", "B"); + usb_confDescFID_iConfiguration = env->GetFieldID(usb_confDescClazz, "iConfiguration", "B"); + usb_confDescFID_bmAttributes = env->GetFieldID(usb_confDescClazz, "bmAttributes", "B"); + usb_confDescFID_MaxPower = env->GetFieldID(usb_confDescClazz, "MaxPower", "B"); + usb_confDescFID_interface_ = env->GetFieldID(usb_confDescClazz, "interface_", "[Lch/ntb/inf/libusbJava/Usb_Interface;"); + usb_confDescFID_extra = env->GetFieldID(usb_confDescClazz, "extra", "[B"); + usb_confDescFID_extralen = env->GetFieldID(usb_confDescClazz, "extralen", "I"); + #ifdef DEBUGON + printf("usb_configuration_descriptor references loaded\n"); + #endif + /* usb_interface*/ + jobject intClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Interface");//returns a local reference + usb_intClazz = (jclass)env->NewGlobalRef(intClazz);//make it global + if (usb_intClazz == NULL) { + return -1; /* exception thrown */ + } + usb_intMid = env->GetMethodID(usb_intClazz, "", "()V"); + if (usb_intMid == NULL) { + return -1; + } + usb_intFID_altsetting = env->GetFieldID(usb_intClazz, "altsetting", "[Lch/ntb/inf/libusbJava/Usb_Interface_Descriptor;"); + usb_intFID_num_altsetting = env->GetFieldID(usb_intClazz, "num_altsetting", "I"); + #ifdef DEBUGON + printf("usb_interface references loaded\n"); + #endif + /* usb_interface_descriptor*/ + jobject intDescClazz = env->FindClass( "ch/ntb/inf/libusbJava/Usb_Interface_Descriptor");//returns a local reference + usb_intDescClazz = (jclass)env->NewGlobalRef(intDescClazz);//make it global + if (usb_intDescClazz == NULL) { + return -1; /* exception thrown */ + } + usb_intDescMid = env->GetMethodID(usb_intDescClazz, "", "()V"); + if (usb_intDescMid == NULL) { + return -1; + } + usb_intDescFID_bLength = env->GetFieldID(usb_intDescClazz, "bLength", "B"); + usb_intDescFID_bDescriptorType = env->GetFieldID(usb_intDescClazz, "bDescriptorType", "B"); + usb_intDescFID_bInterfaceNumber = env->GetFieldID(usb_intDescClazz, "bInterfaceNumber", "B"); + usb_intDescFID_bAlternateSetting = env->GetFieldID(usb_intDescClazz, "bAlternateSetting", "B"); + usb_intDescFID_bNumEndpoints = env->GetFieldID(usb_intDescClazz, "bNumEndpoints", "B"); + usb_intDescFID_bInterfaceClass = env->GetFieldID(usb_intDescClazz, "bInterfaceClass", "B"); + usb_intDescFID_bInterfaceSubClass = env->GetFieldID(usb_intDescClazz, "bInterfaceSubClass", "B"); + usb_intDescFID_bInterfaceProtocol = env->GetFieldID(usb_intDescClazz, "bInterfaceProtocol", "B"); + usb_intDescFID_iInterface = env->GetFieldID(usb_intDescClazz, "iInterface", "B"); + usb_intDescFID_endpoint = env->GetFieldID(usb_intDescClazz, "endpoint", "[Lch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor;"); + usb_intDescFID_extra = env->GetFieldID(usb_intDescClazz, "extra", "[B"); + usb_intDescFID_extralen = env->GetFieldID(usb_intDescClazz, "extralen", "I"); + #ifdef DEBUGON + printf("usb_interface_descriptor references loaded\n"); + #endif + /* usb_endpoint_descriptor*/ + jobject epDescClazz = env->FindClass("ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor");//returns a local reference + usb_epDescClazz = (jclass)env->NewGlobalRef(epDescClazz);//make it global + if (usb_epDescClazz == NULL) { + return -1; /* exception thrown */ + } + usb_epDescMid = env->GetMethodID(usb_epDescClazz, "", "()V"); + if (usb_epDescMid == NULL) { + return -1; + } + usb_epDescFID_bLength = env->GetFieldID(usb_epDescClazz, "bLength", "B"); + usb_epDescFID_bDescriptorType = env->GetFieldID(usb_epDescClazz, "bDescriptorType", "B"); + usb_epDescFID_bEndpointAddress = env->GetFieldID(usb_epDescClazz, "bEndpointAddress", "B"); + usb_epDescFID_bmAttributes = env->GetFieldID(usb_epDescClazz, "bmAttributes", "B"); + usb_epDescFID_wMaxPacketSize = env->GetFieldID(usb_epDescClazz, "wMaxPacketSize", "S"); + usb_epDescFID_bInterval = env->GetFieldID(usb_epDescClazz, "bInterval", "B"); + usb_epDescFID_bRefresh = env->GetFieldID(usb_epDescClazz, "bRefresh", "B"); + usb_epDescFID_bSynchAddress = env->GetFieldID(usb_epDescClazz, "bSynchAddress", "B"); + usb_epDescFID_extra = env->GetFieldID(usb_epDescClazz, "extra", "[B"); + usb_epDescFID_extralen = env->GetFieldID(usb_epDescClazz, "extralen", "I"); + #ifdef DEBUGON + printf("usb_endpoint_descriptor references loaded\n"); + #endif + /*libusb_event*/ + jobject cb_clazz = env->FindClass("ch/ntb/inf/libusbJava/Libusb_event");//returns a local reference + usb_cb_clazz = (jclass)env->NewGlobalRef(cb_clazz);//make it global + if (usb_cb_clazz == NULL) { + printf("load Clazz failed\n"); + return -1; /*exception thrown*/ + } + usb_transfer_cb_Mid = env->GetMethodID(usb_cb_clazz, "transferCallback", "()V"); + if (usb_transfer_cb_Mid == NULL) { + printf("load method transferCallback failed\n"); + return -1; /* exception thrown */ + } + usb_fd_added_cb_Mid = env->GetMethodID(usb_cb_clazz, "fdAddedCallback", "(I)V"); + if (usb_fd_added_cb_Mid == NULL) { + printf("load method fdAddedCallback failed\n"); + return -1;/* exception thrown */ + } + usb_fd_removed_cb_Mid = env->GetMethodID(usb_cb_clazz, "fdRemovedCallback", "(I)V"); + if (usb_fd_removed_cb_Mid == NULL) { + printf("load method fdRemovedCallback failed\n"); + return -1;/* exception thrown */ + } + #ifdef DEBUGON + printf("usb_event_descriptor references loaded\n"); + #endif + /*Libusb_pollfd*/ + jobject pollfd_clazz = env->FindClass("ch/ntb/inf/libusbJava/Libusb_pollfd");//returns a local reference + usb_pollfd_clazz = (jclass)env->NewGlobalRef(pollfd_clazz);//make it global + if (usb_pollfd_clazz == NULL) { + return -1; /*exception thrown*/ + } + usb_pollfd_Mid = env->GetMethodID(usb_pollfd_clazz, "", "()V"); + // Bugfix: if (usb_devMid == NULL) @ Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device_1list - Copy-paste error + if (usb_pollfd_Mid == NULL) { + return -1; /*exception thrown*/ + } + usb_pollfdFID_fd = env->GetFieldID(usb_pollfd_clazz, "fd", "I"); + usb_pollfdFID_events = env->GetFieldID(usb_pollfd_clazz, "events", "B"); + #ifdef DEBUGON + printf("Libusb_pollfd_descriptor references loaded\n"); + #endif + + #ifdef DEBUGON + printf("libusb_init: Field initialization done \n"); + #endif + } +#endif + + instance->jni.objects = objects; + instance->jni.refs_loaded = -1; + } + } + else + { + result = 0; + } + + return result; +} + +/*! \brief Unloads all cached references + * + * \param instance Pointer to an instance of a status data struct containing necessary information. + * \param env Pointer to the JVM-Environment, where actions can be performed with */ +static __inline void ReferencesUnload(tLUJ_Instance *instance, JNIEnv *env) +{ + if (instance->jni.refs_loaded == 0) + return; + + int i = 0; + const JNIObject *objects = instance->jni.objects; + + /* Walk through all registered objects and try to + * disconnect them. */ + while (objects[i].disconnect != NULL) { + objects[i].disconnect(env); + ++i; + } + + instance->jni.refs_loaded = 0; +} + +/* Unit-Tests for References*-Functions */ +#ifdef DO_UNIT_TEST + enum { + TEST_RESULT_TEST1 = 0, + TEST_RESULT_TEST2, + TEST_RESULT_TEST3, + TEST_RESULT_TEST_FAILS, + TEST_RESULT_PARAM_FORWARDING, + + TEST_RESULT_COUNT + }; + + enum { + TEST_OBJECTS_NORMAL = 0, + TEST_OBJECTS_FAILING, + TEST_OBJECTS_EMPTY, + TEST_OBJECTS_PARAM_FORWARDING, + }; + + static struct ReferencesXTestsData { + tLUJ_Instance instance; + + struct { + int connect; + int disconnect; + }executed[TEST_RESULT_COUNT]; + }ReferencesXTestsData; + + static int Test1_connect(JNIEnv *env); + static void Test1_disconnect(JNIEnv *env); + static int Test2_connect(JNIEnv *env); + static void Test2_disconnect(JNIEnv *env); + static int Test3_connect(JNIEnv *env); + static void Test3_disconnect(JNIEnv *env); + static int TestFails_connect(JNIEnv *env); + static void TestFails_disconnect(JNIEnv *env); + static int TestParamForwarding_connect(JNIEnv *env); + static void TestParamForwarding_disconnect(JNIEnv *env); + + static const tJNIObject ReferencesXTestsObjects[][5] = { + { /* TEST_OBJECTS_NORMAL */ + OBJ(Test1), + OBJ(Test2), + { NULL, NULL}, + OBJ(Test3), + { NULL, NULL}, + }, + { /* TEST_OBJECTS_FAILING */ + OBJ(Test1), + OBJ(Test2), + OBJ(TestFails), + { NULL, NULL}, + { NULL, NULL}, + }, + { /* TEST_OBJECTS_EMPTY */ + { NULL, NULL}, + { NULL, NULL}, + { NULL, NULL}, + { NULL, NULL}, + { NULL, NULL}, + }, + { /* TEST_OBJECTS_PARAM_FORWARDING */ + OBJ(TestParamForwarding), + { NULL, NULL }, + { NULL, NULL }, + { NULL, NULL }, + { NULL, NULL }, + } + }; + + TEST_CASE(ReferencesCheckTest) { + TEST_CONTEXT(); + memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); + CuAssert(tc, "Return value", ReferencesCheck(&ReferencesXTestsData.instance, env) < 0); + CuAssert(tc, "Exception Thrown", env->ExceptionCheck() == JNI_TRUE); + + ThrowLibusbErrorTestEvaluate(tc, env, ERROR_JAVA_REFERENCES_NOT_LOADED); + + ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[2]); + CuAssert(tc, "Return value", ReferencesCheck(&ReferencesXTestsData.instance, env) == 0); + CuAssert(tc, "No exception Thrown", env->ExceptionCheck() == JNI_FALSE); + } + + TEST_CASE(ReferencesLoadTest) { + TEST_CONTEXT(); + + /* Check initial loading of modules */ + memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); + CuAssert(tc, "References loaded return value", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); + CuAssert(tc, "1st module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect != 0); + CuAssert(tc, "1st module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); + CuAssert(tc, "2nd module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect != 0); + CuAssert(tc, "2nd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); + CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); + + /* Check repeated load call */ + memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); + CuAssert(tc, "References loaded return value", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); + CuAssert(tc, "1st module NOT loaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); + CuAssert(tc, "1st module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); + CuAssert(tc, "2nd module NOT loaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); + CuAssert(tc, "2nd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); + CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); + + memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); + CuAssert(tc, "References loaded empty list", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_EMPTY]) >= 0); + CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); + CuAssert(tc, "1st module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); + CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); + CuAssert(tc, "2nd module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); + CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); + } + + TEST_CASE(ReferencesUnloadTest) { + TEST_CONTEXT(); + + memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); + CuAssert(tc, "References loaded", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); + + /* Check initial unloading of modules */ + memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); + ReferencesUnload(&ReferencesXTestsData.instance, env); + CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); + CuAssert(tc, "1st module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect != 0); + CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); + CuAssert(tc, "2nd module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect != 0); + CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); + + /* Check repeated unload call */ + memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); + ReferencesUnload(&ReferencesXTestsData.instance, env); + CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); + CuAssert(tc, "1st module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); + CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); + CuAssert(tc, "2nd module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); + CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); + + memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); + CuAssert(tc, "References loaded", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_NORMAL]) >= 0); + + memset(ReferencesXTestsData.executed, 0, sizeof(ReferencesXTestsData.executed)); + CuAssert(tc, "References loaded empty list", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_EMPTY]) >= 0); + CuAssert(tc, "1st module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect == 0); + CuAssert(tc, "1st module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect == 0); + CuAssert(tc, "2nd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect == 0); + CuAssert(tc, "2nd module NOT unloaded again", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect == 0); + CuAssert(tc, "3rd module NOT loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect == 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect == 0); + } + + TEST_CASE(ReferencesLoadRollbackTest) { + TEST_CONTEXT(); + + memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); + CuAssert(tc, "References load rollback", ReferencesLoad(&ReferencesXTestsData.instance, env, ReferencesXTestsObjects[TEST_OBJECTS_FAILING]) < 0); + CuAssert(tc, "1st module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect != 0); + CuAssert(tc, "1st module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect != 0); + CuAssert(tc, "2nd module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect != 0); + CuAssert(tc, "2nd module unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect != 0); + CuAssert(tc, "3rd module loaded", ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].connect != 0); + CuAssert(tc, "3rd module NOT unloaded", ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].disconnect == 0); + } + + TEST_CASE(ReferencesParameterForwardTest) { + memset(&ReferencesXTestsData, 0, sizeof(struct ReferencesXTestsData)); + CuAssert(tc, "References load", ReferencesLoad(&ReferencesXTestsData.instance, (JNIEnv *)0x06051982, ReferencesXTestsObjects[TEST_OBJECTS_PARAM_FORWARDING]) >= 0); + ReferencesUnload(&ReferencesXTestsData.instance, (JNIEnv *)0x06051982); + CuAssert(tc, "Connect parameter arrived.", ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].connect != 0); + CuAssert(tc, "Disconnect parameter arrived.", ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].disconnect != 0); + } + + static int Test1_connect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST1].connect = -1; + return 0; + } + + static void Test1_disconnect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST1].disconnect = -1; + } + + static int Test2_connect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST2].connect = -1; + return 0; + } + + static void Test2_disconnect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST2].disconnect = -1; + } + + static int Test3_connect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST3].connect = -1; + return 0; + } + + static void Test3_disconnect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST3].disconnect = -1; + } + + static int TestFails_connect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].connect = -1; + return -1; + } + + static void TestFails_disconnect(JNIEnv *env) { + ReferencesXTestsData.executed[TEST_RESULT_TEST_FAILS].disconnect = -1; + } + + static int TestParamForwarding_connect(JNIEnv *env) { + if (env != ((JNIEnv *)0x06051982)) + { + ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].connect = 0; + return -1; + } + + ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].connect = -1; + return 0; + } + + static void TestParamForwarding_disconnect(JNIEnv *env) { + if (env != ((JNIEnv *)0x06051982)) + { + ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].disconnect = 0; + return; + } + + ReferencesXTestsData.executed[TEST_RESULT_PARAM_FORWARDING].disconnect = -1; + } +#endif + +#ifdef DO_UNIT_TEST + typedef CuSuite* (*tSuiteNew)(void); + + extern "C" JNIEXPORT CuSuite* GetLibusbJavaSuite(tSuiteNew SuiteNew, JNIEnv *env); + + TEST_CASE(Usb_Device_Tests) { +// TEST_CONTEXT(); + + CuAssert(tc, "TODO", 0); + } + +/*! \brief Exports the test suite for the libraries helper functions + * + * \param SuiteNew Pointer to an allocator function for a CuTest instance + * \param env JNI Environment for the test + * + * \return A fully setup test suite. */ +JNIEXPORT CuSuite* GetLibusbJavaSuite(tSuiteNew SuiteNew, JNIEnv *env) +{ + CuSuite* suite = SuiteNew(); + + SUITE_ADD_TEST(suite, JNI_OnLoad_test); + + SUITE_ADD_TEST(suite, ReferencesLoadTest); + SUITE_ADD_TEST(suite, ReferencesUnloadTest); + SUITE_ADD_TEST(suite, ReferencesLoadRollbackTest); + SUITE_ADD_TEST(suite, ReferencesCheckTest); + SUITE_ADD_TEST(suite, ReferencesParameterForwardTest); + + + SUITE_ADD_TEST(suite, ThrowLibusbErrorTest); + SUITE_ADD_TEST(suite, ThrowIfUnsuccessfulTest); + + SUITE_ADD_TEST(suite, Usb_Device_Tests); + + test_context.env = env; + return suite; +} +#endif diff --git a/LibusbJava/objects/Usb_Device.cpp b/src/main/cpp/Usb_Device.cpp similarity index 96% rename from LibusbJava/objects/Usb_Device.cpp rename to src/main/cpp/Usb_Device.cpp index 062bd9c..f26eaab 100644 --- a/LibusbJava/objects/Usb_Device.cpp +++ b/src/main/cpp/Usb_Device.cpp @@ -1,141 +1,141 @@ -/*! \file - * - * C++ Stub for the java class of a java class ch.ntb.inf.libusbJava.Usb_Device. - * - * \author Ueli Niederer - */ -#include "Usb_Device.h" -#include - -#ifdef DO_UNIT_TEST -# include - -# define TEST_CASE(name) static void name(CuTest *tc) -#endif - -typedef struct JField { - const char *type; - const char *name; - jfieldID id; -}tJField; - -typedef struct Usb_Device { - int loaded; - - jclass clazz; - - jmethodID constructor; - - jfieldID next; - jfieldID prev; - jfieldID filename; - jfieldID bus; - jfieldID descriptor; - jfieldID config; - jfieldID devnum; - jfieldID num_children; - jfieldID children; - jfieldID devStructAddr; -}tUsb_Device; - -#define LOAD_FIELD(env, me, type, name) me->name = env->GetFieldID(me->clazz, #name, (type)) -#if 0 -#define SANITY_CHECK() { if (me->loaded == 0) Usb_Device_connect(env); } -#else -#define SANITY_CHECK() -#endif - -static tUsb_Device instance = { 0 }; -static tUsb_Device *me = &instance; - -int Usb_Device_connect(JNIEnv *env) -{ - jobject theClass = env->FindClass("ch/ntb/inf/libusbJava/Usb_Device"); - if (theClass == NULL) goto no_class; - - me->clazz = (jclass) env->NewGlobalRef(theClass); // make it global to avoid class unloading and therefore - // invalidating the references obtained. - if (me->clazz == NULL) goto no_memory; - - me->constructor = env->GetMethodID(me->clazz, "", "()V"); - if (me->constructor == NULL) goto no_constructor; - - LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device;", next); - LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device;", prev); - LOAD_FIELD(env, me, "Ljava/lang/String;", filename); - LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Bus;", bus); - LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device_Descriptor;", descriptor); - LOAD_FIELD(env, me, "[Lch/ntb/inf/libusbJava/Usb_Config_Descriptor;", config); - LOAD_FIELD(env, me, "B", devnum); - LOAD_FIELD(env, me, "B", num_children); - LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device;", children); - LOAD_FIELD(env, me, "J", devStructAddr); - - me->loaded = 1; - return 0; - -no_constructor: - env->DeleteGlobalRef(me->clazz); -no_memory: -no_class: - return -1; -} - -void Usb_Device_disconnect(JNIEnv *env) -{ - if (me->loaded == 0) return; - - env->DeleteGlobalRef(me->clazz); - memset(me, 0, sizeof(tUsb_Device)); -} - -jobject Usb_Device_create(JNIEnv *env, libusb_device *handle, uint8_t address){ - if (me->loaded == 0) return NULL; - - jobject result = env->NewObject(me->clazz, me->constructor); - - if (result != NULL) { - char filename[4]; - - snprintf(filename, 4, "%03d", address); - - env->SetLongField(result, me->devStructAddr, (jlong)handle); - env->SetByteField(result, me->devnum, address); - env->SetObjectField(result, me->filename, env->NewStringUTF(filename)); - - env->SetByteField(result, me->num_children, 0); /*Hardcoded to 0, like the compatibility Layer*/ - env->SetObjectField(result, me->children, NULL); /*Hardcoded to NULL, like the compatibility Layer*/ - } - - return result; -} - -libusb_device * Usb_Device_HandleGet(JNIEnv *env, jobject dev) -{ - if (me->loaded == 0) return NULL; - - return (libusb_device*)env->GetLongField(dev, me->devStructAddr); -} - -void Usb_Device_HandleSet(JNIEnv *env, jobject dev, libusb_device *handle) -{ - env->SetLongField(dev, me->devStructAddr, (jlong)handle); -} - -void Usb_Device_ConfigSet(JNIEnv *env, jobject dev, jobjectArray config) -{ - env->SetObjectField(dev, me->config, config); -} - -void Usb_Device_DescriptorSet(JNIEnv *env, jobject dev, jobject desc) -{ - env->SetObjectField(dev, me->descriptor, desc); -} - -void Usb_Device_NextSet(JNIEnv *env, jobject dev, jobject next) { - env->SetObjectField(dev, me->next, next); -} - -void Usb_Device_PrevSet(JNIEnv *env, jobject dev, jobject prev) { - env->SetObjectField(dev, me->prev, prev); -} +/*! \file + * + * C++ Stub for the java class of a java class ch.ntb.inf.libusbJava.Usb_Device. + * + * \author Ueli Niederer + */ +#include "Usb_Device.h" +#include + +#ifdef DO_UNIT_TEST +# include + +# define TEST_CASE(name) static void name(CuTest *tc) +#endif + +typedef struct JField { + const char *type; + const char *name; + jfieldID id; +}tJField; + +typedef struct Usb_Device { + int loaded; + + jclass clazz; + + jmethodID constructor; + + jfieldID next; + jfieldID prev; + jfieldID filename; + jfieldID bus; + jfieldID descriptor; + jfieldID config; + jfieldID devnum; + jfieldID num_children; + jfieldID children; + jfieldID devStructAddr; +}tUsb_Device; + +#define LOAD_FIELD(env, me, type, name) me->name = env->GetFieldID(me->clazz, #name, (type)) +#if 0 +#define SANITY_CHECK() { if (me->loaded == 0) Usb_Device_connect(env); } +#else +#define SANITY_CHECK() +#endif + +static tUsb_Device instance = { 0 }; +static tUsb_Device *me = &instance; + +int Usb_Device_connect(JNIEnv *env) +{ + jobject theClass = env->FindClass("ch/ntb/inf/libusbJava/Usb_Device"); + if (theClass == NULL) goto no_class; + + me->clazz = (jclass) env->NewGlobalRef(theClass); // make it global to avoid class unloading and therefore + // invalidating the references obtained. + if (me->clazz == NULL) goto no_memory; + + me->constructor = env->GetMethodID(me->clazz, "", "()V"); + if (me->constructor == NULL) goto no_constructor; + + LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device;", next); + LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device;", prev); + LOAD_FIELD(env, me, "Ljava/lang/String;", filename); + LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Bus;", bus); + LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device_Descriptor;", descriptor); + LOAD_FIELD(env, me, "[Lch/ntb/inf/libusbJava/Usb_Config_Descriptor;", config); + LOAD_FIELD(env, me, "B", devnum); + LOAD_FIELD(env, me, "B", num_children); + LOAD_FIELD(env, me, "Lch/ntb/inf/libusbJava/Usb_Device;", children); + LOAD_FIELD(env, me, "J", devStructAddr); + + me->loaded = 1; + return 0; + +no_constructor: + env->DeleteGlobalRef(me->clazz); +no_memory: +no_class: + return -1; +} + +void Usb_Device_disconnect(JNIEnv *env) +{ + if (me->loaded == 0) return; + + env->DeleteGlobalRef(me->clazz); + memset(me, 0, sizeof(tUsb_Device)); +} + +jobject Usb_Device_create(JNIEnv *env, libusb_device *handle, uint8_t address){ + if (me->loaded == 0) return NULL; + + jobject result = env->NewObject(me->clazz, me->constructor); + + if (result != NULL) { + char filename[4]; + + snprintf(filename, 4, "%03d", address); + + env->SetLongField(result, me->devStructAddr, (jlong)handle); + env->SetByteField(result, me->devnum, address); + env->SetObjectField(result, me->filename, env->NewStringUTF(filename)); + + env->SetByteField(result, me->num_children, 0); /*Hardcoded to 0, like the compatibility Layer*/ + env->SetObjectField(result, me->children, NULL); /*Hardcoded to NULL, like the compatibility Layer*/ + } + + return result; +} + +libusb_device * Usb_Device_HandleGet(JNIEnv *env, jobject dev) +{ + if (me->loaded == 0) return NULL; + + return (libusb_device*)env->GetLongField(dev, me->devStructAddr); +} + +void Usb_Device_HandleSet(JNIEnv *env, jobject dev, libusb_device *handle) +{ + env->SetLongField(dev, me->devStructAddr, (jlong)handle); +} + +void Usb_Device_ConfigSet(JNIEnv *env, jobject dev, jobjectArray config) +{ + env->SetObjectField(dev, me->config, config); +} + +void Usb_Device_DescriptorSet(JNIEnv *env, jobject dev, jobject desc) +{ + env->SetObjectField(dev, me->descriptor, desc); +} + +void Usb_Device_NextSet(JNIEnv *env, jobject dev, jobject next) { + env->SetObjectField(dev, me->next, next); +} + +void Usb_Device_PrevSet(JNIEnv *env, jobject dev, jobject prev) { + env->SetObjectField(dev, me->prev, prev); +} diff --git a/LibusbJava/LibusbJava.h b/src/main/headers/LibusbJava.h similarity index 96% rename from LibusbJava/LibusbJava.h rename to src/main/headers/LibusbJava.h index 9b4e1ea..ef37b4d 100644 --- a/LibusbJava/LibusbJava.h +++ b/src/main/headers/LibusbJava.h @@ -1,509 +1,509 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class ch_ntb_inf_libusbJava_LibusbJava1 */ - -#ifndef _Included_ch_ntb_inf_libusbJava_LibusbJava1 -#define _Included_ch_ntb_inf_libusbJava_LibusbJava1 -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_debug - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1debug - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_init - * Signature: ()J - */ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1init - (JNIEnv *, jclass); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_exit - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1exit - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_device_list - * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; - */ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device_1list - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_bus_number - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)S - */ -JNIEXPORT jshort JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1bus_1number - (JNIEnv *, jclass, jobject); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_max_iso_packet_size - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;S)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1max_1iso_1packet_1size - (JNIEnv *, jclass, jobject, jshort); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_ref_device - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Device; - */ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1ref_1device - (JNIEnv *, jclass, jobject); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_unref_device - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unref_1device - (JNIEnv *, jclass, jobject); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_open - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)J - */ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open - (JNIEnv *, jclass, jobject); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_open_device_with_vid_pid - * Signature: (JII)J - */ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open_1device_1with_1vid_1pid - (JNIEnv *, jclass, jlong, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_close - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1close - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_device - * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; - */ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_configuration - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1configuration - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_configuration - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1configuration - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_claim_interface - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1claim_1interface - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_release_interface - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1release_1interface - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_interface_alt_setting - * Signature: (JII)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1interface_1alt_1setting - (JNIEnv *, jclass, jlong, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_clear_halt - * Signature: (JS)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1clear_1halt - (JNIEnv *, jclass, jlong, jshort); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_reset_device - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1reset_1device - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_kernel_driver_active - * Signature: (JI)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1kernel_1driver_1active - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_detach_kernel_driver - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1detach_1kernel_1driver - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_attach_kernel_driver - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1attach_1kernel_1driver - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_active_config_descriptor - * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Config_Descriptor; - */ -JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1active_1config_1descriptor - (JNIEnv *, jclass, jobject); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_string_descriptor_ascii - * Signature: (JSI)Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor_1ascii - (JNIEnv *, jclass, jlong, jshort, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_descriptor - * Signature: (JISI)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1descriptor - (JNIEnv *, jclass, jlong, jint, jshort, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_string_descriptor - * Signature: (JSII)Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor - (JNIEnv *, jclass, jlong, jshort, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_alloc_transfer - * Signature: (I)J - */ -JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1alloc_1transfer - (JNIEnv *, jclass, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_free_transfer - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1free_1transfer - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_submit_transfer - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1submit_1transfer - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_cancel_transfer - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1cancel_1transfer - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_control_transfer_get_data - * Signature: (J)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1data - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_control_transfer_get_setup - * Signature: (J)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1setup - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_control_setup - * Signature: (IIIII)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1setup - (JNIEnv *, jclass, jint, jint, jint, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_control_transfer - * Signature: (JJ[BI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1transfer - (JNIEnv *, jclass, jlong, jlong, jbyteArray, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_bulk_transfer - * Signature: (JJB[BII)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1bulk_1transfer - (JNIEnv *, jclass, jlong, jlong, jbyte, jbyteArray, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_interrupt_transfer - * Signature: (JJB[BII)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1interrupt_1transfer - (JNIEnv *, jclass, jlong, jlong, jbyte, jbyteArray, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_fill_iso_transfer - * Signature: (JJB[BIII)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1iso_1transfer - (JNIEnv *, jclass, jlong, jlong, jbyte, jbyteArray, jint, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_iso_packet_lengths - * Signature: (JI)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1iso_1packet_1lengths - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_iso_packet_buffer - * Signature: (JI)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_iso_packet_buffer_simple - * Signature: (JI)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer_1simple - (JNIEnv *, jclass, jlong, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_try_lock_events - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1try_1lock_1events - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_lock_events - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1events - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_unlock_events - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1events - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_event_handling_ok - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handling_1ok - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_event_handler_active - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handler_1active - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_lock_event_waiters - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1event_1waiters - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_unlock_event_waiters - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1event_1waiters - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_wait_for_event - * Signature: (JJ)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1wait_1for_1event - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_handle_events_timeout - * Signature: (JJ)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1timeout - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_handle_events - * Signature: (J)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_handle_events_locked - * Signature: (JJ)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1locked - (JNIEnv *, jclass, jlong, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_pollfds_handle_timeouts - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1pollfds_1handle_1timeouts - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_next_timeout - * Signature: (J)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1next_1timeout - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_set_pollfd_notifiers - * Signature: (JZ)V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1pollfd_1notifiers - (JNIEnv *, jclass, jlong, jboolean); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_get_pollfds - * Signature: (J)[Lch/ntb/inf/libusbJava/Libusb_pollfd; - */ -JNIEXPORT jobjectArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1pollfds - (JNIEnv *, jclass, jlong); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_control_transfer - * Signature: (JIIII[BII)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer - (JNIEnv *, jclass, jlong, jint, jint, jint, jint, jbyteArray, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_bulk_transfer - * Signature: (JB[BII)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1bulk_1transfer - (JNIEnv *, jclass, jlong, jbyte, jbyteArray, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_interrupt_transfer - * Signature: (JB[BII)I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1interrupt_1transfer - (JNIEnv *, jclass, jlong, jbyte, jbyteArray, jint, jint); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: libusb_strerror - * Signature: ()Ljava/lang/String; - */ -JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1strerror - (JNIEnv *, jclass); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: setup - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_setup - (JNIEnv *, jclass); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: teardown - * Signature: ()V - */ -JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_teardown - (JNIEnv *, jclass); - -/* - * Class: ch_ntb_inf_libusbJava_LibusbJava1 - * Method: to_byteArrayTest - * Signature: (Ljava/lang/String;I)[B - */ -JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_to_1byteArrayTest - (JNIEnv *, jclass, jstring, jint); - -#ifdef __cplusplus -} -#endif -#endif +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class ch_ntb_inf_libusbJava_LibusbJava1 */ + +#ifndef _Included_ch_ntb_inf_libusbJava_LibusbJava1 +#define _Included_ch_ntb_inf_libusbJava_LibusbJava1 +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_debug + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1debug + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_init + * Signature: ()J + */ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1init + (JNIEnv *, jclass); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_exit + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1exit + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_device_list + * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; + */ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device_1list + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_bus_number + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)S + */ +JNIEXPORT jshort JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1bus_1number + (JNIEnv *, jclass, jobject); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_max_iso_packet_size + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;S)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1max_1iso_1packet_1size + (JNIEnv *, jclass, jobject, jshort); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_ref_device + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Device; + */ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1ref_1device + (JNIEnv *, jclass, jobject); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_unref_device + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unref_1device + (JNIEnv *, jclass, jobject); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_open + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)J + */ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open + (JNIEnv *, jclass, jobject); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_open_device_with_vid_pid + * Signature: (JII)J + */ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1open_1device_1with_1vid_1pid + (JNIEnv *, jclass, jlong, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_close + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1close + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_device + * Signature: (J)Lch/ntb/inf/libusbJava/Usb_Device; + */ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1device + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_configuration + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1configuration + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_configuration + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1configuration + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_claim_interface + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1claim_1interface + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_release_interface + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1release_1interface + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_interface_alt_setting + * Signature: (JII)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1interface_1alt_1setting + (JNIEnv *, jclass, jlong, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_clear_halt + * Signature: (JS)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1clear_1halt + (JNIEnv *, jclass, jlong, jshort); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_reset_device + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1reset_1device + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_kernel_driver_active + * Signature: (JI)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1kernel_1driver_1active + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_detach_kernel_driver + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1detach_1kernel_1driver + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_attach_kernel_driver + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1attach_1kernel_1driver + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_active_config_descriptor + * Signature: (Lch/ntb/inf/libusbJava/Usb_Device;)Lch/ntb/inf/libusbJava/Usb_Config_Descriptor; + */ +JNIEXPORT jobject JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1active_1config_1descriptor + (JNIEnv *, jclass, jobject); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_string_descriptor_ascii + * Signature: (JSI)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor_1ascii + (JNIEnv *, jclass, jlong, jshort, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_descriptor + * Signature: (JISI)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1descriptor + (JNIEnv *, jclass, jlong, jint, jshort, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_string_descriptor + * Signature: (JSII)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1string_1descriptor + (JNIEnv *, jclass, jlong, jshort, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_alloc_transfer + * Signature: (I)J + */ +JNIEXPORT jlong JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1alloc_1transfer + (JNIEnv *, jclass, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_free_transfer + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1free_1transfer + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_submit_transfer + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1submit_1transfer + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_cancel_transfer + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1cancel_1transfer + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_control_transfer_get_data + * Signature: (J)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1data + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_control_transfer_get_setup + * Signature: (J)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer_1get_1setup + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_control_setup + * Signature: (IIIII)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1setup + (JNIEnv *, jclass, jint, jint, jint, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_control_transfer + * Signature: (JJ[BI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1control_1transfer + (JNIEnv *, jclass, jlong, jlong, jbyteArray, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_bulk_transfer + * Signature: (JJB[BII)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1bulk_1transfer + (JNIEnv *, jclass, jlong, jlong, jbyte, jbyteArray, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_interrupt_transfer + * Signature: (JJB[BII)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1interrupt_1transfer + (JNIEnv *, jclass, jlong, jlong, jbyte, jbyteArray, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_fill_iso_transfer + * Signature: (JJB[BIII)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1fill_1iso_1transfer + (JNIEnv *, jclass, jlong, jlong, jbyte, jbyteArray, jint, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_iso_packet_lengths + * Signature: (JI)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1iso_1packet_1lengths + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_iso_packet_buffer + * Signature: (JI)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_iso_packet_buffer_simple + * Signature: (JI)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1iso_1packet_1buffer_1simple + (JNIEnv *, jclass, jlong, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_try_lock_events + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1try_1lock_1events + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_lock_events + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1events + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_unlock_events + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1events + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_event_handling_ok + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handling_1ok + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_event_handler_active + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1event_1handler_1active + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_lock_event_waiters + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1lock_1event_1waiters + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_unlock_event_waiters + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1unlock_1event_1waiters + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_wait_for_event + * Signature: (JJ)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1wait_1for_1event + (JNIEnv *, jclass, jlong, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_handle_events_timeout + * Signature: (JJ)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1timeout + (JNIEnv *, jclass, jlong, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_handle_events + * Signature: (J)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_handle_events_locked + * Signature: (JJ)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1handle_1events_1locked + (JNIEnv *, jclass, jlong, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_pollfds_handle_timeouts + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1pollfds_1handle_1timeouts + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_next_timeout + * Signature: (J)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1next_1timeout + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_set_pollfd_notifiers + * Signature: (JZ)V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1set_1pollfd_1notifiers + (JNIEnv *, jclass, jlong, jboolean); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_get_pollfds + * Signature: (J)[Lch/ntb/inf/libusbJava/Libusb_pollfd; + */ +JNIEXPORT jobjectArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1get_1pollfds + (JNIEnv *, jclass, jlong); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_control_transfer + * Signature: (JIIII[BII)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1control_1transfer + (JNIEnv *, jclass, jlong, jint, jint, jint, jint, jbyteArray, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_bulk_transfer + * Signature: (JB[BII)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1bulk_1transfer + (JNIEnv *, jclass, jlong, jbyte, jbyteArray, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_interrupt_transfer + * Signature: (JB[BII)I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1interrupt_1transfer + (JNIEnv *, jclass, jlong, jbyte, jbyteArray, jint, jint); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: libusb_strerror + * Signature: ()Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_libusb_1strerror + (JNIEnv *, jclass); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: setup + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_setup + (JNIEnv *, jclass); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: teardown + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_teardown + (JNIEnv *, jclass); + +/* + * Class: ch_ntb_inf_libusbJava_LibusbJava1 + * Method: to_byteArrayTest + * Signature: (Ljava/lang/String;I)[B + */ +JNIEXPORT jbyteArray JNICALL Java_ch_ntb_inf_libusbJava_LibusbJava1_to_1byteArrayTest + (JNIEnv *, jclass, jstring, jint); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/LibusbJava/objects/Usb_Device.h b/src/main/headers/Usb_Device.h similarity index 97% rename from LibusbJava/objects/Usb_Device.h rename to src/main/headers/Usb_Device.h index f7ec224..3ca554c 100644 --- a/LibusbJava/objects/Usb_Device.h +++ b/src/main/headers/Usb_Device.h @@ -1,18 +1,18 @@ -#ifndef USBDEVICE_H_ -#define USBDEVICE_H_ - - #include - #include - - int Usb_Device_connect(JNIEnv *env); - void Usb_Device_disconnect(JNIEnv *env); - - jobject Usb_Device_create(JNIEnv *env, libusb_device *handle, uint8_t address); - libusb_device * Usb_Device_HandleGet(JNIEnv *env, jobject dev); - void Usb_Device_HandleSet(JNIEnv *env, jobject dev, libusb_device *handle); - void Usb_Device_ConfigSet(JNIEnv *env, jobject dev, jobjectArray config); - void Usb_Device_DescriptorSet(JNIEnv *env, jobject dev, jobject desc); - void Usb_Device_NextSet(JNIEnv *env, jobject dev, jobject next); - void Usb_Device_PrevSet(JNIEnv *env, jobject dev, jobject prev); - -#endif /* USBDEVICE_H_ */ +#ifndef USBDEVICE_H_ +#define USBDEVICE_H_ + + #include + #include + + int Usb_Device_connect(JNIEnv *env); + void Usb_Device_disconnect(JNIEnv *env); + + jobject Usb_Device_create(JNIEnv *env, libusb_device *handle, uint8_t address); + libusb_device * Usb_Device_HandleGet(JNIEnv *env, jobject dev); + void Usb_Device_HandleSet(JNIEnv *env, jobject dev, libusb_device *handle); + void Usb_Device_ConfigSet(JNIEnv *env, jobject dev, jobjectArray config); + void Usb_Device_DescriptorSet(JNIEnv *env, jobject dev, jobject desc); + void Usb_Device_NextSet(JNIEnv *env, jobject dev, jobject next); + void Usb_Device_PrevSet(JNIEnv *env, jobject dev, jobject prev); + +#endif /* USBDEVICE_H_ */ diff --git a/LibusbJava/libusb/include/libusb.h b/src/main/headers/libusb.h similarity index 97% rename from LibusbJava/libusb/include/libusb.h rename to src/main/headers/libusb.h index 1984ae5..da94c9b 100644 --- a/LibusbJava/libusb/include/libusb.h +++ b/src/main/headers/libusb.h @@ -1,1506 +1,1506 @@ -/* - * Public libusbx header file - * Copyright © 2001 Johannes Erdfelt - * Copyright © 2007-2008 Daniel Drake - * Copyright © 2012 Pete Batard - * For more information, please visit: http://libusbx.org - * - * 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 - */ - -#ifndef LIBUSB_H -#define LIBUSB_H - -#ifdef _MSC_VER -/* on MS environments, the inline keyword is available in C++ only */ -#if !defined(__cplusplus) -#define inline __inline -#endif -/* ssize_t is also not available (copy/paste from MinGW) */ -#ifndef _SSIZE_T_DEFINED -#define _SSIZE_T_DEFINED -#undef ssize_t -#ifdef _WIN64 - typedef __int64 ssize_t; -#else - typedef int ssize_t; -#endif /* _WIN64 */ -#endif /* _SSIZE_T_DEFINED */ -#endif /* _MSC_VER */ - -/* stdint.h is also not usually available on MS */ -#if defined(_MSC_VER) && (_MSC_VER < 1600) && (!defined(_STDINT)) && (!defined(_STDINT_H)) -typedef unsigned __int8 uint8_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int32 uint32_t; -#else -#include -#endif - -#include -#include -#include - -#if defined(__linux) || defined(__APPLE__) || defined(__CYGWIN__) -#include -#endif - -/* 'interface' might be defined as a macro on Windows, so we need to - * undefine it so as not to break the current libusbx API, because - * libusb_config_descriptor has an 'interface' member - * As this can be problematic if you include windows.h after libusb.h - * in your sources, we force windows.h to be included first. */ -#if defined(_WIN32) || defined(__CYGWIN__) -#include -#if defined(interface) -#undef interface -#endif -#endif - -/** \def LIBUSB_CALL - * \ingroup misc - * libusbx's Windows calling convention. - * - * Under Windows, the selection of available compilers and configurations - * means that, unlike other platforms, there is not one true calling - * convention (calling convention: the manner in which parameters are - * passed to funcions in the generated assembly code). - * - * Matching the Windows API itself, libusbx uses the WINAPI convention (which - * translates to the stdcall convention) and guarantees that the - * library is compiled in this way. The public header file also includes - * appropriate annotations so that your own software will use the right - * convention, even if another convention is being used by default within - * your codebase. - * - * The one consideration that you must apply in your software is to mark - * all functions which you use as libusbx callbacks with this LIBUSB_CALL - * annotation, so that they too get compiled for the correct calling - * convention. - * - * On non-Windows operating systems, this macro is defined as nothing. This - * means that you can apply it to your code without worrying about - * cross-platform compatibility. - */ -/* LIBUSB_CALL must be defined on both definition and declaration of libusbx - * functions. You'd think that declaration would be enough, but cygwin will - * complain about conflicting types unless both are marked this way. - * The placement of this macro is important too; it must appear after the - * return type, before the function name. See internal documentation for - * API_EXPORTED. - */ -#if defined(_WIN32) || defined(__CYGWIN__) -#define LIBUSB_CALL WINAPI -#else -#define LIBUSB_CALL -#endif - -/** \def LIBUSBX_API_VERSION - * \ingroup misc - * libusbx's API version. - * - * Since version 1.0.13, to help with feature detection, libusbx defines - * a LIBUSBX_API_VERSION macro that gets increased every time there is a - * significant change to the API, such as the introduction of a new call, - * the definition of a new macro/enum member, or any other element that - * libusbx applications may want to detect at compilation time. - * - * The macro is typically used in an application as follows: - * \code - * #if defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01001234) - * // Use one of the newer features from the libusbx API - * #endif - * \endcode - * - * Another feature of LIBUSBX_API_VERSION is that it can be used to detect - * whether you are compiling against the libusb or the libusbx library. - * - * Internally, LIBUSBX_API_VERSION is defined as follows: - * (libusbx major << 24) | (libusbx minor << 16) | (16 bit incremental) - */ -#define LIBUSBX_API_VERSION 0x010000FF - -#ifdef __cplusplus -extern "C" { -#endif - -/** \def libusb_cpu_to_le16 - * \ingroup misc - * Convert a 16-bit value from host-endian to little-endian format. On - * little endian systems, this function does nothing. On big endian systems, - * the bytes are swapped. - * \param x the host-endian value to convert - * \returns the value in little-endian byte order - */ -static inline uint16_t libusb_cpu_to_le16(const uint16_t x) -{ - union { - uint8_t b8[2]; - uint16_t b16; - } _tmp; - _tmp.b8[1] = x >> 8; - _tmp.b8[0] = x & 0xff; - return _tmp.b16; -} - -/** \def libusb_le16_to_cpu - * \ingroup misc - * Convert a 16-bit value from little-endian to host-endian format. On - * little endian systems, this function does nothing. On big endian systems, - * the bytes are swapped. - * \param x the little-endian value to convert - * \returns the value in host-endian byte order - */ -#define libusb_le16_to_cpu libusb_cpu_to_le16 - -/* standard USB stuff */ - -/** \ingroup desc - * Device and/or Interface Class codes */ -enum libusb_class_code { - /** In the context of a \ref libusb_device_descriptor "device descriptor", - * this bDeviceClass value indicates that each interface specifies its - * own class information and all interfaces operate independently. - */ - LIBUSB_CLASS_PER_INTERFACE = 0, - - /** Audio class */ - LIBUSB_CLASS_AUDIO = 1, - - /** Communications class */ - LIBUSB_CLASS_COMM = 2, - - /** Human Interface Device class */ - LIBUSB_CLASS_HID = 3, - - /** Physical */ - LIBUSB_CLASS_PHYSICAL = 5, - - /** Printer class */ - LIBUSB_CLASS_PRINTER = 7, - - /** Image class */ - LIBUSB_CLASS_PTP = 6, /* legacy name from libusb-0.1 usb.h */ - LIBUSB_CLASS_IMAGE = 6, - - /** Mass storage class */ - LIBUSB_CLASS_MASS_STORAGE = 8, - - /** Hub class */ - LIBUSB_CLASS_HUB = 9, - - /** Data class */ - LIBUSB_CLASS_DATA = 10, - - /** Smart Card */ - LIBUSB_CLASS_SMART_CARD = 0x0b, - - /** Content Security */ - LIBUSB_CLASS_CONTENT_SECURITY = 0x0d, - - /** Video */ - LIBUSB_CLASS_VIDEO = 0x0e, - - /** Personal Healthcare */ - LIBUSB_CLASS_PERSONAL_HEALTHCARE = 0x0f, - - /** Diagnostic Device */ - LIBUSB_CLASS_DIAGNOSTIC_DEVICE = 0xdc, - - /** Wireless class */ - LIBUSB_CLASS_WIRELESS = 0xe0, - - /** Application class */ - LIBUSB_CLASS_APPLICATION = 0xfe, - - /** Class is vendor-specific */ - LIBUSB_CLASS_VENDOR_SPEC = 0xff -}; - -/** \ingroup desc - * Descriptor types as defined by the USB specification. */ -enum libusb_descriptor_type { - /** Device descriptor. See libusb_device_descriptor. */ - LIBUSB_DT_DEVICE = 0x01, - - /** Configuration descriptor. See libusb_config_descriptor. */ - LIBUSB_DT_CONFIG = 0x02, - - /** String descriptor */ - LIBUSB_DT_STRING = 0x03, - - /** Interface descriptor. See libusb_interface_descriptor. */ - LIBUSB_DT_INTERFACE = 0x04, - - /** Endpoint descriptor. See libusb_endpoint_descriptor. */ - LIBUSB_DT_ENDPOINT = 0x05, - - /** HID descriptor */ - LIBUSB_DT_HID = 0x21, - - /** HID report descriptor */ - LIBUSB_DT_REPORT = 0x22, - - /** Physical descriptor */ - LIBUSB_DT_PHYSICAL = 0x23, - - /** Hub descriptor */ - LIBUSB_DT_HUB = 0x29, - - /** SuperSpeed Hub descriptor */ - LIBUSB_DT_SUPERSPEED_HUB = 0x2A, -}; - -/* Descriptor sizes per descriptor type */ -#define LIBUSB_DT_DEVICE_SIZE 18 -#define LIBUSB_DT_CONFIG_SIZE 9 -#define LIBUSB_DT_INTERFACE_SIZE 9 -#define LIBUSB_DT_ENDPOINT_SIZE 7 -#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */ -#define LIBUSB_DT_HUB_NONVAR_SIZE 7 - -#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */ -#define LIBUSB_ENDPOINT_DIR_MASK 0x80 - -/** \ingroup desc - * Endpoint direction. Values for bit 7 of the - * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme. - */ -enum libusb_endpoint_direction { - /** In: device-to-host */ - LIBUSB_ENDPOINT_IN = 0x80, - - /** Out: host-to-device */ - LIBUSB_ENDPOINT_OUT = 0x00 -}; - -#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */ - -/** \ingroup desc - * Endpoint transfer type. Values for bits 0:1 of the - * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field. - */ -enum libusb_transfer_type { - /** Control endpoint */ - LIBUSB_TRANSFER_TYPE_CONTROL = 0, - - /** Isochronous endpoint */ - LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1, - - /** Bulk endpoint */ - LIBUSB_TRANSFER_TYPE_BULK = 2, - - /** Interrupt endpoint */ - LIBUSB_TRANSFER_TYPE_INTERRUPT = 3 -}; - -/** \ingroup misc - * Standard requests, as defined in table 9-5 of the USB 3.0 specifications */ -enum libusb_standard_request { - /** Request status of the specific recipient */ - LIBUSB_REQUEST_GET_STATUS = 0x00, - - /** Clear or disable a specific feature */ - LIBUSB_REQUEST_CLEAR_FEATURE = 0x01, - - /* 0x02 is reserved */ - - /** Set or enable a specific feature */ - LIBUSB_REQUEST_SET_FEATURE = 0x03, - - /* 0x04 is reserved */ - - /** Set device address for all future accesses */ - LIBUSB_REQUEST_SET_ADDRESS = 0x05, - - /** Get the specified descriptor */ - LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06, - - /** Used to update existing descriptors or add new descriptors */ - LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07, - - /** Get the current device configuration value */ - LIBUSB_REQUEST_GET_CONFIGURATION = 0x08, - - /** Set device configuration */ - LIBUSB_REQUEST_SET_CONFIGURATION = 0x09, - - /** Return the selected alternate setting for the specified interface */ - LIBUSB_REQUEST_GET_INTERFACE = 0x0A, - - /** Select an alternate interface for the specified interface */ - LIBUSB_REQUEST_SET_INTERFACE = 0x0B, - - /** Set then report an endpoint's synchronization frame */ - LIBUSB_REQUEST_SYNCH_FRAME = 0x0C, - - /** Sets both the U1 and U2 Exit Latency */ - LIBUSB_REQUEST_SET_SEL = 0x30, - - /** Delay from the time a host transmits a packet to the time it is - * received by the device. */ - LIBUSB_SET_ISOCH_DELAY = 0x31, -}; - -/** \ingroup misc - * Request type bits of the - * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control - * transfers. */ -enum libusb_request_type { - /** Standard */ - LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5), - - /** Class */ - LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5), - - /** Vendor */ - LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5), - - /** Reserved */ - LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5) -}; - -/** \ingroup misc - * Recipient bits of the - * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control - * transfers. Values 4 through 31 are reserved. */ -enum libusb_request_recipient { - /** Device */ - LIBUSB_RECIPIENT_DEVICE = 0x00, - - /** Interface */ - LIBUSB_RECIPIENT_INTERFACE = 0x01, - - /** Endpoint */ - LIBUSB_RECIPIENT_ENDPOINT = 0x02, - - /** Other */ - LIBUSB_RECIPIENT_OTHER = 0x03, -}; - -#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C - -/** \ingroup desc - * Synchronization type for isochronous endpoints. Values for bits 2:3 of the - * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in - * libusb_endpoint_descriptor. - */ -enum libusb_iso_sync_type { - /** No synchronization */ - LIBUSB_ISO_SYNC_TYPE_NONE = 0, - - /** Asynchronous */ - LIBUSB_ISO_SYNC_TYPE_ASYNC = 1, - - /** Adaptive */ - LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2, - - /** Synchronous */ - LIBUSB_ISO_SYNC_TYPE_SYNC = 3 -}; - -#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30 - -/** \ingroup desc - * Usage type for isochronous endpoints. Values for bits 4:5 of the - * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in - * libusb_endpoint_descriptor. - */ -enum libusb_iso_usage_type { - /** Data endpoint */ - LIBUSB_ISO_USAGE_TYPE_DATA = 0, - - /** Feedback endpoint */ - LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1, - - /** Implicit feedback Data endpoint */ - LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2, -}; - -/** \ingroup desc - * A structure representing the standard USB device descriptor. This - * descriptor is documented in section 9.6.1 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_device_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this - * context. */ - uint8_t bDescriptorType; - - /** USB specification release number in binary-coded decimal. A value of - * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */ - uint16_t bcdUSB; - - /** USB-IF class code for the device. See \ref libusb_class_code. */ - uint8_t bDeviceClass; - - /** USB-IF subclass code for the device, qualified by the bDeviceClass - * value */ - uint8_t bDeviceSubClass; - - /** USB-IF protocol code for the device, qualified by the bDeviceClass and - * bDeviceSubClass values */ - uint8_t bDeviceProtocol; - - /** Maximum packet size for endpoint 0 */ - uint8_t bMaxPacketSize0; - - /** USB-IF vendor ID */ - uint16_t idVendor; - - /** USB-IF product ID */ - uint16_t idProduct; - - /** Device release number in binary-coded decimal */ - uint16_t bcdDevice; - - /** Index of string descriptor describing manufacturer */ - uint8_t iManufacturer; - - /** Index of string descriptor describing product */ - uint8_t iProduct; - - /** Index of string descriptor containing device serial number */ - uint8_t iSerialNumber; - - /** Number of possible configurations */ - uint8_t bNumConfigurations; -}; - -/** \ingroup desc - * A structure representing the standard USB endpoint descriptor. This - * descriptor is documented in section 9.6.6 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_endpoint_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in - * this context. */ - uint8_t bDescriptorType; - - /** The address of the endpoint described by this descriptor. Bits 0:3 are - * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction, - * see \ref libusb_endpoint_direction. - */ - uint8_t bEndpointAddress; - - /** Attributes which apply to the endpoint when it is configured using - * the bConfigurationValue. Bits 0:1 determine the transfer type and - * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for - * isochronous endpoints and correspond to \ref libusb_iso_sync_type. - * Bits 4:5 are also only used for isochronous endpoints and correspond to - * \ref libusb_iso_usage_type. Bits 6:7 are reserved. - */ - uint8_t bmAttributes; - - /** Maximum packet size this endpoint is capable of sending/receiving. */ - uint16_t wMaxPacketSize; - - /** Interval for polling endpoint for data transfers. */ - uint8_t bInterval; - - /** For audio devices only: the rate at which synchronization feedback - * is provided. */ - uint8_t bRefresh; - - /** For audio devices only: the address if the synch endpoint */ - uint8_t bSynchAddress; - - /** Extra descriptors. If libusbx encounters unknown endpoint descriptors, - * it will store them here, should you wish to parse them. */ - const unsigned char *extra; - - /** Length of the extra descriptors, in bytes. */ - int extra_length; -}; - -/** \ingroup desc - * A structure representing the standard USB interface descriptor. This - * descriptor is documented in section 9.6.5 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_interface_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE - * in this context. */ - uint8_t bDescriptorType; - - /** Number of this interface */ - uint8_t bInterfaceNumber; - - /** Value used to select this alternate setting for this interface */ - uint8_t bAlternateSetting; - - /** Number of endpoints used by this interface (excluding the control - * endpoint). */ - uint8_t bNumEndpoints; - - /** USB-IF class code for this interface. See \ref libusb_class_code. */ - uint8_t bInterfaceClass; - - /** USB-IF subclass code for this interface, qualified by the - * bInterfaceClass value */ - uint8_t bInterfaceSubClass; - - /** USB-IF protocol code for this interface, qualified by the - * bInterfaceClass and bInterfaceSubClass values */ - uint8_t bInterfaceProtocol; - - /** Index of string descriptor describing this interface */ - uint8_t iInterface; - - /** Array of endpoint descriptors. This length of this array is determined - * by the bNumEndpoints field. */ - const struct libusb_endpoint_descriptor *endpoint; - - /** Extra descriptors. If libusbx encounters unknown interface descriptors, - * it will store them here, should you wish to parse them. */ - const unsigned char *extra; - - /** Length of the extra descriptors, in bytes. */ - int extra_length; -}; - -/** \ingroup desc - * A collection of alternate settings for a particular USB interface. - */ -struct libusb_interface { - /** Array of interface descriptors. The length of this array is determined - * by the num_altsetting field. */ - const struct libusb_interface_descriptor *altsetting; - - /** The number of alternate settings that belong to this interface */ - int num_altsetting; -}; - -/** \ingroup desc - * A structure representing the standard USB configuration descriptor. This - * descriptor is documented in section 9.6.3 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_config_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG - * in this context. */ - uint8_t bDescriptorType; - - /** Total length of data returned for this configuration */ - uint16_t wTotalLength; - - /** Number of interfaces supported by this configuration */ - uint8_t bNumInterfaces; - - /** Identifier value for this configuration */ - uint8_t bConfigurationValue; - - /** Index of string descriptor describing this configuration */ - uint8_t iConfiguration; - - /** Configuration characteristics */ - uint8_t bmAttributes; - - /** Maximum power consumption of the USB device from this bus in this - * configuration when the device is fully opreation. Expressed in units - * of 2 mA. */ - uint8_t MaxPower; - - /** Array of interfaces supported by this configuration. The length of - * this array is determined by the bNumInterfaces field. */ - const struct libusb_interface *interface; - - /** Extra descriptors. If libusbx encounters unknown configuration - * descriptors, it will store them here, should you wish to parse them. */ - const unsigned char *extra; - - /** Length of the extra descriptors, in bytes. */ - int extra_length; -}; - -/** \ingroup asyncio - * Setup packet for control transfers. */ -struct libusb_control_setup { - /** Request type. Bits 0:4 determine recipient, see - * \ref libusb_request_recipient. Bits 5:6 determine type, see - * \ref libusb_request_type. Bit 7 determines data transfer direction, see - * \ref libusb_endpoint_direction. - */ - uint8_t bmRequestType; - - /** Request. If the type bits of bmRequestType are equal to - * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD - * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to - * \ref libusb_standard_request. For other cases, use of this field is - * application-specific. */ - uint8_t bRequest; - - /** Value. Varies according to request */ - uint16_t wValue; - - /** Index. Varies according to request, typically used to pass an index - * or offset */ - uint16_t wIndex; - - /** Number of bytes to transfer */ - uint16_t wLength; -}; - -#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup)) - -/* libusbx */ - -struct libusb_context; -struct libusb_device; -struct libusb_device_handle; - -/** \ingroup lib - * Structure providing the version of the libusbx runtime - */ -struct libusb_version { - /** Library major version. */ - const uint16_t major; - - /** Library minor version. */ - const uint16_t minor; - - /** Library micro version. */ - const uint16_t micro; - - /** Library nano version. */ - const uint16_t nano; - - /** Library release candidate suffix string, e.g. "-rc4". */ - const char *rc; - - /** For ABI compatibility only. */ - const char* describe; -}; - -/** \ingroup lib - * Structure representing a libusbx session. The concept of individual libusbx - * sessions allows for your program to use two libraries (or dynamically - * load two modules) which both independently use libusb. This will prevent - * interference between the individual libusbx users - for example - * libusb_set_debug() will not affect the other user of the library, and - * libusb_exit() will not destroy resources that the other user is still - * using. - * - * Sessions are created by libusb_init() and destroyed through libusb_exit(). - * If your application is guaranteed to only ever include a single libusbx - * user (i.e. you), you do not have to worry about contexts: pass NULL in - * every function call where a context is required. The default context - * will be used. - * - * For more information, see \ref contexts. - */ -typedef struct libusb_context libusb_context; - -/** \ingroup dev - * Structure representing a USB device detected on the system. This is an - * opaque type for which you are only ever provided with a pointer, usually - * originating from libusb_get_device_list(). - * - * Certain operations can be performed on a device, but in order to do any - * I/O you will have to first obtain a device handle using libusb_open(). - * - * Devices are reference counted with libusb_device_ref() and - * libusb_device_unref(), and are freed when the reference count reaches 0. - * New devices presented by libusb_get_device_list() have a reference count of - * 1, and libusb_free_device_list() can optionally decrease the reference count - * on all devices in the list. libusb_open() adds another reference which is - * later destroyed by libusb_close(). - */ -typedef struct libusb_device libusb_device; - - -/** \ingroup dev - * Structure representing a handle on a USB device. This is an opaque type for - * which you are only ever provided with a pointer, usually originating from - * libusb_open(). - * - * A device handle is used to perform I/O and other operations. When finished - * with a device handle, you should call libusb_close(). - */ -typedef struct libusb_device_handle libusb_device_handle; - -/** \ingroup dev - * Speed codes. Indicates the speed at which the device is operating. - */ -enum libusb_speed { - /** The OS doesn't report or know the device speed. */ - LIBUSB_SPEED_UNKNOWN = 0, - - /** The device is operating at low speed (1.5MBit/s). */ - LIBUSB_SPEED_LOW = 1, - - /** The device is operating at full speed (12MBit/s). */ - LIBUSB_SPEED_FULL = 2, - - /** The device is operating at high speed (480MBit/s). */ - LIBUSB_SPEED_HIGH = 3, - - /** The device is operating at super speed (5000MBit/s). */ - LIBUSB_SPEED_SUPER = 4, -}; - -/** \ingroup misc - * Error codes. Most libusbx functions return 0 on success or one of these - * codes on failure. - * You can call \ref libusb_error_name() to retrieve a string representation - * of an error code. - */ -enum libusb_error { - /** Success (no error) */ - LIBUSB_SUCCESS = 0, - - /** Input/output error */ - LIBUSB_ERROR_IO = -1, - - /** Invalid parameter */ - LIBUSB_ERROR_INVALID_PARAM = -2, - - /** Access denied (insufficient permissions) */ - LIBUSB_ERROR_ACCESS = -3, - - /** No such device (it may have been disconnected) */ - LIBUSB_ERROR_NO_DEVICE = -4, - - /** Entity not found */ - LIBUSB_ERROR_NOT_FOUND = -5, - - /** Resource busy */ - LIBUSB_ERROR_BUSY = -6, - - /** Operation timed out */ - LIBUSB_ERROR_TIMEOUT = -7, - - /** Overflow */ - LIBUSB_ERROR_OVERFLOW = -8, - - /** Pipe error */ - LIBUSB_ERROR_PIPE = -9, - - /** System call interrupted (perhaps due to signal) */ - LIBUSB_ERROR_INTERRUPTED = -10, - - /** Insufficient memory */ - LIBUSB_ERROR_NO_MEM = -11, - - /** Operation not supported or unimplemented on this platform */ - LIBUSB_ERROR_NOT_SUPPORTED = -12, - - /* NB! Remember to update libusb_error_name() - when adding new error codes here. */ - - /** Other error */ - LIBUSB_ERROR_OTHER = -99, -}; - -/** \ingroup asyncio - * Transfer status codes */ -enum libusb_transfer_status { - /** Transfer completed without error. Note that this does not indicate - * that the entire amount of requested data was transferred. */ - LIBUSB_TRANSFER_COMPLETED, - - /** Transfer failed */ - LIBUSB_TRANSFER_ERROR, - - /** Transfer timed out */ - LIBUSB_TRANSFER_TIMED_OUT, - - /** Transfer was cancelled */ - LIBUSB_TRANSFER_CANCELLED, - - /** For bulk/interrupt endpoints: halt condition detected (endpoint - * stalled). For control endpoints: control request not supported. */ - LIBUSB_TRANSFER_STALL, - - /** Device was disconnected */ - LIBUSB_TRANSFER_NO_DEVICE, - - /** Device sent more data than requested */ - LIBUSB_TRANSFER_OVERFLOW, - - /* NB! Remember to update libusb_error_name() - when adding new status codes here. */ -}; - -/** \ingroup asyncio - * libusb_transfer.flags values */ -enum libusb_transfer_flags { - /** Report short frames as errors */ - LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0, - - /** Automatically free() transfer buffer during libusb_free_transfer() */ - LIBUSB_TRANSFER_FREE_BUFFER = 1<<1, - - /** Automatically call libusb_free_transfer() after callback returns. - * If this flag is set, it is illegal to call libusb_free_transfer() - * from your transfer callback, as this will result in a double-free - * when this flag is acted upon. */ - LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2, - - /** Terminate transfers that are a multiple of the endpoint's - * wMaxPacketSize with an extra zero length packet. This is useful - * when a device protocol mandates that each logical request is - * terminated by an incomplete packet (i.e. the logical requests are - * not separated by other means). - * - * This flag only affects host-to-device transfers to bulk and interrupt - * endpoints. In other situations, it is ignored. - * - * This flag only affects transfers with a length that is a multiple of - * the endpoint's wMaxPacketSize. On transfers of other lengths, this - * flag has no effect. Therefore, if you are working with a device that - * needs a ZLP whenever the end of the logical request falls on a packet - * boundary, then it is sensible to set this flag on every - * transfer (you do not have to worry about only setting it on transfers - * that end on the boundary). - * - * This flag is currently only supported on Linux. - * On other systems, libusb_submit_transfer() will return - * LIBUSB_ERROR_NOT_SUPPORTED for every transfer where this flag is set. - * - * Available since libusb-1.0.9. - */ - LIBUSB_TRANSFER_ADD_ZERO_PACKET = 1 << 3, -}; - -/** \ingroup asyncio - * Isochronous packet descriptor. */ -struct libusb_iso_packet_descriptor { - /** Length of data to request in this packet */ - unsigned int length; - - /** Amount of data that was actually transferred */ - unsigned int actual_length; - - /** Status code for this packet */ - enum libusb_transfer_status status; -}; - -struct libusb_transfer; - -/** \ingroup asyncio - * Asynchronous transfer callback function type. When submitting asynchronous - * transfers, you pass a pointer to a callback function of this type via the - * \ref libusb_transfer::callback "callback" member of the libusb_transfer - * structure. libusbx will call this function later, when the transfer has - * completed or failed. See \ref asyncio for more information. - * \param transfer The libusb_transfer struct the callback function is being - * notified about. - */ -typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer); - -/** \ingroup asyncio - * The generic USB transfer structure. The user populates this structure and - * then submits it in order to request a transfer. After the transfer has - * completed, the library populates the transfer with the results and passes - * it back to the user. - */ -struct libusb_transfer { - /** Handle of the device that this transfer will be submitted to */ - libusb_device_handle *dev_handle; - - /** A bitwise OR combination of \ref libusb_transfer_flags. */ - uint8_t flags; - - /** Address of the endpoint where this transfer will be sent. */ - unsigned char endpoint; - - /** Type of the endpoint from \ref libusb_transfer_type */ - unsigned char type; - - /** Timeout for this transfer in millseconds. A value of 0 indicates no - * timeout. */ - unsigned int timeout; - - /** The status of the transfer. Read-only, and only for use within - * transfer callback function. - * - * If this is an isochronous transfer, this field may read COMPLETED even - * if there were errors in the frames. Use the - * \ref libusb_iso_packet_descriptor::status "status" field in each packet - * to determine if errors occurred. */ - enum libusb_transfer_status status; - - /** Length of the data buffer */ - int length; - - /** Actual length of data that was transferred. Read-only, and only for - * use within transfer callback function. Not valid for isochronous - * endpoint transfers. */ - int actual_length; - - /** Callback function. This will be invoked when the transfer completes, - * fails, or is cancelled. */ - libusb_transfer_cb_fn callback; - - /** User context data to pass to the callback function. */ - void *user_data; - - /** Data buffer */ - unsigned char *buffer; - - /** Number of isochronous packets. Only used for I/O with isochronous - * endpoints. */ - int num_iso_packets; - - /** Isochronous packet descriptors, for isochronous transfers only. */ - struct libusb_iso_packet_descriptor iso_packet_desc -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif - ; -}; - -/** \ingroup misc - * Capabilities supported by this instance of libusb. Test if the loaded - * library supports a given capability by calling - * \ref libusb_has_capability(). - */ -enum libusb_capability { - /** The libusb_has_capability() API is available. */ - LIBUSB_CAP_HAS_CAPABILITY = 0, -}; - -/** \ingroup lib - * Log message levels. - * - LIBUSB_LOG_LEVEL_NONE (0) : no messages ever printed by the library (default) - * - LIBUSB_LOG_LEVEL_ERROR (1) : error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_WARNING (2) : warning and error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_INFO (3) : informational messages are printed to stdout, warning - * and error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_DEBUG (4) : debug and informational messages are printed to stdout, - * warnings and errors to stderr - */ -enum libusb_log_level { - LIBUSB_LOG_LEVEL_NONE = 0, - LIBUSB_LOG_LEVEL_ERROR, - LIBUSB_LOG_LEVEL_WARNING, - LIBUSB_LOG_LEVEL_INFO, - LIBUSB_LOG_LEVEL_DEBUG, -}; - -int LIBUSB_CALL libusb_init(libusb_context **ctx); -void LIBUSB_CALL libusb_exit(libusb_context *ctx); -void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level); -const struct libusb_version * LIBUSB_CALL libusb_get_version(void); -int LIBUSB_CALL libusb_has_capability(uint32_t capability); -const char * LIBUSB_CALL libusb_error_name(int errcode); - -ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx, - libusb_device ***list); -void LIBUSB_CALL libusb_free_device_list(libusb_device **list, - int unref_devices); -libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev); -void LIBUSB_CALL libusb_unref_device(libusb_device *dev); - -int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev, - int *config); -int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev, - struct libusb_device_descriptor *desc); -int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev, - struct libusb_config_descriptor **config); -int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev, - uint8_t config_index, struct libusb_config_descriptor **config); -int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev, - uint8_t bConfigurationValue, struct libusb_config_descriptor **config); -void LIBUSB_CALL libusb_free_config_descriptor( - struct libusb_config_descriptor *config); -uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev); -uint8_t LIBUSB_CALL libusb_get_port_number(libusb_device *dev); -libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev); -int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_length); -uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev); -int LIBUSB_CALL libusb_get_device_speed(libusb_device *dev); -int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev, - unsigned char endpoint); -int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev, - unsigned char endpoint); - -int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **handle); -void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle); -libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle); - -int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev, - int configuration); -int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev, - int interface_number); -int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev, - int interface_number); - -libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid( - libusb_context *ctx, uint16_t vendor_id, uint16_t product_id); - -int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev, - int interface_number, int alternate_setting); -int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev, - unsigned char endpoint); -int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev); - -int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev, - int interface_number); -int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev, - int interface_number); -int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev, - int interface_number); - -/* async I/O */ - -/** \ingroup asyncio - * Get the data section of a control transfer. This convenience function is here - * to remind you that the data does not start until 8 bytes into the actual - * buffer, as the setup packet comes first. - * - * Calling this function only makes sense from a transfer callback function, - * or situations where you have already allocated a suitably sized buffer at - * transfer->buffer. - * - * \param transfer a transfer - * \returns pointer to the first byte of the data section - */ -static inline unsigned char *libusb_control_transfer_get_data( - struct libusb_transfer *transfer) -{ - return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; -} - -/** \ingroup asyncio - * Get the control setup packet of a control transfer. This convenience - * function is here to remind you that the control setup occupies the first - * 8 bytes of the transfer data buffer. - * - * Calling this function only makes sense from a transfer callback function, - * or situations where you have already allocated a suitably sized buffer at - * transfer->buffer. - * - * \param transfer a transfer - * \returns a casted pointer to the start of the transfer data buffer - */ -static inline struct libusb_control_setup *libusb_control_transfer_get_setup( - struct libusb_transfer *transfer) -{ - return (struct libusb_control_setup *) transfer->buffer; -} - -/** \ingroup asyncio - * Helper function to populate the setup packet (first 8 bytes of the data - * buffer) for a control transfer. The wIndex, wValue and wLength values should - * be given in host-endian byte order. - * - * \param buffer buffer to output the setup packet into - * \param bmRequestType see the - * \ref libusb_control_setup::bmRequestType "bmRequestType" field of - * \ref libusb_control_setup - * \param bRequest see the - * \ref libusb_control_setup::bRequest "bRequest" field of - * \ref libusb_control_setup - * \param wValue see the - * \ref libusb_control_setup::wValue "wValue" field of - * \ref libusb_control_setup - * \param wIndex see the - * \ref libusb_control_setup::wIndex "wIndex" field of - * \ref libusb_control_setup - * \param wLength see the - * \ref libusb_control_setup::wLength "wLength" field of - * \ref libusb_control_setup - */ -static inline void libusb_fill_control_setup(unsigned char *buffer, - uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, - uint16_t wLength) -{ - struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer; - setup->bmRequestType = bmRequestType; - setup->bRequest = bRequest; - setup->wValue = libusb_cpu_to_le16(wValue); - setup->wIndex = libusb_cpu_to_le16(wIndex); - setup->wLength = libusb_cpu_to_le16(wLength); -} - -struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets); -int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer); -int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer); -void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer); - -/** \ingroup asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for a control transfer. - * - * If you pass a transfer buffer to this function, the first 8 bytes will - * be interpreted as a control setup packet, and the wLength field will be - * used to automatically populate the \ref libusb_transfer::length "length" - * field of the transfer. Therefore the recommended approach is: - * -# Allocate a suitably sized data buffer (including space for control setup) - * -# Call libusb_fill_control_setup() - * -# If this is a host-to-device transfer with a data stage, put the data - * in place after the setup packet - * -# Call this function - * -# Call libusb_submit_transfer() - * - * It is also legal to pass a NULL buffer to this function, in which case this - * function will not attempt to populate the length field. Remember that you - * must then populate the buffer and length fields later. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param buffer data buffer. If provided, this function will interpret the - * first 8 bytes as a setup packet and infer the transfer length from that. - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_control_transfer( - struct libusb_transfer *transfer, libusb_device_handle *dev_handle, - unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data, - unsigned int timeout) -{ - struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer; - transfer->dev_handle = dev_handle; - transfer->endpoint = 0; - transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL; - transfer->timeout = timeout; - transfer->buffer = buffer; - if (setup) - transfer->length = LIBUSB_CONTROL_SETUP_SIZE - + libusb_le16_to_cpu(setup->wLength); - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for a bulk transfer. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param buffer data buffer - * \param length length of data buffer - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer, - libusb_device_handle *dev_handle, unsigned char endpoint, - unsigned char *buffer, int length, libusb_transfer_cb_fn callback, - void *user_data, unsigned int timeout) -{ - transfer->dev_handle = dev_handle; - transfer->endpoint = endpoint; - transfer->type = LIBUSB_TRANSFER_TYPE_BULK; - transfer->timeout = timeout; - transfer->buffer = buffer; - transfer->length = length; - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for an interrupt transfer. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param buffer data buffer - * \param length length of data buffer - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_interrupt_transfer( - struct libusb_transfer *transfer, libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *buffer, int length, - libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) -{ - transfer->dev_handle = dev_handle; - transfer->endpoint = endpoint; - transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT; - transfer->timeout = timeout; - transfer->buffer = buffer; - transfer->length = length; - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for an isochronous transfer. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param buffer data buffer - * \param length length of data buffer - * \param num_iso_packets the number of isochronous packets - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer, - libusb_device_handle *dev_handle, unsigned char endpoint, - unsigned char *buffer, int length, int num_iso_packets, - libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) -{ - transfer->dev_handle = dev_handle; - transfer->endpoint = endpoint; - transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS; - transfer->timeout = timeout; - transfer->buffer = buffer; - transfer->length = length; - transfer->num_iso_packets = num_iso_packets; - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup asyncio - * Convenience function to set the length of all packets in an isochronous - * transfer, based on the num_iso_packets field in the transfer structure. - * - * \param transfer a transfer - * \param length the length to set in each isochronous packet descriptor - * \see libusb_get_max_packet_size() - */ -static inline void libusb_set_iso_packet_lengths( - struct libusb_transfer *transfer, unsigned int length) -{ - int i; - for (i = 0; i < transfer->num_iso_packets; i++) - transfer->iso_packet_desc[i].length = length; -} - -/** \ingroup asyncio - * Convenience function to locate the position of an isochronous packet - * within the buffer of an isochronous transfer. - * - * This is a thorough function which loops through all preceding packets, - * accumulating their lengths to find the position of the specified packet. - * Typically you will assign equal lengths to each packet in the transfer, - * and hence the above method is sub-optimal. You may wish to use - * libusb_get_iso_packet_buffer_simple() instead. - * - * \param transfer a transfer - * \param packet the packet to return the address of - * \returns the base address of the packet buffer inside the transfer buffer, - * or NULL if the packet does not exist. - * \see libusb_get_iso_packet_buffer_simple() - */ -static inline unsigned char *libusb_get_iso_packet_buffer( - struct libusb_transfer *transfer, unsigned int packet) -{ - int i; - size_t offset = 0; - int _packet; - - /* oops..slight bug in the API. packet is an unsigned int, but we use - * signed integers almost everywhere else. range-check and convert to - * signed to avoid compiler warnings. FIXME for libusb-2. */ - if (packet > INT_MAX) - return NULL; - _packet = packet; - - if (_packet >= transfer->num_iso_packets) - return NULL; - - for (i = 0; i < _packet; i++) - offset += transfer->iso_packet_desc[i].length; - - return transfer->buffer + offset; -} - -/** \ingroup asyncio - * Convenience function to locate the position of an isochronous packet - * within the buffer of an isochronous transfer, for transfers where each - * packet is of identical size. - * - * This function relies on the assumption that every packet within the transfer - * is of identical size to the first packet. Calculating the location of - * the packet buffer is then just a simple calculation: - * buffer + (packet_size * packet) - * - * Do not use this function on transfers other than those that have identical - * packet lengths for each packet. - * - * \param transfer a transfer - * \param packet the packet to return the address of - * \returns the base address of the packet buffer inside the transfer buffer, - * or NULL if the packet does not exist. - * \see libusb_get_iso_packet_buffer() - */ -static inline unsigned char *libusb_get_iso_packet_buffer_simple( - struct libusb_transfer *transfer, unsigned int packet) -{ - int _packet; - - /* oops..slight bug in the API. packet is an unsigned int, but we use - * signed integers almost everywhere else. range-check and convert to - * signed to avoid compiler warnings. FIXME for libusb-2. */ - if (packet > INT_MAX) - return NULL; - _packet = packet; - - if (_packet >= transfer->num_iso_packets) - return NULL; - - return transfer->buffer + (transfer->iso_packet_desc[0].length * _packet); -} - -/* sync I/O */ - -int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle, - uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, - unsigned char *data, uint16_t wLength, unsigned int timeout); - -int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *data, int length, - int *actual_length, unsigned int timeout); - -int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *data, int length, - int *actual_length, unsigned int timeout); - -/** \ingroup desc - * Retrieve a descriptor from the default control pipe. - * This is a convenience function which formulates the appropriate control - * message to retrieve the descriptor. - * - * \param dev a device handle - * \param desc_type the descriptor type, see \ref libusb_descriptor_type - * \param desc_index the index of the descriptor to retrieve - * \param data output buffer for descriptor - * \param length size of data buffer - * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure - */ -static inline int libusb_get_descriptor(libusb_device_handle *dev, - uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length) -{ - return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN, - LIBUSB_REQUEST_GET_DESCRIPTOR, (desc_type << 8) | desc_index, 0, data, - (uint16_t) length, 1000); -} - -/** \ingroup desc - * Retrieve a descriptor from a device. - * This is a convenience function which formulates the appropriate control - * message to retrieve the descriptor. The string returned is Unicode, as - * detailed in the USB specifications. - * - * \param dev a device handle - * \param desc_index the index of the descriptor to retrieve - * \param langid the language ID for the string descriptor - * \param data output buffer for descriptor - * \param length size of data buffer - * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure - * \see libusb_get_string_descriptor_ascii() - */ -static inline int libusb_get_string_descriptor(libusb_device_handle *dev, - uint8_t desc_index, uint16_t langid, unsigned char *data, int length) -{ - return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN, - LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t)((LIBUSB_DT_STRING << 8) | desc_index), - langid, data, (uint16_t) length, 1000); -} - -int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev, - uint8_t desc_index, unsigned char *data, int length); - -/* polling and timeouts */ - -int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx); -void LIBUSB_CALL libusb_lock_events(libusb_context *ctx); -void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx); -int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx); -int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx); -void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx); -void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx); -int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv); - -int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx, - struct timeval *tv); -int LIBUSB_CALL libusb_handle_events_timeout_completed(libusb_context *ctx, - struct timeval *tv, int *completed); -int LIBUSB_CALL libusb_handle_events(libusb_context *ctx); -int LIBUSB_CALL libusb_handle_events_completed(libusb_context *ctx, int *completed); -int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx, - struct timeval *tv); -int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx); -int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx, - struct timeval *tv); - -/** \ingroup poll - * File descriptor for polling - */ -struct libusb_pollfd { - /** Numeric file descriptor */ - int fd; - - /** Event flags to poll for from . POLLIN indicates that you - * should monitor this file descriptor for becoming ready to read from, - * and POLLOUT indicates that you should monitor this file descriptor for - * nonblocking write readiness. */ - short events; -}; - -/** \ingroup poll - * Callback function, invoked when a new file descriptor should be added - * to the set of file descriptors monitored for events. - * \param fd the new file descriptor - * \param events events to monitor for, see \ref libusb_pollfd for a - * description - * \param user_data User data pointer specified in - * libusb_set_pollfd_notifiers() call - * \see libusb_set_pollfd_notifiers() - */ -typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events, - void *user_data); - -/** \ingroup poll - * Callback function, invoked when a file descriptor should be removed from - * the set of file descriptors being monitored for events. After returning - * from this callback, do not use that file descriptor again. - * \param fd the file descriptor to stop monitoring - * \param user_data User data pointer specified in - * libusb_set_pollfd_notifiers() call - * \see libusb_set_pollfd_notifiers() - */ -typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data); - -const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds( - libusb_context *ctx); -void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx, - libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb, - void *user_data); - -#ifdef __cplusplus -} -#endif - -#endif +/* + * Public libusbx header file + * Copyright © 2001 Johannes Erdfelt + * Copyright © 2007-2008 Daniel Drake + * Copyright © 2012 Pete Batard + * For more information, please visit: http://libusbx.org + * + * 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 + */ + +#ifndef LIBUSB_H +#define LIBUSB_H + +#ifdef _MSC_VER +/* on MS environments, the inline keyword is available in C++ only */ +#if !defined(__cplusplus) +#define inline __inline +#endif +/* ssize_t is also not available (copy/paste from MinGW) */ +#ifndef _SSIZE_T_DEFINED +#define _SSIZE_T_DEFINED +#undef ssize_t +#ifdef _WIN64 + typedef __int64 ssize_t; +#else + typedef int ssize_t; +#endif /* _WIN64 */ +#endif /* _SSIZE_T_DEFINED */ +#endif /* _MSC_VER */ + +/* stdint.h is also not usually available on MS */ +#if defined(_MSC_VER) && (_MSC_VER < 1600) && (!defined(_STDINT)) && (!defined(_STDINT_H)) +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; +#else +#include +#endif + +#include +#include +#include + +#if defined(__linux) || defined(__APPLE__) || defined(__CYGWIN__) +#include +#endif + +/* 'interface' might be defined as a macro on Windows, so we need to + * undefine it so as not to break the current libusbx API, because + * libusb_config_descriptor has an 'interface' member + * As this can be problematic if you include windows.h after libusb.h + * in your sources, we force windows.h to be included first. */ +#if defined(_WIN32) || defined(__CYGWIN__) +#include +#if defined(interface) +#undef interface +#endif +#endif + +/** \def LIBUSB_CALL + * \ingroup misc + * libusbx's Windows calling convention. + * + * Under Windows, the selection of available compilers and configurations + * means that, unlike other platforms, there is not one true calling + * convention (calling convention: the manner in which parameters are + * passed to funcions in the generated assembly code). + * + * Matching the Windows API itself, libusbx uses the WINAPI convention (which + * translates to the stdcall convention) and guarantees that the + * library is compiled in this way. The public header file also includes + * appropriate annotations so that your own software will use the right + * convention, even if another convention is being used by default within + * your codebase. + * + * The one consideration that you must apply in your software is to mark + * all functions which you use as libusbx callbacks with this LIBUSB_CALL + * annotation, so that they too get compiled for the correct calling + * convention. + * + * On non-Windows operating systems, this macro is defined as nothing. This + * means that you can apply it to your code without worrying about + * cross-platform compatibility. + */ +/* LIBUSB_CALL must be defined on both definition and declaration of libusbx + * functions. You'd think that declaration would be enough, but cygwin will + * complain about conflicting types unless both are marked this way. + * The placement of this macro is important too; it must appear after the + * return type, before the function name. See internal documentation for + * API_EXPORTED. + */ +#if defined(_WIN32) || defined(__CYGWIN__) +#define LIBUSB_CALL WINAPI +#else +#define LIBUSB_CALL +#endif + +/** \def LIBUSBX_API_VERSION + * \ingroup misc + * libusbx's API version. + * + * Since version 1.0.13, to help with feature detection, libusbx defines + * a LIBUSBX_API_VERSION macro that gets increased every time there is a + * significant change to the API, such as the introduction of a new call, + * the definition of a new macro/enum member, or any other element that + * libusbx applications may want to detect at compilation time. + * + * The macro is typically used in an application as follows: + * \code + * #if defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01001234) + * // Use one of the newer features from the libusbx API + * #endif + * \endcode + * + * Another feature of LIBUSBX_API_VERSION is that it can be used to detect + * whether you are compiling against the libusb or the libusbx library. + * + * Internally, LIBUSBX_API_VERSION is defined as follows: + * (libusbx major << 24) | (libusbx minor << 16) | (16 bit incremental) + */ +#define LIBUSBX_API_VERSION 0x010000FF + +#ifdef __cplusplus +extern "C" { +#endif + +/** \def libusb_cpu_to_le16 + * \ingroup misc + * Convert a 16-bit value from host-endian to little-endian format. On + * little endian systems, this function does nothing. On big endian systems, + * the bytes are swapped. + * \param x the host-endian value to convert + * \returns the value in little-endian byte order + */ +static inline uint16_t libusb_cpu_to_le16(const uint16_t x) +{ + union { + uint8_t b8[2]; + uint16_t b16; + } _tmp; + _tmp.b8[1] = x >> 8; + _tmp.b8[0] = x & 0xff; + return _tmp.b16; +} + +/** \def libusb_le16_to_cpu + * \ingroup misc + * Convert a 16-bit value from little-endian to host-endian format. On + * little endian systems, this function does nothing. On big endian systems, + * the bytes are swapped. + * \param x the little-endian value to convert + * \returns the value in host-endian byte order + */ +#define libusb_le16_to_cpu libusb_cpu_to_le16 + +/* standard USB stuff */ + +/** \ingroup desc + * Device and/or Interface Class codes */ +enum libusb_class_code { + /** In the context of a \ref libusb_device_descriptor "device descriptor", + * this bDeviceClass value indicates that each interface specifies its + * own class information and all interfaces operate independently. + */ + LIBUSB_CLASS_PER_INTERFACE = 0, + + /** Audio class */ + LIBUSB_CLASS_AUDIO = 1, + + /** Communications class */ + LIBUSB_CLASS_COMM = 2, + + /** Human Interface Device class */ + LIBUSB_CLASS_HID = 3, + + /** Physical */ + LIBUSB_CLASS_PHYSICAL = 5, + + /** Printer class */ + LIBUSB_CLASS_PRINTER = 7, + + /** Image class */ + LIBUSB_CLASS_PTP = 6, /* legacy name from libusb-0.1 usb.h */ + LIBUSB_CLASS_IMAGE = 6, + + /** Mass storage class */ + LIBUSB_CLASS_MASS_STORAGE = 8, + + /** Hub class */ + LIBUSB_CLASS_HUB = 9, + + /** Data class */ + LIBUSB_CLASS_DATA = 10, + + /** Smart Card */ + LIBUSB_CLASS_SMART_CARD = 0x0b, + + /** Content Security */ + LIBUSB_CLASS_CONTENT_SECURITY = 0x0d, + + /** Video */ + LIBUSB_CLASS_VIDEO = 0x0e, + + /** Personal Healthcare */ + LIBUSB_CLASS_PERSONAL_HEALTHCARE = 0x0f, + + /** Diagnostic Device */ + LIBUSB_CLASS_DIAGNOSTIC_DEVICE = 0xdc, + + /** Wireless class */ + LIBUSB_CLASS_WIRELESS = 0xe0, + + /** Application class */ + LIBUSB_CLASS_APPLICATION = 0xfe, + + /** Class is vendor-specific */ + LIBUSB_CLASS_VENDOR_SPEC = 0xff +}; + +/** \ingroup desc + * Descriptor types as defined by the USB specification. */ +enum libusb_descriptor_type { + /** Device descriptor. See libusb_device_descriptor. */ + LIBUSB_DT_DEVICE = 0x01, + + /** Configuration descriptor. See libusb_config_descriptor. */ + LIBUSB_DT_CONFIG = 0x02, + + /** String descriptor */ + LIBUSB_DT_STRING = 0x03, + + /** Interface descriptor. See libusb_interface_descriptor. */ + LIBUSB_DT_INTERFACE = 0x04, + + /** Endpoint descriptor. See libusb_endpoint_descriptor. */ + LIBUSB_DT_ENDPOINT = 0x05, + + /** HID descriptor */ + LIBUSB_DT_HID = 0x21, + + /** HID report descriptor */ + LIBUSB_DT_REPORT = 0x22, + + /** Physical descriptor */ + LIBUSB_DT_PHYSICAL = 0x23, + + /** Hub descriptor */ + LIBUSB_DT_HUB = 0x29, + + /** SuperSpeed Hub descriptor */ + LIBUSB_DT_SUPERSPEED_HUB = 0x2A, +}; + +/* Descriptor sizes per descriptor type */ +#define LIBUSB_DT_DEVICE_SIZE 18 +#define LIBUSB_DT_CONFIG_SIZE 9 +#define LIBUSB_DT_INTERFACE_SIZE 9 +#define LIBUSB_DT_ENDPOINT_SIZE 7 +#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */ +#define LIBUSB_DT_HUB_NONVAR_SIZE 7 + +#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */ +#define LIBUSB_ENDPOINT_DIR_MASK 0x80 + +/** \ingroup desc + * Endpoint direction. Values for bit 7 of the + * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme. + */ +enum libusb_endpoint_direction { + /** In: device-to-host */ + LIBUSB_ENDPOINT_IN = 0x80, + + /** Out: host-to-device */ + LIBUSB_ENDPOINT_OUT = 0x00 +}; + +#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */ + +/** \ingroup desc + * Endpoint transfer type. Values for bits 0:1 of the + * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field. + */ +enum libusb_transfer_type { + /** Control endpoint */ + LIBUSB_TRANSFER_TYPE_CONTROL = 0, + + /** Isochronous endpoint */ + LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1, + + /** Bulk endpoint */ + LIBUSB_TRANSFER_TYPE_BULK = 2, + + /** Interrupt endpoint */ + LIBUSB_TRANSFER_TYPE_INTERRUPT = 3 +}; + +/** \ingroup misc + * Standard requests, as defined in table 9-5 of the USB 3.0 specifications */ +enum libusb_standard_request { + /** Request status of the specific recipient */ + LIBUSB_REQUEST_GET_STATUS = 0x00, + + /** Clear or disable a specific feature */ + LIBUSB_REQUEST_CLEAR_FEATURE = 0x01, + + /* 0x02 is reserved */ + + /** Set or enable a specific feature */ + LIBUSB_REQUEST_SET_FEATURE = 0x03, + + /* 0x04 is reserved */ + + /** Set device address for all future accesses */ + LIBUSB_REQUEST_SET_ADDRESS = 0x05, + + /** Get the specified descriptor */ + LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06, + + /** Used to update existing descriptors or add new descriptors */ + LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07, + + /** Get the current device configuration value */ + LIBUSB_REQUEST_GET_CONFIGURATION = 0x08, + + /** Set device configuration */ + LIBUSB_REQUEST_SET_CONFIGURATION = 0x09, + + /** Return the selected alternate setting for the specified interface */ + LIBUSB_REQUEST_GET_INTERFACE = 0x0A, + + /** Select an alternate interface for the specified interface */ + LIBUSB_REQUEST_SET_INTERFACE = 0x0B, + + /** Set then report an endpoint's synchronization frame */ + LIBUSB_REQUEST_SYNCH_FRAME = 0x0C, + + /** Sets both the U1 and U2 Exit Latency */ + LIBUSB_REQUEST_SET_SEL = 0x30, + + /** Delay from the time a host transmits a packet to the time it is + * received by the device. */ + LIBUSB_SET_ISOCH_DELAY = 0x31, +}; + +/** \ingroup misc + * Request type bits of the + * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control + * transfers. */ +enum libusb_request_type { + /** Standard */ + LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5), + + /** Class */ + LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5), + + /** Vendor */ + LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5), + + /** Reserved */ + LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5) +}; + +/** \ingroup misc + * Recipient bits of the + * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control + * transfers. Values 4 through 31 are reserved. */ +enum libusb_request_recipient { + /** Device */ + LIBUSB_RECIPIENT_DEVICE = 0x00, + + /** Interface */ + LIBUSB_RECIPIENT_INTERFACE = 0x01, + + /** Endpoint */ + LIBUSB_RECIPIENT_ENDPOINT = 0x02, + + /** Other */ + LIBUSB_RECIPIENT_OTHER = 0x03, +}; + +#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C + +/** \ingroup desc + * Synchronization type for isochronous endpoints. Values for bits 2:3 of the + * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in + * libusb_endpoint_descriptor. + */ +enum libusb_iso_sync_type { + /** No synchronization */ + LIBUSB_ISO_SYNC_TYPE_NONE = 0, + + /** Asynchronous */ + LIBUSB_ISO_SYNC_TYPE_ASYNC = 1, + + /** Adaptive */ + LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2, + + /** Synchronous */ + LIBUSB_ISO_SYNC_TYPE_SYNC = 3 +}; + +#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30 + +/** \ingroup desc + * Usage type for isochronous endpoints. Values for bits 4:5 of the + * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in + * libusb_endpoint_descriptor. + */ +enum libusb_iso_usage_type { + /** Data endpoint */ + LIBUSB_ISO_USAGE_TYPE_DATA = 0, + + /** Feedback endpoint */ + LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1, + + /** Implicit feedback Data endpoint */ + LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2, +}; + +/** \ingroup desc + * A structure representing the standard USB device descriptor. This + * descriptor is documented in section 9.6.1 of the USB 3.0 specification. + * All multiple-byte fields are represented in host-endian format. + */ +struct libusb_device_descriptor { + /** Size of this descriptor (in bytes) */ + uint8_t bLength; + + /** Descriptor type. Will have value + * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this + * context. */ + uint8_t bDescriptorType; + + /** USB specification release number in binary-coded decimal. A value of + * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */ + uint16_t bcdUSB; + + /** USB-IF class code for the device. See \ref libusb_class_code. */ + uint8_t bDeviceClass; + + /** USB-IF subclass code for the device, qualified by the bDeviceClass + * value */ + uint8_t bDeviceSubClass; + + /** USB-IF protocol code for the device, qualified by the bDeviceClass and + * bDeviceSubClass values */ + uint8_t bDeviceProtocol; + + /** Maximum packet size for endpoint 0 */ + uint8_t bMaxPacketSize0; + + /** USB-IF vendor ID */ + uint16_t idVendor; + + /** USB-IF product ID */ + uint16_t idProduct; + + /** Device release number in binary-coded decimal */ + uint16_t bcdDevice; + + /** Index of string descriptor describing manufacturer */ + uint8_t iManufacturer; + + /** Index of string descriptor describing product */ + uint8_t iProduct; + + /** Index of string descriptor containing device serial number */ + uint8_t iSerialNumber; + + /** Number of possible configurations */ + uint8_t bNumConfigurations; +}; + +/** \ingroup desc + * A structure representing the standard USB endpoint descriptor. This + * descriptor is documented in section 9.6.6 of the USB 3.0 specification. + * All multiple-byte fields are represented in host-endian format. + */ +struct libusb_endpoint_descriptor { + /** Size of this descriptor (in bytes) */ + uint8_t bLength; + + /** Descriptor type. Will have value + * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in + * this context. */ + uint8_t bDescriptorType; + + /** The address of the endpoint described by this descriptor. Bits 0:3 are + * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction, + * see \ref libusb_endpoint_direction. + */ + uint8_t bEndpointAddress; + + /** Attributes which apply to the endpoint when it is configured using + * the bConfigurationValue. Bits 0:1 determine the transfer type and + * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for + * isochronous endpoints and correspond to \ref libusb_iso_sync_type. + * Bits 4:5 are also only used for isochronous endpoints and correspond to + * \ref libusb_iso_usage_type. Bits 6:7 are reserved. + */ + uint8_t bmAttributes; + + /** Maximum packet size this endpoint is capable of sending/receiving. */ + uint16_t wMaxPacketSize; + + /** Interval for polling endpoint for data transfers. */ + uint8_t bInterval; + + /** For audio devices only: the rate at which synchronization feedback + * is provided. */ + uint8_t bRefresh; + + /** For audio devices only: the address if the synch endpoint */ + uint8_t bSynchAddress; + + /** Extra descriptors. If libusbx encounters unknown endpoint descriptors, + * it will store them here, should you wish to parse them. */ + const unsigned char *extra; + + /** Length of the extra descriptors, in bytes. */ + int extra_length; +}; + +/** \ingroup desc + * A structure representing the standard USB interface descriptor. This + * descriptor is documented in section 9.6.5 of the USB 3.0 specification. + * All multiple-byte fields are represented in host-endian format. + */ +struct libusb_interface_descriptor { + /** Size of this descriptor (in bytes) */ + uint8_t bLength; + + /** Descriptor type. Will have value + * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE + * in this context. */ + uint8_t bDescriptorType; + + /** Number of this interface */ + uint8_t bInterfaceNumber; + + /** Value used to select this alternate setting for this interface */ + uint8_t bAlternateSetting; + + /** Number of endpoints used by this interface (excluding the control + * endpoint). */ + uint8_t bNumEndpoints; + + /** USB-IF class code for this interface. See \ref libusb_class_code. */ + uint8_t bInterfaceClass; + + /** USB-IF subclass code for this interface, qualified by the + * bInterfaceClass value */ + uint8_t bInterfaceSubClass; + + /** USB-IF protocol code for this interface, qualified by the + * bInterfaceClass and bInterfaceSubClass values */ + uint8_t bInterfaceProtocol; + + /** Index of string descriptor describing this interface */ + uint8_t iInterface; + + /** Array of endpoint descriptors. This length of this array is determined + * by the bNumEndpoints field. */ + const struct libusb_endpoint_descriptor *endpoint; + + /** Extra descriptors. If libusbx encounters unknown interface descriptors, + * it will store them here, should you wish to parse them. */ + const unsigned char *extra; + + /** Length of the extra descriptors, in bytes. */ + int extra_length; +}; + +/** \ingroup desc + * A collection of alternate settings for a particular USB interface. + */ +struct libusb_interface { + /** Array of interface descriptors. The length of this array is determined + * by the num_altsetting field. */ + const struct libusb_interface_descriptor *altsetting; + + /** The number of alternate settings that belong to this interface */ + int num_altsetting; +}; + +/** \ingroup desc + * A structure representing the standard USB configuration descriptor. This + * descriptor is documented in section 9.6.3 of the USB 3.0 specification. + * All multiple-byte fields are represented in host-endian format. + */ +struct libusb_config_descriptor { + /** Size of this descriptor (in bytes) */ + uint8_t bLength; + + /** Descriptor type. Will have value + * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG + * in this context. */ + uint8_t bDescriptorType; + + /** Total length of data returned for this configuration */ + uint16_t wTotalLength; + + /** Number of interfaces supported by this configuration */ + uint8_t bNumInterfaces; + + /** Identifier value for this configuration */ + uint8_t bConfigurationValue; + + /** Index of string descriptor describing this configuration */ + uint8_t iConfiguration; + + /** Configuration characteristics */ + uint8_t bmAttributes; + + /** Maximum power consumption of the USB device from this bus in this + * configuration when the device is fully opreation. Expressed in units + * of 2 mA. */ + uint8_t MaxPower; + + /** Array of interfaces supported by this configuration. The length of + * this array is determined by the bNumInterfaces field. */ + const struct libusb_interface *interface; + + /** Extra descriptors. If libusbx encounters unknown configuration + * descriptors, it will store them here, should you wish to parse them. */ + const unsigned char *extra; + + /** Length of the extra descriptors, in bytes. */ + int extra_length; +}; + +/** \ingroup asyncio + * Setup packet for control transfers. */ +struct libusb_control_setup { + /** Request type. Bits 0:4 determine recipient, see + * \ref libusb_request_recipient. Bits 5:6 determine type, see + * \ref libusb_request_type. Bit 7 determines data transfer direction, see + * \ref libusb_endpoint_direction. + */ + uint8_t bmRequestType; + + /** Request. If the type bits of bmRequestType are equal to + * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD + * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to + * \ref libusb_standard_request. For other cases, use of this field is + * application-specific. */ + uint8_t bRequest; + + /** Value. Varies according to request */ + uint16_t wValue; + + /** Index. Varies according to request, typically used to pass an index + * or offset */ + uint16_t wIndex; + + /** Number of bytes to transfer */ + uint16_t wLength; +}; + +#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup)) + +/* libusbx */ + +struct libusb_context; +struct libusb_device; +struct libusb_device_handle; + +/** \ingroup lib + * Structure providing the version of the libusbx runtime + */ +struct libusb_version { + /** Library major version. */ + const uint16_t major; + + /** Library minor version. */ + const uint16_t minor; + + /** Library micro version. */ + const uint16_t micro; + + /** Library nano version. */ + const uint16_t nano; + + /** Library release candidate suffix string, e.g. "-rc4". */ + const char *rc; + + /** For ABI compatibility only. */ + const char* describe; +}; + +/** \ingroup lib + * Structure representing a libusbx session. The concept of individual libusbx + * sessions allows for your program to use two libraries (or dynamically + * load two modules) which both independently use libusb. This will prevent + * interference between the individual libusbx users - for example + * libusb_set_debug() will not affect the other user of the library, and + * libusb_exit() will not destroy resources that the other user is still + * using. + * + * Sessions are created by libusb_init() and destroyed through libusb_exit(). + * If your application is guaranteed to only ever include a single libusbx + * user (i.e. you), you do not have to worry about contexts: pass NULL in + * every function call where a context is required. The default context + * will be used. + * + * For more information, see \ref contexts. + */ +typedef struct libusb_context libusb_context; + +/** \ingroup dev + * Structure representing a USB device detected on the system. This is an + * opaque type for which you are only ever provided with a pointer, usually + * originating from libusb_get_device_list(). + * + * Certain operations can be performed on a device, but in order to do any + * I/O you will have to first obtain a device handle using libusb_open(). + * + * Devices are reference counted with libusb_device_ref() and + * libusb_device_unref(), and are freed when the reference count reaches 0. + * New devices presented by libusb_get_device_list() have a reference count of + * 1, and libusb_free_device_list() can optionally decrease the reference count + * on all devices in the list. libusb_open() adds another reference which is + * later destroyed by libusb_close(). + */ +typedef struct libusb_device libusb_device; + + +/** \ingroup dev + * Structure representing a handle on a USB device. This is an opaque type for + * which you are only ever provided with a pointer, usually originating from + * libusb_open(). + * + * A device handle is used to perform I/O and other operations. When finished + * with a device handle, you should call libusb_close(). + */ +typedef struct libusb_device_handle libusb_device_handle; + +/** \ingroup dev + * Speed codes. Indicates the speed at which the device is operating. + */ +enum libusb_speed { + /** The OS doesn't report or know the device speed. */ + LIBUSB_SPEED_UNKNOWN = 0, + + /** The device is operating at low speed (1.5MBit/s). */ + LIBUSB_SPEED_LOW = 1, + + /** The device is operating at full speed (12MBit/s). */ + LIBUSB_SPEED_FULL = 2, + + /** The device is operating at high speed (480MBit/s). */ + LIBUSB_SPEED_HIGH = 3, + + /** The device is operating at super speed (5000MBit/s). */ + LIBUSB_SPEED_SUPER = 4, +}; + +/** \ingroup misc + * Error codes. Most libusbx functions return 0 on success or one of these + * codes on failure. + * You can call \ref libusb_error_name() to retrieve a string representation + * of an error code. + */ +enum libusb_error { + /** Success (no error) */ + LIBUSB_SUCCESS = 0, + + /** Input/output error */ + LIBUSB_ERROR_IO = -1, + + /** Invalid parameter */ + LIBUSB_ERROR_INVALID_PARAM = -2, + + /** Access denied (insufficient permissions) */ + LIBUSB_ERROR_ACCESS = -3, + + /** No such device (it may have been disconnected) */ + LIBUSB_ERROR_NO_DEVICE = -4, + + /** Entity not found */ + LIBUSB_ERROR_NOT_FOUND = -5, + + /** Resource busy */ + LIBUSB_ERROR_BUSY = -6, + + /** Operation timed out */ + LIBUSB_ERROR_TIMEOUT = -7, + + /** Overflow */ + LIBUSB_ERROR_OVERFLOW = -8, + + /** Pipe error */ + LIBUSB_ERROR_PIPE = -9, + + /** System call interrupted (perhaps due to signal) */ + LIBUSB_ERROR_INTERRUPTED = -10, + + /** Insufficient memory */ + LIBUSB_ERROR_NO_MEM = -11, + + /** Operation not supported or unimplemented on this platform */ + LIBUSB_ERROR_NOT_SUPPORTED = -12, + + /* NB! Remember to update libusb_error_name() + when adding new error codes here. */ + + /** Other error */ + LIBUSB_ERROR_OTHER = -99, +}; + +/** \ingroup asyncio + * Transfer status codes */ +enum libusb_transfer_status { + /** Transfer completed without error. Note that this does not indicate + * that the entire amount of requested data was transferred. */ + LIBUSB_TRANSFER_COMPLETED, + + /** Transfer failed */ + LIBUSB_TRANSFER_ERROR, + + /** Transfer timed out */ + LIBUSB_TRANSFER_TIMED_OUT, + + /** Transfer was cancelled */ + LIBUSB_TRANSFER_CANCELLED, + + /** For bulk/interrupt endpoints: halt condition detected (endpoint + * stalled). For control endpoints: control request not supported. */ + LIBUSB_TRANSFER_STALL, + + /** Device was disconnected */ + LIBUSB_TRANSFER_NO_DEVICE, + + /** Device sent more data than requested */ + LIBUSB_TRANSFER_OVERFLOW, + + /* NB! Remember to update libusb_error_name() + when adding new status codes here. */ +}; + +/** \ingroup asyncio + * libusb_transfer.flags values */ +enum libusb_transfer_flags { + /** Report short frames as errors */ + LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0, + + /** Automatically free() transfer buffer during libusb_free_transfer() */ + LIBUSB_TRANSFER_FREE_BUFFER = 1<<1, + + /** Automatically call libusb_free_transfer() after callback returns. + * If this flag is set, it is illegal to call libusb_free_transfer() + * from your transfer callback, as this will result in a double-free + * when this flag is acted upon. */ + LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2, + + /** Terminate transfers that are a multiple of the endpoint's + * wMaxPacketSize with an extra zero length packet. This is useful + * when a device protocol mandates that each logical request is + * terminated by an incomplete packet (i.e. the logical requests are + * not separated by other means). + * + * This flag only affects host-to-device transfers to bulk and interrupt + * endpoints. In other situations, it is ignored. + * + * This flag only affects transfers with a length that is a multiple of + * the endpoint's wMaxPacketSize. On transfers of other lengths, this + * flag has no effect. Therefore, if you are working with a device that + * needs a ZLP whenever the end of the logical request falls on a packet + * boundary, then it is sensible to set this flag on every + * transfer (you do not have to worry about only setting it on transfers + * that end on the boundary). + * + * This flag is currently only supported on Linux. + * On other systems, libusb_submit_transfer() will return + * LIBUSB_ERROR_NOT_SUPPORTED for every transfer where this flag is set. + * + * Available since libusb-1.0.9. + */ + LIBUSB_TRANSFER_ADD_ZERO_PACKET = 1 << 3, +}; + +/** \ingroup asyncio + * Isochronous packet descriptor. */ +struct libusb_iso_packet_descriptor { + /** Length of data to request in this packet */ + unsigned int length; + + /** Amount of data that was actually transferred */ + unsigned int actual_length; + + /** Status code for this packet */ + enum libusb_transfer_status status; +}; + +struct libusb_transfer; + +/** \ingroup asyncio + * Asynchronous transfer callback function type. When submitting asynchronous + * transfers, you pass a pointer to a callback function of this type via the + * \ref libusb_transfer::callback "callback" member of the libusb_transfer + * structure. libusbx will call this function later, when the transfer has + * completed or failed. See \ref asyncio for more information. + * \param transfer The libusb_transfer struct the callback function is being + * notified about. + */ +typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer); + +/** \ingroup asyncio + * The generic USB transfer structure. The user populates this structure and + * then submits it in order to request a transfer. After the transfer has + * completed, the library populates the transfer with the results and passes + * it back to the user. + */ +struct libusb_transfer { + /** Handle of the device that this transfer will be submitted to */ + libusb_device_handle *dev_handle; + + /** A bitwise OR combination of \ref libusb_transfer_flags. */ + uint8_t flags; + + /** Address of the endpoint where this transfer will be sent. */ + unsigned char endpoint; + + /** Type of the endpoint from \ref libusb_transfer_type */ + unsigned char type; + + /** Timeout for this transfer in millseconds. A value of 0 indicates no + * timeout. */ + unsigned int timeout; + + /** The status of the transfer. Read-only, and only for use within + * transfer callback function. + * + * If this is an isochronous transfer, this field may read COMPLETED even + * if there were errors in the frames. Use the + * \ref libusb_iso_packet_descriptor::status "status" field in each packet + * to determine if errors occurred. */ + enum libusb_transfer_status status; + + /** Length of the data buffer */ + int length; + + /** Actual length of data that was transferred. Read-only, and only for + * use within transfer callback function. Not valid for isochronous + * endpoint transfers. */ + int actual_length; + + /** Callback function. This will be invoked when the transfer completes, + * fails, or is cancelled. */ + libusb_transfer_cb_fn callback; + + /** User context data to pass to the callback function. */ + void *user_data; + + /** Data buffer */ + unsigned char *buffer; + + /** Number of isochronous packets. Only used for I/O with isochronous + * endpoints. */ + int num_iso_packets; + + /** Isochronous packet descriptors, for isochronous transfers only. */ + struct libusb_iso_packet_descriptor iso_packet_desc +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) + [] /* valid C99 code */ +#else + [0] /* non-standard, but usually working code */ +#endif + ; +}; + +/** \ingroup misc + * Capabilities supported by this instance of libusb. Test if the loaded + * library supports a given capability by calling + * \ref libusb_has_capability(). + */ +enum libusb_capability { + /** The libusb_has_capability() API is available. */ + LIBUSB_CAP_HAS_CAPABILITY = 0, +}; + +/** \ingroup lib + * Log message levels. + * - LIBUSB_LOG_LEVEL_NONE (0) : no messages ever printed by the library (default) + * - LIBUSB_LOG_LEVEL_ERROR (1) : error messages are printed to stderr + * - LIBUSB_LOG_LEVEL_WARNING (2) : warning and error messages are printed to stderr + * - LIBUSB_LOG_LEVEL_INFO (3) : informational messages are printed to stdout, warning + * and error messages are printed to stderr + * - LIBUSB_LOG_LEVEL_DEBUG (4) : debug and informational messages are printed to stdout, + * warnings and errors to stderr + */ +enum libusb_log_level { + LIBUSB_LOG_LEVEL_NONE = 0, + LIBUSB_LOG_LEVEL_ERROR, + LIBUSB_LOG_LEVEL_WARNING, + LIBUSB_LOG_LEVEL_INFO, + LIBUSB_LOG_LEVEL_DEBUG, +}; + +int LIBUSB_CALL libusb_init(libusb_context **ctx); +void LIBUSB_CALL libusb_exit(libusb_context *ctx); +void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level); +const struct libusb_version * LIBUSB_CALL libusb_get_version(void); +int LIBUSB_CALL libusb_has_capability(uint32_t capability); +const char * LIBUSB_CALL libusb_error_name(int errcode); + +ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx, + libusb_device ***list); +void LIBUSB_CALL libusb_free_device_list(libusb_device **list, + int unref_devices); +libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev); +void LIBUSB_CALL libusb_unref_device(libusb_device *dev); + +int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev, + int *config); +int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev, + struct libusb_device_descriptor *desc); +int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev, + struct libusb_config_descriptor **config); +int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev, + uint8_t config_index, struct libusb_config_descriptor **config); +int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev, + uint8_t bConfigurationValue, struct libusb_config_descriptor **config); +void LIBUSB_CALL libusb_free_config_descriptor( + struct libusb_config_descriptor *config); +uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev); +uint8_t LIBUSB_CALL libusb_get_port_number(libusb_device *dev); +libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev); +int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_length); +uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev); +int LIBUSB_CALL libusb_get_device_speed(libusb_device *dev); +int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev, + unsigned char endpoint); +int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev, + unsigned char endpoint); + +int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **handle); +void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle); +libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle); + +int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev, + int configuration); +int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev, + int interface_number); +int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev, + int interface_number); + +libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid( + libusb_context *ctx, uint16_t vendor_id, uint16_t product_id); + +int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev, + int interface_number, int alternate_setting); +int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev, + unsigned char endpoint); +int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev); + +int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev, + int interface_number); +int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev, + int interface_number); +int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev, + int interface_number); + +/* async I/O */ + +/** \ingroup asyncio + * Get the data section of a control transfer. This convenience function is here + * to remind you that the data does not start until 8 bytes into the actual + * buffer, as the setup packet comes first. + * + * Calling this function only makes sense from a transfer callback function, + * or situations where you have already allocated a suitably sized buffer at + * transfer->buffer. + * + * \param transfer a transfer + * \returns pointer to the first byte of the data section + */ +static inline unsigned char *libusb_control_transfer_get_data( + struct libusb_transfer *transfer) +{ + return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; +} + +/** \ingroup asyncio + * Get the control setup packet of a control transfer. This convenience + * function is here to remind you that the control setup occupies the first + * 8 bytes of the transfer data buffer. + * + * Calling this function only makes sense from a transfer callback function, + * or situations where you have already allocated a suitably sized buffer at + * transfer->buffer. + * + * \param transfer a transfer + * \returns a casted pointer to the start of the transfer data buffer + */ +static inline struct libusb_control_setup *libusb_control_transfer_get_setup( + struct libusb_transfer *transfer) +{ + return (struct libusb_control_setup *) transfer->buffer; +} + +/** \ingroup asyncio + * Helper function to populate the setup packet (first 8 bytes of the data + * buffer) for a control transfer. The wIndex, wValue and wLength values should + * be given in host-endian byte order. + * + * \param buffer buffer to output the setup packet into + * \param bmRequestType see the + * \ref libusb_control_setup::bmRequestType "bmRequestType" field of + * \ref libusb_control_setup + * \param bRequest see the + * \ref libusb_control_setup::bRequest "bRequest" field of + * \ref libusb_control_setup + * \param wValue see the + * \ref libusb_control_setup::wValue "wValue" field of + * \ref libusb_control_setup + * \param wIndex see the + * \ref libusb_control_setup::wIndex "wIndex" field of + * \ref libusb_control_setup + * \param wLength see the + * \ref libusb_control_setup::wLength "wLength" field of + * \ref libusb_control_setup + */ +static inline void libusb_fill_control_setup(unsigned char *buffer, + uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, + uint16_t wLength) +{ + struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer; + setup->bmRequestType = bmRequestType; + setup->bRequest = bRequest; + setup->wValue = libusb_cpu_to_le16(wValue); + setup->wIndex = libusb_cpu_to_le16(wIndex); + setup->wLength = libusb_cpu_to_le16(wLength); +} + +struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets); +int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer); +int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer); +void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer); + +/** \ingroup asyncio + * Helper function to populate the required \ref libusb_transfer fields + * for a control transfer. + * + * If you pass a transfer buffer to this function, the first 8 bytes will + * be interpreted as a control setup packet, and the wLength field will be + * used to automatically populate the \ref libusb_transfer::length "length" + * field of the transfer. Therefore the recommended approach is: + * -# Allocate a suitably sized data buffer (including space for control setup) + * -# Call libusb_fill_control_setup() + * -# If this is a host-to-device transfer with a data stage, put the data + * in place after the setup packet + * -# Call this function + * -# Call libusb_submit_transfer() + * + * It is also legal to pass a NULL buffer to this function, in which case this + * function will not attempt to populate the length field. Remember that you + * must then populate the buffer and length fields later. + * + * \param transfer the transfer to populate + * \param dev_handle handle of the device that will handle the transfer + * \param buffer data buffer. If provided, this function will interpret the + * first 8 bytes as a setup packet and infer the transfer length from that. + * \param callback callback function to be invoked on transfer completion + * \param user_data user data to pass to callback function + * \param timeout timeout for the transfer in milliseconds + */ +static inline void libusb_fill_control_transfer( + struct libusb_transfer *transfer, libusb_device_handle *dev_handle, + unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data, + unsigned int timeout) +{ + struct libusb_control_setup *setup = (struct libusb_control_setup *) buffer; + transfer->dev_handle = dev_handle; + transfer->endpoint = 0; + transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL; + transfer->timeout = timeout; + transfer->buffer = buffer; + if (setup) + transfer->length = LIBUSB_CONTROL_SETUP_SIZE + + libusb_le16_to_cpu(setup->wLength); + transfer->user_data = user_data; + transfer->callback = callback; +} + +/** \ingroup asyncio + * Helper function to populate the required \ref libusb_transfer fields + * for a bulk transfer. + * + * \param transfer the transfer to populate + * \param dev_handle handle of the device that will handle the transfer + * \param endpoint address of the endpoint where this transfer will be sent + * \param buffer data buffer + * \param length length of data buffer + * \param callback callback function to be invoked on transfer completion + * \param user_data user data to pass to callback function + * \param timeout timeout for the transfer in milliseconds + */ +static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer, + libusb_device_handle *dev_handle, unsigned char endpoint, + unsigned char *buffer, int length, libusb_transfer_cb_fn callback, + void *user_data, unsigned int timeout) +{ + transfer->dev_handle = dev_handle; + transfer->endpoint = endpoint; + transfer->type = LIBUSB_TRANSFER_TYPE_BULK; + transfer->timeout = timeout; + transfer->buffer = buffer; + transfer->length = length; + transfer->user_data = user_data; + transfer->callback = callback; +} + +/** \ingroup asyncio + * Helper function to populate the required \ref libusb_transfer fields + * for an interrupt transfer. + * + * \param transfer the transfer to populate + * \param dev_handle handle of the device that will handle the transfer + * \param endpoint address of the endpoint where this transfer will be sent + * \param buffer data buffer + * \param length length of data buffer + * \param callback callback function to be invoked on transfer completion + * \param user_data user data to pass to callback function + * \param timeout timeout for the transfer in milliseconds + */ +static inline void libusb_fill_interrupt_transfer( + struct libusb_transfer *transfer, libusb_device_handle *dev_handle, + unsigned char endpoint, unsigned char *buffer, int length, + libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) +{ + transfer->dev_handle = dev_handle; + transfer->endpoint = endpoint; + transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT; + transfer->timeout = timeout; + transfer->buffer = buffer; + transfer->length = length; + transfer->user_data = user_data; + transfer->callback = callback; +} + +/** \ingroup asyncio + * Helper function to populate the required \ref libusb_transfer fields + * for an isochronous transfer. + * + * \param transfer the transfer to populate + * \param dev_handle handle of the device that will handle the transfer + * \param endpoint address of the endpoint where this transfer will be sent + * \param buffer data buffer + * \param length length of data buffer + * \param num_iso_packets the number of isochronous packets + * \param callback callback function to be invoked on transfer completion + * \param user_data user data to pass to callback function + * \param timeout timeout for the transfer in milliseconds + */ +static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer, + libusb_device_handle *dev_handle, unsigned char endpoint, + unsigned char *buffer, int length, int num_iso_packets, + libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) +{ + transfer->dev_handle = dev_handle; + transfer->endpoint = endpoint; + transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS; + transfer->timeout = timeout; + transfer->buffer = buffer; + transfer->length = length; + transfer->num_iso_packets = num_iso_packets; + transfer->user_data = user_data; + transfer->callback = callback; +} + +/** \ingroup asyncio + * Convenience function to set the length of all packets in an isochronous + * transfer, based on the num_iso_packets field in the transfer structure. + * + * \param transfer a transfer + * \param length the length to set in each isochronous packet descriptor + * \see libusb_get_max_packet_size() + */ +static inline void libusb_set_iso_packet_lengths( + struct libusb_transfer *transfer, unsigned int length) +{ + int i; + for (i = 0; i < transfer->num_iso_packets; i++) + transfer->iso_packet_desc[i].length = length; +} + +/** \ingroup asyncio + * Convenience function to locate the position of an isochronous packet + * within the buffer of an isochronous transfer. + * + * This is a thorough function which loops through all preceding packets, + * accumulating their lengths to find the position of the specified packet. + * Typically you will assign equal lengths to each packet in the transfer, + * and hence the above method is sub-optimal. You may wish to use + * libusb_get_iso_packet_buffer_simple() instead. + * + * \param transfer a transfer + * \param packet the packet to return the address of + * \returns the base address of the packet buffer inside the transfer buffer, + * or NULL if the packet does not exist. + * \see libusb_get_iso_packet_buffer_simple() + */ +static inline unsigned char *libusb_get_iso_packet_buffer( + struct libusb_transfer *transfer, unsigned int packet) +{ + int i; + size_t offset = 0; + int _packet; + + /* oops..slight bug in the API. packet is an unsigned int, but we use + * signed integers almost everywhere else. range-check and convert to + * signed to avoid compiler warnings. FIXME for libusb-2. */ + if (packet > INT_MAX) + return NULL; + _packet = packet; + + if (_packet >= transfer->num_iso_packets) + return NULL; + + for (i = 0; i < _packet; i++) + offset += transfer->iso_packet_desc[i].length; + + return transfer->buffer + offset; +} + +/** \ingroup asyncio + * Convenience function to locate the position of an isochronous packet + * within the buffer of an isochronous transfer, for transfers where each + * packet is of identical size. + * + * This function relies on the assumption that every packet within the transfer + * is of identical size to the first packet. Calculating the location of + * the packet buffer is then just a simple calculation: + * buffer + (packet_size * packet) + * + * Do not use this function on transfers other than those that have identical + * packet lengths for each packet. + * + * \param transfer a transfer + * \param packet the packet to return the address of + * \returns the base address of the packet buffer inside the transfer buffer, + * or NULL if the packet does not exist. + * \see libusb_get_iso_packet_buffer() + */ +static inline unsigned char *libusb_get_iso_packet_buffer_simple( + struct libusb_transfer *transfer, unsigned int packet) +{ + int _packet; + + /* oops..slight bug in the API. packet is an unsigned int, but we use + * signed integers almost everywhere else. range-check and convert to + * signed to avoid compiler warnings. FIXME for libusb-2. */ + if (packet > INT_MAX) + return NULL; + _packet = packet; + + if (_packet >= transfer->num_iso_packets) + return NULL; + + return transfer->buffer + (transfer->iso_packet_desc[0].length * _packet); +} + +/* sync I/O */ + +int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle, + uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, + unsigned char *data, uint16_t wLength, unsigned int timeout); + +int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle, + unsigned char endpoint, unsigned char *data, int length, + int *actual_length, unsigned int timeout); + +int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle, + unsigned char endpoint, unsigned char *data, int length, + int *actual_length, unsigned int timeout); + +/** \ingroup desc + * Retrieve a descriptor from the default control pipe. + * This is a convenience function which formulates the appropriate control + * message to retrieve the descriptor. + * + * \param dev a device handle + * \param desc_type the descriptor type, see \ref libusb_descriptor_type + * \param desc_index the index of the descriptor to retrieve + * \param data output buffer for descriptor + * \param length size of data buffer + * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure + */ +static inline int libusb_get_descriptor(libusb_device_handle *dev, + uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length) +{ + return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN, + LIBUSB_REQUEST_GET_DESCRIPTOR, (desc_type << 8) | desc_index, 0, data, + (uint16_t) length, 1000); +} + +/** \ingroup desc + * Retrieve a descriptor from a device. + * This is a convenience function which formulates the appropriate control + * message to retrieve the descriptor. The string returned is Unicode, as + * detailed in the USB specifications. + * + * \param dev a device handle + * \param desc_index the index of the descriptor to retrieve + * \param langid the language ID for the string descriptor + * \param data output buffer for descriptor + * \param length size of data buffer + * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure + * \see libusb_get_string_descriptor_ascii() + */ +static inline int libusb_get_string_descriptor(libusb_device_handle *dev, + uint8_t desc_index, uint16_t langid, unsigned char *data, int length) +{ + return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN, + LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t)((LIBUSB_DT_STRING << 8) | desc_index), + langid, data, (uint16_t) length, 1000); +} + +int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev, + uint8_t desc_index, unsigned char *data, int length); + +/* polling and timeouts */ + +int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx); +void LIBUSB_CALL libusb_lock_events(libusb_context *ctx); +void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx); +int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx); +int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx); +void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx); +void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx); +int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv); + +int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx, + struct timeval *tv); +int LIBUSB_CALL libusb_handle_events_timeout_completed(libusb_context *ctx, + struct timeval *tv, int *completed); +int LIBUSB_CALL libusb_handle_events(libusb_context *ctx); +int LIBUSB_CALL libusb_handle_events_completed(libusb_context *ctx, int *completed); +int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx, + struct timeval *tv); +int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx); +int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx, + struct timeval *tv); + +/** \ingroup poll + * File descriptor for polling + */ +struct libusb_pollfd { + /** Numeric file descriptor */ + int fd; + + /** Event flags to poll for from . POLLIN indicates that you + * should monitor this file descriptor for becoming ready to read from, + * and POLLOUT indicates that you should monitor this file descriptor for + * nonblocking write readiness. */ + short events; +}; + +/** \ingroup poll + * Callback function, invoked when a new file descriptor should be added + * to the set of file descriptors monitored for events. + * \param fd the new file descriptor + * \param events events to monitor for, see \ref libusb_pollfd for a + * description + * \param user_data User data pointer specified in + * libusb_set_pollfd_notifiers() call + * \see libusb_set_pollfd_notifiers() + */ +typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events, + void *user_data); + +/** \ingroup poll + * Callback function, invoked when a file descriptor should be removed from + * the set of file descriptors being monitored for events. After returning + * from this callback, do not use that file descriptor again. + * \param fd the file descriptor to stop monitoring + * \param user_data User data pointer specified in + * libusb_set_pollfd_notifiers() call + * \see libusb_set_pollfd_notifiers() + */ +typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data); + +const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds( + libusb_context *ctx); +void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx, + libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb, + void *user_data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/java/src/ch/ntb/inf/libusbJava/Device.java b/src/main/java/ch/ntb/inf/libusbJava/Device.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/Device.java rename to src/main/java/ch/ntb/inf/libusbJava/Device.java index 6315937..5da307d 100644 --- a/java/src/ch/ntb/inf/libusbJava/Device.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Device.java @@ -1,822 +1,822 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import ch.ntb.inf.libusbJava.logger.LogUtil; - -/** - * This class represents an USB device.
- * To get an instance of an USB device use USB.getDevice(...). - * - */ -public class Device { - - private static final Logger logger = LogUtil.getLogger("ch.ntb.inf.libusbJava"); - - private int maxPacketSize; - - /** - * Mandatory identification values for the device. - */ - private int idVendor, idProduct; - - /** - * Optional identification value for the device (e.g. if there are multiple - * devices with the same vendor and product id). - */ - private String filename; - - /** - * Optional identification value for the device (e.g. if there are multiple - * devices with the same vendor and product id). - */ - private String busName; - - private int dev_configuration, dev_interface, dev_altinterface; - - private long usbDevHandle; - - private boolean resetOnFirstOpen, resetDone; - - private int resetTimeout = 2000; - - private Usb_Device dev; - - protected Device(short idVendor, short idProduct) { - resetOnFirstOpen = false; - resetDone = false; - maxPacketSize = -1; - this.idVendor = idVendor; - this.idProduct = idProduct; - this.filename = null; - } - - protected Device(short idVendor, short idProduct, String busName, - String filename) { - resetOnFirstOpen = false; - resetDone = false; - maxPacketSize = -1; - this.idVendor = idVendor; - this.idProduct = idProduct; - this.busName = busName; - this.filename = filename; - } - - private void updateMaxPacketSize(Usb_Device device) throws USBException { - maxPacketSize = -1; - Usb_Config_Descriptor[] confDesc = device.getConfig(); - for (int i = 0; i < confDesc.length; i++) { - Usb_Interface[] int_ = confDesc[i].getInterface(); - for (int j = 0; j < int_.length; j++) { - Usb_Interface_Descriptor[] intDesc = int_[j].getAltsetting(); - for (int k = 0; k < intDesc.length; k++) { - Usb_Endpoint_Descriptor[] epDesc = intDesc[k].getEndpoint(); - for (int l = 0; l < epDesc.length; l++) { - maxPacketSize = Math.max(epDesc[l].getWMaxPacketSize(), - maxPacketSize); - } - } - } - } - if (maxPacketSize <= 0) { - throw new USBException( - "No USB endpoints found. Check the device configuration"); - } - } - - /** - * Initializes the device. The parameters idVendor and - * idProduct are mandatory. The parameter filename - * is optional. - */ - private Usb_Device initDevice(int idVendorParam, int idProductParam, - String busName, String filename) throws USBException { - Usb_Bus bus = USB.getBus(); - - Usb_Device device = null; - // search for device - while (bus != null) { - device = bus.getDevices(); - while (device != null) { - Usb_Device_Descriptor devDesc = device.getDescriptor(); - if (busName != null && filename != null) { - if (busName.compareTo(bus.getDirname()) == 0 - && filename.compareTo(device.getFilename()) == 0 - && devDesc.getIdVendor() == idVendor - && devDesc.getIdProduct() == idProduct) { - logger.info("Device found. bus: " + bus.getDirname() - + ", filename: " + device.getFilename()); - updateMaxPacketSize(device); - return device; - } - } else if (filename != null) { - if (filename.compareTo(device.getFilename()) == 0 - && devDesc.getIdVendor() == idVendor - && devDesc.getIdProduct() == idProduct) { - logger.info("Device found. bus: " + bus.getDirname() - + ", filename: " + device.getFilename()); - updateMaxPacketSize(device); - return device; - } - } else if (busName != null) { - if (busName.compareTo(bus.getDirname()) == 0 - && devDesc.getIdVendor() == idVendor - && devDesc.getIdProduct() == idProduct) { - logger.info("Device found. bus: " + bus.getDirname() - + ", filename: " + device.getFilename()); - updateMaxPacketSize(device); - return device; - } - } else if (devDesc.getIdVendor() == idVendor - && devDesc.getIdProduct() == idProduct) { - logger.info("Device found. bus: " + bus.getDirname() - + ", filename: " + device.getFilename()); - updateMaxPacketSize(device); - return device; - } - device = device.getNext(); - } - bus = bus.getNext(); - } - return null; - } - - /** - * Updates the device and descriptor information from the bus.
- * The descriptors can be read with {@link #getDeviceDescriptor()} and - * {@link #getConfigDescriptors()}. - * - * @throws USBException - */ - public void updateDescriptors() throws USBException { - dev = initDevice(idVendor, idProduct, busName, filename); - } - - /** - * Returns the device descriptor associated with this device.
- * The descriptor is updated by calling {@link #updateDescriptors()} or - * {@link #open(int, int, int)}. - * - * @return the device descriptor associated with this device or - * null - */ - public Usb_Device_Descriptor getDeviceDescriptor() { - if (dev == null) { - return null; - } - return dev.getDescriptor(); - } - - /** - * Returns the configuration descriptors associated with this device.
- * The descriptors are updated by calling {@link #updateDescriptors()} or - * {@link #open(int, int, int)}. - * - * @return the configuration descriptors associated with this device or - * null - */ - public Usb_Config_Descriptor[] getConfigDescriptors() { - if (dev == null) { - return null; - } - return dev.getConfig(); - } - - /** - * Opens the device and claims the specified configuration, interface and - * altinterface.
- * First the bus is enumerated. If the device is found its descriptors are - * read and the maxPacketSize value is updated. If no endpoints - * are found in the descriptors an exception is thrown. - * - * @param configuration - * the configuration, see - * {@link Usb_Config_Descriptor#getBConfigurationValue()} - * @param interface_ - * the interface, see - * {@link Usb_Interface_Descriptor#getBInterfaceNumber()} - * @param altinterface - * the alternate interface, see - * {@link Usb_Interface_Descriptor#getBAlternateSetting()}. If no - * alternate interface must be set -1 can be used. - * @throws USBException - */ - public void open(int configuration, int interface_, int altinterface) - throws USBException { - this.dev_configuration = configuration; - this.dev_interface = interface_; - this.dev_altinterface = altinterface; - - if (usbDevHandle != 0) { - throw new USBException("device opened, close or reset first"); - } - - dev = initDevice(idVendor, idProduct, busName, filename); - - if (dev != null) { - long res = LibusbJava.usb_open(dev); - if (res == 0) { - throw new USBException("LibusbJava.usb_open: " - + LibusbJava.usb_strerror()); - } - usbDevHandle = res; - } - - if (dev == null || usbDevHandle == 0) { - throw new USBException("USB device with " + toString() - + " not found on USB"); - } - claim_interface(usbDevHandle, configuration, interface_, altinterface); - if (resetOnFirstOpen & !resetDone) { - logger.info("reset on first open"); - resetDone = true; - reset(); - try { - Thread.sleep(resetTimeout); - } catch (InterruptedException e) { - // - } - open(configuration, interface_, altinterface); - } - } - - /** - * Release the claimed interface and close the opened device.
- * - * @throws USBException - */ - public void close() throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - release_interface(usbDevHandle, dev_interface); - if (LibusbJava.usb_close(usbDevHandle) < 0) { - usbDevHandle = 0; - throw new USBException("LibusbJava.usb_close: " - + LibusbJava.usb_strerror()); - } - usbDevHandle = 0; - maxPacketSize = -1; - logger.info("device closed"); - } - - /** - * Sends an USB reset to the device. The device handle will no longer be - * valid. To use the device again, {@link #open(int, int, int)} must be - * called.
- * Note that the device is re-attached to the USB which may cause the bus - * and filename to be changed. If the bus and filename parameters are used - * in {@link USB#getDevice(short, short, String, String)} unregister the - * device using {@link USB#unregisterDevice(Device)}, re-enumerate the bus - * and create a new device instance. If that is not done the device may not - * be found. - * - * @throws USBException - */ - public void reset() throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - release_interface(usbDevHandle, dev_interface); - if (LibusbJava.usb_reset(usbDevHandle) < 0) { - usbDevHandle = 0; - throw new USBException("LibusbJava.usb_reset: " - + LibusbJava.usb_strerror()); - } - usbDevHandle = 0; - logger.info("device reset"); - } - - /** - * Write data to the device using a bulk transfer.
- * - * @param out_ep_address - * endpoint address to write to - * @param data - * data to write to this endpoint - * @param size - * size of the data - * @param timeout - * amount of time in ms the device will try to send the data - * until a timeout exception is thrown - * @param reopenOnTimeout - * if set to true, the device will try to open the connection and - * send the data again before a timeout exception is thrown - * @return the actual number of bytes written - * @throws USBException - */ - public int writeBulk(int out_ep_address, byte[] data, int size, - int timeout, boolean reopenOnTimeout) throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - if (data == null) { - throw new USBException("data must not be null"); - } - if (size <= 0 || size > data.length) { - throw new ArrayIndexOutOfBoundsException("invalid size: " + size); - } - int lenWritten = LibusbJava.usb_bulk_write(usbDevHandle, - out_ep_address, data, size, timeout); - if (lenWritten < 0) { - if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { - // try to reopen the device and send the data again - if (reopenOnTimeout) { - logger.info("try to reopen"); - reset(); - open(dev_configuration, dev_interface, dev_altinterface); - return writeBulk(out_ep_address, data, size, timeout, false); - } - throw new USBTimeoutException("LibusbJava.usb_bulk_write: " - + LibusbJava.usb_strerror()); - } - throw new USBException("LibusbJava.usb_bulk_write: " - + LibusbJava.usb_strerror()); - } - - logger.info("length written: " + lenWritten); - if (logger.isLoggable(Level.FINEST)) { - StringBuffer sb = new StringBuffer("bulkwrite, ep 0x" - + Integer.toHexString(out_ep_address) + ": " + lenWritten - + " Bytes sent: "); - for (int i = 0; i < lenWritten; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } - return lenWritten; - } - - /** - * Read data from the device using a bulk transfer.
- * - * @param in_ep_address - * endpoint address to read from - * @param data - * data buffer for the data to be read - * @param size - * the maximum requested data size - * @param timeout - * amount of time in ms the device will try to receive data until - * a timeout exception is thrown - * @param reopenOnTimeout - * if set to true, the device will try to open the connection and - * receive the data again before a timeout exception is thrown - * @return the actual number of bytes read - * @throws USBException - */ - public int readBulk(int in_ep_address, byte[] data, int size, int timeout, - boolean reopenOnTimeout) throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - if (data == null) { - throw new USBException("data must not be null"); - } - if (size <= 0 || size > data.length) { - throw new ArrayIndexOutOfBoundsException("invalid size: " + size); - } - int lenRead = LibusbJava.usb_bulk_read(usbDevHandle, in_ep_address, - data, size, timeout); - if (lenRead < 0) { - if (lenRead == LibusbJava.ERROR_TIMEDOUT) { - // try to reopen the device and send the data again - if (reopenOnTimeout) { - logger.info("try to reopen"); - reset(); - open(dev_configuration, dev_interface, dev_altinterface); - return readBulk(in_ep_address, data, size, timeout, false); - } - throw new USBTimeoutException("LibusbJava.usb_bulk_read: " - + LibusbJava.usb_strerror()); - } - throw new USBException("LibusbJava.usb_bulk_read: " - + LibusbJava.usb_strerror()); - } - - logger.info("length read: " + lenRead); - if (logger.isLoggable(Level.FINEST)) { - StringBuffer sb = new StringBuffer("bulkread, ep 0x" - + Integer.toHexString(in_ep_address) + ": " + lenRead - + " Bytes received: "); - for (int i = 0; i < lenRead; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } - return lenRead; - } - - /** - * Write data to the device using a interrupt transfer.
- * - * @param out_ep_address - * endpoint address to write to - * @param data - * data to write to this endpoint - * @param size - * size of the data - * @param timeout - * amount of time in ms the device will try to send the data - * until a timeout exception is thrown - * @param reopenOnTimeout - * if set to true, the device will try to open the connection and - * send the data again before a timeout exception is thrown - * @return the actual number of bytes written - * @throws USBException - */ - public int writeInterrupt(int out_ep_address, byte[] data, int size, - int timeout, boolean reopenOnTimeout) throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - if (data == null) { - throw new USBException("data must not be null"); - } - if (size <= 0 || size > data.length) { - throw new ArrayIndexOutOfBoundsException("invalid size: " + size); - } - int lenWritten = LibusbJava.usb_interrupt_write(usbDevHandle, - out_ep_address, data, size, timeout); - if (lenWritten < 0) { - if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { - // try to reopen the device and send the data again - if (reopenOnTimeout) { - logger.info("try to reopen"); - reset(); - open(dev_configuration, dev_interface, dev_altinterface); - return writeInterrupt(out_ep_address, data, size, timeout, - false); - } - throw new USBTimeoutException( - "LibusbJava.usb_interrupt_write: " - + LibusbJava.usb_strerror()); - } - throw new USBException("LibusbJava.usb_interrupt_write: " - + LibusbJava.usb_strerror()); - } - - logger.info("length written: " + lenWritten); - if (logger.isLoggable(Level.FINEST)) { - StringBuffer sb = new StringBuffer("interruptwrite, ep 0x" - + Integer.toHexString(out_ep_address) + ": " + lenWritten - + " Bytes sent: "); - for (int i = 0; i < lenWritten; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } - return lenWritten; - } - - /** - * Read data from the device using a interrupt transfer.
- * - * @param in_ep_address - * endpoint address to read from - * @param data - * data buffer for the data to be read - * @param size - * the maximum requested data size - * @param timeout - * amount of time in ms the device will try to receive data until - * a timeout exception is thrown - * @param reopenOnTimeout - * if set to true, the device will try to open the connection and - * receive the data again before a timeout exception is thrown - * @return the actual number of bytes read - * @throws USBException - */ - public int readInterrupt(int in_ep_address, byte[] data, int size, - int timeout, boolean reopenOnTimeout) throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - if (data == null) { - throw new USBException("data must not be null"); - } - if (size <= 0 || size > data.length) { - throw new ArrayIndexOutOfBoundsException("invalid size: " + size); - } - int lenRead = LibusbJava.usb_interrupt_read(usbDevHandle, - in_ep_address, data, size, timeout); - if (lenRead < 0) { - if (lenRead == LibusbJava.ERROR_TIMEDOUT) { - // try to reopen the device and send the data again - if (reopenOnTimeout) { - logger.info("try to reopen"); - reset(); - open(dev_configuration, dev_interface, dev_altinterface); - return readInterrupt(in_ep_address, data, size, timeout, - false); - } - throw new USBTimeoutException("LibusbJava.usb_interrupt_read: " - + LibusbJava.usb_strerror()); - } - throw new USBException("LibusbJava.usb_interrupt_read: " - + LibusbJava.usb_strerror()); - } - - logger.info("length read: " + lenRead); - if (logger.isLoggable(Level.FINEST)) { - StringBuffer sb = new StringBuffer("interrupt, ep 0x" - + Integer.toHexString(in_ep_address) + ": " + lenRead - + " Bytes received: "); - for (int i = 0; i < lenRead; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } - return lenRead; - } - - /** - * Performs a control request to the default control pipe on a device.
- * The parameters mirror the types of the same name in the USB - * specification. - * - * @param requestType - * USB device request type (USB specification 9.3, - * bmRequestType). Use constants from {@link ch.ntb.inf.libusbJava.USB} - * (REQ_TYPE_xxx). - * @param request - * specific request (USB specification 9.4, bRequest). Use - * constants from {@link ch.ntb.inf.libusbJava.USB} (REQ_xxx). - * @param value - * field that varies according to request (USB specification 9.4, - * wValue) - * @param index - * field that varies according to request (USB specification 9.4, - * wIndex) - * @param data - * the send/receive buffer - * @param size - * the buffer size. 0 is a valid value, but there must still be a - * dummy data buffer provided. - * @param timeout - * amount of time in ms the device will try to send/receive data - * until a timeout exception is thrown - * @param reopenOnTimeout - * if set to true, the device will try to open the connection and - * send/receive the data again before a timeout exception is - * thrown - * @return the number of bytes written/read - * @throws USBException - */ - public int controlMsg(int requestType, int request, int value, int index, - byte[] data, int size, int timeout, boolean reopenOnTimeout) - throws USBException { - if (usbDevHandle == 0) { - throw new USBException("invalid device handle"); - } - if (data == null) { - throw new USBException("data must not be null"); - } - if (size < 0 || size > data.length) { - throw new ArrayIndexOutOfBoundsException("invalid size: " + size); - } - int len = LibusbJava.usb_control_msg(usbDevHandle, requestType, - request, value, index, data, size, timeout); - if (len < 0) { - if (len == LibusbJava.ERROR_TIMEDOUT) { - // try to reopen the device and send the data again - if (reopenOnTimeout) { - logger.info("try to reopen"); - reset(); - open(dev_configuration, dev_interface, dev_altinterface); - return controlMsg(requestType, request, value, index, data, - size, timeout, false); - } - throw new USBTimeoutException("LibusbJava.controlMsg: " - + LibusbJava.usb_strerror()); - } - throw new USBException("LibusbJava.controlMsg: " - + LibusbJava.usb_strerror()); - } - - logger.info("length read/written: " + len); - if (logger.isLoggable(Level.FINEST)) { - StringBuffer sb = new StringBuffer("controlMsg: " + len - + " Bytes received(written: "); - for (int i = 0; i < len; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } - return len; - } - - /** - * Claim an interface to send and receive USB data.
- * - * @param usb_dev_handle - * the handle of the device (MUST BE VALID) - * @param configuration - * the configuration to use - * @param interface_ - * the interface to claim - * @param altinterface - * the alternate interface to use. If no alternate interface must - * be set -1 can be used. - * @throws USBException - * throws an USBException if the action fails - */ - private void claim_interface(long usb_dev_handle, int configuration, - int interface_, int altinterface) throws USBException { - if (LibusbJava.usb_set_configuration(usb_dev_handle, configuration) < 0) { - usbDevHandle = 0; - throw new USBException("LibusbJava.usb_set_configuration: " - + LibusbJava.usb_strerror()); - } - if (LibusbJava.usb_claim_interface(usb_dev_handle, interface_) < 0) { - usbDevHandle = 0; - throw new USBException("LibusbJava.usb_claim_interface: " - + LibusbJava.usb_strerror()); - } - if (altinterface >= 0) { - if (LibusbJava.usb_set_altinterface(usb_dev_handle, altinterface) < 0) { - try { - release_interface(usb_dev_handle, interface_); - } catch (USBException e) { - // ignore - } - usbDevHandle = 0; - throw new USBException("LibusbJava.usb_set_altinterface: " - + LibusbJava.usb_strerror()); - } - } - logger.info("interface claimed"); - } - - /** - * Release a previously claimed interface.
- * - * @param dev_handle - * the handle of the device (MUST BE VALID) - * @param interface_ - * the interface to claim - * @throws USBException - * throws an USBException if the action fails - */ - private void release_interface(long dev_handle, int interface_) - throws USBException { - if (LibusbJava.usb_release_interface(dev_handle, interface_) < 0) { - usbDevHandle = 0; - throw new USBException("LibusbJava.usb_release_interface: " - + LibusbJava.usb_strerror()); - } - logger.info("interface released"); - } - - /** - * Returns the product ID of the device.
- * - * @return the product ID of the device. - */ - public int getIdProduct() { - return idProduct; - } - - /** - * Returns the vendor ID of the device.
- * - * @return the vendor ID of the device. - */ - public int getIdVendor() { - return idVendor; - } - - /** - * Returns the alternative interface.
- * This value is only valid after opening the device. - * - * @return the alternative interface. This value is only valid after opening - * the device. - */ - public int getAltinterface() { - return dev_altinterface; - } - - /** - * Returns the current configuration used.
- * This value is only valid after opening the device. - * - * @return the current configuration used. This value is only valid after - * opening the device. - */ - public int getConfiguration() { - return dev_configuration; - } - - /** - * Returns the current interface.
- * This value is only valid after opening the device. - * - * @return the current interface. This value is only valid after opening the - * device. - */ - public int getInterface() { - return dev_interface; - } - - /** - * Returns the maximum packet size in bytes which is allowed to be - * transmitted at once.
- * The value is determined by reading the endpoint descriptor(s) when - * opening the device. It is invalid before the device is opened! Note that - * if some endpoints use different packet sizes the maximum packet size is - * return. This value may be used to determine if a device is opened in - * fullspeed or highspeed mode. - * - * @return the maximum packet size - */ - public int getMaxPacketSize() { - return maxPacketSize; - } - - /** - * Check if the device is open, attached and work.
- * - * @return true if the device is open and work. - */ - public boolean isOpen() { - if(usbDevHandle != 0){ - try { - updateDescriptors(); - } catch (USBException e) { - return false; - } - return dev != null; - } - return false; - } - - /** - * If enabled, the device is reset when first opened.
- * This will only happen once. When the application is started, the device - * state is unknown. If the device is not reset, read or write may result in - * a {@link USBTimeoutException}.
- *
- * This feature is disabled by default. - * - * @param enable - * true if the device should be reset when first opened - * @param timeout - * the timeout between the reset and the reopening - */ - public void setResetOnFirstOpen(boolean enable, int timeout) { - resetOnFirstOpen = enable; - resetTimeout = timeout; - } - - /** - * Returns the optional filename which is set when there are multiple - * devices with the same vendor and product id. See - * {@link USB#getDevice(short, short, String, String)}. Use - * {@link Usb_Device#getFilename()} to read the filename of a device. - * - * @return the filename or null - */ - protected String getFilename() { - return filename; - } - - /** - * Returns the optional bus name which is set when there are multiple - * devices with the same vendor and product id. See - * {@link USB#getDevice(short, short, String, String)}. Use - * {@link Usb_Bus#getDirname()} to read the name of a bus. - * - * @return the bus name or null - */ - protected String getBusName() { - return busName; - } - - /** - * Returns the Usb_Device instance associated with this device. This value - * is only valid after opening the device. - * - * @return the Usb_Device instance associated with this device. - */ - public Usb_Device getDevice() { - return dev; - } - - @Override - public String toString() { - return "idVendor: 0x" + Integer.toHexString(getIdVendor() & 0xffff) - + ", idProduct: 0x" - + Integer.toHexString(getIdProduct() & 0xffff) + ", busName: " - + getBusName() + ", filename: " + getFilename(); - } - -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import ch.ntb.inf.libusbJava.logger.LogUtil; + +/** + * This class represents an USB device.
+ * To get an instance of an USB device use USB.getDevice(...). + * + */ +public class Device { + + private static final Logger logger = LogUtil.getLogger("ch.ntb.inf.libusbJava"); + + private int maxPacketSize; + + /** + * Mandatory identification values for the device. + */ + private int idVendor, idProduct; + + /** + * Optional identification value for the device (e.g. if there are multiple + * devices with the same vendor and product id). + */ + private String filename; + + /** + * Optional identification value for the device (e.g. if there are multiple + * devices with the same vendor and product id). + */ + private String busName; + + private int dev_configuration, dev_interface, dev_altinterface; + + private long usbDevHandle; + + private boolean resetOnFirstOpen, resetDone; + + private int resetTimeout = 2000; + + private Usb_Device dev; + + protected Device(short idVendor, short idProduct) { + resetOnFirstOpen = false; + resetDone = false; + maxPacketSize = -1; + this.idVendor = idVendor; + this.idProduct = idProduct; + this.filename = null; + } + + protected Device(short idVendor, short idProduct, String busName, + String filename) { + resetOnFirstOpen = false; + resetDone = false; + maxPacketSize = -1; + this.idVendor = idVendor; + this.idProduct = idProduct; + this.busName = busName; + this.filename = filename; + } + + private void updateMaxPacketSize(Usb_Device device) throws USBException { + maxPacketSize = -1; + Usb_Config_Descriptor[] confDesc = device.getConfig(); + for (int i = 0; i < confDesc.length; i++) { + Usb_Interface[] int_ = confDesc[i].getInterface(); + for (int j = 0; j < int_.length; j++) { + Usb_Interface_Descriptor[] intDesc = int_[j].getAltsetting(); + for (int k = 0; k < intDesc.length; k++) { + Usb_Endpoint_Descriptor[] epDesc = intDesc[k].getEndpoint(); + for (int l = 0; l < epDesc.length; l++) { + maxPacketSize = Math.max(epDesc[l].getWMaxPacketSize(), + maxPacketSize); + } + } + } + } + if (maxPacketSize <= 0) { + throw new USBException( + "No USB endpoints found. Check the device configuration"); + } + } + + /** + * Initializes the device. The parameters idVendor and + * idProduct are mandatory. The parameter filename + * is optional. + */ + private Usb_Device initDevice(int idVendorParam, int idProductParam, + String busName, String filename) throws USBException { + Usb_Bus bus = USB.getBus(); + + Usb_Device device = null; + // search for device + while (bus != null) { + device = bus.getDevices(); + while (device != null) { + Usb_Device_Descriptor devDesc = device.getDescriptor(); + if (busName != null && filename != null) { + if (busName.compareTo(bus.getDirname()) == 0 + && filename.compareTo(device.getFilename()) == 0 + && devDesc.getIdVendor() == idVendor + && devDesc.getIdProduct() == idProduct) { + logger.info("Device found. bus: " + bus.getDirname() + + ", filename: " + device.getFilename()); + updateMaxPacketSize(device); + return device; + } + } else if (filename != null) { + if (filename.compareTo(device.getFilename()) == 0 + && devDesc.getIdVendor() == idVendor + && devDesc.getIdProduct() == idProduct) { + logger.info("Device found. bus: " + bus.getDirname() + + ", filename: " + device.getFilename()); + updateMaxPacketSize(device); + return device; + } + } else if (busName != null) { + if (busName.compareTo(bus.getDirname()) == 0 + && devDesc.getIdVendor() == idVendor + && devDesc.getIdProduct() == idProduct) { + logger.info("Device found. bus: " + bus.getDirname() + + ", filename: " + device.getFilename()); + updateMaxPacketSize(device); + return device; + } + } else if (devDesc.getIdVendor() == idVendor + && devDesc.getIdProduct() == idProduct) { + logger.info("Device found. bus: " + bus.getDirname() + + ", filename: " + device.getFilename()); + updateMaxPacketSize(device); + return device; + } + device = device.getNext(); + } + bus = bus.getNext(); + } + return null; + } + + /** + * Updates the device and descriptor information from the bus.
+ * The descriptors can be read with {@link #getDeviceDescriptor()} and + * {@link #getConfigDescriptors()}. + * + * @throws USBException + */ + public void updateDescriptors() throws USBException { + dev = initDevice(idVendor, idProduct, busName, filename); + } + + /** + * Returns the device descriptor associated with this device.
+ * The descriptor is updated by calling {@link #updateDescriptors()} or + * {@link #open(int, int, int)}. + * + * @return the device descriptor associated with this device or + * null + */ + public Usb_Device_Descriptor getDeviceDescriptor() { + if (dev == null) { + return null; + } + return dev.getDescriptor(); + } + + /** + * Returns the configuration descriptors associated with this device.
+ * The descriptors are updated by calling {@link #updateDescriptors()} or + * {@link #open(int, int, int)}. + * + * @return the configuration descriptors associated with this device or + * null + */ + public Usb_Config_Descriptor[] getConfigDescriptors() { + if (dev == null) { + return null; + } + return dev.getConfig(); + } + + /** + * Opens the device and claims the specified configuration, interface and + * altinterface.
+ * First the bus is enumerated. If the device is found its descriptors are + * read and the maxPacketSize value is updated. If no endpoints + * are found in the descriptors an exception is thrown. + * + * @param configuration + * the configuration, see + * {@link Usb_Config_Descriptor#getBConfigurationValue()} + * @param interface_ + * the interface, see + * {@link Usb_Interface_Descriptor#getBInterfaceNumber()} + * @param altinterface + * the alternate interface, see + * {@link Usb_Interface_Descriptor#getBAlternateSetting()}. If no + * alternate interface must be set -1 can be used. + * @throws USBException + */ + public void open(int configuration, int interface_, int altinterface) + throws USBException { + this.dev_configuration = configuration; + this.dev_interface = interface_; + this.dev_altinterface = altinterface; + + if (usbDevHandle != 0) { + throw new USBException("device opened, close or reset first"); + } + + dev = initDevice(idVendor, idProduct, busName, filename); + + if (dev != null) { + long res = LibusbJava.usb_open(dev); + if (res == 0) { + throw new USBException("LibusbJava.usb_open: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = res; + } + + if (dev == null || usbDevHandle == 0) { + throw new USBException("USB device with " + toString() + + " not found on USB"); + } + claim_interface(usbDevHandle, configuration, interface_, altinterface); + if (resetOnFirstOpen & !resetDone) { + logger.info("reset on first open"); + resetDone = true; + reset(); + try { + Thread.sleep(resetTimeout); + } catch (InterruptedException e) { + // + } + open(configuration, interface_, altinterface); + } + } + + /** + * Release the claimed interface and close the opened device.
+ * + * @throws USBException + */ + public void close() throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + release_interface(usbDevHandle, dev_interface); + if (LibusbJava.usb_close(usbDevHandle) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_close: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = 0; + maxPacketSize = -1; + logger.info("device closed"); + } + + /** + * Sends an USB reset to the device. The device handle will no longer be + * valid. To use the device again, {@link #open(int, int, int)} must be + * called.
+ * Note that the device is re-attached to the USB which may cause the bus + * and filename to be changed. If the bus and filename parameters are used + * in {@link USB#getDevice(short, short, String, String)} unregister the + * device using {@link USB#unregisterDevice(Device)}, re-enumerate the bus + * and create a new device instance. If that is not done the device may not + * be found. + * + * @throws USBException + */ + public void reset() throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + release_interface(usbDevHandle, dev_interface); + if (LibusbJava.usb_reset(usbDevHandle) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_reset: " + + LibusbJava.usb_strerror()); + } + usbDevHandle = 0; + logger.info("device reset"); + } + + /** + * Write data to the device using a bulk transfer.
+ * + * @param out_ep_address + * endpoint address to write to + * @param data + * data to write to this endpoint + * @param size + * size of the data + * @param timeout + * amount of time in ms the device will try to send the data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send the data again before a timeout exception is thrown + * @return the actual number of bytes written + * @throws USBException + */ + public int writeBulk(int out_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenWritten = LibusbJava.usb_bulk_write(usbDevHandle, + out_ep_address, data, size, timeout); + if (lenWritten < 0) { + if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return writeBulk(out_ep_address, data, size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.usb_bulk_write: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_bulk_write: " + + LibusbJava.usb_strerror()); + } + + logger.info("length written: " + lenWritten); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("bulkwrite, ep 0x" + + Integer.toHexString(out_ep_address) + ": " + lenWritten + + " Bytes sent: "); + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenWritten; + } + + /** + * Read data from the device using a bulk transfer.
+ * + * @param in_ep_address + * endpoint address to read from + * @param data + * data buffer for the data to be read + * @param size + * the maximum requested data size + * @param timeout + * amount of time in ms the device will try to receive data until + * a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * receive the data again before a timeout exception is thrown + * @return the actual number of bytes read + * @throws USBException + */ + public int readBulk(int in_ep_address, byte[] data, int size, int timeout, + boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenRead = LibusbJava.usb_bulk_read(usbDevHandle, in_ep_address, + data, size, timeout); + if (lenRead < 0) { + if (lenRead == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return readBulk(in_ep_address, data, size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.usb_bulk_read: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_bulk_read: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read: " + lenRead); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("bulkread, ep 0x" + + Integer.toHexString(in_ep_address) + ": " + lenRead + + " Bytes received: "); + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenRead; + } + + /** + * Write data to the device using a interrupt transfer.
+ * + * @param out_ep_address + * endpoint address to write to + * @param data + * data to write to this endpoint + * @param size + * size of the data + * @param timeout + * amount of time in ms the device will try to send the data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send the data again before a timeout exception is thrown + * @return the actual number of bytes written + * @throws USBException + */ + public int writeInterrupt(int out_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenWritten = LibusbJava.usb_interrupt_write(usbDevHandle, + out_ep_address, data, size, timeout); + if (lenWritten < 0) { + if (lenWritten == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return writeInterrupt(out_ep_address, data, size, timeout, + false); + } + throw new USBTimeoutException( + "LibusbJava.usb_interrupt_write: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_interrupt_write: " + + LibusbJava.usb_strerror()); + } + + logger.info("length written: " + lenWritten); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("interruptwrite, ep 0x" + + Integer.toHexString(out_ep_address) + ": " + lenWritten + + " Bytes sent: "); + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenWritten; + } + + /** + * Read data from the device using a interrupt transfer.
+ * + * @param in_ep_address + * endpoint address to read from + * @param data + * data buffer for the data to be read + * @param size + * the maximum requested data size + * @param timeout + * amount of time in ms the device will try to receive data until + * a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * receive the data again before a timeout exception is thrown + * @return the actual number of bytes read + * @throws USBException + */ + public int readInterrupt(int in_ep_address, byte[] data, int size, + int timeout, boolean reopenOnTimeout) throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size <= 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int lenRead = LibusbJava.usb_interrupt_read(usbDevHandle, + in_ep_address, data, size, timeout); + if (lenRead < 0) { + if (lenRead == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return readInterrupt(in_ep_address, data, size, timeout, + false); + } + throw new USBTimeoutException("LibusbJava.usb_interrupt_read: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.usb_interrupt_read: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read: " + lenRead); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("interrupt, ep 0x" + + Integer.toHexString(in_ep_address) + ": " + lenRead + + " Bytes received: "); + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return lenRead; + } + + /** + * Performs a control request to the default control pipe on a device.
+ * The parameters mirror the types of the same name in the USB + * specification. + * + * @param requestType + * USB device request type (USB specification 9.3, + * bmRequestType). Use constants from {@link ch.ntb.inf.libusbJava.USB} + * (REQ_TYPE_xxx). + * @param request + * specific request (USB specification 9.4, bRequest). Use + * constants from {@link ch.ntb.inf.libusbJava.USB} (REQ_xxx). + * @param value + * field that varies according to request (USB specification 9.4, + * wValue) + * @param index + * field that varies according to request (USB specification 9.4, + * wIndex) + * @param data + * the send/receive buffer + * @param size + * the buffer size. 0 is a valid value, but there must still be a + * dummy data buffer provided. + * @param timeout + * amount of time in ms the device will try to send/receive data + * until a timeout exception is thrown + * @param reopenOnTimeout + * if set to true, the device will try to open the connection and + * send/receive the data again before a timeout exception is + * thrown + * @return the number of bytes written/read + * @throws USBException + */ + public int controlMsg(int requestType, int request, int value, int index, + byte[] data, int size, int timeout, boolean reopenOnTimeout) + throws USBException { + if (usbDevHandle == 0) { + throw new USBException("invalid device handle"); + } + if (data == null) { + throw new USBException("data must not be null"); + } + if (size < 0 || size > data.length) { + throw new ArrayIndexOutOfBoundsException("invalid size: " + size); + } + int len = LibusbJava.usb_control_msg(usbDevHandle, requestType, + request, value, index, data, size, timeout); + if (len < 0) { + if (len == LibusbJava.ERROR_TIMEDOUT) { + // try to reopen the device and send the data again + if (reopenOnTimeout) { + logger.info("try to reopen"); + reset(); + open(dev_configuration, dev_interface, dev_altinterface); + return controlMsg(requestType, request, value, index, data, + size, timeout, false); + } + throw new USBTimeoutException("LibusbJava.controlMsg: " + + LibusbJava.usb_strerror()); + } + throw new USBException("LibusbJava.controlMsg: " + + LibusbJava.usb_strerror()); + } + + logger.info("length read/written: " + len); + if (logger.isLoggable(Level.FINEST)) { + StringBuffer sb = new StringBuffer("controlMsg: " + len + + " Bytes received(written: "); + for (int i = 0; i < len; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } + return len; + } + + /** + * Claim an interface to send and receive USB data.
+ * + * @param usb_dev_handle + * the handle of the device (MUST BE VALID) + * @param configuration + * the configuration to use + * @param interface_ + * the interface to claim + * @param altinterface + * the alternate interface to use. If no alternate interface must + * be set -1 can be used. + * @throws USBException + * throws an USBException if the action fails + */ + private void claim_interface(long usb_dev_handle, int configuration, + int interface_, int altinterface) throws USBException { + if (LibusbJava.usb_set_configuration(usb_dev_handle, configuration) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_set_configuration: " + + LibusbJava.usb_strerror()); + } + if (LibusbJava.usb_claim_interface(usb_dev_handle, interface_) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_claim_interface: " + + LibusbJava.usb_strerror()); + } + if (altinterface >= 0) { + if (LibusbJava.usb_set_altinterface(usb_dev_handle, altinterface) < 0) { + try { + release_interface(usb_dev_handle, interface_); + } catch (USBException e) { + // ignore + } + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_set_altinterface: " + + LibusbJava.usb_strerror()); + } + } + logger.info("interface claimed"); + } + + /** + * Release a previously claimed interface.
+ * + * @param dev_handle + * the handle of the device (MUST BE VALID) + * @param interface_ + * the interface to claim + * @throws USBException + * throws an USBException if the action fails + */ + private void release_interface(long dev_handle, int interface_) + throws USBException { + if (LibusbJava.usb_release_interface(dev_handle, interface_) < 0) { + usbDevHandle = 0; + throw new USBException("LibusbJava.usb_release_interface: " + + LibusbJava.usb_strerror()); + } + logger.info("interface released"); + } + + /** + * Returns the product ID of the device.
+ * + * @return the product ID of the device. + */ + public int getIdProduct() { + return idProduct; + } + + /** + * Returns the vendor ID of the device.
+ * + * @return the vendor ID of the device. + */ + public int getIdVendor() { + return idVendor; + } + + /** + * Returns the alternative interface.
+ * This value is only valid after opening the device. + * + * @return the alternative interface. This value is only valid after opening + * the device. + */ + public int getAltinterface() { + return dev_altinterface; + } + + /** + * Returns the current configuration used.
+ * This value is only valid after opening the device. + * + * @return the current configuration used. This value is only valid after + * opening the device. + */ + public int getConfiguration() { + return dev_configuration; + } + + /** + * Returns the current interface.
+ * This value is only valid after opening the device. + * + * @return the current interface. This value is only valid after opening the + * device. + */ + public int getInterface() { + return dev_interface; + } + + /** + * Returns the maximum packet size in bytes which is allowed to be + * transmitted at once.
+ * The value is determined by reading the endpoint descriptor(s) when + * opening the device. It is invalid before the device is opened! Note that + * if some endpoints use different packet sizes the maximum packet size is + * return. This value may be used to determine if a device is opened in + * fullspeed or highspeed mode. + * + * @return the maximum packet size + */ + public int getMaxPacketSize() { + return maxPacketSize; + } + + /** + * Check if the device is open, attached and work.
+ * + * @return true if the device is open and work. + */ + public boolean isOpen() { + if(usbDevHandle != 0){ + try { + updateDescriptors(); + } catch (USBException e) { + return false; + } + return dev != null; + } + return false; + } + + /** + * If enabled, the device is reset when first opened.
+ * This will only happen once. When the application is started, the device + * state is unknown. If the device is not reset, read or write may result in + * a {@link USBTimeoutException}.
+ *
+ * This feature is disabled by default. + * + * @param enable + * true if the device should be reset when first opened + * @param timeout + * the timeout between the reset and the reopening + */ + public void setResetOnFirstOpen(boolean enable, int timeout) { + resetOnFirstOpen = enable; + resetTimeout = timeout; + } + + /** + * Returns the optional filename which is set when there are multiple + * devices with the same vendor and product id. See + * {@link USB#getDevice(short, short, String, String)}. Use + * {@link Usb_Device#getFilename()} to read the filename of a device. + * + * @return the filename or null + */ + protected String getFilename() { + return filename; + } + + /** + * Returns the optional bus name which is set when there are multiple + * devices with the same vendor and product id. See + * {@link USB#getDevice(short, short, String, String)}. Use + * {@link Usb_Bus#getDirname()} to read the name of a bus. + * + * @return the bus name or null + */ + protected String getBusName() { + return busName; + } + + /** + * Returns the Usb_Device instance associated with this device. This value + * is only valid after opening the device. + * + * @return the Usb_Device instance associated with this device. + */ + public Usb_Device getDevice() { + return dev; + } + + @Override + public String toString() { + return "idVendor: 0x" + Integer.toHexString(getIdVendor() & 0xffff) + + ", idProduct: 0x" + + Integer.toHexString(getIdProduct() & 0xffff) + ", busName: " + + getBusName() + ", filename: " + getFilename(); + } + +} diff --git a/java/src/ch/ntb/inf/libusbJava/LibusbJava.java b/src/main/java/ch/ntb/inf/libusbJava/LibusbJava.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/LibusbJava.java rename to src/main/java/ch/ntb/inf/libusbJava/LibusbJava.java index c15887f..506e943 100644 --- a/java/src/ch/ntb/inf/libusbJava/LibusbJava.java +++ b/src/main/java/ch/ntb/inf/libusbJava/LibusbJava.java @@ -1,734 +1,734 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - * - * Changes: - * 12.04.2012 NTB / Ueli Niederer implemented exception handling - * 18.10.2010 NTB / Roger Millischer change from native interface to compatibility layer - * - */ -package ch.ntb.inf.libusbJava; - -import ch.ntb.inf.libusbJava.exceptions.LibusbError; - -/** - * This class is used as compatibility layer for libusb 0.1 projects. - * - * @deprecated This class will not be subject to test anymore. Be aware that possible - * modifications could always break the functionality. For new - * projects only use {@link LibusbJava1}. - */ -public class LibusbJava { - - private static Usb_Bus busses = null; - private static long defaultCTX = 0; - /** - * System error codes.
- * This list is not complete! For more error codes see the file 'errorno.h' - * on your system. - */ - public static final int ERROR_SUCCESS = LibusbError.ERROR_NONE; - public static final int ERROR_BUSY = LibusbError.ERROR_BUSY; - public static final int ERROR_INVALID_PARAMETER = LibusbError.ERROR_INVALID_PARAM; - public static final int ERROR_TIMEDOUT = LibusbError.ERROR_TIMEOUT; - public static final int ERROR_IO_ERROR = LibusbError.ERROR_IO; - public static final int ERROR_NOT_ENOUGH_MEMORY = LibusbError.ERROR_NO_MEM; - - /** - * Sets the debugging level of libusb.
- * - * The range is from 0 to 255, where 0 disables debug output and 255 enables - * all output. On application start, debugging is disabled (0). - * - * @param level - * 0 to 255 - */ - public static void usb_set_debug(int level) { - LibusbJava1.libusb_set_debug(0, level); - } - - // Core - /** - * Just like the name implies, usb_init sets up some internal - * structures. usb_init must be called before any other libusb - * functions. - */ - public static void usb_init() { - if (defaultCTX != 0) { - return; - } - try { - defaultCTX = LibusbJava1.libusb_init(); - } catch (LibusbError e) { - System.err.println("LibusbJava-1.0 init failed with errorcode: " - + e.getMessage()); - e.printStackTrace(); - defaultCTX = 0; - } - LibusbJava1.libusb_set_debug(0, 0); - } - - /** - * usb_find_busses will find all of the busses on the system. - * - * @return the number of changes since previous call to this function (total - * of new busses and busses removed). - */ - public static int usb_find_busses() { - int changes = 0; - long tmpBusNumber; - Usb_Bus nbusses = null; - Usb_Bus bus = nbusses, tmp; - boolean found = false; - Usb_Device devices = null; - devices = LibusbJava1.libusb_get_device_list(0); - - // no busses - if (devices.getDevnum() == -1) { - while (busses != null) { - changes++; - busses = busses.getNext(); - } - return changes; - } - // find busses - while (devices != null) { - tmpBusNumber = (long) LibusbJava1.libusb_get_bus_number(devices); - while (bus != null) { - if (bus.getLocation() == tmpBusNumber) { - found = true; - break; - } - bus = bus.getNext(); - } - if (found) { - devices = devices.getNext(); - found = false; - continue; - } - if (nbusses == null) { - nbusses = new Usb_Bus(Long.toString(tmpBusNumber), tmpBusNumber); - } else { - tmp = new Usb_Bus(Long.toString(tmpBusNumber), tmpBusNumber); - bus = nbusses; - // append - while (bus.getNext() != null) { - bus = bus.getNext(); - } - tmp.setPrev(bus); - bus.setNext(tmp); - } - bus = nbusses; - devices = devices.getNext(); - } - // compare to existing bus-list - bus = busses; - tmp = nbusses; - found = false; - while (bus != null) { - tmpBusNumber = bus.getLocation(); - while (tmp != null) { - if (tmpBusNumber == tmp.getLocation()) { - found = true; - // remove from nbusses list - if (tmp.getPrev() != null) { - tmp.getPrev().setNext(tmp.getNext()); - } else { - nbusses = tmp.getNext(); - } - if (tmp.getNext() != null) { - tmp.getNext().setPrev(tmp.getPrev()); - } - break; - } - tmp = tmp.getNext(); - } - if (!found) { - // remove from busses an increment changes - if (bus.getPrev() != null) { - bus.getPrev().setNext(bus.getNext()); - } else { - busses = bus.getNext(); - } - if (bus.getNext() != null) { - bus.getNext().setPrev(bus.getPrev()); - } - changes++; - } - bus = bus.getNext(); - tmp = nbusses; - found = false; - } - // add new busses - bus = busses; - while (tmp != null) { - tmp = tmp.getNext(); - changes++; - } - if (busses != null) { - while (bus.getNext() != null) { - bus = bus.getNext(); - } - bus.setNext(nbusses); - } else { - busses = nbusses; - } - return changes; - } - - /** - * usb_find_devices will find all of the devices on each bus. - * This should be called after usb_find_busses. - * - * @return the number of changes since the previous call to this function - * (total of new device and devices removed). - */ - public static int usb_find_devices() { - int changes = 0; - byte tmpDevnum; - long tmpBusNumber; - Usb_Bus bus = busses; - boolean found = false; - Usb_Device devices, dev, ndev; - - devices = LibusbJava1.libusb_get_device_list(0); - // Compare to existing bus-structure and remove removed devices - while (bus != null) { - dev = bus.getDevices(); - while (dev != null) { - tmpDevnum = dev.getDevnum(); - ndev = devices; - while (ndev != null) { - // if dev already exist remove from ndev list - if (tmpDevnum == ndev.getDevnum()) { - found = true; - if (ndev.getPrev() != null) { - ndev.getPrev().setNext(ndev.getNext()); - } else { - devices = ndev.getNext(); - } - if (ndev.getNext() != null) { - ndev.getNext().setPrev(ndev.getPrev()); - } - break; - } - ndev = ndev.getNext(); - } - if (!found) { - // remove device from bus an increment changes - if (dev.getPrev() != null) { - dev.getPrev().setNext(dev.getNext()); - } else { - bus.setDevices(dev.getNext()); - } - if (dev.getNext() != null) { - dev.getNext().setPrev(dev.getPrev()); - } - changes++; - } else { - found = false; - } - dev = dev.getNext(); - } - bus = bus.getNext(); - } - // Add new Devices - bus = busses; - while (devices != null) { - ndev = devices.getNext(); - // find correct bus - tmpBusNumber = (long) LibusbJava1.libusb_get_bus_number(devices); - while (bus != null) { - if (bus.getLocation() == tmpBusNumber) { - break; - } - bus = bus.getNext(); - } - // insert device - if (bus != null) { - if (bus.getDevices() == null) { - devices.setNext(null); - } else { - devices.setNext(bus.getDevices()); - devices.getNext().setPrev(devices); - } - devices.setPrev(null); - bus.setDevices(devices); - devices.setBus(bus); - changes++; - } - devices = ndev; - bus = busses; - } - return changes; - } - - /** - * usb_get_busses returns a tree of descriptor objects.
- * The tree represents the bus structure with devices, configurations, - * interfaces and endpoints. Note that this is only a copy. To refresh the - * information, usb_get_busses() must be called again.
- * The name of the objects contained in the tree is starting with - * Usb_. - * - * @return the structure of all busses and devices. Note: The - * java objects are copies of the C structs. - */ - public static Usb_Bus usb_get_busses() { - return busses; - } - - // Device Operations - /** - * usb_open is to be used to open up a device for use. - * usb_open must be called before attempting to perform any - * operations to the device. - * - * @param dev - * The device to open. - * @return a handle used in future communication with the device. 0 if an - * error has occurred. - */ - public static long usb_open(Usb_Device dev) { - long handle = 0; - - try { - handle = LibusbJava1.libusb_open(dev); - } - catch (LibusbError e) { - System.err.println("LibusbJava-1.0 failed with errorcode: " - + e.getMessage()); - e.printStackTrace(); - handle = 0; - } - - return handle; - } - - /** - * usb_close closes a device opened with usb_open. - * - * @param dev_handle - * The handle to the device. - * @return 0 - */ - public static int usb_close(long dev_handle) { - LibusbJava1.libusb_close(dev_handle); - return 0; - } - - /** - * Sets the active configuration of a device - * - * @param dev_handle - * The handle to the device. - * @param configuration - * The value as specified in the descriptor field - * bConfigurationValue. - * @return 0 on success or < 0 on error. - */ - public static int usb_set_configuration(long dev_handle, int configuration) { - int result = 0; - - try { - LibusbJava1.libusb_set_configuration(dev_handle, configuration); - } catch (LibusbError e) { - result = -1; - } - - return result; - } - - /** - * Sets the active alternate setting of the current interface - * - * @param dev_handle - * The handle to the device. - * @param alternate - * The value as specified in the descriptor field - * bAlternateSetting. - * @return 0 on success or < 0 on error. - */ - public static int usb_set_altinterface(long dev_handle, int alternate) { - Usb_Device dev = LibusbJava1.libusb_get_device(dev_handle); - int nofInterfaces = LibusbJava1 - .libusb_get_active_config_descriptor(dev).getBNumInterfaces(); - int interface_number, success = 0; - for (interface_number = 0; interface_number < nofInterfaces; interface_number++) { - try - { - LibusbJava1.libusb_release_interface(dev_handle, interface_number); - - try - { - LibusbJava1.libusb_claim_interface(dev_handle, interface_number); - } - catch (LibusbError e) - { - return e.getErrorCode(); - } - break; - } - catch (LibusbError e) - { - /* Move ahead. */ - } - } - - try { - LibusbJava1.libusb_set_interface_alt_setting(dev_handle, interface_number, alternate); - success = 0; - } - catch (LibusbError e) { - success = -1; - } - - return success; - } - - /** - * Clears any halt status on an endpoint. - * - * @param dev_handle - * The handle to the device. - * @param ep - * The value specified in the descriptor field bEndpointAddress. - * @return 0 on success or < 0 on error. - */ - public static int usb_clear_halt(long dev_handle, int ep) { - int result = 0; - - try { - LibusbJava1.libusb_clear_halt(dev_handle, (short) ep); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - /** - * Resets a device by sending a RESET down the port it is connected to.
- *
- * Causes re-enumeration: After calling usb_reset, the - * device will need to re-enumerate and thusly, requires you to find the new - * device and open a new handle. The handle used to call - * usb_reset will no longer work. - * - * @param dev_handle - * The handle to the device. - * @return 0 on success or < 0 on error. - */ - public static int usb_reset(long dev_handle) { - int res = 0; - - try { - LibusbJava1.libusb_claim_interface(dev_handle, 0); - try { - LibusbJava1.libusb_reset_device(dev_handle); - } - catch (LibusbError e) { - res = e.getErrorCode(); - } - LibusbJava1.libusb_release_interface(dev_handle, 0); - LibusbJava1.libusb_close(dev_handle); - } catch (LibusbError e) { - /* Ignore all errors of these calls */ - } - - return res; - - } - - /** - * Claim an interface of a device.
- *
- * Must be called!: usb_claim_interface must be called - * before you perform any operations related to this interface (like - * usb_set_altinterface, usb_bulk_write, etc). - * - * @param dev_handle - * The handle to the device. - * @param interface_ - * The value as specified in the descriptor field - * bInterfaceNumber. - * @return 0 on success or < 0 on error. - */ - public static int usb_claim_interface(long dev_handle, int interface_) { - int result = 0; - - try { - LibusbJava1.libusb_claim_interface(dev_handle, interface_); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - /** - * Releases a previously claimed interface - * - * @param dev_handle - * The handle to the device. - * @param interface_ - * The value as specified in the descriptor field - * bInterfaceNumber. - * @return 0 on success or < 0 on error. - */ - public static int usb_release_interface(long dev_handle, int interface_) { - int result = 0; - - try { - LibusbJava1.libusb_release_interface(dev_handle, interface_); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - // Control Transfers - /** - * Performs a control request to the default control pipe on a device. The - * parameters mirror the types of the same name in the USB specification. - * - * @param dev_handle - * The handle to the device. - * @param requesttype - * @param request - * @param value - * @param index - * @param bytes - * @param size - * @param timeout - * @return the number of bytes written/read or < 0 on error. - */ - public static int usb_control_msg(long dev_handle, int requesttype, - int request, int value, int index, byte[] bytes, int size, - int timeout) { - return LibusbJava1.libusb_control_transfer(dev_handle, requesttype, - request, value, index, bytes, size, timeout); - } - - /** - * Retrieves the string descriptor specified by index and langid from a - * device. - * - * @param dev_handle - * The handle to the device. - * @param index - * @param langid - * @return the descriptor String or null - */ - public static String usb_get_string(long dev_handle, int index, int langid) { - String result; - - try { - result = LibusbJava1.libusb_get_string_descriptor(dev_handle, (short) index, langid, 255); - } catch (LibusbError e) { - result = null; - } - - return result; - } - - /** - * usb_get_string_simple is a wrapper around - * usb_get_string that retrieves the string description - * specified by index in the first language for the descriptor. - * - * @param dev_handle - * The handle to the device. - * @param index - * @return the descriptor String or null - */ - public static String usb_get_string_simple(long dev_handle, int index) { - String result = null; - - try { - result = LibusbJava1.libusb_get_string_descriptor_ascii(dev_handle,(short) index, 255); - } catch (LibusbError e) { - result = null; - } - - return result; - } - - /** - * Retrieves a descriptor from the device identified by the type and index - * of the descriptor from the default control pipe.
- *
- * See {@link #usb_get_descriptor_by_endpoint(long, int, byte, byte, int)} - * for a function that allows the control endpoint to be specified. - * - * @param dev_handle - * The handle to the device. - * @param type - * @param index - * @param size - * number of charactes which will be retrieved (the length of the - * resulting String) - * @return the descriptor String or null - */ - public static byte[] usb_get_descriptor(long dev_handle, byte type, - byte index, int size) { - byte[] result = null; - - try { - result = LibusbJava1.libusb_get_descriptor(dev_handle, type, index, size); - } catch (LibusbError e) { - e.printStackTrace(); - } - - return result; - } - - /** - * Retrieves a descriptor from the device identified by the type and index - * of the descriptor from the control pipe identified by ep. - * - * @param dev_handle - * The handle to the device. - * @param ep - * @param type - * @param index - * @param size - * number of charactes which will be retrieved (the length of the - * resulting String) - * @return the descriptor String or null - */ - public static String usb_get_descriptor_by_endpoint(long dev_handle, - int ep, byte type, byte index, int size) { - - // We just send a control message directly; - byte data[] = new byte[size]; - char string[] = new char[size]; - int transfered; - transfered = LibusbJava1.libusb_control_transfer(dev_handle, - 0x80 | (ep & 0xFF), 0x07, (type << 8) | index, 0, data, size, - 1000); - if (transfered > 0) { - for (int i = 0; i < transfered; i++) { - string[i] = (char) data[i]; - } - return String.valueOf(string); - } - return null; - } - - // Bulk Transfers - /** - * Performs a bulk write request to the endpoint specified by ep. - * - * @param dev_handle - * The handle to the device. - * @param ep - * @param bytes - * @param size - * @param timeout - * @return the number of bytes written on success or < 0 on error. - */ - public static int usb_bulk_write(long dev_handle, int ep, byte[] bytes, - int size, int timeout) { - int result = LibusbError.ERROR_OTHER; - - try { - result = LibusbJava1.libusb_bulk_transfer(dev_handle, (byte) ep, - bytes, size, timeout); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - /** - * Performs a bulk read request to the endpoint specified by ep. - * - * @param dev_handle - * The handle to the device. - * @param ep - * @param bytes - * @param size - * @param timeout - * @return the number of bytes read on success or < 0 on error. - */ - public static int usb_bulk_read(long dev_handle, int ep, byte[] bytes, - int size, int timeout) { - int result = LibusbError.ERROR_OTHER; - - try { - result = LibusbJava1.libusb_bulk_transfer(dev_handle, (byte) ep, - bytes, size, timeout); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - // Interrupt Transfers - /** - * Performs an interrupt write request to the endpoint specified by ep. - * - * @param dev_handle - * The handle to the device. - * @param ep - * @param bytes - * @param size - * @param timeout - * @return the number of bytes written on success or < 0 on error. - */ - public static int usb_interrupt_write(long dev_handle, int ep, - byte[] bytes, int size, int timeout) { - int result = LibusbError.ERROR_OTHER; - - try { - result = LibusbJava1.libusb_interrupt_transfer(dev_handle, (byte) ep, - bytes, size, timeout); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - /** - * Performs a interrupt read request to the endpoint specified by ep. - * - * @param dev_handle - * The handle to the device. - * @param ep - * @param bytes - * @param size - * @param timeout - * @return the number of bytes read on success or < 0 on error. - */ - public static int usb_interrupt_read(long dev_handle, int ep, byte[] bytes, - int size, int timeout) { - int result = LibusbError.ERROR_OTHER; - - try { - result = LibusbJava1.libusb_interrupt_transfer(dev_handle, (byte) ep, - bytes, size, timeout); - } catch (LibusbError e) { - result = e.getErrorCode(); - } - - return result; - } - - /** - * Returns the error string after an error occured. - * - * @return the last error sring. - */ - public static String usb_strerror() { - return LibusbJava1.libusb_strerror(); - } - +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + * + * Changes: + * 12.04.2012 NTB / Ueli Niederer implemented exception handling + * 18.10.2010 NTB / Roger Millischer change from native interface to compatibility layer + * + */ +package ch.ntb.inf.libusbJava; + +import ch.ntb.inf.libusbJava.exceptions.LibusbError; + +/** + * This class is used as compatibility layer for libusb 0.1 projects. + * + * @deprecated This class will not be subject to test anymore. Be aware that possible + * modifications could always break the functionality. For new + * projects only use {@link LibusbJava1}. + */ +public class LibusbJava { + + private static Usb_Bus busses = null; + private static long defaultCTX = 0; + /** + * System error codes.
+ * This list is not complete! For more error codes see the file 'errorno.h' + * on your system. + */ + public static final int ERROR_SUCCESS = LibusbError.ERROR_NONE; + public static final int ERROR_BUSY = LibusbError.ERROR_BUSY; + public static final int ERROR_INVALID_PARAMETER = LibusbError.ERROR_INVALID_PARAM; + public static final int ERROR_TIMEDOUT = LibusbError.ERROR_TIMEOUT; + public static final int ERROR_IO_ERROR = LibusbError.ERROR_IO; + public static final int ERROR_NOT_ENOUGH_MEMORY = LibusbError.ERROR_NO_MEM; + + /** + * Sets the debugging level of libusb.
+ * + * The range is from 0 to 255, where 0 disables debug output and 255 enables + * all output. On application start, debugging is disabled (0). + * + * @param level + * 0 to 255 + */ + public static void usb_set_debug(int level) { + LibusbJava1.libusb_set_debug(0, level); + } + + // Core + /** + * Just like the name implies, usb_init sets up some internal + * structures. usb_init must be called before any other libusb + * functions. + */ + public static void usb_init() { + if (defaultCTX != 0) { + return; + } + try { + defaultCTX = LibusbJava1.libusb_init(); + } catch (LibusbError e) { + System.err.println("LibusbJava-1.0 init failed with errorcode: " + + e.getMessage()); + e.printStackTrace(); + defaultCTX = 0; + } + LibusbJava1.libusb_set_debug(0, 0); + } + + /** + * usb_find_busses will find all of the busses on the system. + * + * @return the number of changes since previous call to this function (total + * of new busses and busses removed). + */ + public static int usb_find_busses() { + int changes = 0; + long tmpBusNumber; + Usb_Bus nbusses = null; + Usb_Bus bus = nbusses, tmp; + boolean found = false; + Usb_Device devices = null; + devices = LibusbJava1.libusb_get_device_list(0); + + // no busses + if (devices.getDevnum() == -1) { + while (busses != null) { + changes++; + busses = busses.getNext(); + } + return changes; + } + // find busses + while (devices != null) { + tmpBusNumber = (long) LibusbJava1.libusb_get_bus_number(devices); + while (bus != null) { + if (bus.getLocation() == tmpBusNumber) { + found = true; + break; + } + bus = bus.getNext(); + } + if (found) { + devices = devices.getNext(); + found = false; + continue; + } + if (nbusses == null) { + nbusses = new Usb_Bus(Long.toString(tmpBusNumber), tmpBusNumber); + } else { + tmp = new Usb_Bus(Long.toString(tmpBusNumber), tmpBusNumber); + bus = nbusses; + // append + while (bus.getNext() != null) { + bus = bus.getNext(); + } + tmp.setPrev(bus); + bus.setNext(tmp); + } + bus = nbusses; + devices = devices.getNext(); + } + // compare to existing bus-list + bus = busses; + tmp = nbusses; + found = false; + while (bus != null) { + tmpBusNumber = bus.getLocation(); + while (tmp != null) { + if (tmpBusNumber == tmp.getLocation()) { + found = true; + // remove from nbusses list + if (tmp.getPrev() != null) { + tmp.getPrev().setNext(tmp.getNext()); + } else { + nbusses = tmp.getNext(); + } + if (tmp.getNext() != null) { + tmp.getNext().setPrev(tmp.getPrev()); + } + break; + } + tmp = tmp.getNext(); + } + if (!found) { + // remove from busses an increment changes + if (bus.getPrev() != null) { + bus.getPrev().setNext(bus.getNext()); + } else { + busses = bus.getNext(); + } + if (bus.getNext() != null) { + bus.getNext().setPrev(bus.getPrev()); + } + changes++; + } + bus = bus.getNext(); + tmp = nbusses; + found = false; + } + // add new busses + bus = busses; + while (tmp != null) { + tmp = tmp.getNext(); + changes++; + } + if (busses != null) { + while (bus.getNext() != null) { + bus = bus.getNext(); + } + bus.setNext(nbusses); + } else { + busses = nbusses; + } + return changes; + } + + /** + * usb_find_devices will find all of the devices on each bus. + * This should be called after usb_find_busses. + * + * @return the number of changes since the previous call to this function + * (total of new device and devices removed). + */ + public static int usb_find_devices() { + int changes = 0; + byte tmpDevnum; + long tmpBusNumber; + Usb_Bus bus = busses; + boolean found = false; + Usb_Device devices, dev, ndev; + + devices = LibusbJava1.libusb_get_device_list(0); + // Compare to existing bus-structure and remove removed devices + while (bus != null) { + dev = bus.getDevices(); + while (dev != null) { + tmpDevnum = dev.getDevnum(); + ndev = devices; + while (ndev != null) { + // if dev already exist remove from ndev list + if (tmpDevnum == ndev.getDevnum()) { + found = true; + if (ndev.getPrev() != null) { + ndev.getPrev().setNext(ndev.getNext()); + } else { + devices = ndev.getNext(); + } + if (ndev.getNext() != null) { + ndev.getNext().setPrev(ndev.getPrev()); + } + break; + } + ndev = ndev.getNext(); + } + if (!found) { + // remove device from bus an increment changes + if (dev.getPrev() != null) { + dev.getPrev().setNext(dev.getNext()); + } else { + bus.setDevices(dev.getNext()); + } + if (dev.getNext() != null) { + dev.getNext().setPrev(dev.getPrev()); + } + changes++; + } else { + found = false; + } + dev = dev.getNext(); + } + bus = bus.getNext(); + } + // Add new Devices + bus = busses; + while (devices != null) { + ndev = devices.getNext(); + // find correct bus + tmpBusNumber = (long) LibusbJava1.libusb_get_bus_number(devices); + while (bus != null) { + if (bus.getLocation() == tmpBusNumber) { + break; + } + bus = bus.getNext(); + } + // insert device + if (bus != null) { + if (bus.getDevices() == null) { + devices.setNext(null); + } else { + devices.setNext(bus.getDevices()); + devices.getNext().setPrev(devices); + } + devices.setPrev(null); + bus.setDevices(devices); + devices.setBus(bus); + changes++; + } + devices = ndev; + bus = busses; + } + return changes; + } + + /** + * usb_get_busses returns a tree of descriptor objects.
+ * The tree represents the bus structure with devices, configurations, + * interfaces and endpoints. Note that this is only a copy. To refresh the + * information, usb_get_busses() must be called again.
+ * The name of the objects contained in the tree is starting with + * Usb_. + * + * @return the structure of all busses and devices. Note: The + * java objects are copies of the C structs. + */ + public static Usb_Bus usb_get_busses() { + return busses; + } + + // Device Operations + /** + * usb_open is to be used to open up a device for use. + * usb_open must be called before attempting to perform any + * operations to the device. + * + * @param dev + * The device to open. + * @return a handle used in future communication with the device. 0 if an + * error has occurred. + */ + public static long usb_open(Usb_Device dev) { + long handle = 0; + + try { + handle = LibusbJava1.libusb_open(dev); + } + catch (LibusbError e) { + System.err.println("LibusbJava-1.0 failed with errorcode: " + + e.getMessage()); + e.printStackTrace(); + handle = 0; + } + + return handle; + } + + /** + * usb_close closes a device opened with usb_open. + * + * @param dev_handle + * The handle to the device. + * @return 0 + */ + public static int usb_close(long dev_handle) { + LibusbJava1.libusb_close(dev_handle); + return 0; + } + + /** + * Sets the active configuration of a device + * + * @param dev_handle + * The handle to the device. + * @param configuration + * The value as specified in the descriptor field + * bConfigurationValue. + * @return 0 on success or < 0 on error. + */ + public static int usb_set_configuration(long dev_handle, int configuration) { + int result = 0; + + try { + LibusbJava1.libusb_set_configuration(dev_handle, configuration); + } catch (LibusbError e) { + result = -1; + } + + return result; + } + + /** + * Sets the active alternate setting of the current interface + * + * @param dev_handle + * The handle to the device. + * @param alternate + * The value as specified in the descriptor field + * bAlternateSetting. + * @return 0 on success or < 0 on error. + */ + public static int usb_set_altinterface(long dev_handle, int alternate) { + Usb_Device dev = LibusbJava1.libusb_get_device(dev_handle); + int nofInterfaces = LibusbJava1 + .libusb_get_active_config_descriptor(dev).getBNumInterfaces(); + int interface_number, success = 0; + for (interface_number = 0; interface_number < nofInterfaces; interface_number++) { + try + { + LibusbJava1.libusb_release_interface(dev_handle, interface_number); + + try + { + LibusbJava1.libusb_claim_interface(dev_handle, interface_number); + } + catch (LibusbError e) + { + return e.getErrorCode(); + } + break; + } + catch (LibusbError e) + { + /* Move ahead. */ + } + } + + try { + LibusbJava1.libusb_set_interface_alt_setting(dev_handle, interface_number, alternate); + success = 0; + } + catch (LibusbError e) { + success = -1; + } + + return success; + } + + /** + * Clears any halt status on an endpoint. + * + * @param dev_handle + * The handle to the device. + * @param ep + * The value specified in the descriptor field bEndpointAddress. + * @return 0 on success or < 0 on error. + */ + public static int usb_clear_halt(long dev_handle, int ep) { + int result = 0; + + try { + LibusbJava1.libusb_clear_halt(dev_handle, (short) ep); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + /** + * Resets a device by sending a RESET down the port it is connected to.
+ *
+ * Causes re-enumeration: After calling usb_reset, the + * device will need to re-enumerate and thusly, requires you to find the new + * device and open a new handle. The handle used to call + * usb_reset will no longer work. + * + * @param dev_handle + * The handle to the device. + * @return 0 on success or < 0 on error. + */ + public static int usb_reset(long dev_handle) { + int res = 0; + + try { + LibusbJava1.libusb_claim_interface(dev_handle, 0); + try { + LibusbJava1.libusb_reset_device(dev_handle); + } + catch (LibusbError e) { + res = e.getErrorCode(); + } + LibusbJava1.libusb_release_interface(dev_handle, 0); + LibusbJava1.libusb_close(dev_handle); + } catch (LibusbError e) { + /* Ignore all errors of these calls */ + } + + return res; + + } + + /** + * Claim an interface of a device.
+ *
+ * Must be called!: usb_claim_interface must be called + * before you perform any operations related to this interface (like + * usb_set_altinterface, usb_bulk_write, etc). + * + * @param dev_handle + * The handle to the device. + * @param interface_ + * The value as specified in the descriptor field + * bInterfaceNumber. + * @return 0 on success or < 0 on error. + */ + public static int usb_claim_interface(long dev_handle, int interface_) { + int result = 0; + + try { + LibusbJava1.libusb_claim_interface(dev_handle, interface_); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + /** + * Releases a previously claimed interface + * + * @param dev_handle + * The handle to the device. + * @param interface_ + * The value as specified in the descriptor field + * bInterfaceNumber. + * @return 0 on success or < 0 on error. + */ + public static int usb_release_interface(long dev_handle, int interface_) { + int result = 0; + + try { + LibusbJava1.libusb_release_interface(dev_handle, interface_); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + // Control Transfers + /** + * Performs a control request to the default control pipe on a device. The + * parameters mirror the types of the same name in the USB specification. + * + * @param dev_handle + * The handle to the device. + * @param requesttype + * @param request + * @param value + * @param index + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written/read or < 0 on error. + */ + public static int usb_control_msg(long dev_handle, int requesttype, + int request, int value, int index, byte[] bytes, int size, + int timeout) { + return LibusbJava1.libusb_control_transfer(dev_handle, requesttype, + request, value, index, bytes, size, timeout); + } + + /** + * Retrieves the string descriptor specified by index and langid from a + * device. + * + * @param dev_handle + * The handle to the device. + * @param index + * @param langid + * @return the descriptor String or null + */ + public static String usb_get_string(long dev_handle, int index, int langid) { + String result; + + try { + result = LibusbJava1.libusb_get_string_descriptor(dev_handle, (short) index, langid, 255); + } catch (LibusbError e) { + result = null; + } + + return result; + } + + /** + * usb_get_string_simple is a wrapper around + * usb_get_string that retrieves the string description + * specified by index in the first language for the descriptor. + * + * @param dev_handle + * The handle to the device. + * @param index + * @return the descriptor String or null + */ + public static String usb_get_string_simple(long dev_handle, int index) { + String result = null; + + try { + result = LibusbJava1.libusb_get_string_descriptor_ascii(dev_handle,(short) index, 255); + } catch (LibusbError e) { + result = null; + } + + return result; + } + + /** + * Retrieves a descriptor from the device identified by the type and index + * of the descriptor from the default control pipe.
+ *
+ * See {@link #usb_get_descriptor_by_endpoint(long, int, byte, byte, int)} + * for a function that allows the control endpoint to be specified. + * + * @param dev_handle + * The handle to the device. + * @param type + * @param index + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return the descriptor String or null + */ + public static byte[] usb_get_descriptor(long dev_handle, byte type, + byte index, int size) { + byte[] result = null; + + try { + result = LibusbJava1.libusb_get_descriptor(dev_handle, type, index, size); + } catch (LibusbError e) { + e.printStackTrace(); + } + + return result; + } + + /** + * Retrieves a descriptor from the device identified by the type and index + * of the descriptor from the control pipe identified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param type + * @param index + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return the descriptor String or null + */ + public static String usb_get_descriptor_by_endpoint(long dev_handle, + int ep, byte type, byte index, int size) { + + // We just send a control message directly; + byte data[] = new byte[size]; + char string[] = new char[size]; + int transfered; + transfered = LibusbJava1.libusb_control_transfer(dev_handle, + 0x80 | (ep & 0xFF), 0x07, (type << 8) | index, 0, data, size, + 1000); + if (transfered > 0) { + for (int i = 0; i < transfered; i++) { + string[i] = (char) data[i]; + } + return String.valueOf(string); + } + return null; + } + + // Bulk Transfers + /** + * Performs a bulk write request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written on success or < 0 on error. + */ + public static int usb_bulk_write(long dev_handle, int ep, byte[] bytes, + int size, int timeout) { + int result = LibusbError.ERROR_OTHER; + + try { + result = LibusbJava1.libusb_bulk_transfer(dev_handle, (byte) ep, + bytes, size, timeout); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + /** + * Performs a bulk read request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes read on success or < 0 on error. + */ + public static int usb_bulk_read(long dev_handle, int ep, byte[] bytes, + int size, int timeout) { + int result = LibusbError.ERROR_OTHER; + + try { + result = LibusbJava1.libusb_bulk_transfer(dev_handle, (byte) ep, + bytes, size, timeout); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + // Interrupt Transfers + /** + * Performs an interrupt write request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes written on success or < 0 on error. + */ + public static int usb_interrupt_write(long dev_handle, int ep, + byte[] bytes, int size, int timeout) { + int result = LibusbError.ERROR_OTHER; + + try { + result = LibusbJava1.libusb_interrupt_transfer(dev_handle, (byte) ep, + bytes, size, timeout); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + /** + * Performs a interrupt read request to the endpoint specified by ep. + * + * @param dev_handle + * The handle to the device. + * @param ep + * @param bytes + * @param size + * @param timeout + * @return the number of bytes read on success or < 0 on error. + */ + public static int usb_interrupt_read(long dev_handle, int ep, byte[] bytes, + int size, int timeout) { + int result = LibusbError.ERROR_OTHER; + + try { + result = LibusbJava1.libusb_interrupt_transfer(dev_handle, (byte) ep, + bytes, size, timeout); + } catch (LibusbError e) { + result = e.getErrorCode(); + } + + return result; + } + + /** + * Returns the error string after an error occured. + * + * @return the last error sring. + */ + public static String usb_strerror() { + return LibusbJava1.libusb_strerror(); + } + } \ No newline at end of file diff --git a/java/src/ch/ntb/inf/libusbJava/LibusbJava1.java b/src/main/java/ch/ntb/inf/libusbJava/LibusbJava1.java similarity index 97% rename from java/src/ch/ntb/inf/libusbJava/LibusbJava1.java rename to src/main/java/ch/ntb/inf/libusbJava/LibusbJava1.java index f0e5554..d1843fa 100644 --- a/java/src/ch/ntb/inf/libusbJava/LibusbJava1.java +++ b/src/main/java/ch/ntb/inf/libusbJava/LibusbJava1.java @@ -1,1427 +1,1427 @@ -/** - * Java libusb1.0 wrapper - * Roger Millischer - * - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -import ch.ntb.inf.libusbJava.exceptions.LibusbError; - -/** - * This class represents the Java Native Interface to the shared library which - * is (with some exceptions) a one-to-one representation of the libusb1.0 API.
- *
- *

Project Description

Java libusb1.0 is a Java wrapper for the - * libusb1.0 USB library. - * - * libusb aim is to create a library for - * use by user level applications to access USB devices regardless of OS.
- * Libusb-Windows - * backend aim of this project is to bring a Windows backend to the mainline - * libusb 1.0 branch, so that libusb 1.0 can easily be used on Windows - * platforms. The library allows user space applications to access any USB - * device on Windows in a generic way without writing any line of kernel driver - * code.
- *
- * The API description of this class has been copied from the libusb-1.0 API - * Reference and adapted where neccessary.
- * - */ -public class LibusbJava1 { - /** - * Set message verbosity. - *
    - *
  • Level 0: no messages ever printed by the library (default)
  • - *
  • Level 1: error messages are printed to stderr
  • - *
  • Level 2: warning and error messages are printed to stderr
  • - *
  • Level 3: informational messages are printed to stdout, warning and - * error messages are printed to stderr
  • - *
- * - * The default level is 0, which means no messages are ever printed. If you - * choose to increase the message verbosity level, ensure that your - * application does not close the stdout/stderr file descriptors.
- *
- * You are advised to set level 3. libusb is conservative with its message - * logging and most of the time, will only log messages that explain error - * conditions and other oddities. This will help you debug your software.
- *
- * If the LIBUSB_DEBUG environment variable was set when libusb was - * initialized, this function does nothing: the message verbosity is fixed - * to the value in the environment variable.
- *
- * If libusb was compiled without any message logging, this function does - * nothing: you'll never get any messages.
- *
- * If libusb was compiled with verbose debug message logging, this function - * does nothing: you'll always get messages from all levels.
- *
- * - * @param ctx - * the context to operate on, or NULL for the default context - * @param level - * debug level to set - */ - - public static native void libusb_set_debug(long ctx, int level); - - /** - * Initialize libusb.
- *
- * This function must be called before calling any other libusb function.
- *
- * - * @return a context to operate on - * @throws LibusbError - * if an error occured - */ - public static native long libusb_init() throws LibusbError; - - /** - * Deinitialize libusb.
- *
- * Should be called after closing all open devices and before your - * application terminates.
- *
- * - * @param ctx - * the context to deinitialize, or 0 if the default context has - * been used. - */ - public static native void libusb_exit(long ctx); - - /** - * Returns a list of USB devices currently attached to the system.
- *
- * This is your entry point into finding a USB device to operate.
- *
- * - * @param ctx - * the context to operate on, or NULL for the default context - * - * @return Usb_Devices currently attached to the system
- * if no device is attached the devnum of the returned device is set - * to -1
- * or NULL if an error occurs - */ - public static native Usb_Device libusb_get_device_list(long ctx); - - /** - * Get the number of the bus that a device is connected to. - * - * @param dev - * a device - * @return the bus number - */ - public static native short libusb_get_bus_number(Usb_Device dev); - - /** - * Calculate the maximum packet size which a specific endpoint is capable is - * sending or receiving in the duration of 1 microframe.
- *
- * Only the active configution is examined. The calculation is based on the - * wMaxPacketSize field in the endpoint descriptor as described in section - * 9.6.6 in the USB 2.0 specifications.
- *
- * If acting on an isochronous or interrupt endpoint, this function will - * multiply the value found in bits 0:10 by the number of transactions per - * microframe (determined by bits 11:12). Otherwise, this function just - * returns the numeric value found in bits 0:10.
- *
- * This function is useful for setting up isochronous transfers, for example - * you might pass the return value from this function to - * libusb_set_iso_packet_lengths() in order to set the length - * field of every isochronous packet in a transfer.
- *
- * Since libusb v1.0.3.
- *
- * This functionality is not available on Windows-Systems
- *
- * - * @param dev - * a device - * @param endpoint - * address of the endpoint in question - * @return the maximum packet size which can be sent/received on this - * endpoint
- * LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
- * LIBUSB_ERROR_OTHER on other failure
- * TODO wenn funktion impl. richtig verlinken @see - * libusb_set_iso_packet_lengths() - */ - - public static native int libusb_get_max_iso_packet_size(Usb_Device dev, - short endpoint); - - /** - * Increment the reference count of a device. - * - * @param dev - * the device to reference - * @return the same device - */ - public static native Usb_Device libusb_ref_device(Usb_Device dev); - - /** - * Decrement the reference count of a device.
- *
- * If the decrement operation causes the reference count to reach zero, the - * device shall be destroyed.
- *
- * - * @param dev - * the device to unreference - */ - - public static native void libusb_unref_device(Usb_Device dev); - - /** - * Open a device and obtain a device handle.
- *
- * A handle allows you to perform I/O on the device in question.
- *
- * Internally, this function adds a reference to the device and makes it - * available to you through libusb_get_device(). This reference - * is removed during libusb_close().
- *
- * This is a non-blocking function; no requests are sent over the bus.
- *
- * - * @param dev - * the device to open - * - * @return a device handle >= 0 - * - * @throws LibusbError - * in case of an error
- * Possible causes are:
- * - ERROR_NO_MEM on memory allocation failure
- * - ERROR_ACCESS if the user has insufficient permissions
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another ERROR code on other failure - * - * @see #libusb_get_device(long) - */ - public static native long libusb_open(Usb_Device dev) throws LibusbError; - - /** - * Convenience function for finding a device with a particular - * idVendor/idProduct combination.
- *
- * This function is intended for those scenarios where you are using libusb - * to knock up a quick test application - it allows you to avoid calling - * libusb_get_device_list() and worrying about - * traversing/freeing the list.
- *
- * This function has limitations and is hence not intended for use in real - * applications: if multiple devices have the same IDs it will only give you - * the first one, etc.
- * - * @param ctx - * the context to operate on, or NULL for the default context - * @param vendor_id - * the idVendor value to search for - * @param product_id - * the idProduct value to search for - * @return a handle for the first found device, or NULL on error or if the - * device could not be found. - * @see #libusb_get_device_list(long) - */ - public static native long libusb_open_device_with_vid_pid(long ctx, - int vendor_id, int product_id); - - /** - * Close a device handle.
- *
- * Should be called on all open handles before your application exits.
- *
- * Internally, this function destroys the reference that was added by - * libusb_open() on the given device.
- *
- * This is a non-blocking function; no requests are sent over the bus.
- *
- * - * @param dev_handle - * the handle to close - */ - public static native void libusb_close(long dev_handle); - - /** - * Get the underlying device for a handle.
- *
- * This function does not modify the reference count of the returned device, - * so do not feel compelled to unreference it when you are done.
- *
- * - * @param dev_handle - * a device handle - * @return the underlying {@link Usb_Device} - */ - public static native Usb_Device libusb_get_device(long dev_handle); - - /** - * Determine the bConfigurationValue of the currently active configuration.
- *
- * You could formulate your own control request to obtain this information, - * but this function has the advantage that it may be able to retrieve the - * information from operating system caches (no I/O involved).
- *
- * If the OS does not cache this information, then this function will block - * while a control transfer is submitted to retrieve the information.
- *
- * This function will return a value of 0 if the device is in unconfigured - * state.
- *
- * - * @param dev_handle - * a device handle - * @return bConfigurationValue of the currently active configuration - * @throws LibusbError - * in case of an error
- * Possible error causes are:
- * - ERROR_NO_DEVICE if the device has been disconnected - - * another ERROR code on other failure - */ - public static native int libusb_get_configuration(long dev_handle) - throws LibusbError; - - /** - * Set the active configuration for a device.
- *
- * The operating system may or may not have already set an active - * configuration on the device. It is up to your application to ensure the - * correct configuration is selected before you attempt to claim interfaces - * and perform other operations.
- *
- * If you call this function on a device already configured with the - * selected configuration, then this function will act as a lightweight - * device reset: it will issue a SET_CONFIGURATION request using the current - * configuration, causing most USB-related device state to be reset - * (altsetting reset to zero, endpoint halts cleared, toggles reset).
- *
- * You cannot change/reset configuration if your application has claimed - * interfaces - you should free them with - * {@link #libusb_release_interface(long, int)} first. You cannot - * change/reset configuration if other applications or drivers have claimed - * interfaces.
- *
- * A configuration value of -1 will put the device in unconfigured state. - * The USB specifications state that a configuration value of 0 does this, - * however buggy devices exist which actually have a configuration 0.
- *
- * You should always use this function rather than formulating your own - * SET_CONFIGURATION control request. This is because the underlying - * operating system needs to know when such changes happen.
- *
- * This is a blocking function.
- *
- * - * @param dev_handle - * a device handle - * @param configuration - * the bConfigurationValue of the configuration you wish to - * activate, or -1 if you wish to put the device in unconfigured - * state - * @throws LibusbError - * in case of an error
- * Possible error causes are:
- * - ERROR_NOT_FOUND if the requested configuration does not - * exist
- * - ERROR_BUSY if interfaces are currently claimed
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another LIBUSB_ERROR code on other failure
- */ - public static native void libusb_set_configuration(long dev_handle, - int configuration) throws LibusbError; - - /** - * Claim an interface on a given device handle.
- *
- * You must claim the interface you wish to use before you can perform I/O - * on any of its endpoints.
- *
- * It is legal to attempt to claim an already-claimed interface, in which - * case libusb just returns 0 without doing anything.
- *
- * Claiming of interfaces is a purely logical operation, it does not cause - * any requests to be sent over the bus. Interface claiming is used to - * instruct the underlying operating system that your application wishes to - * take ownership of the interface.
- *
- * This is a non-blocking function.
- *
- * - * @param dev_handle - * a device handle - * @param interface_number - * the bInterfaceNumber of the interface you wish to claim - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if the interface was not claimed
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - ERROR_BUSY if another program or driver has claimed the - * interface
- * - another LIBUSB_ERROR code on other failure
- */ - public static native void libusb_claim_interface(long dev_handle, - int interface_number) throws LibusbError; - - /** - * Release an interface previously claimed with - * {@link #libusb_claim_interface(long, int)}.
- *
- * You should release all claimed interfaces before closing a device handle.
- *
- * This is a blocking function. A SET_INTERFACE control request will be sent - * to the device, resetting interface state to the first alternate setting.
- *
- * - * @param dev_handle - * a device handle - * @param interface_number - * the bInterfaceNumber of the previously-claimed interface - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if the interface was not claimed
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another ERROR code on other failure
- */ - public static native void libusb_release_interface(long dev_handle, - int interface_number) throws LibusbError; - - /** - * Activate an alternate setting for an interface.
- *
- * The interface must have been previously claimed with - * {@link #libusb_claim_interface(long, int)}.
- *
- * You should always use this function rather than formulating your own - * SET_INTERFACE control request. This is because the underlying operating - * system needs to know when such changes happen.
- *
- * This is a blocking function.
- *
- * - * @param dev_handle - * a device handle - * @param interface_number - * the bInterfaceNumber of the previously-claimed interface - * @param alternate_setting - * the bAlternateSetting of the alternate setting to activate - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if the interface was not claimed, or the - * requested alternate setting does not exist
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another LIBUSB_ERROR code on other failure
- */ - public static native void libusb_set_interface_alt_setting(long dev_handle, - int interface_number, int alternate_setting) throws LibusbError; - - /** - * Clear the halt/stall condition for an endpoint.
- *
- * Endpoints with halt status are unable to receive or transmit data until - * the halt condition is stalled.
- *
- * You should cancel all pending transfers before attempting to clear the - * halt condition.
- *
- * This is a blocking function.
- *
- * - * @param dev_handle - * a device handle - * @param endpoint - * the endpoint to clear halt status - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if the endpoint does not exist
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another LIBUSB_ERROR code on other failure
- */ - public static native void libusb_clear_halt(long dev_handle, short endpoint) - throws LibusbError; - - /** - * Perform a USB port reset to reinitialize a device.
- *
- * The system will attempt to restore the previous configuration and - * alternate settings after the reset has completed.
- *
- * If the reset fails, the descriptors change, or the previous state cannot - * be restored, the device will appear to be disconnected and reconnected. - * This means that the device handle is no longer valid (you should close - * it) and rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND - * indicates when this is the case.
- *
- * This is a blocking function which usually incurs a noticeable delay.
- *
- * - * @param dev_handle - * a handle of the device to reset - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if re-enumeration is required, or if the - * device has been disconnected
- * - another LIBUSB_ERROR code on other failure
- */ - public static native void libusb_reset_device(long dev_handle) - throws LibusbError; - - /** - * Determine if a kernel driver is active on an interface.
- *
- * If a kernel driver is active, you cannot claim the interface, and libusb - * will be unable to perform I/O.
- *
- * - * @param dev_handle - * a device handle - * @param interface_number - * the interface to check - * @return 0 if no kernel driver is active
- * 1 if a kernel driver is active
- * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another LIBUSB_ERROR code on other failure
- * @see #libusb_detach_kernel_driver(long, int) - */ - public static native int libusb_kernel_driver_active(long dev_handle, - int interface_number) throws LibusbError; - - /** - * Detach a kernel driver from an interface.
- *
- * If successful, you will then be able to claim the interface and perform - * I/O.
- *
- * - * @param dev_handle - * a device handle - * @param interface_number - * the interface to detach the driver from - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if no kernel driver was active
- * - ERROR_INVALID_PARAM if the interface does not exist
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another ERROR code on other failure
- * @see #libusb_kernel_driver_active(long, int) - */ - public static native void libusb_detach_kernel_driver(long dev_handle, - int interface_number) throws LibusbError; - - /** - * Re-attach an interface's kernel driver, which was previously detached - * using {@link #libusb_detach_kernel_driver(long, int)}.
- * - * @param dev_handle - * a device handle - * @param interface_number - * the interface to attach the driver from - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if no kernel driver was active
- * - ERROR_INVALID_PARAM if the interface does not exist
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - ERROR_BUSY if the driver cannot be attached because the - * interface is claimed by a program or driver
- * - another ERROR code on other failure
- * @see #libusb_kernel_driver_active(long, int) - */ - public static native void libusb_attach_kernel_driver(long dev_handle, - int interface_number) throws LibusbError; - - /** - * Get the USB configuration descriptor for the currently active - * configuration.
- *
- * This is a non-blocking function which does not involve any requests being - * sent to the device.
- *
- * - * @param dev - * a device - * @return {@link Usb_Config_Descriptor} - */ - public static native Usb_Config_Descriptor libusb_get_active_config_descriptor( - Usb_Device dev); - - /** - * Retrieve a string descriptor in C style ASCII.
- *
- * Wrapper around - * {@link #libusb_get_string_descriptor(long, short, int, int)}. Uses the - * first language supported by the device. - * - * @param dev_handle - * a device handle - * @param desc_index - * the index of the descriptor to retrieve - * @param size - * number of charactes which will be retrieved (the length of the - * resulting String) - * @return a string which contains the string descriptor - * @throws LibusbError - * in case of an error
- */ - public static native String libusb_get_string_descriptor_ascii( - long dev_handle, short desc_index, int size) throws LibusbError; - - /** - * Retrieve a descriptor from the default control pipe.
- *
- * This is a convenience function which formulates the appropriate control - * message to retrieve the descriptor. - * - * @param dev_handle - * a device handle - * @param desc_type - * the descriptor type - * @param desc_index - * the index of the descriptor to retrieve - * @param size - * number of bytes which will be retrieved (the length of the - * resulting byte[]) - * @return a byte[] which contains the descriptor or null on failure - * @throws LibusbError - * in case of an error
- * - */ - public static native byte[] libusb_get_descriptor(long dev_handle, - int desc_type, short desc_index, int size) throws LibusbError; - - /** - * Retrieve a descriptor from a device.
- *
- * This is a convenience function which formulates the appropriate control - * message to retrieve the descriptor. The string returned is Unicode, as - * detailed in the USB specifications. - * - * @param dev_handle - * a device handle - * @param desc_index - * the index of the descriptor to retrieve - * @param langid - * the language ID for the string descriptor - * @param size - * number of charactes which will be retrieved (the length of the - * resulting String) - * @return a string which contains the string descriptor - * @throws LibusbError - * in case of an error
- * @see #libusb_get_string_descriptor_ascii(long, short, int) - */ - public static native String libusb_get_string_descriptor(long dev_handle, - short desc_index, int langid, int size) throws LibusbError; - - /** - * Allocate a libusb transfer with a specified number of isochronous packet - * descriptors.
- * - * The returned transfer is pre-initialized for you. When the new transfer - * is no longer needed, it should be freed with - * libusb_free_transfer().
- *
- * Transfers intended for non-isochronous endpoints (e.g. control, bulk, - * interrupt) should specify an iso_packets count of zero.
- *
- * For transfers intended for isochronous endpoints, specify an appropriate - * number of packet descriptors to be allocated as part of the transfer. The - * returned transfer is not specially initialized for isochronous I/O you - * are still required to set the num_iso_packets and type - * fields accordingly.
- *
- * It is safe to allocate a transfer with some isochronous packets and then - * use it on a non-isochronous endpoint. If you do this, ensure that at time - * of submission, num_iso_packets is 0 and that type is set appropriately.
- * - * @param iso_packets - * number of isochronous packet descriptors to allocate - * @return a newly allocated transfernumber, or NULL on error - */ - public static native long libusb_alloc_transfer(int iso_packets); - - /** - * Free a transfer. - * - * This should be called for all transfers allocated with - * libusb_alloc_transfer().
- *
- * It is legal to call this function with a NULL transfer. In this case, the - * function will simply return safely.
- *
- * It is not legal to free an active transfer (one which has been submitted - * and has not yet completed).
- *
- * - * @param transfernumber - * the transfer to free - */ - public static native void libusb_free_transfer(long transfernumber); - - /** - * Submit a transfer.
- *
- * This function will fire off the USB transfer and then return immediately.
- *
- * - * @param transfernumber - * the transfer to submit - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - ERROR_BUSY if the transfer has already been submitted.
- * - another LIBUSB_ERROR code on other failure
- */ - public static native void libusb_submit_transfer(long transfernumber) - throws LibusbError; - - /** - * Asynchronously cancel a previously submitted transfer.
- *
- * This function returns immediately, but this does not indicate - * cancellation is complete. Libusb_event will be invoked at some later time - * to notify you. - * - * @param transfernumber - * a transfer - * @throws LibusbError - * in case of an error
- * Possible causes for errors are:
- * - ERROR_NOT_FOUND if the transfer is already complete or - * cancelled.
- * - a LIBUSB_ERROR code on failure
- */ - public static native void libusb_cancel_transfer(long transfernumber) - throws LibusbError; - - /** - * Get the data section of a control transfer.
- *
- * This convenience function is here to remind you that the data does not - * start until 8 bytes into the actual buffer, as the setup packet comes - * first.
- *
- * Calling this function only makes sense from a transfer event handler, or - * situations where you have already allocated a suitably sized buffer. - * - * @param transfernumber - * a transfer - * @return the data section from the transfer, null if the transfer number - * was invalid. - */ - public static native byte[] libusb_control_transfer_get_data( - long transfernumber); - - /** - * Get the control setup packet of a control transfer.
- *
- * This convenience function is here to remind you that the control setup - * occupies the first 8 bytes of the transfer data buffer.
- *
- * Calling this function only makes sense from a transfer event handler, or - * situations where you have already allocated a suitably sized buffer at - * transfer->buffer. - * - * @param transfernumber - * a transfer - * @return the setup packet from the transfer, null if the transfer number - * was invalid. - */ - public static native byte[] libusb_control_transfer_get_setup( - long transfernumber); - - /** - * Helper function to populate the setup packet (first 8 bytes of the data - * buffer) for a control transfer.
- * - * @param bmRequestType - * @param bRequest - * @param wValue - * @param wIndex - * @param wLength - * @return the setup packet - */ - public static native byte[] libusb_fill_control_setup(int bmRequestType, - int bRequest, int wValue, int wIndex, int wLength); - - /** - * Helper function to populate the required libusb_transfer fields for a - * control transfer.
- *
- * If you pass a transfer buffer to this function, the first 8 bytes will be - * interpreted as a control setup packet, and the wLength field will be used - * to automatically populate the length field of the transfer. Therefore the - * recommended approach is:
- *
- * 1. Call libusb_fill_control_setup()
- * 2. Allocate a suitably sized data buffer (including space for control - * setup)
- * 3. Put the retrieved setup packet into the firste 8 byte of the data - * buffer.
- * 4. If this is a host-to-device transfer with a data stage, put the data - * in place after the setup packet
- * 5. Call this function
- * 6. Call libusb_submit_transfer()
- *
- * It is also legal to pass a NULL buffer to this function, in which case - * this function will not attempt to populate the length field. Remember - * that you must then populate the buffer and length fields later. - * - * @param transfernumber - * transfer to populate - * @param dev_handle - * handle of the device that - * @param buffer - * data buffer. If provided, this function will interpret the - * first 8 bytes as a setup packet and infer the transfer length - * from that. - * @param timeout - * timeout for the transfer in milliseconds - */ - public static native void libusb_fill_control_transfer(long transfernumber, - long dev_handle, byte[] buffer, int timeout); - - /** - * Helper function to populate the required libusb_transfer fields for a - * bulk transfer. - * - * @param transfernumber - * the transfer to populate - * @param dev_handle - * handle of the device that will handle the transfer - * @param endpoint - * address of the endpoint where this transfer will be sent - * @param buffer - * data buffer - * @param length - * length of data buffer - * @param timeout - * timeout for the transfer in milliseconds - */ - public static native void libusb_fill_bulk_transfer(long transfernumber, - long dev_handle, byte endpoint, byte[] buffer, int length, - int timeout); - - /** - * Helper function to populate the required libusb_transfer fields for an - * interrupt transfer. - * - * @param transfernumber - * the transfer to populate - * @param dev_handle - * handle of the device that will handle the transfer - * @param endpoint - * address of the endpoint where this transfer will be sent - * @param buffer - * data buffer - * @param length - * length of data buffer - * @param timeout - * timeout for the transfer in milliseconds - */ - public static native void libusb_fill_interrupt_transfer( - long transfernumber, long dev_handle, byte endpoint, byte[] buffer, - int length, int timeout); - - /** - * Helper function to populate the required libusb_transfer fields for an - * isochronous transfer. - * - * @param transfernumber - * the transfer to populate - * @param dev_handle - * handle of the device that will handle the transfer - * @param endpoint - * address of the endpoint where this transfer will be sent - * @param buffer - * data buffer - * @param length - * length of data buffer - * @param num_iso_packets - * the number of isochronous packets - * @param timeout - * timeout for the transfer in milliseconds - */ - public static native void libusb_fill_iso_transfer(long transfernumber, - long dev_handle, byte endpoint, byte[] buffer, int length, - int num_iso_packets, int timeout); - - /** - * Convenience function to set the length of all packets in an isochronous - * transfer, based on the num_iso_packets field in the transfer structure. - * - * @param transfer - * a transfer - * @param length - * the length to set in each isochronous packet descriptor - */ - public static native void libusb_set_iso_packet_lengths(long transfer, - int length); - - /** - * Convenience function to locate the position of an isochronous packet - * within the buffer of an isochronous transfer.
- *
- * This is a thorough function which loops through all preceding packets, - * accumulating their lengths to find the position of the specified packet. - * Typically you will assign equal lengths to each packet in the transfer, - * and hence the above method is sub-optimal. You may wish to use - * libusb_get_iso_packet_buffer_simple() instead.
- *
- * - * @param transfer - * a transfer - * @param packet - * the packet to return - * @return the packet buffer inside the transfer buffer, or NULL if the - * packet does not exist - */ - public static native byte[] libusb_get_iso_packet_buffer(long transfer, - int packet); - - /** - * Convenience function to locate the position of an isochronous packet - * within the buffer of an isochronous transfer, for transfers where each - * packet is of identical size.
- *
- * This function relies on the assumption that every packet within the - * transfer is of identical size to the first packet. Calculating the - * location of the packet buffer is then just a simple calculation: buffer + - * (packet_size * packet)
- *
- * Do not use this function on transfers other than those that have - * identical packet lengths for each packet. - * - * @param transfernumber - * a transfer - * @param packet - * he packet to return - * @return the packet buffer inside the transfer buffer, or NULL if the - * packet does not exist. - */ - public static native byte[] libusb_get_iso_packet_buffer_simple( - long transfernumber, int packet); - - /** - * Attempt to acquire the event handling lock.
- *
- * This lock is used to ensure that only one thread is monitoring libusb - * event sources at any one time.
- *
- * You only need to use this lock if you are developing an application which - * calls poll() or select() on libusb's file descriptors directly. If you - * stick to libusb's event handling loop functions (e.g. - * libusb_handle_events()) then you do not need to be concerned - * with this locking.
- *
- * While holding this lock, you are trusted to actually be handling events. - * If you are no longer handling events, you must call - * libusb_unlock_events() as soon as possible. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @return 0 if the lock was obtained successfully
- * 1 if the lock was not obtained (i.e. another thread holds the - * lock)
- */ - public static native int libusb_try_lock_events(long ctx); - - /** - * Acquire the event handling lock, blocking until successful acquisition if - * it is contended.
- *
- * This lock is used to ensure that only one thread is monitoring libusb - * event sources at any one time.
- *
- * You only need to use this lock if you are developing an application which - * calls poll() or select() on libusb's file descriptors directly. If you - * stick to libusb's event handling loop functions (e.g. - * libusb_handle_events()) then you do not need to be concerned - * with this locking.
- *
- * While holding this lock, you are trusted to actually be handling events. - * If you are no longer handling events, you must call - * libusb_unlock_events() as soon as possible. - * - * @param ctx - * the context to operate on, or NULL for the default context - */ - public static native void libusb_lock_events(long ctx); - - /** - * Release the lock previously acquired with - * libusb_try_lock_events() or - * libusb_lock_events().
- *
- * Releasing this lock will wake up any threads blocked on - * libusb_wait_for_event(). - * - * @param ctx - * the context to operate on, or NULL for the default context - */ - public static native void libusb_unlock_events(long ctx); - - /** - * Determine if it is still OK for this thread to be doing event handling.
- *
- * Sometimes, libusb needs to temporarily pause all event handlers, and this - * is the function you should use before polling file descriptors to see if - * this is the case.
- *
- * If this function instructs your thread to give up the events lock, you - * should just continue the usual logic. On the next iteration, your thread - * will fail to obtain the events lock, and will hence become an event - * waiter.
- *
- * This function should be called while the events lock is held: you don't - * need to worry about the results of this function if your thread is not - * the current event handler. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @return 1 if event handling can start or continue
- * 0 if this thread must give up the events lock
- */ - public static native int libusb_event_handling_ok(long ctx); - - /** - * Determine if an active thread is handling events (i.e. if anyone is - * holding the event handling lock). - * - * @param ctx - * the context to operate on, or NULL for the default context - * @return 1 if a thread is handling events
- * 0 if there are no threads currently handling events
- */ - public static native int libusb_event_handler_active(long ctx); - - /** - * Acquire the event waiters lock.
- *
- * This lock is designed to be obtained under the situation where you want - * to be aware when events are completed, but some other thread is event - * handling so calling libusb_handle_events() is not allowed.
- *
- * You then obtain this lock, re-check that another thread is still handling - * events, then call libusb_wait_for_event().
- *
- * You only need to use this lock if you are developing an application which - * calls poll() or select() on libusb's file descriptors directly, and may - * potentially be handling events from 2 threads simultaenously. If you - * stick to libusb's event handling loop functions (e.g. - * libusb_handle_events()) then you do not need to be concerned - * with this locking. - * - * @param ctx - * the context to operate on, or NULL for the default context - */ - public static native void libusb_lock_event_waiters(long ctx); - - /** - * Release the event waiters lock. - * - * @param ctx - * the context to operate on, or NULL for the default context - */ - public static native void libusb_unlock_event_waiters(long ctx); - - /** - * Wait for another thread to signal completion of an event.
- *
- * Must be called with the event waiters lock held, see - * libusb_lock_event_waiters().
- *
- * This function will block until any of the following conditions are met:
- * - * 1. The timeout expires
- * 2. A transfer completes
- * 3. A thread releases the event handling lock through - * libusb_unlock_events()
- *
- * Condition 1 is obvious. Condition 2 unblocks your thread after the - * callback for the transfer has completed. Condition 3 is important because - * it means that the thread that was previously handling events is no longer - * doing so, so if any events are to complete, another thread needs to step - * up and start event handling.
- *
- * This function releases the event waiters lock before putting your thread - * to sleep, and reacquires the lock as it is being woken up. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @param timeval - * maximum timeout in seconds for this blocking function. 0 - * seconds indicates unlimited timeout - * @return 0 after a transfer completes or another thread stops event - * handling
- * 1 if the timeout expired
- */ - public static native int libusb_wait_for_event(long ctx, long timeval); - - /** - * Handle any pending events.
- *
- * libusb determines "pending events" by checking if any timeouts have - * expired and by checking the set of file descriptors for activity.
- *
- * If a zero timeval is passed, this function will handle any - * already-pending events and then immediately return in non-blocking style.
- *
- * If a non-zero timeval is passed and no events are currently pending, this - * function will block waiting for events to handle up until the specified - * timeout. If an event arrives or a signal is raised, this function will - * return early. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @param timeval - * the maximum time to block waiting for events, or zero for - * non-blocking mode - * @throws LibusbError - * in case of an error
- */ - public static native void libusb_handle_events_timeout(long ctx, - long timeval) throws LibusbError; - - /** - * Handle any pending events in blocking mode with a sensible timeout.
- *
- * This timeout is currently hardcoded at 2 seconds but we may change this - * if we decide other values are more sensible. For finer control over - * whether this function is blocking or non-blocking, or the maximum - * timeout, use libusb_handle_events_timeout() instead. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @throws LibusbError - * in case of an error
- */ - public static native void libusb_handle_events(long ctx) throws LibusbError; - - /** - * Handle any pending events by polling file descriptors, without checking - * if any other threads are already doing so.
- *
- * Must be called with the event lock held, see - * libusb_lock_events().
- *
- * This function is designed to be called under the situation where you have - * taken the event lock and are calling poll()/select() directly on libusb's - * file descriptors (as opposed to using libusb_handle_events() - * or similar). You detect events on libusb's descriptors, so you then call - * this function with a zero timeout value (while still holding the event - * lock). - * - * @param ctx - * the context to operate on, or NULL for the default context - * @param timeval - * the maximum time in seconds to block waiting for events, or - * zero for non-blocking mode - * @throws LibusbError - * in case of an error
- */ - public static native void libusb_handle_events_locked(long ctx, long timeval) - throws LibusbError; - - /** - * Determines whether your application must apply special timing - * considerations when monitoring libusb's file descriptors.
- *
- * This function is only useful for applications which retrieve and poll - * libusb's file descriptors in their own main loop (The more advanced - * option).
- *
- * Ordinarily, libusb's event handler needs to be called into at specific - * moments in time (in addition to times when there is activity on the file - * descriptor set). The usual approach is to use - * libusb_get_next_timeout() to learn about when the next - * timeout occurs, and to adjust your poll()/select() timeout accordingly so - * that you can make a call into the library at that time.
- *
- * Some platforms supported by libusb do not come with this baggage - any - * events relevant to timing will be represented by activity on the file - * descriptor set, and libusb_get_next_timeout() will always - * return 0. This function allows you to detect whether you are running on - * such a platform.
- *
- * Since v1.0.5. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @return 0 if you must call into libusb at times determined by - * libusb_get_next_timeout(), or 1 if all timeout - * events are handled internally or through regular activity on the - * file descriptors. - */ - public static native int libusb_pollfds_handle_timeouts(long ctx); - - /** - * Determine the next internal timeout that libusb needs to handle.
- *
- * You only need to use this function if you are calling poll() or select() - * or similar on libusb's file descriptors yourself - you do not need to use - * it if you are calling libusb_handle_events() or a variant directly.
- *
- * You should call this function in your main loop in order to determine how - * long to wait for select() or poll() to return results. libusb needs to be - * called into at this timeout, so you should use it as an upper bound on - * your select() or poll() call.
- *
- * When the timeout has expired, call into libusb_handle_events_timeout() - * (perhaps in non-blocking mode) so that libusb can handle the timeout.
- *
- * This function may return an zero timevalue. If this is the case, it - * indicates that libusb has a timeout that has already expired so you - * should call libusb_handle_events_timeout() or similar immediately. A - * return code of -1 indicates that there are no pending timeouts.
- *
- * On some platforms, this function will always returns -1 (no pending - * timeouts). - * - * @param ctx - * the context to operate on, or NULL for the default context - * @return time to next timeout
- * -1 if there are no pending timeouts
- * @throws LibusbError - * If an error is occured in libusb - */ - public static native int libusb_get_next_timeout(long ctx) - throws LibusbError; - - /** - * Register notification functions for file descriptor additions/removals.
- *
- * These functions will be invoked for every new or removed file descriptor - * that libusb uses as an event source.
- *
- * To remove notifiers, set remove TRUE.
- *
- * Note that file descriptors may have been added even before you register - * these notifiers (e.g. at libusb_init() time).
- *
- * Additionally, note that the removal notifier may be called during - * libusb_exit() (e.g. when it is closing file descriptors that - * were opened and added to the poll set at libusb_init() - * time).
- * If you don't want this, remove the notifiers immediately before calling - * libusb_exit(). - * - * @param ctx - * the context to operate on, or NULL for the default context - * @param remove - * select add or remove notifiers - */ - public static native void libusb_set_pollfd_notifiers(long ctx, - boolean remove); - - /** - * Retrieve a array of file descriptors that should be polled by your main - * loop as libusb event sources.
- *
- * - * The actual list contents must not be touched. - * - * @param ctx - * the context to operate on, or NULL for the default context - * @return array of Libusb_pollfd or NULL on error - */ - public static native Libusb_pollfd[] libusb_get_pollfds(long ctx); - - /** - * Perform a USB control transfer.
- *
- * The direction of the transfer is inferred from the bmRequestType field of - * the setup packet.
- *
- * The wValue, wIndex and wLength fields values should be given in - * host-endian byte order. - * - * @param dev_handle - * a handle for the device to communicate with - * @param bmRequestType - * the request type field for the setup packet - * @param bRequest - * the request field for the setup packet - * @param wValue - * the value field for the setup packet - * @param wIndex - * the index field for the setup packet - * @param data - * a suitably-sized data buffer for either input or output - * (depending on direction bits within bmRequestType) - * @param wLength - * the length field for the setup packet. The data buffer should - * be at least this size. - * @param timeout - * timeout (in millseconds) that this function should wait before - * giving up due to no response being received. For an unlimited - * timeout, use value 0. - * @return on success, the number of bytes actually transferred
- * LIBUSB_ERROR_TIMEOUT if the transfer timed out
- * LIBUSB_ERROR_PIPE if the control request was not supported by the - * device
- * LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
- * another LIBUSB_ERROR code on other failures - */ - public static native int libusb_control_transfer(long dev_handle, - int bmRequestType, int bRequest, int wValue, int wIndex, - byte[] data, int wLength, int timeout); - - /** - * Perform a USB bulk transfer.
- *
- * The direction of the transfer is inferred from the direction bits of the - * endpoint address.
- *
- * For bulk reads, the length field indicates the maximum length of data you - * are expecting to receive. If less data arrives than expected, this - * function will return that data, so be sure to check the returned value.
- *
- * You should also check this value for bulk writes. Not all of the data may - * have been written. - * - * @param dev_handle - * a handle for the device to communicate with - * @param endpoint - * the address of a valid endpoint to communicate with - * @param data - * a suitably-sized data buffer for either input or output - * (depending on endpoint) - * @param length - * for bulk writes, the number of bytes from data to be sent. for - * bulk reads, the maximum number of bytes to receive into the - * data buffer. - * @param timeout - * timeout (in millseconds) that this function should wait before - * giving up due to no response being received. For an unlimited - * timeout, use value 0. - * @return The number of bytes actually transferred - * @throws LibusbError - * in case an error occured
- * Possible causes are:
- * - ERROR_TIMEOUT if the transfer timed out
- * - ERROR_PIPE if the control request was not supported by the - * device
- * - ERROR_OVERFLOW if the device offered more data
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another code on other failures. - */ - public static native int libusb_bulk_transfer(long dev_handle, - byte endpoint, byte[] data, int length, int timeout) - throws LibusbError; - - /** - * Perform a USB interrupt transfer.
- *
- * The direction of the transfer is inferred from the direction bits of the - * endpoint address.
- *
- * For bulk reads, the length field indicates the maximum length of data you - * are expecting to receive. If less data arrives than expected, this - * function will return that data, so be sure to check the returned value.
- *
- * You should also check this value for bulk writes. Not all of the data may - * have been written.
- *
- * The default endpoint bInterval value is used as the polling interval. - * - * @param dev_handle - * a handle for the device to communicate with - * @param endpoint - * the address of a valid endpoint to communicate with - * @param data - * a suitably-sized data buffer for either input or output - * (depending on endpoint) - * @param length - * for bulk writes, the number of bytes from data to be sent. for - * bulk reads, the maximum number of bytes to receive into the - * data buffer. - * @param timeout - * timeout (in millseconds) that this function should wait before - * giving up due to no response being received. For an unlimited - * timeout, use value 0. - * @return The number of bytes actually transferred
- * @throws LibusbError - * in case an error occured
- * Possible causes are:
- * - ERROR_TIMEOUT if the transfer timed out
- * - ERROR_PIPE if the control request was not supported by the - * device
- * - ERROR_OVERFLOW if the device offered more data
- * - ERROR_NO_DEVICE if the device has been disconnected
- * - another ERROR code on other failures - */ - public static native int libusb_interrupt_transfer(long dev_handle, - byte endpoint, byte[] data, int length, int timeout) - throws LibusbError; - - /** - * Returns the error string after an error occured. - * - * @return the last error sring. - */ - public static native String libusb_strerror(); - - static { - String os = System.getProperty("os.name"); - if (os.contains("Windows")) { - System.loadLibrary("LibusbJava-1_0"); - } else { - System.loadLibrary("usbJava-1.0"); - } - - /* - * After loading the library, we register a "shutdown hook" to be called - * for cleaning up stuff in the library when exiting. - */ - Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - try { - LibusbJava1.teardown(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - /* - * After setting up the cleanup callback, it's now safe to call the code - * that initializes stuff in the native library - */ - int setup_result = setup(); - - if (setup_result < 0) { - throw new UnsatisfiedLinkError("Could not setup the library. (" - + setup_result + ")"); - } - } - - /** - * This method is used to setup stuff in the native library. After calling - * this function, {@link #teardown()} has to be called if the native library - * is not used anymore. - * - * @return - 0 if successful - <0 if an error occured - */ - private static native int setup(); - - /** - * This method cleans up stuff initialized using {@link #setup()}. - */ - private static native void teardown(); -} +/** + * Java libusb1.0 wrapper + * Roger Millischer + * + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +import ch.ntb.inf.libusbJava.exceptions.LibusbError; + +/** + * This class represents the Java Native Interface to the shared library which + * is (with some exceptions) a one-to-one representation of the libusb1.0 API.
+ *
+ *

Project Description

Java libusb1.0 is a Java wrapper for the + * libusb1.0 USB library. + * + * libusb aim is to create a library for + * use by user level applications to access USB devices regardless of OS.
+ * Libusb-Windows + * backend aim of this project is to bring a Windows backend to the mainline + * libusb 1.0 branch, so that libusb 1.0 can easily be used on Windows + * platforms. The library allows user space applications to access any USB + * device on Windows in a generic way without writing any line of kernel driver + * code.
+ *
+ * The API description of this class has been copied from the libusb-1.0 API + * Reference and adapted where neccessary.
+ * + */ +public class LibusbJava1 { + /** + * Set message verbosity. + *
    + *
  • Level 0: no messages ever printed by the library (default)
  • + *
  • Level 1: error messages are printed to stderr
  • + *
  • Level 2: warning and error messages are printed to stderr
  • + *
  • Level 3: informational messages are printed to stdout, warning and + * error messages are printed to stderr
  • + *
+ * + * The default level is 0, which means no messages are ever printed. If you + * choose to increase the message verbosity level, ensure that your + * application does not close the stdout/stderr file descriptors.
+ *
+ * You are advised to set level 3. libusb is conservative with its message + * logging and most of the time, will only log messages that explain error + * conditions and other oddities. This will help you debug your software.
+ *
+ * If the LIBUSB_DEBUG environment variable was set when libusb was + * initialized, this function does nothing: the message verbosity is fixed + * to the value in the environment variable.
+ *
+ * If libusb was compiled without any message logging, this function does + * nothing: you'll never get any messages.
+ *
+ * If libusb was compiled with verbose debug message logging, this function + * does nothing: you'll always get messages from all levels.
+ *
+ * + * @param ctx + * the context to operate on, or NULL for the default context + * @param level + * debug level to set + */ + + public static native void libusb_set_debug(long ctx, int level); + + /** + * Initialize libusb.
+ *
+ * This function must be called before calling any other libusb function.
+ *
+ * + * @return a context to operate on + * @throws LibusbError + * if an error occured + */ + public static native long libusb_init() throws LibusbError; + + /** + * Deinitialize libusb.
+ *
+ * Should be called after closing all open devices and before your + * application terminates.
+ *
+ * + * @param ctx + * the context to deinitialize, or 0 if the default context has + * been used. + */ + public static native void libusb_exit(long ctx); + + /** + * Returns a list of USB devices currently attached to the system.
+ *
+ * This is your entry point into finding a USB device to operate.
+ *
+ * + * @param ctx + * the context to operate on, or NULL for the default context + * + * @return Usb_Devices currently attached to the system
+ * if no device is attached the devnum of the returned device is set + * to -1
+ * or NULL if an error occurs + */ + public static native Usb_Device libusb_get_device_list(long ctx); + + /** + * Get the number of the bus that a device is connected to. + * + * @param dev + * a device + * @return the bus number + */ + public static native short libusb_get_bus_number(Usb_Device dev); + + /** + * Calculate the maximum packet size which a specific endpoint is capable is + * sending or receiving in the duration of 1 microframe.
+ *
+ * Only the active configution is examined. The calculation is based on the + * wMaxPacketSize field in the endpoint descriptor as described in section + * 9.6.6 in the USB 2.0 specifications.
+ *
+ * If acting on an isochronous or interrupt endpoint, this function will + * multiply the value found in bits 0:10 by the number of transactions per + * microframe (determined by bits 11:12). Otherwise, this function just + * returns the numeric value found in bits 0:10.
+ *
+ * This function is useful for setting up isochronous transfers, for example + * you might pass the return value from this function to + * libusb_set_iso_packet_lengths() in order to set the length + * field of every isochronous packet in a transfer.
+ *
+ * Since libusb v1.0.3.
+ *
+ * This functionality is not available on Windows-Systems
+ *
+ * + * @param dev + * a device + * @param endpoint + * address of the endpoint in question + * @return the maximum packet size which can be sent/received on this + * endpoint
+ * LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist
+ * LIBUSB_ERROR_OTHER on other failure
+ * TODO wenn funktion impl. richtig verlinken @see + * libusb_set_iso_packet_lengths() + */ + + public static native int libusb_get_max_iso_packet_size(Usb_Device dev, + short endpoint); + + /** + * Increment the reference count of a device. + * + * @param dev + * the device to reference + * @return the same device + */ + public static native Usb_Device libusb_ref_device(Usb_Device dev); + + /** + * Decrement the reference count of a device.
+ *
+ * If the decrement operation causes the reference count to reach zero, the + * device shall be destroyed.
+ *
+ * + * @param dev + * the device to unreference + */ + + public static native void libusb_unref_device(Usb_Device dev); + + /** + * Open a device and obtain a device handle.
+ *
+ * A handle allows you to perform I/O on the device in question.
+ *
+ * Internally, this function adds a reference to the device and makes it + * available to you through libusb_get_device(). This reference + * is removed during libusb_close().
+ *
+ * This is a non-blocking function; no requests are sent over the bus.
+ *
+ * + * @param dev + * the device to open + * + * @return a device handle >= 0 + * + * @throws LibusbError + * in case of an error
+ * Possible causes are:
+ * - ERROR_NO_MEM on memory allocation failure
+ * - ERROR_ACCESS if the user has insufficient permissions
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another ERROR code on other failure + * + * @see #libusb_get_device(long) + */ + public static native long libusb_open(Usb_Device dev) throws LibusbError; + + /** + * Convenience function for finding a device with a particular + * idVendor/idProduct combination.
+ *
+ * This function is intended for those scenarios where you are using libusb + * to knock up a quick test application - it allows you to avoid calling + * libusb_get_device_list() and worrying about + * traversing/freeing the list.
+ *
+ * This function has limitations and is hence not intended for use in real + * applications: if multiple devices have the same IDs it will only give you + * the first one, etc.
+ * + * @param ctx + * the context to operate on, or NULL for the default context + * @param vendor_id + * the idVendor value to search for + * @param product_id + * the idProduct value to search for + * @return a handle for the first found device, or NULL on error or if the + * device could not be found. + * @see #libusb_get_device_list(long) + */ + public static native long libusb_open_device_with_vid_pid(long ctx, + int vendor_id, int product_id); + + /** + * Close a device handle.
+ *
+ * Should be called on all open handles before your application exits.
+ *
+ * Internally, this function destroys the reference that was added by + * libusb_open() on the given device.
+ *
+ * This is a non-blocking function; no requests are sent over the bus.
+ *
+ * + * @param dev_handle + * the handle to close + */ + public static native void libusb_close(long dev_handle); + + /** + * Get the underlying device for a handle.
+ *
+ * This function does not modify the reference count of the returned device, + * so do not feel compelled to unreference it when you are done.
+ *
+ * + * @param dev_handle + * a device handle + * @return the underlying {@link Usb_Device} + */ + public static native Usb_Device libusb_get_device(long dev_handle); + + /** + * Determine the bConfigurationValue of the currently active configuration.
+ *
+ * You could formulate your own control request to obtain this information, + * but this function has the advantage that it may be able to retrieve the + * information from operating system caches (no I/O involved).
+ *
+ * If the OS does not cache this information, then this function will block + * while a control transfer is submitted to retrieve the information.
+ *
+ * This function will return a value of 0 if the device is in unconfigured + * state.
+ *
+ * + * @param dev_handle + * a device handle + * @return bConfigurationValue of the currently active configuration + * @throws LibusbError + * in case of an error
+ * Possible error causes are:
+ * - ERROR_NO_DEVICE if the device has been disconnected - + * another ERROR code on other failure + */ + public static native int libusb_get_configuration(long dev_handle) + throws LibusbError; + + /** + * Set the active configuration for a device.
+ *
+ * The operating system may or may not have already set an active + * configuration on the device. It is up to your application to ensure the + * correct configuration is selected before you attempt to claim interfaces + * and perform other operations.
+ *
+ * If you call this function on a device already configured with the + * selected configuration, then this function will act as a lightweight + * device reset: it will issue a SET_CONFIGURATION request using the current + * configuration, causing most USB-related device state to be reset + * (altsetting reset to zero, endpoint halts cleared, toggles reset).
+ *
+ * You cannot change/reset configuration if your application has claimed + * interfaces - you should free them with + * {@link #libusb_release_interface(long, int)} first. You cannot + * change/reset configuration if other applications or drivers have claimed + * interfaces.
+ *
+ * A configuration value of -1 will put the device in unconfigured state. + * The USB specifications state that a configuration value of 0 does this, + * however buggy devices exist which actually have a configuration 0.
+ *
+ * You should always use this function rather than formulating your own + * SET_CONFIGURATION control request. This is because the underlying + * operating system needs to know when such changes happen.
+ *
+ * This is a blocking function.
+ *
+ * + * @param dev_handle + * a device handle + * @param configuration + * the bConfigurationValue of the configuration you wish to + * activate, or -1 if you wish to put the device in unconfigured + * state + * @throws LibusbError + * in case of an error
+ * Possible error causes are:
+ * - ERROR_NOT_FOUND if the requested configuration does not + * exist
+ * - ERROR_BUSY if interfaces are currently claimed
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another LIBUSB_ERROR code on other failure
+ */ + public static native void libusb_set_configuration(long dev_handle, + int configuration) throws LibusbError; + + /** + * Claim an interface on a given device handle.
+ *
+ * You must claim the interface you wish to use before you can perform I/O + * on any of its endpoints.
+ *
+ * It is legal to attempt to claim an already-claimed interface, in which + * case libusb just returns 0 without doing anything.
+ *
+ * Claiming of interfaces is a purely logical operation, it does not cause + * any requests to be sent over the bus. Interface claiming is used to + * instruct the underlying operating system that your application wishes to + * take ownership of the interface.
+ *
+ * This is a non-blocking function.
+ *
+ * + * @param dev_handle + * a device handle + * @param interface_number + * the bInterfaceNumber of the interface you wish to claim + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if the interface was not claimed
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - ERROR_BUSY if another program or driver has claimed the + * interface
+ * - another LIBUSB_ERROR code on other failure
+ */ + public static native void libusb_claim_interface(long dev_handle, + int interface_number) throws LibusbError; + + /** + * Release an interface previously claimed with + * {@link #libusb_claim_interface(long, int)}.
+ *
+ * You should release all claimed interfaces before closing a device handle.
+ *
+ * This is a blocking function. A SET_INTERFACE control request will be sent + * to the device, resetting interface state to the first alternate setting.
+ *
+ * + * @param dev_handle + * a device handle + * @param interface_number + * the bInterfaceNumber of the previously-claimed interface + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if the interface was not claimed
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another ERROR code on other failure
+ */ + public static native void libusb_release_interface(long dev_handle, + int interface_number) throws LibusbError; + + /** + * Activate an alternate setting for an interface.
+ *
+ * The interface must have been previously claimed with + * {@link #libusb_claim_interface(long, int)}.
+ *
+ * You should always use this function rather than formulating your own + * SET_INTERFACE control request. This is because the underlying operating + * system needs to know when such changes happen.
+ *
+ * This is a blocking function.
+ *
+ * + * @param dev_handle + * a device handle + * @param interface_number + * the bInterfaceNumber of the previously-claimed interface + * @param alternate_setting + * the bAlternateSetting of the alternate setting to activate + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if the interface was not claimed, or the + * requested alternate setting does not exist
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another LIBUSB_ERROR code on other failure
+ */ + public static native void libusb_set_interface_alt_setting(long dev_handle, + int interface_number, int alternate_setting) throws LibusbError; + + /** + * Clear the halt/stall condition for an endpoint.
+ *
+ * Endpoints with halt status are unable to receive or transmit data until + * the halt condition is stalled.
+ *
+ * You should cancel all pending transfers before attempting to clear the + * halt condition.
+ *
+ * This is a blocking function.
+ *
+ * + * @param dev_handle + * a device handle + * @param endpoint + * the endpoint to clear halt status + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if the endpoint does not exist
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another LIBUSB_ERROR code on other failure
+ */ + public static native void libusb_clear_halt(long dev_handle, short endpoint) + throws LibusbError; + + /** + * Perform a USB port reset to reinitialize a device.
+ *
+ * The system will attempt to restore the previous configuration and + * alternate settings after the reset has completed.
+ *
+ * If the reset fails, the descriptors change, or the previous state cannot + * be restored, the device will appear to be disconnected and reconnected. + * This means that the device handle is no longer valid (you should close + * it) and rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND + * indicates when this is the case.
+ *
+ * This is a blocking function which usually incurs a noticeable delay.
+ *
+ * + * @param dev_handle + * a handle of the device to reset + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if re-enumeration is required, or if the + * device has been disconnected
+ * - another LIBUSB_ERROR code on other failure
+ */ + public static native void libusb_reset_device(long dev_handle) + throws LibusbError; + + /** + * Determine if a kernel driver is active on an interface.
+ *
+ * If a kernel driver is active, you cannot claim the interface, and libusb + * will be unable to perform I/O.
+ *
+ * + * @param dev_handle + * a device handle + * @param interface_number + * the interface to check + * @return 0 if no kernel driver is active
+ * 1 if a kernel driver is active
+ * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another LIBUSB_ERROR code on other failure
+ * @see #libusb_detach_kernel_driver(long, int) + */ + public static native int libusb_kernel_driver_active(long dev_handle, + int interface_number) throws LibusbError; + + /** + * Detach a kernel driver from an interface.
+ *
+ * If successful, you will then be able to claim the interface and perform + * I/O.
+ *
+ * + * @param dev_handle + * a device handle + * @param interface_number + * the interface to detach the driver from + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if no kernel driver was active
+ * - ERROR_INVALID_PARAM if the interface does not exist
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another ERROR code on other failure
+ * @see #libusb_kernel_driver_active(long, int) + */ + public static native void libusb_detach_kernel_driver(long dev_handle, + int interface_number) throws LibusbError; + + /** + * Re-attach an interface's kernel driver, which was previously detached + * using {@link #libusb_detach_kernel_driver(long, int)}.
+ * + * @param dev_handle + * a device handle + * @param interface_number + * the interface to attach the driver from + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if no kernel driver was active
+ * - ERROR_INVALID_PARAM if the interface does not exist
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - ERROR_BUSY if the driver cannot be attached because the + * interface is claimed by a program or driver
+ * - another ERROR code on other failure
+ * @see #libusb_kernel_driver_active(long, int) + */ + public static native void libusb_attach_kernel_driver(long dev_handle, + int interface_number) throws LibusbError; + + /** + * Get the USB configuration descriptor for the currently active + * configuration.
+ *
+ * This is a non-blocking function which does not involve any requests being + * sent to the device.
+ *
+ * + * @param dev + * a device + * @return {@link Usb_Config_Descriptor} + */ + public static native Usb_Config_Descriptor libusb_get_active_config_descriptor( + Usb_Device dev); + + /** + * Retrieve a string descriptor in C style ASCII.
+ *
+ * Wrapper around + * {@link #libusb_get_string_descriptor(long, short, int, int)}. Uses the + * first language supported by the device. + * + * @param dev_handle + * a device handle + * @param desc_index + * the index of the descriptor to retrieve + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return a string which contains the string descriptor + * @throws LibusbError + * in case of an error
+ */ + public static native String libusb_get_string_descriptor_ascii( + long dev_handle, short desc_index, int size) throws LibusbError; + + /** + * Retrieve a descriptor from the default control pipe.
+ *
+ * This is a convenience function which formulates the appropriate control + * message to retrieve the descriptor. + * + * @param dev_handle + * a device handle + * @param desc_type + * the descriptor type + * @param desc_index + * the index of the descriptor to retrieve + * @param size + * number of bytes which will be retrieved (the length of the + * resulting byte[]) + * @return a byte[] which contains the descriptor or null on failure + * @throws LibusbError + * in case of an error
+ * + */ + public static native byte[] libusb_get_descriptor(long dev_handle, + int desc_type, short desc_index, int size) throws LibusbError; + + /** + * Retrieve a descriptor from a device.
+ *
+ * This is a convenience function which formulates the appropriate control + * message to retrieve the descriptor. The string returned is Unicode, as + * detailed in the USB specifications. + * + * @param dev_handle + * a device handle + * @param desc_index + * the index of the descriptor to retrieve + * @param langid + * the language ID for the string descriptor + * @param size + * number of charactes which will be retrieved (the length of the + * resulting String) + * @return a string which contains the string descriptor + * @throws LibusbError + * in case of an error
+ * @see #libusb_get_string_descriptor_ascii(long, short, int) + */ + public static native String libusb_get_string_descriptor(long dev_handle, + short desc_index, int langid, int size) throws LibusbError; + + /** + * Allocate a libusb transfer with a specified number of isochronous packet + * descriptors.
+ * + * The returned transfer is pre-initialized for you. When the new transfer + * is no longer needed, it should be freed with + * libusb_free_transfer().
+ *
+ * Transfers intended for non-isochronous endpoints (e.g. control, bulk, + * interrupt) should specify an iso_packets count of zero.
+ *
+ * For transfers intended for isochronous endpoints, specify an appropriate + * number of packet descriptors to be allocated as part of the transfer. The + * returned transfer is not specially initialized for isochronous I/O you + * are still required to set the num_iso_packets and type + * fields accordingly.
+ *
+ * It is safe to allocate a transfer with some isochronous packets and then + * use it on a non-isochronous endpoint. If you do this, ensure that at time + * of submission, num_iso_packets is 0 and that type is set appropriately.
+ * + * @param iso_packets + * number of isochronous packet descriptors to allocate + * @return a newly allocated transfernumber, or NULL on error + */ + public static native long libusb_alloc_transfer(int iso_packets); + + /** + * Free a transfer. + * + * This should be called for all transfers allocated with + * libusb_alloc_transfer().
+ *
+ * It is legal to call this function with a NULL transfer. In this case, the + * function will simply return safely.
+ *
+ * It is not legal to free an active transfer (one which has been submitted + * and has not yet completed).
+ *
+ * + * @param transfernumber + * the transfer to free + */ + public static native void libusb_free_transfer(long transfernumber); + + /** + * Submit a transfer.
+ *
+ * This function will fire off the USB transfer and then return immediately.
+ *
+ * + * @param transfernumber + * the transfer to submit + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - ERROR_BUSY if the transfer has already been submitted.
+ * - another LIBUSB_ERROR code on other failure
+ */ + public static native void libusb_submit_transfer(long transfernumber) + throws LibusbError; + + /** + * Asynchronously cancel a previously submitted transfer.
+ *
+ * This function returns immediately, but this does not indicate + * cancellation is complete. Libusb_event will be invoked at some later time + * to notify you. + * + * @param transfernumber + * a transfer + * @throws LibusbError + * in case of an error
+ * Possible causes for errors are:
+ * - ERROR_NOT_FOUND if the transfer is already complete or + * cancelled.
+ * - a LIBUSB_ERROR code on failure
+ */ + public static native void libusb_cancel_transfer(long transfernumber) + throws LibusbError; + + /** + * Get the data section of a control transfer.
+ *
+ * This convenience function is here to remind you that the data does not + * start until 8 bytes into the actual buffer, as the setup packet comes + * first.
+ *
+ * Calling this function only makes sense from a transfer event handler, or + * situations where you have already allocated a suitably sized buffer. + * + * @param transfernumber + * a transfer + * @return the data section from the transfer, null if the transfer number + * was invalid. + */ + public static native byte[] libusb_control_transfer_get_data( + long transfernumber); + + /** + * Get the control setup packet of a control transfer.
+ *
+ * This convenience function is here to remind you that the control setup + * occupies the first 8 bytes of the transfer data buffer.
+ *
+ * Calling this function only makes sense from a transfer event handler, or + * situations where you have already allocated a suitably sized buffer at + * transfer->buffer. + * + * @param transfernumber + * a transfer + * @return the setup packet from the transfer, null if the transfer number + * was invalid. + */ + public static native byte[] libusb_control_transfer_get_setup( + long transfernumber); + + /** + * Helper function to populate the setup packet (first 8 bytes of the data + * buffer) for a control transfer.
+ * + * @param bmRequestType + * @param bRequest + * @param wValue + * @param wIndex + * @param wLength + * @return the setup packet + */ + public static native byte[] libusb_fill_control_setup(int bmRequestType, + int bRequest, int wValue, int wIndex, int wLength); + + /** + * Helper function to populate the required libusb_transfer fields for a + * control transfer.
+ *
+ * If you pass a transfer buffer to this function, the first 8 bytes will be + * interpreted as a control setup packet, and the wLength field will be used + * to automatically populate the length field of the transfer. Therefore the + * recommended approach is:
+ *
+ * 1. Call libusb_fill_control_setup()
+ * 2. Allocate a suitably sized data buffer (including space for control + * setup)
+ * 3. Put the retrieved setup packet into the firste 8 byte of the data + * buffer.
+ * 4. If this is a host-to-device transfer with a data stage, put the data + * in place after the setup packet
+ * 5. Call this function
+ * 6. Call libusb_submit_transfer()
+ *
+ * It is also legal to pass a NULL buffer to this function, in which case + * this function will not attempt to populate the length field. Remember + * that you must then populate the buffer and length fields later. + * + * @param transfernumber + * transfer to populate + * @param dev_handle + * handle of the device that + * @param buffer + * data buffer. If provided, this function will interpret the + * first 8 bytes as a setup packet and infer the transfer length + * from that. + * @param timeout + * timeout for the transfer in milliseconds + */ + public static native void libusb_fill_control_transfer(long transfernumber, + long dev_handle, byte[] buffer, int timeout); + + /** + * Helper function to populate the required libusb_transfer fields for a + * bulk transfer. + * + * @param transfernumber + * the transfer to populate + * @param dev_handle + * handle of the device that will handle the transfer + * @param endpoint + * address of the endpoint where this transfer will be sent + * @param buffer + * data buffer + * @param length + * length of data buffer + * @param timeout + * timeout for the transfer in milliseconds + */ + public static native void libusb_fill_bulk_transfer(long transfernumber, + long dev_handle, byte endpoint, byte[] buffer, int length, + int timeout); + + /** + * Helper function to populate the required libusb_transfer fields for an + * interrupt transfer. + * + * @param transfernumber + * the transfer to populate + * @param dev_handle + * handle of the device that will handle the transfer + * @param endpoint + * address of the endpoint where this transfer will be sent + * @param buffer + * data buffer + * @param length + * length of data buffer + * @param timeout + * timeout for the transfer in milliseconds + */ + public static native void libusb_fill_interrupt_transfer( + long transfernumber, long dev_handle, byte endpoint, byte[] buffer, + int length, int timeout); + + /** + * Helper function to populate the required libusb_transfer fields for an + * isochronous transfer. + * + * @param transfernumber + * the transfer to populate + * @param dev_handle + * handle of the device that will handle the transfer + * @param endpoint + * address of the endpoint where this transfer will be sent + * @param buffer + * data buffer + * @param length + * length of data buffer + * @param num_iso_packets + * the number of isochronous packets + * @param timeout + * timeout for the transfer in milliseconds + */ + public static native void libusb_fill_iso_transfer(long transfernumber, + long dev_handle, byte endpoint, byte[] buffer, int length, + int num_iso_packets, int timeout); + + /** + * Convenience function to set the length of all packets in an isochronous + * transfer, based on the num_iso_packets field in the transfer structure. + * + * @param transfer + * a transfer + * @param length + * the length to set in each isochronous packet descriptor + */ + public static native void libusb_set_iso_packet_lengths(long transfer, + int length); + + /** + * Convenience function to locate the position of an isochronous packet + * within the buffer of an isochronous transfer.
+ *
+ * This is a thorough function which loops through all preceding packets, + * accumulating their lengths to find the position of the specified packet. + * Typically you will assign equal lengths to each packet in the transfer, + * and hence the above method is sub-optimal. You may wish to use + * libusb_get_iso_packet_buffer_simple() instead.
+ *
+ * + * @param transfer + * a transfer + * @param packet + * the packet to return + * @return the packet buffer inside the transfer buffer, or NULL if the + * packet does not exist + */ + public static native byte[] libusb_get_iso_packet_buffer(long transfer, + int packet); + + /** + * Convenience function to locate the position of an isochronous packet + * within the buffer of an isochronous transfer, for transfers where each + * packet is of identical size.
+ *
+ * This function relies on the assumption that every packet within the + * transfer is of identical size to the first packet. Calculating the + * location of the packet buffer is then just a simple calculation: buffer + + * (packet_size * packet)
+ *
+ * Do not use this function on transfers other than those that have + * identical packet lengths for each packet. + * + * @param transfernumber + * a transfer + * @param packet + * he packet to return + * @return the packet buffer inside the transfer buffer, or NULL if the + * packet does not exist. + */ + public static native byte[] libusb_get_iso_packet_buffer_simple( + long transfernumber, int packet); + + /** + * Attempt to acquire the event handling lock.
+ *
+ * This lock is used to ensure that only one thread is monitoring libusb + * event sources at any one time.
+ *
+ * You only need to use this lock if you are developing an application which + * calls poll() or select() on libusb's file descriptors directly. If you + * stick to libusb's event handling loop functions (e.g. + * libusb_handle_events()) then you do not need to be concerned + * with this locking.
+ *
+ * While holding this lock, you are trusted to actually be handling events. + * If you are no longer handling events, you must call + * libusb_unlock_events() as soon as possible. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @return 0 if the lock was obtained successfully
+ * 1 if the lock was not obtained (i.e. another thread holds the + * lock)
+ */ + public static native int libusb_try_lock_events(long ctx); + + /** + * Acquire the event handling lock, blocking until successful acquisition if + * it is contended.
+ *
+ * This lock is used to ensure that only one thread is monitoring libusb + * event sources at any one time.
+ *
+ * You only need to use this lock if you are developing an application which + * calls poll() or select() on libusb's file descriptors directly. If you + * stick to libusb's event handling loop functions (e.g. + * libusb_handle_events()) then you do not need to be concerned + * with this locking.
+ *
+ * While holding this lock, you are trusted to actually be handling events. + * If you are no longer handling events, you must call + * libusb_unlock_events() as soon as possible. + * + * @param ctx + * the context to operate on, or NULL for the default context + */ + public static native void libusb_lock_events(long ctx); + + /** + * Release the lock previously acquired with + * libusb_try_lock_events() or + * libusb_lock_events().
+ *
+ * Releasing this lock will wake up any threads blocked on + * libusb_wait_for_event(). + * + * @param ctx + * the context to operate on, or NULL for the default context + */ + public static native void libusb_unlock_events(long ctx); + + /** + * Determine if it is still OK for this thread to be doing event handling.
+ *
+ * Sometimes, libusb needs to temporarily pause all event handlers, and this + * is the function you should use before polling file descriptors to see if + * this is the case.
+ *
+ * If this function instructs your thread to give up the events lock, you + * should just continue the usual logic. On the next iteration, your thread + * will fail to obtain the events lock, and will hence become an event + * waiter.
+ *
+ * This function should be called while the events lock is held: you don't + * need to worry about the results of this function if your thread is not + * the current event handler. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @return 1 if event handling can start or continue
+ * 0 if this thread must give up the events lock
+ */ + public static native int libusb_event_handling_ok(long ctx); + + /** + * Determine if an active thread is handling events (i.e. if anyone is + * holding the event handling lock). + * + * @param ctx + * the context to operate on, or NULL for the default context + * @return 1 if a thread is handling events
+ * 0 if there are no threads currently handling events
+ */ + public static native int libusb_event_handler_active(long ctx); + + /** + * Acquire the event waiters lock.
+ *
+ * This lock is designed to be obtained under the situation where you want + * to be aware when events are completed, but some other thread is event + * handling so calling libusb_handle_events() is not allowed.
+ *
+ * You then obtain this lock, re-check that another thread is still handling + * events, then call libusb_wait_for_event().
+ *
+ * You only need to use this lock if you are developing an application which + * calls poll() or select() on libusb's file descriptors directly, and may + * potentially be handling events from 2 threads simultaenously. If you + * stick to libusb's event handling loop functions (e.g. + * libusb_handle_events()) then you do not need to be concerned + * with this locking. + * + * @param ctx + * the context to operate on, or NULL for the default context + */ + public static native void libusb_lock_event_waiters(long ctx); + + /** + * Release the event waiters lock. + * + * @param ctx + * the context to operate on, or NULL for the default context + */ + public static native void libusb_unlock_event_waiters(long ctx); + + /** + * Wait for another thread to signal completion of an event.
+ *
+ * Must be called with the event waiters lock held, see + * libusb_lock_event_waiters().
+ *
+ * This function will block until any of the following conditions are met:
+ * + * 1. The timeout expires
+ * 2. A transfer completes
+ * 3. A thread releases the event handling lock through + * libusb_unlock_events()
+ *
+ * Condition 1 is obvious. Condition 2 unblocks your thread after the + * callback for the transfer has completed. Condition 3 is important because + * it means that the thread that was previously handling events is no longer + * doing so, so if any events are to complete, another thread needs to step + * up and start event handling.
+ *
+ * This function releases the event waiters lock before putting your thread + * to sleep, and reacquires the lock as it is being woken up. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @param timeval + * maximum timeout in seconds for this blocking function. 0 + * seconds indicates unlimited timeout + * @return 0 after a transfer completes or another thread stops event + * handling
+ * 1 if the timeout expired
+ */ + public static native int libusb_wait_for_event(long ctx, long timeval); + + /** + * Handle any pending events.
+ *
+ * libusb determines "pending events" by checking if any timeouts have + * expired and by checking the set of file descriptors for activity.
+ *
+ * If a zero timeval is passed, this function will handle any + * already-pending events and then immediately return in non-blocking style.
+ *
+ * If a non-zero timeval is passed and no events are currently pending, this + * function will block waiting for events to handle up until the specified + * timeout. If an event arrives or a signal is raised, this function will + * return early. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @param timeval + * the maximum time to block waiting for events, or zero for + * non-blocking mode + * @throws LibusbError + * in case of an error
+ */ + public static native void libusb_handle_events_timeout(long ctx, + long timeval) throws LibusbError; + + /** + * Handle any pending events in blocking mode with a sensible timeout.
+ *
+ * This timeout is currently hardcoded at 2 seconds but we may change this + * if we decide other values are more sensible. For finer control over + * whether this function is blocking or non-blocking, or the maximum + * timeout, use libusb_handle_events_timeout() instead. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @throws LibusbError + * in case of an error
+ */ + public static native void libusb_handle_events(long ctx) throws LibusbError; + + /** + * Handle any pending events by polling file descriptors, without checking + * if any other threads are already doing so.
+ *
+ * Must be called with the event lock held, see + * libusb_lock_events().
+ *
+ * This function is designed to be called under the situation where you have + * taken the event lock and are calling poll()/select() directly on libusb's + * file descriptors (as opposed to using libusb_handle_events() + * or similar). You detect events on libusb's descriptors, so you then call + * this function with a zero timeout value (while still holding the event + * lock). + * + * @param ctx + * the context to operate on, or NULL for the default context + * @param timeval + * the maximum time in seconds to block waiting for events, or + * zero for non-blocking mode + * @throws LibusbError + * in case of an error
+ */ + public static native void libusb_handle_events_locked(long ctx, long timeval) + throws LibusbError; + + /** + * Determines whether your application must apply special timing + * considerations when monitoring libusb's file descriptors.
+ *
+ * This function is only useful for applications which retrieve and poll + * libusb's file descriptors in their own main loop (The more advanced + * option).
+ *
+ * Ordinarily, libusb's event handler needs to be called into at specific + * moments in time (in addition to times when there is activity on the file + * descriptor set). The usual approach is to use + * libusb_get_next_timeout() to learn about when the next + * timeout occurs, and to adjust your poll()/select() timeout accordingly so + * that you can make a call into the library at that time.
+ *
+ * Some platforms supported by libusb do not come with this baggage - any + * events relevant to timing will be represented by activity on the file + * descriptor set, and libusb_get_next_timeout() will always + * return 0. This function allows you to detect whether you are running on + * such a platform.
+ *
+ * Since v1.0.5. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @return 0 if you must call into libusb at times determined by + * libusb_get_next_timeout(), or 1 if all timeout + * events are handled internally or through regular activity on the + * file descriptors. + */ + public static native int libusb_pollfds_handle_timeouts(long ctx); + + /** + * Determine the next internal timeout that libusb needs to handle.
+ *
+ * You only need to use this function if you are calling poll() or select() + * or similar on libusb's file descriptors yourself - you do not need to use + * it if you are calling libusb_handle_events() or a variant directly.
+ *
+ * You should call this function in your main loop in order to determine how + * long to wait for select() or poll() to return results. libusb needs to be + * called into at this timeout, so you should use it as an upper bound on + * your select() or poll() call.
+ *
+ * When the timeout has expired, call into libusb_handle_events_timeout() + * (perhaps in non-blocking mode) so that libusb can handle the timeout.
+ *
+ * This function may return an zero timevalue. If this is the case, it + * indicates that libusb has a timeout that has already expired so you + * should call libusb_handle_events_timeout() or similar immediately. A + * return code of -1 indicates that there are no pending timeouts.
+ *
+ * On some platforms, this function will always returns -1 (no pending + * timeouts). + * + * @param ctx + * the context to operate on, or NULL for the default context + * @return time to next timeout
+ * -1 if there are no pending timeouts
+ * @throws LibusbError + * If an error is occured in libusb + */ + public static native int libusb_get_next_timeout(long ctx) + throws LibusbError; + + /** + * Register notification functions for file descriptor additions/removals.
+ *
+ * These functions will be invoked for every new or removed file descriptor + * that libusb uses as an event source.
+ *
+ * To remove notifiers, set remove TRUE.
+ *
+ * Note that file descriptors may have been added even before you register + * these notifiers (e.g. at libusb_init() time).
+ *
+ * Additionally, note that the removal notifier may be called during + * libusb_exit() (e.g. when it is closing file descriptors that + * were opened and added to the poll set at libusb_init() + * time).
+ * If you don't want this, remove the notifiers immediately before calling + * libusb_exit(). + * + * @param ctx + * the context to operate on, or NULL for the default context + * @param remove + * select add or remove notifiers + */ + public static native void libusb_set_pollfd_notifiers(long ctx, + boolean remove); + + /** + * Retrieve a array of file descriptors that should be polled by your main + * loop as libusb event sources.
+ *
+ * + * The actual list contents must not be touched. + * + * @param ctx + * the context to operate on, or NULL for the default context + * @return array of Libusb_pollfd or NULL on error + */ + public static native Libusb_pollfd[] libusb_get_pollfds(long ctx); + + /** + * Perform a USB control transfer.
+ *
+ * The direction of the transfer is inferred from the bmRequestType field of + * the setup packet.
+ *
+ * The wValue, wIndex and wLength fields values should be given in + * host-endian byte order. + * + * @param dev_handle + * a handle for the device to communicate with + * @param bmRequestType + * the request type field for the setup packet + * @param bRequest + * the request field for the setup packet + * @param wValue + * the value field for the setup packet + * @param wIndex + * the index field for the setup packet + * @param data + * a suitably-sized data buffer for either input or output + * (depending on direction bits within bmRequestType) + * @param wLength + * the length field for the setup packet. The data buffer should + * be at least this size. + * @param timeout + * timeout (in millseconds) that this function should wait before + * giving up due to no response being received. For an unlimited + * timeout, use value 0. + * @return on success, the number of bytes actually transferred
+ * LIBUSB_ERROR_TIMEOUT if the transfer timed out
+ * LIBUSB_ERROR_PIPE if the control request was not supported by the + * device
+ * LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
+ * another LIBUSB_ERROR code on other failures + */ + public static native int libusb_control_transfer(long dev_handle, + int bmRequestType, int bRequest, int wValue, int wIndex, + byte[] data, int wLength, int timeout); + + /** + * Perform a USB bulk transfer.
+ *
+ * The direction of the transfer is inferred from the direction bits of the + * endpoint address.
+ *
+ * For bulk reads, the length field indicates the maximum length of data you + * are expecting to receive. If less data arrives than expected, this + * function will return that data, so be sure to check the returned value.
+ *
+ * You should also check this value for bulk writes. Not all of the data may + * have been written. + * + * @param dev_handle + * a handle for the device to communicate with + * @param endpoint + * the address of a valid endpoint to communicate with + * @param data + * a suitably-sized data buffer for either input or output + * (depending on endpoint) + * @param length + * for bulk writes, the number of bytes from data to be sent. for + * bulk reads, the maximum number of bytes to receive into the + * data buffer. + * @param timeout + * timeout (in millseconds) that this function should wait before + * giving up due to no response being received. For an unlimited + * timeout, use value 0. + * @return The number of bytes actually transferred + * @throws LibusbError + * in case an error occured
+ * Possible causes are:
+ * - ERROR_TIMEOUT if the transfer timed out
+ * - ERROR_PIPE if the control request was not supported by the + * device
+ * - ERROR_OVERFLOW if the device offered more data
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another code on other failures. + */ + public static native int libusb_bulk_transfer(long dev_handle, + byte endpoint, byte[] data, int length, int timeout) + throws LibusbError; + + /** + * Perform a USB interrupt transfer.
+ *
+ * The direction of the transfer is inferred from the direction bits of the + * endpoint address.
+ *
+ * For bulk reads, the length field indicates the maximum length of data you + * are expecting to receive. If less data arrives than expected, this + * function will return that data, so be sure to check the returned value.
+ *
+ * You should also check this value for bulk writes. Not all of the data may + * have been written.
+ *
+ * The default endpoint bInterval value is used as the polling interval. + * + * @param dev_handle + * a handle for the device to communicate with + * @param endpoint + * the address of a valid endpoint to communicate with + * @param data + * a suitably-sized data buffer for either input or output + * (depending on endpoint) + * @param length + * for bulk writes, the number of bytes from data to be sent. for + * bulk reads, the maximum number of bytes to receive into the + * data buffer. + * @param timeout + * timeout (in millseconds) that this function should wait before + * giving up due to no response being received. For an unlimited + * timeout, use value 0. + * @return The number of bytes actually transferred
+ * @throws LibusbError + * in case an error occured
+ * Possible causes are:
+ * - ERROR_TIMEOUT if the transfer timed out
+ * - ERROR_PIPE if the control request was not supported by the + * device
+ * - ERROR_OVERFLOW if the device offered more data
+ * - ERROR_NO_DEVICE if the device has been disconnected
+ * - another ERROR code on other failures + */ + public static native int libusb_interrupt_transfer(long dev_handle, + byte endpoint, byte[] data, int length, int timeout) + throws LibusbError; + + /** + * Returns the error string after an error occured. + * + * @return the last error sring. + */ + public static native String libusb_strerror(); + + static { + String os = System.getProperty("os.name"); + if (os.contains("Windows")) { + System.loadLibrary("LibusbJava-1_0"); + } else { + System.loadLibrary("usbJava-1.0"); + } + + /* + * After loading the library, we register a "shutdown hook" to be called + * for cleaning up stuff in the library when exiting. + */ + Runtime.getRuntime().addShutdownHook(new Thread() { + public void run() { + try { + LibusbJava1.teardown(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + + /* + * After setting up the cleanup callback, it's now safe to call the code + * that initializes stuff in the native library + */ + int setup_result = setup(); + + if (setup_result < 0) { + throw new UnsatisfiedLinkError("Could not setup the library. (" + + setup_result + ")"); + } + } + + /** + * This method is used to setup stuff in the native library. After calling + * this function, {@link #teardown()} has to be called if the native library + * is not used anymore. + * + * @return - 0 if successful - <0 if an error occured + */ + private static native int setup(); + + /** + * This method cleans up stuff initialized using {@link #setup()}. + */ + private static native void teardown(); +} diff --git a/java/src/ch/ntb/inf/libusbJava/Libusb_event.java b/src/main/java/ch/ntb/inf/libusbJava/Libusb_event.java similarity index 93% rename from java/src/ch/ntb/inf/libusbJava/Libusb_event.java rename to src/main/java/ch/ntb/inf/libusbJava/Libusb_event.java index 5268951..c7a34c8 100644 --- a/java/src/ch/ntb/inf/libusbJava/Libusb_event.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Libusb_event.java @@ -1,19 +1,19 @@ -package ch.ntb.inf.libusbJava; - -public class Libusb_event { - - public void transferCallback(){ - - } - - public void fdAddedCallback(int fd){ - System.out.println("addedCallback"); - - } - - public void fdRemovedCallback(int fd){ - System.out.println("removedCallback"); - - } - -} +package ch.ntb.inf.libusbJava; + +public class Libusb_event { + + public void transferCallback(){ + + } + + public void fdAddedCallback(int fd){ + System.out.println("addedCallback"); + + } + + public void fdRemovedCallback(int fd){ + System.out.println("removedCallback"); + + } + +} diff --git a/java/src/ch/ntb/inf/libusbJava/Libusb_pollfd.java b/src/main/java/ch/ntb/inf/libusbJava/Libusb_pollfd.java similarity index 92% rename from java/src/ch/ntb/inf/libusbJava/Libusb_pollfd.java rename to src/main/java/ch/ntb/inf/libusbJava/Libusb_pollfd.java index 64c2552..e05d311 100644 --- a/java/src/ch/ntb/inf/libusbJava/Libusb_pollfd.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Libusb_pollfd.java @@ -1,7 +1,7 @@ -package ch.ntb.inf.libusbJava; - -public class Libusb_pollfd { - int fd; - byte events; - -} +package ch.ntb.inf.libusbJava; + +public class Libusb_pollfd { + int fd; + byte events; + +} diff --git a/java/src/ch/ntb/inf/libusbJava/USB.java b/src/main/java/ch/ntb/inf/libusbJava/USB.java similarity index 97% rename from java/src/ch/ntb/inf/libusbJava/USB.java rename to src/main/java/ch/ntb/inf/libusbJava/USB.java index 7cde236..e02211c 100644 --- a/java/src/ch/ntb/inf/libusbJava/USB.java +++ b/src/main/java/ch/ntb/inf/libusbJava/USB.java @@ -1,318 +1,318 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.logging.Logger; - -import ch.ntb.inf.libusbJava.logger.LogUtil; - -/** - * This class manages all USB devices and defines some USB specific constants.
- * - */ -public class USB { - - // Standard requests (USB spec 9.4) - /** - * This request returns status for the specified recipient (USB spec 9.4.5). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_GET_STATUS = 0x00; - /** - * This request is used to clear or disable a specific feature (USB spec - * 9.4.1). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_CLEAR_FEATURE = 0x01; - // 0x02 is reserved - /** - * This request is used to set or enable a specific feature (USB spec - * 9.4.9). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_SET_FEATURE = 0x03; - // 0x04 is reserved - /** - * This request sets the device address for all future device accesses (USB - * spec 9.4.6). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_SET_ADDRESS = 0x05; - /** - * This request returns the specified descriptor if the descriptor exists - * (USB spec 9.4.3). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_GET_DESCRIPTOR = 0x06; - /** - * This request is optional and may be used to update existing descriptors - * or new descriptors may be added (USB spec 9.4.8). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_SET_DESCRIPTOR = 0x07; - /** - * This request returns the current device configuration value (USB spec - * 9.4.2). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_GET_CONFIGURATION = 0x08; - /** - * This request sets the device configuration (USB spec 9.4.7). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_SET_CONFIGURATION = 0x09; - /** - * This request returns the selected alternate setting for the specified - * interface (USB spec 9.4.4). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_GET_INTERFACE = 0x0A; - /** - * This request allows the host to select an alternate setting for the - * specified interface (USB spec 9.4.10). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_SET_INTERFACE = 0x0B; - /** - * This request is used to set and then report an endpoint’s synchronization - * frame (USB spec 9.4.11). - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_SYNCH_FRAME = 0x0C; - - // data transfer direction (USB spec 9.3) - /** - * Identifies the direction of data transfer in the second phase of the - * control transfer.
- * The state of the Direction bit is ignored if the wLength field is zero, - * signifying there is no Data stage.
- * Specifies bit 7 of bmRequestType. - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_TYPE_DIR_HOST_TO_DEVICE = (0x00 << 7), - REQ_TYPE_DIR_DEVICE_TO_HOST = (0x01 << 7); - - // request types (USB spec 9.3) - /** - * Specifies the type of the request.
- * Specifies bits 6..5 of bmRequestType. - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_TYPE_TYPE_STANDARD = (0x00 << 5), - REQ_TYPE_TYPE_CLASS = (0x01 << 5), - REQ_TYPE_TYPE_VENDOR = (0x02 << 5), - REQ_TYPE_TYPE_RESERVED = (0x03 << 5); - - // request recipient (USB spec 9.3) - /** - * Specifies the intended recipient of the request.
- * Requests may be directed to the device, an interface on the device, or a - * specific endpoint on a device. When an interface or endpoint is - * specified, the wIndex field identifies the interface or endpoint.
- * Specifies bits 4..0 of bmRequestType. - * - * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, - * boolean) - */ - public static final int REQ_TYPE_RECIP_DEVICE = 0x00, - REQ_TYPE_RECIP_INTERFACE = 0x01, REQ_TYPE_RECIP_ENDPOINT = 0x02, - REQ_TYPE_RECIP_OTHER = 0x03; - - /** - * The maximum packet size of a bulk transfer when operating in highspeed - * (480 MB/s) mode. - */ - public static int HIGHSPEED_MAX_BULK_PACKET_SIZE = 512; - - /** - * The maximum packet size of a bulk transfer when operating in fullspeed - * (12 MB/s) mode. - */ - public static int FULLSPEED_MAX_BULK_PACKET_SIZE = 64; - - private static final Logger logger = LogUtil.getLogger("ch.ntb.inf.libusbJava"); - - private static LinkedList devices = new LinkedList(); - - private static boolean initUSBDone = false; - - /** - * Create a new device an register it in a device list. If the device is - * already registered, a reference to it will be returned.
- * After resetting or re-attaching a device the busName and filename may - * change. You can unregister the current device instance (see - * {@link #unregisterDevice(Device)}) and get a new instance with the - * updated bus and filename. - * - * @param idVendor - * the vendor id of the USB device - * @param idProduct - * the product id of the USB device - * @param busName - * optional name of the bus which can be used to distinguish - * multiple devices with the same vendor and product id.
- * see {@link Usb_Bus#getDirname()} - * @param filename - * optional filename which can be used to distinguish multiple - * devices with the same vendor and product id.
- * see {@link Usb_Device#getFilename()} - * @return a newly created device or an already registered device - */ - public static Device getDevice(short idVendor, short idProduct, - String busName, String filename) { - - // check if this device is already registered - Device dev = getRegisteredDevice(idVendor, idProduct, busName, filename); - if (dev != null) { - logger.info("return already registered device: " + dev); - return dev; - } - dev = new Device(idVendor, idProduct, busName, filename); - logger.info("create new device: " + dev); - devices.add(dev); - return dev; - } - - /** - * See {@link #getDevice(short, short, String, String)}. The parameter - * filename and busNameis set to null. - * - * @param idVendor - * @param idProduct - * @return a newly created device or an already registered device - */ - public static Device getDevice(short idVendor, short idProduct) { - return getDevice(idVendor, idProduct, null, null); - } - - /** - * Unregister a registered device. - * - * @param dev - * the device to unregister - * @return true if the device has been removed, else false - */ - public static boolean unregisterDevice(Device dev) { - return devices.remove(dev); - } - - /** - * Get an already registered device or null if the device does not exist.
- * To uniquely identify a device bus and filename should be set. If only one - * of those is set the first device matching the criteria is returned. - * - * @param idVendor - * the vendor id of the USB device - * @param idProduct - * the product id of the USB device - * @param busName - * the name of the bus which can be used to distinguish multiple - * devices with the same vendor and product id.
- * see {@link Usb_Bus#getDirname()} - * @param filename - * an optional filename which can be used to distinguish multiple - * devices with the same vendor and product id. see - * {@link Usb_Device#getFilename()} - * - * @return the device or null - */ - private static Device getRegisteredDevice(short idVendor, short idProduct, - String busName, String filename) { - for (Iterator iter = devices.iterator(); iter.hasNext();) { - Device dev = iter.next(); - // bus and filename - if (busName != null && filename != null) { - if (busName.compareTo(dev.getBusName() == null ? "" : dev - .getBusName()) == 0 - && filename.compareTo(dev.getFilename() == null ? "" - : dev.getFilename()) == 0 - && dev.getIdVendor() == idVendor - && dev.getIdProduct() == idProduct) { - return dev; - } - } else if (filename != null) { - if (filename.compareTo(dev.getFilename() == null ? "" : dev - .getFilename()) == 0 - && dev.getIdVendor() == idVendor - && dev.getIdProduct() == idProduct) { - return dev; - } - } else if (busName != null) { - if (busName.compareTo(dev.getBusName() == null ? "" : dev - .getBusName()) == 0 - && dev.getIdVendor() == idVendor - && dev.getIdProduct() == idProduct) { - return dev; - } - } else if (dev.getIdVendor() == idVendor - && dev.getIdProduct() == idProduct) { - return dev; - } - } - return null; - } - - /** - * Returns the root {@link Usb_Bus} element. - * - * @return the root {@link Usb_Bus} element - * @throws USBException - */ - public static Usb_Bus getBus() throws USBException { - if (!initUSBDone) { - init(); - } - LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - - Usb_Bus bus = LibusbJava.usb_get_busses(); - if (bus == null) { - throw new USBException("LibusbJava.usb_get_busses(): " - + LibusbJava.usb_strerror()); - } - return bus; - } - - /** - * Explicitly calls {@link LibusbJava#usb_init()}. Note that you don't need - * to call this procedure as it is called implicitly when creating a new - * device with {@link USB#getDevice(short, short, String, String)}. - */ - public static void init() { - LibusbJava.usb_init(); - initUSBDone = true; - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.logging.Logger; + +import ch.ntb.inf.libusbJava.logger.LogUtil; + +/** + * This class manages all USB devices and defines some USB specific constants.
+ * + */ +public class USB { + + // Standard requests (USB spec 9.4) + /** + * This request returns status for the specified recipient (USB spec 9.4.5). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_STATUS = 0x00; + /** + * This request is used to clear or disable a specific feature (USB spec + * 9.4.1). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_CLEAR_FEATURE = 0x01; + // 0x02 is reserved + /** + * This request is used to set or enable a specific feature (USB spec + * 9.4.9). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_FEATURE = 0x03; + // 0x04 is reserved + /** + * This request sets the device address for all future device accesses (USB + * spec 9.4.6). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_ADDRESS = 0x05; + /** + * This request returns the specified descriptor if the descriptor exists + * (USB spec 9.4.3). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_DESCRIPTOR = 0x06; + /** + * This request is optional and may be used to update existing descriptors + * or new descriptors may be added (USB spec 9.4.8). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_DESCRIPTOR = 0x07; + /** + * This request returns the current device configuration value (USB spec + * 9.4.2). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_CONFIGURATION = 0x08; + /** + * This request sets the device configuration (USB spec 9.4.7). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_CONFIGURATION = 0x09; + /** + * This request returns the selected alternate setting for the specified + * interface (USB spec 9.4.4). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_GET_INTERFACE = 0x0A; + /** + * This request allows the host to select an alternate setting for the + * specified interface (USB spec 9.4.10). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SET_INTERFACE = 0x0B; + /** + * This request is used to set and then report an endpoint’s synchronization + * frame (USB spec 9.4.11). + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_SYNCH_FRAME = 0x0C; + + // data transfer direction (USB spec 9.3) + /** + * Identifies the direction of data transfer in the second phase of the + * control transfer.
+ * The state of the Direction bit is ignored if the wLength field is zero, + * signifying there is no Data stage.
+ * Specifies bit 7 of bmRequestType. + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_DIR_HOST_TO_DEVICE = (0x00 << 7), + REQ_TYPE_DIR_DEVICE_TO_HOST = (0x01 << 7); + + // request types (USB spec 9.3) + /** + * Specifies the type of the request.
+ * Specifies bits 6..5 of bmRequestType. + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_TYPE_STANDARD = (0x00 << 5), + REQ_TYPE_TYPE_CLASS = (0x01 << 5), + REQ_TYPE_TYPE_VENDOR = (0x02 << 5), + REQ_TYPE_TYPE_RESERVED = (0x03 << 5); + + // request recipient (USB spec 9.3) + /** + * Specifies the intended recipient of the request.
+ * Requests may be directed to the device, an interface on the device, or a + * specific endpoint on a device. When an interface or endpoint is + * specified, the wIndex field identifies the interface or endpoint.
+ * Specifies bits 4..0 of bmRequestType. + * + * @see ch.ntb.inf.libusbJava.Device#controlMsg(int, int, int, int, byte[], int, int, + * boolean) + */ + public static final int REQ_TYPE_RECIP_DEVICE = 0x00, + REQ_TYPE_RECIP_INTERFACE = 0x01, REQ_TYPE_RECIP_ENDPOINT = 0x02, + REQ_TYPE_RECIP_OTHER = 0x03; + + /** + * The maximum packet size of a bulk transfer when operating in highspeed + * (480 MB/s) mode. + */ + public static int HIGHSPEED_MAX_BULK_PACKET_SIZE = 512; + + /** + * The maximum packet size of a bulk transfer when operating in fullspeed + * (12 MB/s) mode. + */ + public static int FULLSPEED_MAX_BULK_PACKET_SIZE = 64; + + private static final Logger logger = LogUtil.getLogger("ch.ntb.inf.libusbJava"); + + private static LinkedList devices = new LinkedList(); + + private static boolean initUSBDone = false; + + /** + * Create a new device an register it in a device list. If the device is + * already registered, a reference to it will be returned.
+ * After resetting or re-attaching a device the busName and filename may + * change. You can unregister the current device instance (see + * {@link #unregisterDevice(Device)}) and get a new instance with the + * updated bus and filename. + * + * @param idVendor + * the vendor id of the USB device + * @param idProduct + * the product id of the USB device + * @param busName + * optional name of the bus which can be used to distinguish + * multiple devices with the same vendor and product id.
+ * see {@link Usb_Bus#getDirname()} + * @param filename + * optional filename which can be used to distinguish multiple + * devices with the same vendor and product id.
+ * see {@link Usb_Device#getFilename()} + * @return a newly created device or an already registered device + */ + public static Device getDevice(short idVendor, short idProduct, + String busName, String filename) { + + // check if this device is already registered + Device dev = getRegisteredDevice(idVendor, idProduct, busName, filename); + if (dev != null) { + logger.info("return already registered device: " + dev); + return dev; + } + dev = new Device(idVendor, idProduct, busName, filename); + logger.info("create new device: " + dev); + devices.add(dev); + return dev; + } + + /** + * See {@link #getDevice(short, short, String, String)}. The parameter + * filename and busNameis set to null. + * + * @param idVendor + * @param idProduct + * @return a newly created device or an already registered device + */ + public static Device getDevice(short idVendor, short idProduct) { + return getDevice(idVendor, idProduct, null, null); + } + + /** + * Unregister a registered device. + * + * @param dev + * the device to unregister + * @return true if the device has been removed, else false + */ + public static boolean unregisterDevice(Device dev) { + return devices.remove(dev); + } + + /** + * Get an already registered device or null if the device does not exist.
+ * To uniquely identify a device bus and filename should be set. If only one + * of those is set the first device matching the criteria is returned. + * + * @param idVendor + * the vendor id of the USB device + * @param idProduct + * the product id of the USB device + * @param busName + * the name of the bus which can be used to distinguish multiple + * devices with the same vendor and product id.
+ * see {@link Usb_Bus#getDirname()} + * @param filename + * an optional filename which can be used to distinguish multiple + * devices with the same vendor and product id. see + * {@link Usb_Device#getFilename()} + * + * @return the device or null + */ + private static Device getRegisteredDevice(short idVendor, short idProduct, + String busName, String filename) { + for (Iterator iter = devices.iterator(); iter.hasNext();) { + Device dev = iter.next(); + // bus and filename + if (busName != null && filename != null) { + if (busName.compareTo(dev.getBusName() == null ? "" : dev + .getBusName()) == 0 + && filename.compareTo(dev.getFilename() == null ? "" + : dev.getFilename()) == 0 + && dev.getIdVendor() == idVendor + && dev.getIdProduct() == idProduct) { + return dev; + } + } else if (filename != null) { + if (filename.compareTo(dev.getFilename() == null ? "" : dev + .getFilename()) == 0 + && dev.getIdVendor() == idVendor + && dev.getIdProduct() == idProduct) { + return dev; + } + } else if (busName != null) { + if (busName.compareTo(dev.getBusName() == null ? "" : dev + .getBusName()) == 0 + && dev.getIdVendor() == idVendor + && dev.getIdProduct() == idProduct) { + return dev; + } + } else if (dev.getIdVendor() == idVendor + && dev.getIdProduct() == idProduct) { + return dev; + } + } + return null; + } + + /** + * Returns the root {@link Usb_Bus} element. + * + * @return the root {@link Usb_Bus} element + * @throws USBException + */ + public static Usb_Bus getBus() throws USBException { + if (!initUSBDone) { + init(); + } + LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + + Usb_Bus bus = LibusbJava.usb_get_busses(); + if (bus == null) { + throw new USBException("LibusbJava.usb_get_busses(): " + + LibusbJava.usb_strerror()); + } + return bus; + } + + /** + * Explicitly calls {@link LibusbJava#usb_init()}. Note that you don't need + * to call this procedure as it is called implicitly when creating a new + * device with {@link USB#getDevice(short, short, String, String)}. + */ + public static void init() { + LibusbJava.usb_init(); + initUSBDone = true; + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/USBException.java b/src/main/java/ch/ntb/inf/libusbJava/USBException.java similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/USBException.java rename to src/main/java/ch/ntb/inf/libusbJava/USBException.java index 5273f2a..ff4fd1d 100644 --- a/java/src/ch/ntb/inf/libusbJava/USBException.java +++ b/src/main/java/ch/ntb/inf/libusbJava/USBException.java @@ -1,23 +1,23 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -import java.io.IOException; - -public class USBException extends IOException { - - public USBException(String string) { - super(string); - } - - /** - * - */ - private static final long serialVersionUID = 1690857437804284710L; - -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +import java.io.IOException; + +public class USBException extends IOException { + + public USBException(String string) { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = 1690857437804284710L; + +} diff --git a/java/src/ch/ntb/inf/libusbJava/USBTimeoutException.java b/src/main/java/ch/ntb/inf/libusbJava/USBTimeoutException.java similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/USBTimeoutException.java rename to src/main/java/ch/ntb/inf/libusbJava/USBTimeoutException.java index 1bd6c00..2aa9aeb 100644 --- a/java/src/ch/ntb/inf/libusbJava/USBTimeoutException.java +++ b/src/main/java/ch/ntb/inf/libusbJava/USBTimeoutException.java @@ -1,21 +1,21 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -public class USBTimeoutException extends USBException { - - public USBTimeoutException(String string) { - super(string); - } - - /** - * - */ - private static final long serialVersionUID = -1065328371159778249L; - -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +public class USBTimeoutException extends USBException { + + public USBTimeoutException(String string) { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = -1065328371159778249L; + +} diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Bus.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Bus.java similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/Usb_Bus.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Bus.java index 6930ee7..9ff2bdb 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Bus.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Bus.java @@ -1,107 +1,107 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents an USB bus.
- * This is the root class for the representation of the libusb USB structure. - * Zero or more devices may be connected to an USB bus. - * - */ -public class Usb_Bus { - - private Usb_Bus next, prev; - - private String dirname; - - private Usb_Device devices; - - private long location; - - private Usb_Device root_dev; - - public Usb_Bus(String dirname, long location) { - this.dirname = dirname; - this.location = location; - } - - /** - * Get the first device ojects of the devices linked list.
- * - * @return the first device ojects of the devices linked list or null - */ - public Usb_Device getDevices() { - return devices; - } - - protected void setDevices(Usb_Device devices) { - this.devices = devices; - } - - /** - * Returns the systems String representation of the bus.
- * - * @return the systems String representation of the bus - */ - public String getDirname() { - return dirname; - } - - /** - * Returns the next bus object.
- * - * @return Returns the next bus object or null - */ - public Usb_Bus getNext() { - return next; - } - - protected void setNext(Usb_Bus bus) { - next = bus; - } - - /** - * Returns the previous bus object.
- * - * @return Returns the previous bus object or null - */ - public Usb_Bus getPrev() { - return prev; - } - - protected void setPrev(Usb_Bus bus) { - prev = bus; - } - - /** - * Get the root device of this bus.
- * - * @return the root device oject or null - */ - public Usb_Device getRootDev() { - return root_dev; - } - - /** - * Returns the location in the USB bus linked list.
- * - * @return the location in the USB bus linked list - */ - public long getLocation() { - return location; - } - - protected void setLocation(long busnumber) { - location = busnumber; - } - - @Override - public String toString() { - return "Usb_Bus " + dirname; - } +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents an USB bus.
+ * This is the root class for the representation of the libusb USB structure. + * Zero or more devices may be connected to an USB bus. + * + */ +public class Usb_Bus { + + private Usb_Bus next, prev; + + private String dirname; + + private Usb_Device devices; + + private long location; + + private Usb_Device root_dev; + + public Usb_Bus(String dirname, long location) { + this.dirname = dirname; + this.location = location; + } + + /** + * Get the first device ojects of the devices linked list.
+ * + * @return the first device ojects of the devices linked list or null + */ + public Usb_Device getDevices() { + return devices; + } + + protected void setDevices(Usb_Device devices) { + this.devices = devices; + } + + /** + * Returns the systems String representation of the bus.
+ * + * @return the systems String representation of the bus + */ + public String getDirname() { + return dirname; + } + + /** + * Returns the next bus object.
+ * + * @return Returns the next bus object or null + */ + public Usb_Bus getNext() { + return next; + } + + protected void setNext(Usb_Bus bus) { + next = bus; + } + + /** + * Returns the previous bus object.
+ * + * @return Returns the previous bus object or null + */ + public Usb_Bus getPrev() { + return prev; + } + + protected void setPrev(Usb_Bus bus) { + prev = bus; + } + + /** + * Get the root device of this bus.
+ * + * @return the root device oject or null + */ + public Usb_Device getRootDev() { + return root_dev; + } + + /** + * Returns the location in the USB bus linked list.
+ * + * @return the location in the USB bus linked list + */ + public long getLocation() { + return location; + } + + protected void setLocation(long busnumber) { + location = busnumber; + } + + @Override + public String toString() { + return "Usb_Bus " + dirname; + } } \ No newline at end of file diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Config_Descriptor.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Config_Descriptor.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/Usb_Config_Descriptor.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Config_Descriptor.java index f511295..ffad600 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Config_Descriptor.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Config_Descriptor.java @@ -1,139 +1,139 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents the descriptor of a USB configuration.
- * A USB device can have several different configuration.
- *
- * The length of the configuration descriptor is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_CONFIG_SIZE} and the type is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_CONFIG}. - * - */ -public class Usb_Config_Descriptor extends Usb_Descriptor { - - /** - * Maximum number of configurations per device - */ - public static final int USB_MAXCONFIG = 8; - - private short wTotalLength; - - private byte bNumInterfaces; - - private byte bConfigurationValue; - - private byte iConfiguration; - - private byte bmAttributes; - - private byte MaxPower; - - private Usb_Interface[] interface_; - - private byte[] extra; /* Extra descriptors */ - - private int extralen; - - /** - * Returns the value to use as an argument to select this configuration ({@link LibusbJava#usb_set_configuration(long, int)}). - * - * @return the value to use as an argument to select this configuration - */ - public byte getBConfigurationValue() { - return bConfigurationValue; - } - - /** - * Returns the power parameters for this configuration.
- *
- * Bit 7: Reserved, set to 1 (USB 1.0 Bus Powered)
- * Bit 6: Self Powered
- * Bit 5: Remote Wakeup
- * Bit 4..0: Reserved, set to 0 - * - * @return the power parameters for this configuration - */ - public byte getBmAttributes() { - return bmAttributes; - } - - /** - * Returns the number of interfaces.
- * - * @return the number of interfaces - */ - public byte getBNumInterfaces() { - return bNumInterfaces; - } - - /** - * Returns the data of extra descriptor(s) if available.
- * - * @return null or a byte array with the extra descriptor data - */ - public byte[] getExtra() { - return extra; - } - - /** - * Returns the number of bytes of the extra descriptor.
- * - * @return the number of bytes of the extra descriptor - */ - public int getExtralen() { - return extralen; - } - - /** - * Returns the index of the String descriptor describing this configuration.
- * - * @return the index of the String descriptor - */ - public byte getIConfiguration() { - return iConfiguration; - } - - /** - * Returns the USB interface descriptors.
- * - * @return the USB interface descriptors - */ - public Usb_Interface[] getInterface() { - return interface_; - } - - /** - * Returns the maximum power consumption in 2mA units.
- * - * @return the maximum power consumption in 2mA units - */ - public byte getMaxPower() { - return MaxPower; - } - - /** - * Returns the total length in bytes of all descriptors.
- * When the configuration descriptor is read, it returns the entire - * configuration hierarchy which includes all related interface and endpoint - * descriptors. The wTotalLength field reflects the number of - * bytes in the hierarchy. - * - * @return the total length in bytes of all descriptors - */ - public short getWTotalLength() { - return wTotalLength; - } - - @Override - public String toString() { - return "Usb_Config_Descriptor bNumInterfaces: 0x" - + Integer.toHexString(bNumInterfaces); - } +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents the descriptor of a USB configuration.
+ * A USB device can have several different configuration.
+ *
+ * The length of the configuration descriptor is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_CONFIG_SIZE} and the type is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_CONFIG}. + * + */ +public class Usb_Config_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of configurations per device + */ + public static final int USB_MAXCONFIG = 8; + + private short wTotalLength; + + private byte bNumInterfaces; + + private byte bConfigurationValue; + + private byte iConfiguration; + + private byte bmAttributes; + + private byte MaxPower; + + private Usb_Interface[] interface_; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + /** + * Returns the value to use as an argument to select this configuration ({@link LibusbJava#usb_set_configuration(long, int)}). + * + * @return the value to use as an argument to select this configuration + */ + public byte getBConfigurationValue() { + return bConfigurationValue; + } + + /** + * Returns the power parameters for this configuration.
+ *
+ * Bit 7: Reserved, set to 1 (USB 1.0 Bus Powered)
+ * Bit 6: Self Powered
+ * Bit 5: Remote Wakeup
+ * Bit 4..0: Reserved, set to 0 + * + * @return the power parameters for this configuration + */ + public byte getBmAttributes() { + return bmAttributes; + } + + /** + * Returns the number of interfaces.
+ * + * @return the number of interfaces + */ + public byte getBNumInterfaces() { + return bNumInterfaces; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the index of the String descriptor describing this configuration.
+ * + * @return the index of the String descriptor + */ + public byte getIConfiguration() { + return iConfiguration; + } + + /** + * Returns the USB interface descriptors.
+ * + * @return the USB interface descriptors + */ + public Usb_Interface[] getInterface() { + return interface_; + } + + /** + * Returns the maximum power consumption in 2mA units.
+ * + * @return the maximum power consumption in 2mA units + */ + public byte getMaxPower() { + return MaxPower; + } + + /** + * Returns the total length in bytes of all descriptors.
+ * When the configuration descriptor is read, it returns the entire + * configuration hierarchy which includes all related interface and endpoint + * descriptors. The wTotalLength field reflects the number of + * bytes in the hierarchy. + * + * @return the total length in bytes of all descriptors + */ + public short getWTotalLength() { + return wTotalLength; + } + + @Override + public String toString() { + return "Usb_Config_Descriptor bNumInterfaces: 0x" + + Integer.toHexString(bNumInterfaces); + } } \ No newline at end of file diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Descriptor.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Descriptor.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/Usb_Descriptor.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Descriptor.java index 10e183e..379a77f 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Descriptor.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Descriptor.java @@ -1,61 +1,61 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Common USB descriptor values.
- * - */ -public class Usb_Descriptor { - - /** - * Descriptor types ({@link #bDescriptorType}). - */ - public static final int USB_DT_DEVICE = 0x01, USB_DT_CONFIG = 0x02, - USB_DT_STRING = 0x03, USB_DT_INTERFACE = 0x04, - USB_DT_ENDPOINT = 0x05; - - /** - * Descriptor types ({@link #bDescriptorType}). - */ - public static final int LIBUSB_DT_DEVICE = 0x01, LIBUSB_DT_CONFIG = 0x02, - LIBUSB_DT_STRING = 0x03, LIBUSB_DT_INTERFACE = 0x04, - LIBUSB_DT_ENDPOINT = 0x05, USB_DT_HID = 0x21, USB_DT_REPORT = 0x22, - USB_DT_PHYSICAL = 0x23, USB_DT_HUB = 0x29; - - /** - * Descriptor sizes per descriptor type ({@link #bLength}). - */ - public static final int USB_DT_DEVICE_SIZE = 18, USB_DT_CONFIG_SIZE = 9, - USB_DT_INTERFACE_SIZE = 9, USB_DT_ENDPOINT_SIZE = 7, - USB_DT_ENDPOINT_AUDIO_SIZE = 9 /* Audio extension */, - USB_DT_HUB_NONVAR_SIZE = 7; - - private byte bLength; - - private byte bDescriptorType; - - /** - * Get the type of this descriptor.
- * - * @return the type of this descriptor - */ - public byte getBDescriptorType() { - return bDescriptorType; - } - - /** - * Get the size of this descriptor in bytes.
- * - * @return the size of this descriptor in bytes - */ - public byte getBLength() { - return bLength; - } - -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Common USB descriptor values.
+ * + */ +public class Usb_Descriptor { + + /** + * Descriptor types ({@link #bDescriptorType}). + */ + public static final int USB_DT_DEVICE = 0x01, USB_DT_CONFIG = 0x02, + USB_DT_STRING = 0x03, USB_DT_INTERFACE = 0x04, + USB_DT_ENDPOINT = 0x05; + + /** + * Descriptor types ({@link #bDescriptorType}). + */ + public static final int LIBUSB_DT_DEVICE = 0x01, LIBUSB_DT_CONFIG = 0x02, + LIBUSB_DT_STRING = 0x03, LIBUSB_DT_INTERFACE = 0x04, + LIBUSB_DT_ENDPOINT = 0x05, USB_DT_HID = 0x21, USB_DT_REPORT = 0x22, + USB_DT_PHYSICAL = 0x23, USB_DT_HUB = 0x29; + + /** + * Descriptor sizes per descriptor type ({@link #bLength}). + */ + public static final int USB_DT_DEVICE_SIZE = 18, USB_DT_CONFIG_SIZE = 9, + USB_DT_INTERFACE_SIZE = 9, USB_DT_ENDPOINT_SIZE = 7, + USB_DT_ENDPOINT_AUDIO_SIZE = 9 /* Audio extension */, + USB_DT_HUB_NONVAR_SIZE = 7; + + private byte bLength; + + private byte bDescriptorType; + + /** + * Get the type of this descriptor.
+ * + * @return the type of this descriptor + */ + public byte getBDescriptorType() { + return bDescriptorType; + } + + /** + * Get the size of this descriptor in bytes.
+ * + * @return the size of this descriptor in bytes + */ + public byte getBLength() { + return bLength; + } + +} diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Device.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Device.java similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/Usb_Device.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Device.java index 77cc598..580f3ec 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Device.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Device.java @@ -1,165 +1,165 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents an USB device.
- * An USB device has one device descriptor and it may have multiple - * configuration descriptors. - * - */ -public class Usb_Device { - - private Usb_Device next, prev; - - private String filename; - - private Usb_Bus bus; - - private Usb_Device_Descriptor descriptor; - - private Usb_Config_Descriptor[] config; - - private byte devnum; - - private byte num_children; - - private Usb_Device children; - - /** - * The address of the device structure to be passed to usb_open. This value - * is used only internally so we don't use getter or setter methods. - */ - public long devStructAddr; - - /** - * Returns the reference to the bus to which this device is connected.
- * - * @return the reference to the bus to which this device is connected - */ - public Usb_Bus getBus() { - return bus; - } - protected void setBus(Usb_Bus bus){ - this.bus = bus; - } - - /** - * Returns a reference to the first child.
- * - * @return a reference to the first child - */ - public Usb_Device getChildren() { - return children; - } - - /** - * Returns the USB config descriptors.
- * - * @return the USB config descriptors - */ - public Usb_Config_Descriptor[] getConfig() { - return config; - } - - /** - * Returns the USB device descriptor.
- * - * @return the USB device descriptor - */ - public Usb_Device_Descriptor getDescriptor() { - return descriptor; - } - - /** - * Returns the number assigned to this device.
- * - * @return the number assigned to this device - */ - public byte getDevnum() { - return devnum; - } - - /** - * Returns the systems String representation.
- * - * @return the systems String representation - */ - public String getFilename() { - return filename; - } - - /** - * Returns the pointer to the next device.
- * - * @return the pointer to the next device or null - */ - public Usb_Device getNext() { - return next; - } - - protected void setNext(Usb_Device dev){ - next = dev; - } - - public static void freeDeviceList(Usb_Device device) - { - Usb_Device curr = device.getPrev(); - - /* Detach the left part of the list */ - device.setPrev(null); - - /* First walk to the left of the list and free all - devices on our way */ - while (curr != null) - { - freeDevice(curr); - curr = curr.getPrev(); - } - - curr = device; - /* Then walk to the right of the list and free all */ - while (curr != null) - { - freeDevice(curr); - curr = curr.getNext(); - } - } - - public static void freeDevice(Usb_Device device) - { - freeDeviceList(device.getChildren()); - LibusbJava1.libusb_unref_device(device); - } - - /** - * Returns the number of children of this device.
- * - * @return the number of children of this device - */ - public byte getNumChildren() { - return num_children; - } - - /** - * Returns the pointer to the previous device.
- * - * @return the pointer to the previous device or null - */ - public Usb_Device getPrev() { - return prev; - } - protected void setPrev(Usb_Device dev){ - prev = dev; - } - - @Override - public String toString() { - return "Usb_Device " + filename; - } +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents an USB device.
+ * An USB device has one device descriptor and it may have multiple + * configuration descriptors. + * + */ +public class Usb_Device { + + private Usb_Device next, prev; + + private String filename; + + private Usb_Bus bus; + + private Usb_Device_Descriptor descriptor; + + private Usb_Config_Descriptor[] config; + + private byte devnum; + + private byte num_children; + + private Usb_Device children; + + /** + * The address of the device structure to be passed to usb_open. This value + * is used only internally so we don't use getter or setter methods. + */ + public long devStructAddr; + + /** + * Returns the reference to the bus to which this device is connected.
+ * + * @return the reference to the bus to which this device is connected + */ + public Usb_Bus getBus() { + return bus; + } + protected void setBus(Usb_Bus bus){ + this.bus = bus; + } + + /** + * Returns a reference to the first child.
+ * + * @return a reference to the first child + */ + public Usb_Device getChildren() { + return children; + } + + /** + * Returns the USB config descriptors.
+ * + * @return the USB config descriptors + */ + public Usb_Config_Descriptor[] getConfig() { + return config; + } + + /** + * Returns the USB device descriptor.
+ * + * @return the USB device descriptor + */ + public Usb_Device_Descriptor getDescriptor() { + return descriptor; + } + + /** + * Returns the number assigned to this device.
+ * + * @return the number assigned to this device + */ + public byte getDevnum() { + return devnum; + } + + /** + * Returns the systems String representation.
+ * + * @return the systems String representation + */ + public String getFilename() { + return filename; + } + + /** + * Returns the pointer to the next device.
+ * + * @return the pointer to the next device or null + */ + public Usb_Device getNext() { + return next; + } + + protected void setNext(Usb_Device dev){ + next = dev; + } + + public static void freeDeviceList(Usb_Device device) + { + Usb_Device curr = device.getPrev(); + + /* Detach the left part of the list */ + device.setPrev(null); + + /* First walk to the left of the list and free all + devices on our way */ + while (curr != null) + { + freeDevice(curr); + curr = curr.getPrev(); + } + + curr = device; + /* Then walk to the right of the list and free all */ + while (curr != null) + { + freeDevice(curr); + curr = curr.getNext(); + } + } + + public static void freeDevice(Usb_Device device) + { + freeDeviceList(device.getChildren()); + LibusbJava1.libusb_unref_device(device); + } + + /** + * Returns the number of children of this device.
+ * + * @return the number of children of this device + */ + public byte getNumChildren() { + return num_children; + } + + /** + * Returns the pointer to the previous device.
+ * + * @return the pointer to the previous device or null + */ + public Usb_Device getPrev() { + return prev; + } + protected void setPrev(Usb_Device dev){ + prev = dev; + } + + @Override + public String toString() { + return "Usb_Device " + filename; + } } \ No newline at end of file diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Device_Descriptor.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Device_Descriptor.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/Usb_Device_Descriptor.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Device_Descriptor.java index 9dc20b3..138c779 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Device_Descriptor.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Device_Descriptor.java @@ -1,191 +1,191 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents the descriptor of a USB device.
- * A USB device can only have one device descriptor. It specifies some basic, - * yet important information about the device.
- *
- * The length of the device descriptor is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_DEVICE_SIZE} and the type is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_DEVICE}. - * - */ -public class Usb_Device_Descriptor extends Usb_Descriptor { - /** - * Device and/or interface class codes. - */ - public static final int USB_CLASS_PER_INTERFACE = 0, USB_CLASS_AUDIO = 1, - USB_CLASS_COMM = 2, USB_CLASS_HID = 3, LIBUSB_CLASS_PTP = 6, - USB_CLASS_PRINTER = 7, USB_CLASS_MASS_STORAGE = 8, - USB_CLASS_HUB = 9, USB_CLASS_DATA = 10, - USB_CLASS_VENDOR_SPEC = 0xff; - - private short bcdUSB; - - private byte bDeviceClass; - - private byte bDeviceSubClass; - - private byte bDeviceProtocol; - - private byte bMaxPacketSize0; - - private short idVendor; - - private short idProduct; - - private short bcdDevice; - - private byte iManufacturer; - - private byte iProduct; - - private byte iSerialNumber; - - private byte bNumConfigurations; - - /** - * Returns the device release number.
- * Assigned by the manufacturer of the device. - * - * @return the device release number - */ - public short getBcdDevice() { - return bcdDevice; - } - - /** - * Returns the USB specification number to which the device complies to.
- * This field reports the highest version of USB the device supports. The - * value is in binary coded decimal with a format of 0xJJMN where JJ is the - * major version number, M is the minor version number and N is the sub - * minor version number.
- * Examples: USB 2.0 is reported as 0x0200, USB 1.1 as 0x0110 and USB 1.0 as - * 0x100 - * - * @return the USB specification number to which the device complies to - */ - public short getBcdUSB() { - return bcdUSB; - } - - /** - * Returns the class code (Assigned by www.usb.org)
- * If equal to zero, each interface specifies it's own class code. If equal - * to 0xFF, the class code is vendor specified. Otherwise the field is a - * valid class code. - * - * @return the class code - */ - public byte getBDeviceClass() { - return bDeviceClass; - } - - /** - * Returns the protocol code (Assigned by www.usb.org)
- * - * @return the protocol code - */ - public byte getBDeviceProtocol() { - return bDeviceProtocol; - } - - /** - * Returns the subclass code (Assigned by www.usb.org)
- * - * @return the subclass code - */ - public byte getBDeviceSubClass() { - return bDeviceSubClass; - } - - /** - * Returns the maximum packet size for endpoint zero.
- * Valid sizes are 8, 16, 32, 64. - * - * @return the maximum packet size for endpoint zero - */ - public byte getBMaxPacketSize0() { - return bMaxPacketSize0; - } - - /** - * Returns the number of possible configurations supported at its current - * speed.
- * - * @return the number of possible configurations supported at its current - * speed - */ - public byte getBNumConfigurations() { - return bNumConfigurations; - } - - /** - * Returns the product ID (Assigned by www.usb.org)
- * - * @return the product ID - */ - public short getIdProduct() { - return idProduct; - } - - /** - * Returns the Vendor ID (Assigned by www.usb.org)
- * - * @return the Vendor ID - */ - public short getIdVendor() { - return idVendor; - } - - /** - * Returns the index of the manufacturer string descriptor.
- * If this value is 0, no string descriptor is used. - * - * @return the index of the manufacturer string descriptor - */ - public byte getIManufacturer() { - return iManufacturer; - } - - /** - * Returns the index of the product string descriptor.
- * If this value is 0, no string descriptor is used. - * - * @return the index of the product string descriptor - */ - public byte getIProduct() { - return iProduct; - } - - /** - * Returns the index of serial number string descriptor.
- * If this value is 0, no string descriptor is used. - * - * @return the index of serial number string descriptor - */ - public byte getISerialNumber() { - return iSerialNumber; - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("Usb_Device_Descriptor idVendor: 0x" - + Integer.toHexString(idVendor & 0xFFFF) + ", idProduct: 0x" - + Integer.toHexString(idProduct & 0xFFFF)); - return sb.toString(); - } +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents the descriptor of a USB device.
+ * A USB device can only have one device descriptor. It specifies some basic, + * yet important information about the device.
+ *
+ * The length of the device descriptor is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_DEVICE_SIZE} and the type is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_DEVICE}. + * + */ +public class Usb_Device_Descriptor extends Usb_Descriptor { + /** + * Device and/or interface class codes. + */ + public static final int USB_CLASS_PER_INTERFACE = 0, USB_CLASS_AUDIO = 1, + USB_CLASS_COMM = 2, USB_CLASS_HID = 3, LIBUSB_CLASS_PTP = 6, + USB_CLASS_PRINTER = 7, USB_CLASS_MASS_STORAGE = 8, + USB_CLASS_HUB = 9, USB_CLASS_DATA = 10, + USB_CLASS_VENDOR_SPEC = 0xff; + + private short bcdUSB; + + private byte bDeviceClass; + + private byte bDeviceSubClass; + + private byte bDeviceProtocol; + + private byte bMaxPacketSize0; + + private short idVendor; + + private short idProduct; + + private short bcdDevice; + + private byte iManufacturer; + + private byte iProduct; + + private byte iSerialNumber; + + private byte bNumConfigurations; + + /** + * Returns the device release number.
+ * Assigned by the manufacturer of the device. + * + * @return the device release number + */ + public short getBcdDevice() { + return bcdDevice; + } + + /** + * Returns the USB specification number to which the device complies to.
+ * This field reports the highest version of USB the device supports. The + * value is in binary coded decimal with a format of 0xJJMN where JJ is the + * major version number, M is the minor version number and N is the sub + * minor version number.
+ * Examples: USB 2.0 is reported as 0x0200, USB 1.1 as 0x0110 and USB 1.0 as + * 0x100 + * + * @return the USB specification number to which the device complies to + */ + public short getBcdUSB() { + return bcdUSB; + } + + /** + * Returns the class code (Assigned by www.usb.org)
+ * If equal to zero, each interface specifies it's own class code. If equal + * to 0xFF, the class code is vendor specified. Otherwise the field is a + * valid class code. + * + * @return the class code + */ + public byte getBDeviceClass() { + return bDeviceClass; + } + + /** + * Returns the protocol code (Assigned by www.usb.org)
+ * + * @return the protocol code + */ + public byte getBDeviceProtocol() { + return bDeviceProtocol; + } + + /** + * Returns the subclass code (Assigned by www.usb.org)
+ * + * @return the subclass code + */ + public byte getBDeviceSubClass() { + return bDeviceSubClass; + } + + /** + * Returns the maximum packet size for endpoint zero.
+ * Valid sizes are 8, 16, 32, 64. + * + * @return the maximum packet size for endpoint zero + */ + public byte getBMaxPacketSize0() { + return bMaxPacketSize0; + } + + /** + * Returns the number of possible configurations supported at its current + * speed.
+ * + * @return the number of possible configurations supported at its current + * speed + */ + public byte getBNumConfigurations() { + return bNumConfigurations; + } + + /** + * Returns the product ID (Assigned by www.usb.org)
+ * + * @return the product ID + */ + public short getIdProduct() { + return idProduct; + } + + /** + * Returns the Vendor ID (Assigned by www.usb.org)
+ * + * @return the Vendor ID + */ + public short getIdVendor() { + return idVendor; + } + + /** + * Returns the index of the manufacturer string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of the manufacturer string descriptor + */ + public byte getIManufacturer() { + return iManufacturer; + } + + /** + * Returns the index of the product string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of the product string descriptor + */ + public byte getIProduct() { + return iProduct; + } + + /** + * Returns the index of serial number string descriptor.
+ * If this value is 0, no string descriptor is used. + * + * @return the index of serial number string descriptor + */ + public byte getISerialNumber() { + return iSerialNumber; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Usb_Device_Descriptor idVendor: 0x" + + Integer.toHexString(idVendor & 0xFFFF) + ", idProduct: 0x" + + Integer.toHexString(idProduct & 0xFFFF)); + return sb.toString(); + } } \ No newline at end of file diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor.java index bd83147..03b4227 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Endpoint_Descriptor.java @@ -1,175 +1,175 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents the descriptor of an USB endpoint.
- * Endpoint descriptors are used to describe endpoints other than endpoint zero. - * Endpoint zero is always assumed to be a control endpoint and is configured - * before any descriptors are even requested. The host will use the information - * returned from these descriptors to determine the bandwidth requirements of - * the bus.
- *
- * The length of the configuration descriptor is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_ENDPOINT_SIZE} and the type is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_ENDPOINT}. - * - */ -public class Usb_Endpoint_Descriptor extends Usb_Descriptor { - - /** - * Maximum number of endpoints - */ - public static final int USB_MAXENDPOINTS = 32; - - /** - * Endpoint address mask (in bEndpointAddress). - */ - public static final int USB_ENDPOINT_ADDRESS_MASK = 0x0f, - USB_ENDPOINT_DIR_MASK = 0x80; - - /** - * Endpoint type mask (in bmAttributes). - */ - public static final int USB_ENDPOINT_TRANSFER_TYPE_MASK = 0x03, - USB_ENDPOINT_ISO_SYNC_TYPE = 0x0C, - USB_ENDPOINT_ISO_USAGE_TYPE = 0x30; - - /** - * Possible endpoint types (in bmAttributes). - */ - public static final int USB_ENDPOINT_TRANSFER_TYPE_CONTROL = 0, - USB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS = 1, - USB_ENDPOINT_TRANSFER_TYPE_BULK = 2, - USB_ENDPOINT_TRANSFER_TYPE_INTERRUPT = 3; - /** - * Possible synchronization types for isochronous endpoints. - */ - public static final int USB_ENDPOINT_ISO_SYNC_TYPE_NONE = 0, - USB_ENDPOINT_ISO_SYNC_TYPE_ASYNC = 1, - USB_ENDPOINT_ISO_SYNC_TYPE_ADAPTIVE = 2, - USB_ENDPOINT_ISO_SYNC_TYPE_SYNC = 3; - - /** - * Possible usage types for isochronous endpoints - */ - public static final int USB_ENDPOINT_ISO_USAGE_TYPE_DATA = 0, - USB_ENDPOINT_ISO_USAGE_TYPE_FEEDBACK = 1, - USB_ENDPOINT_ISO_USAGE_TYPE_IMPLICIT = 2; - - private byte bEndpointAddress; - - private byte bmAttributes; - - private short wMaxPacketSize; - - private byte bInterval; - - private byte bRefresh; - - private byte bSynchAddress; - - private byte[] extra; /* Extra descriptors */ - - private int extralen; - - /** - * Returns the endpoint address.
- *
- * Bits 3..0: Endpoint number
- * Bits 6..4: Reserved. Set to zero
- * Bit 7: Direction (host to device). 0 = OUT (send data from host to - * device), 1 = IN (host receives data from device). Note: these values are - * ignored for control endpoints.
- * - * @return the endpoint address - */ - public byte getBEndpointAddress() { - return bEndpointAddress; - } - - /** - * Returns the intervall for polling endpoint data transfers.
- * Value in frame counts. Ignored for Bulk & Control eEndpoints. Isochronous - * endpoints must equal 1 and field may range from 1 to 255 for interrupt - * endpoints. - * - * @return the intervall for polling endpoint data transfers - */ - public byte getBInterval() { - return bInterval; - } - - /** - * Returns the attributes of this endpoint.
- * - * Bits 1..0: Transfer Type (see USB_ENDPOINT_TYPE_XXX).
- * Bits 7..2: Reserved.
- * - *
-	 * 	If isochronous endpoint:
-	 * 		Bits 3..2: Synchronisation type
-	 *  		00 = No synchronisation
-	 * 			01 = Asynchronous
-	 *          10 = Adaptive
-	 *          11 = Synchronous
-	 *     	Bits 5..4: Usage Type
-	 *      	00 = Data endpoint
-	 *      	01 = Feedback endpoint
-	 *      	10 = Explicit feedback data endpoint
-	 *      	11 = Reserved
-	 * 
- * - * @return the attributes of this endpoint - */ - public byte getBmAttributes() { - return bmAttributes; - } - - public byte getBRefresh() { - return bRefresh; - } - - public byte getBSynchAddress() { - return bSynchAddress; - } - - /** - * Returns the data of extra descriptor(s) if available.
- * - * @return null or a byte array with the extra descriptor data - */ - public byte[] getExtra() { - return extra; - } - - /** - * Returns the number of bytes of the extra descriptor.
- * - * @return the number of bytes of the extra descriptor - */ - public int getExtralen() { - return extralen; - } - - /** - * Returns the maximum packet size of this endpoint is capable of sending or - * receiving.
- * - * @return the maximum packet size - */ - public short getWMaxPacketSize() { - return wMaxPacketSize; - } - - @Override - public String toString() { - return "Usb_Endpoint_Descriptor bEndpointAddress: 0x" - + Integer.toHexString(bEndpointAddress & 0xFF); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents the descriptor of an USB endpoint.
+ * Endpoint descriptors are used to describe endpoints other than endpoint zero. + * Endpoint zero is always assumed to be a control endpoint and is configured + * before any descriptors are even requested. The host will use the information + * returned from these descriptors to determine the bandwidth requirements of + * the bus.
+ *
+ * The length of the configuration descriptor is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_ENDPOINT_SIZE} and the type is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_ENDPOINT}. + * + */ +public class Usb_Endpoint_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of endpoints + */ + public static final int USB_MAXENDPOINTS = 32; + + /** + * Endpoint address mask (in bEndpointAddress). + */ + public static final int USB_ENDPOINT_ADDRESS_MASK = 0x0f, + USB_ENDPOINT_DIR_MASK = 0x80; + + /** + * Endpoint type mask (in bmAttributes). + */ + public static final int USB_ENDPOINT_TRANSFER_TYPE_MASK = 0x03, + USB_ENDPOINT_ISO_SYNC_TYPE = 0x0C, + USB_ENDPOINT_ISO_USAGE_TYPE = 0x30; + + /** + * Possible endpoint types (in bmAttributes). + */ + public static final int USB_ENDPOINT_TRANSFER_TYPE_CONTROL = 0, + USB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS = 1, + USB_ENDPOINT_TRANSFER_TYPE_BULK = 2, + USB_ENDPOINT_TRANSFER_TYPE_INTERRUPT = 3; + /** + * Possible synchronization types for isochronous endpoints. + */ + public static final int USB_ENDPOINT_ISO_SYNC_TYPE_NONE = 0, + USB_ENDPOINT_ISO_SYNC_TYPE_ASYNC = 1, + USB_ENDPOINT_ISO_SYNC_TYPE_ADAPTIVE = 2, + USB_ENDPOINT_ISO_SYNC_TYPE_SYNC = 3; + + /** + * Possible usage types for isochronous endpoints + */ + public static final int USB_ENDPOINT_ISO_USAGE_TYPE_DATA = 0, + USB_ENDPOINT_ISO_USAGE_TYPE_FEEDBACK = 1, + USB_ENDPOINT_ISO_USAGE_TYPE_IMPLICIT = 2; + + private byte bEndpointAddress; + + private byte bmAttributes; + + private short wMaxPacketSize; + + private byte bInterval; + + private byte bRefresh; + + private byte bSynchAddress; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + /** + * Returns the endpoint address.
+ *
+ * Bits 3..0: Endpoint number
+ * Bits 6..4: Reserved. Set to zero
+ * Bit 7: Direction (host to device). 0 = OUT (send data from host to + * device), 1 = IN (host receives data from device). Note: these values are + * ignored for control endpoints.
+ * + * @return the endpoint address + */ + public byte getBEndpointAddress() { + return bEndpointAddress; + } + + /** + * Returns the intervall for polling endpoint data transfers.
+ * Value in frame counts. Ignored for Bulk & Control eEndpoints. Isochronous + * endpoints must equal 1 and field may range from 1 to 255 for interrupt + * endpoints. + * + * @return the intervall for polling endpoint data transfers + */ + public byte getBInterval() { + return bInterval; + } + + /** + * Returns the attributes of this endpoint.
+ * + * Bits 1..0: Transfer Type (see USB_ENDPOINT_TYPE_XXX).
+ * Bits 7..2: Reserved.
+ * + *
+	 * 	If isochronous endpoint:
+	 * 		Bits 3..2: Synchronisation type
+	 *  		00 = No synchronisation
+	 * 			01 = Asynchronous
+	 *          10 = Adaptive
+	 *          11 = Synchronous
+	 *     	Bits 5..4: Usage Type
+	 *      	00 = Data endpoint
+	 *      	01 = Feedback endpoint
+	 *      	10 = Explicit feedback data endpoint
+	 *      	11 = Reserved
+	 * 
+ * + * @return the attributes of this endpoint + */ + public byte getBmAttributes() { + return bmAttributes; + } + + public byte getBRefresh() { + return bRefresh; + } + + public byte getBSynchAddress() { + return bSynchAddress; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the maximum packet size of this endpoint is capable of sending or + * receiving.
+ * + * @return the maximum packet size + */ + public short getWMaxPacketSize() { + return wMaxPacketSize; + } + + @Override + public String toString() { + return "Usb_Endpoint_Descriptor bEndpointAddress: 0x" + + Integer.toHexString(bEndpointAddress & 0xFF); + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Interface.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Interface.java similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/Usb_Interface.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Interface.java index d96d59e..284feb3 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Interface.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Interface.java @@ -1,50 +1,50 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents an USB interface.
- * An interface is a group of alternate settings of a configuration.
- * - */ -public class Usb_Interface { - - /** - * Maximal number of alternate settings - */ - public static final int USB_MAXALTSETTING = 128; /* Hard limit */ - - private Usb_Interface_Descriptor[] altsetting; - - private int num_altsetting; - - @Override - public String toString() { - return "Usb_Interface num_altsetting: 0x" - + Integer.toHexString(num_altsetting); - } - - /** - * Retuns an array of interface descriptors.
- * - * @return an array of interface descriptors - */ - public Usb_Interface_Descriptor[] getAltsetting() { - return altsetting; - } - - /** - * Returns the number of alternate settings.
- * - * @return the number of alternate settings - */ - public int getNumAltsetting() { - return num_altsetting; - } - -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents an USB interface.
+ * An interface is a group of alternate settings of a configuration.
+ * + */ +public class Usb_Interface { + + /** + * Maximal number of alternate settings + */ + public static final int USB_MAXALTSETTING = 128; /* Hard limit */ + + private Usb_Interface_Descriptor[] altsetting; + + private int num_altsetting; + + @Override + public String toString() { + return "Usb_Interface num_altsetting: 0x" + + Integer.toHexString(num_altsetting); + } + + /** + * Retuns an array of interface descriptors.
+ * + * @return an array of interface descriptors + */ + public Usb_Interface_Descriptor[] getAltsetting() { + return altsetting; + } + + /** + * Returns the number of alternate settings.
+ * + * @return the number of alternate settings + */ + public int getNumAltsetting() { + return num_altsetting; + } + +} diff --git a/java/src/ch/ntb/inf/libusbJava/Usb_Interface_Descriptor.java b/src/main/java/ch/ntb/inf/libusbJava/Usb_Interface_Descriptor.java similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/Usb_Interface_Descriptor.java rename to src/main/java/ch/ntb/inf/libusbJava/Usb_Interface_Descriptor.java index a152f29..bedb94e 100644 --- a/java/src/ch/ntb/inf/libusbJava/Usb_Interface_Descriptor.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Usb_Interface_Descriptor.java @@ -1,146 +1,146 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -/** - * Represents the descriptor of a USB interface.
- * The interface descriptor could be seen as a header or grouping of the - * endpoints into a functional group performing a single feature of the device.
- *
- * The length of the interface descriptor is - * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_INTERFACE_SIZE} and the - * type is {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_INTERFACE}. - * - */ -public class Usb_Interface_Descriptor extends Usb_Descriptor { - - /** - * Maximum number of interfaces - */ - public static final int USB_MAXINTERFACES = 32; - - private byte bInterfaceNumber; - - private byte bAlternateSetting; - - private byte bNumEndpoints; - - private byte bInterfaceClass; - - private byte bInterfaceSubClass; - - private byte bInterfaceProtocol; - - private byte iInterface; - - private Usb_Endpoint_Descriptor[] endpoint; - - private byte[] extra; /* Extra descriptors */ - - private int extralen; - - @Override - public String toString() { - return "Usb_Interface_Descriptor bNumEndpoints: 0x" - + Integer.toHexString(bNumEndpoints); - } - - /** - * Returns the value used to select the alternate setting ( - * {@link LibusbJava#usb_set_altinterface(long, int)}).
- * - * @return the alternate setting - */ - public byte getBAlternateSetting() { - return bAlternateSetting; - } - - /** - * Returns the class code (Assigned by www.usb.org).
- * - * @return the class code - */ - public byte getBInterfaceClass() { - return bInterfaceClass; - } - - /** - * Returns the number (identifier) of this interface.
- * - * @return the number (identifier) of this interface - */ - public byte getBInterfaceNumber() { - return bInterfaceNumber; - } - - /** - * Returns the protocol code (Assigned by www.usb.org).
- * - * @return the protocol code - */ - public byte getBInterfaceProtocol() { - return bInterfaceProtocol; - } - - /** - * Returns the subclass code (Assigned by www.usb.org).
- * - * @return the subclass code - */ - public byte getBInterfaceSubClass() { - return bInterfaceSubClass; - } - - /** - * Returns the number of endpoints used for this interface.
- * - * @return the number of endpoints used for this interface - */ - public byte getBNumEndpoints() { - return bNumEndpoints; - } - - /** - * Returns an array of endpoint descriptors.
- * - * @return an array of endpoint descriptors - */ - public Usb_Endpoint_Descriptor[] getEndpoint() { - return endpoint; - } - - /** - * Returns the data of extra descriptor(s) if available.
- * - * @return null or a byte array with the extra descriptor data - */ - public byte[] getExtra() { - return extra; - } - - /** - * Returns the number of bytes of the extra descriptor.
- * - * @return the number of bytes of the extra descriptor - */ - public int getExtralen() { - return extralen; - } - - /** - * Returns the index of the String descriptor describing this interface.
- * - * @return the index of the String descriptor - */ - public byte getIInterface() { - return iInterface; - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +/** + * Represents the descriptor of a USB interface.
+ * The interface descriptor could be seen as a header or grouping of the + * endpoints into a functional group performing a single feature of the device.
+ *
+ * The length of the interface descriptor is + * {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_INTERFACE_SIZE} and the + * type is {@link ch.ntb.inf.libusbJava.Usb_Descriptor#USB_DT_INTERFACE}. + * + */ +public class Usb_Interface_Descriptor extends Usb_Descriptor { + + /** + * Maximum number of interfaces + */ + public static final int USB_MAXINTERFACES = 32; + + private byte bInterfaceNumber; + + private byte bAlternateSetting; + + private byte bNumEndpoints; + + private byte bInterfaceClass; + + private byte bInterfaceSubClass; + + private byte bInterfaceProtocol; + + private byte iInterface; + + private Usb_Endpoint_Descriptor[] endpoint; + + private byte[] extra; /* Extra descriptors */ + + private int extralen; + + @Override + public String toString() { + return "Usb_Interface_Descriptor bNumEndpoints: 0x" + + Integer.toHexString(bNumEndpoints); + } + + /** + * Returns the value used to select the alternate setting ( + * {@link LibusbJava#usb_set_altinterface(long, int)}).
+ * + * @return the alternate setting + */ + public byte getBAlternateSetting() { + return bAlternateSetting; + } + + /** + * Returns the class code (Assigned by www.usb.org).
+ * + * @return the class code + */ + public byte getBInterfaceClass() { + return bInterfaceClass; + } + + /** + * Returns the number (identifier) of this interface.
+ * + * @return the number (identifier) of this interface + */ + public byte getBInterfaceNumber() { + return bInterfaceNumber; + } + + /** + * Returns the protocol code (Assigned by www.usb.org).
+ * + * @return the protocol code + */ + public byte getBInterfaceProtocol() { + return bInterfaceProtocol; + } + + /** + * Returns the subclass code (Assigned by www.usb.org).
+ * + * @return the subclass code + */ + public byte getBInterfaceSubClass() { + return bInterfaceSubClass; + } + + /** + * Returns the number of endpoints used for this interface.
+ * + * @return the number of endpoints used for this interface + */ + public byte getBNumEndpoints() { + return bNumEndpoints; + } + + /** + * Returns an array of endpoint descriptors.
+ * + * @return an array of endpoint descriptors + */ + public Usb_Endpoint_Descriptor[] getEndpoint() { + return endpoint; + } + + /** + * Returns the data of extra descriptor(s) if available.
+ * + * @return null or a byte array with the extra descriptor data + */ + public byte[] getExtra() { + return extra; + } + + /** + * Returns the number of bytes of the extra descriptor.
+ * + * @return the number of bytes of the extra descriptor + */ + public int getExtralen() { + return extralen; + } + + /** + * Returns the index of the String descriptor describing this interface.
+ * + * @return the index of the String descriptor + */ + public byte getIInterface() { + return iInterface; + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/Utils.java b/src/main/java/ch/ntb/inf/libusbJava/Utils.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/Utils.java rename to src/main/java/ch/ntb/inf/libusbJava/Utils.java index 6ba6a73..4e1f89d 100644 --- a/java/src/ch/ntb/inf/libusbJava/Utils.java +++ b/src/main/java/ch/ntb/inf/libusbJava/Utils.java @@ -1,60 +1,60 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava; - -import java.io.PrintStream; - -public class Utils { - - public static void logBus(Usb_Bus bus) { - logBus(bus, System.out); - } - - public static void logBus(Usb_Bus bus, PrintStream out) { - Usb_Bus usb_Bus = bus; - while (usb_Bus != null) { - out.println(usb_Bus.toString()); - Usb_Device dev = usb_Bus.getDevices(); - while (dev != null) { - out.println("\t" + dev.toString()); - // Usb_Device_Descriptor - Usb_Device_Descriptor defDesc = dev.getDescriptor(); - out.println("\t\t" + defDesc.toString()); - // Usb_Config_Descriptor - Usb_Config_Descriptor[] confDesc = dev.getConfig(); - for (int i = 0; i < confDesc.length; i++) { - out.println("\t\t" + confDesc[i].toString()); - Usb_Interface[] int_ = confDesc[i].getInterface(); - if (int_ != null) { - for (int j = 0; j < int_.length; j++) { - out.println("\t\t\t" + int_[j].toString()); - Usb_Interface_Descriptor[] intDesc = int_[j] - .getAltsetting(); - if (intDesc != null) { - for (int k = 0; k < intDesc.length; k++) { - out.println("\t\t\t\t" - + intDesc[k].toString()); - Usb_Endpoint_Descriptor[] epDesc = intDesc[k] - .getEndpoint(); - if (epDesc != null) { - for (int e = 0; e < epDesc.length; e++) { - out.println("\t\t\t\t\t" - + epDesc[e].toString()); - } - } - } - } - } - } - } - dev = dev.getNext(); - } - usb_Bus = usb_Bus.getNext(); - } - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava; + +import java.io.PrintStream; + +public class Utils { + + public static void logBus(Usb_Bus bus) { + logBus(bus, System.out); + } + + public static void logBus(Usb_Bus bus, PrintStream out) { + Usb_Bus usb_Bus = bus; + while (usb_Bus != null) { + out.println(usb_Bus.toString()); + Usb_Device dev = usb_Bus.getDevices(); + while (dev != null) { + out.println("\t" + dev.toString()); + // Usb_Device_Descriptor + Usb_Device_Descriptor defDesc = dev.getDescriptor(); + out.println("\t\t" + defDesc.toString()); + // Usb_Config_Descriptor + Usb_Config_Descriptor[] confDesc = dev.getConfig(); + for (int i = 0; i < confDesc.length; i++) { + out.println("\t\t" + confDesc[i].toString()); + Usb_Interface[] int_ = confDesc[i].getInterface(); + if (int_ != null) { + for (int j = 0; j < int_.length; j++) { + out.println("\t\t\t" + int_[j].toString()); + Usb_Interface_Descriptor[] intDesc = int_[j] + .getAltsetting(); + if (intDesc != null) { + for (int k = 0; k < intDesc.length; k++) { + out.println("\t\t\t\t" + + intDesc[k].toString()); + Usb_Endpoint_Descriptor[] epDesc = intDesc[k] + .getEndpoint(); + if (epDesc != null) { + for (int e = 0; e < epDesc.length; e++) { + out.println("\t\t\t\t\t" + + epDesc[e].toString()); + } + } + } + } + } + } + } + dev = dev.getNext(); + } + usb_Bus = usb_Bus.getNext(); + } + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/demo/LogBus.java b/src/main/java/ch/ntb/inf/libusbJava/demo/LogBus.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/demo/LogBus.java rename to src/main/java/ch/ntb/inf/libusbJava/demo/LogBus.java index dd402a1..d6ad3f1 100644 --- a/java/src/ch/ntb/inf/libusbJava/demo/LogBus.java +++ b/src/main/java/ch/ntb/inf/libusbJava/demo/LogBus.java @@ -1,42 +1,42 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.demo; - -import ch.ntb.inf.libusbJava.LibusbJava; -import ch.ntb.inf.libusbJava.Usb_Bus; -import ch.ntb.inf.libusbJava.Utils; - -/** - * Initalises Libusb and prints the bus(ses) with attached devices to the - * standard out.
- * - * @deprecated This class will be removed with the legacy {@link LibusbJava} - * class - */ -public class LogBus { - - private static void logBus() { - // if you don't use the ch.ntb.inf.libusbJava.Device class you must - // initialise - // Libusb before use - LibusbJava.usb_init(); - LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - - // retrieve a object tree representing the bus with its devices and - // descriptors - Usb_Bus bus = LibusbJava.usb_get_busses(); - - // log the bus structure to standard out - Utils.logBus(bus); - } - - public static void main(String[] args) { - logBus(); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.demo; + +import ch.ntb.inf.libusbJava.LibusbJava; +import ch.ntb.inf.libusbJava.Usb_Bus; +import ch.ntb.inf.libusbJava.Utils; + +/** + * Initalises Libusb and prints the bus(ses) with attached devices to the + * standard out.
+ * + * @deprecated This class will be removed with the legacy {@link LibusbJava} + * class + */ +public class LogBus { + + private static void logBus() { + // if you don't use the ch.ntb.inf.libusbJava.Device class you must + // initialise + // Libusb before use + LibusbJava.usb_init(); + LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + + // retrieve a object tree representing the bus with its devices and + // descriptors + Usb_Bus bus = LibusbJava.usb_get_busses(); + + // log the bus structure to standard out + Utils.logBus(bus); + } + + public static void main(String[] args) { + logBus(); + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/demo/ReadWrite.java b/src/main/java/ch/ntb/inf/libusbJava/demo/ReadWrite.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/demo/ReadWrite.java rename to src/main/java/ch/ntb/inf/libusbJava/demo/ReadWrite.java index e692f64..7dbaf2f 100644 --- a/java/src/ch/ntb/inf/libusbJava/demo/ReadWrite.java +++ b/src/main/java/ch/ntb/inf/libusbJava/demo/ReadWrite.java @@ -1,60 +1,60 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.demo; - -import ch.ntb.inf.libusbJava.Device; -import ch.ntb.inf.libusbJava.USB; -import ch.ntb.inf.libusbJava.USBException; - -/** - * Demo class to demonstrate simple read and write operations to an USB device.
- * - */ -public class ReadWrite { - - private static void logData(byte[] data) { - System.out.print("Data: "); - for (int i = 0; i < data.length; i++) { - System.out.print("0x" + Integer.toHexString(data[i] & 0xff) + " "); - } - System.out.println(); - } - - public static void main(String[] args) { - // get a device instance with vendor id and product id - Device dev = USB.getDevice((short) 0x8235, (short) 0x0100); - try { - // data to write to the device - byte[] data = new byte[] { 0, 1, 2, 3 }; - // data read from the device - byte[] readData = new byte[data.length]; - - // open the device with configuration 1, interface 0 and without - // altinterface - // this will initialise Libusb for you - dev.open(1, 0, -1); - // write some data to the device - // 0x03 is the endpoint address of the OUT endpoint 3 (from PC to - // device) - dev.writeInterrupt(0x02, data, data.length, 2000, false); - // read some data from the device - // 0x84 is the endpoint address of the IN endpoint 4 (from PC to - // device) - // bit 7 (0x80) is set in case of an IN endpoint - dev.readInterrupt(0x86, readData, readData.length, 2000, false); - // log the data from the device - logData(readData); - // close the device - dev.close(); - } catch (USBException e) { - // if an exception occures during connect or read/write an exception - // is thrown - e.printStackTrace(); - } - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.demo; + +import ch.ntb.inf.libusbJava.Device; +import ch.ntb.inf.libusbJava.USB; +import ch.ntb.inf.libusbJava.USBException; + +/** + * Demo class to demonstrate simple read and write operations to an USB device.
+ * + */ +public class ReadWrite { + + private static void logData(byte[] data) { + System.out.print("Data: "); + for (int i = 0; i < data.length; i++) { + System.out.print("0x" + Integer.toHexString(data[i] & 0xff) + " "); + } + System.out.println(); + } + + public static void main(String[] args) { + // get a device instance with vendor id and product id + Device dev = USB.getDevice((short) 0x8235, (short) 0x0100); + try { + // data to write to the device + byte[] data = new byte[] { 0, 1, 2, 3 }; + // data read from the device + byte[] readData = new byte[data.length]; + + // open the device with configuration 1, interface 0 and without + // altinterface + // this will initialise Libusb for you + dev.open(1, 0, -1); + // write some data to the device + // 0x03 is the endpoint address of the OUT endpoint 3 (from PC to + // device) + dev.writeInterrupt(0x02, data, data.length, 2000, false); + // read some data from the device + // 0x84 is the endpoint address of the IN endpoint 4 (from PC to + // device) + // bit 7 (0x80) is set in case of an IN endpoint + dev.readInterrupt(0x86, readData, readData.length, 2000, false); + // log the data from the device + logData(readData); + // close the device + dev.close(); + } catch (USBException e) { + // if an exception occures during connect or read/write an exception + // is thrown + e.printStackTrace(); + } + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/exceptions/LibusbError.java b/src/main/java/ch/ntb/inf/libusbJava/exceptions/LibusbError.java similarity index 94% rename from java/src/ch/ntb/inf/libusbJava/exceptions/LibusbError.java rename to src/main/java/ch/ntb/inf/libusbJava/exceptions/LibusbError.java index 7f28e78..86db07a 100644 --- a/java/src/ch/ntb/inf/libusbJava/exceptions/LibusbError.java +++ b/src/main/java/ch/ntb/inf/libusbJava/exceptions/LibusbError.java @@ -1,150 +1,150 @@ -package ch.ntb.inf.libusbJava.exceptions; - -public class LibusbError extends Exception { - private static final long serialVersionUID = 9096323614080207236L; - - /** - * libusb error codes - */ - public static final int ERROR_NONE = 0; - public static final int ERROR_IO = -1; - public static final int ERROR_INVALID_PARAM = -2; - public static final int ERROR_ACCESS = -3; - public static final int ERROR_NO_DEVICE = -4; - public static final int ERROR_NOT_FOUND = -5; - public static final int ERROR_BUSY = -6; - public static final int ERROR_TIMEOUT = -7; - public static final int ERROR_OVERFLOW = -8; - public static final int ERROR_PIPE = -9; - public static final int ERROR_INTERRUPTED = -10; - public static final int ERROR_NO_MEM = -11; - public static final int ERROR_NOT_SUPPORTED = -12; - public static final int ERROR_OTHER = -99; - public static final int ERROR_JAVA_REFERENCES_NOT_LOADED = -100; - public static final int ERROR_JAVA_WRONG_ENVIRONMENT = -101; - public static final int ERROR_JAVA_ILEGAL_DEVICE_HANDLE = -102; - - private int code = ERROR_NONE; - - public LibusbError(int code) - { - super("libusb result: " + getStringFromCode(code)); - this.code = code; - } - - public int getErrorCode() - { - return code; - } - - public static String getStringFromCode(int code) - { - String result; - - switch (code) - { - case ERROR_IO: - { - result = "ERROR_IO"; - break; - } - case ERROR_INVALID_PARAM: - { - result = "ERROR_INVALID_PARAM"; - break; - } - case ERROR_ACCESS: - { - result = "ERROR_ACCESS"; - break; - } - case ERROR_NO_DEVICE: - { - result = "ERROR_NO_DEVICE"; - break; - } - case ERROR_NOT_FOUND: - { - result = "ERROR_NOT_FOUND"; - break; - } - case ERROR_BUSY: - { - result = "ERROR_BUSY"; - break; - } - - case ERROR_TIMEOUT: - { - result = "ERROR_TIMEOUT"; - break; - } - - case ERROR_OVERFLOW: - { - result = "ERROR_OVERFLOW"; - break; - } - - case ERROR_PIPE: - { - result = "ERROR_PIPE"; - break; - } - - case ERROR_INTERRUPTED: - { - result = "ERROR_INTERRUPTED"; - break; - } - - case ERROR_NO_MEM: - { - result = "ERROR_NO_MEM"; - break; - } - - case ERROR_NOT_SUPPORTED: - { - result = "ERROR_NOT_SUPPORTED"; - break; - } - - case ERROR_OTHER: - { - result = "ERROR_OTHER"; - break; - } - - case ERROR_JAVA_REFERENCES_NOT_LOADED: - { - result = "ERROR_JAVA_REFERENCES_NOT_LOADED"; - break; - } - - case ERROR_JAVA_WRONG_ENVIRONMENT: - { - result = "ERROR_JAVA_WRONG_ENVIRONMENT"; - break; - } - - case ERROR_JAVA_ILEGAL_DEVICE_HANDLE: - { - result = "ERROR_JAVA_ILEGAL_DEVICE_HANDLE"; - break; - } - - default: - { - result = "ERROR_UNKNWON (" + code + ")"; - break; - } - } - - return result; - } - - public String getErrorString() { - return getStringFromCode(getErrorCode()); - } -} +package ch.ntb.inf.libusbJava.exceptions; + +public class LibusbError extends Exception { + private static final long serialVersionUID = 9096323614080207236L; + + /** + * libusb error codes + */ + public static final int ERROR_NONE = 0; + public static final int ERROR_IO = -1; + public static final int ERROR_INVALID_PARAM = -2; + public static final int ERROR_ACCESS = -3; + public static final int ERROR_NO_DEVICE = -4; + public static final int ERROR_NOT_FOUND = -5; + public static final int ERROR_BUSY = -6; + public static final int ERROR_TIMEOUT = -7; + public static final int ERROR_OVERFLOW = -8; + public static final int ERROR_PIPE = -9; + public static final int ERROR_INTERRUPTED = -10; + public static final int ERROR_NO_MEM = -11; + public static final int ERROR_NOT_SUPPORTED = -12; + public static final int ERROR_OTHER = -99; + public static final int ERROR_JAVA_REFERENCES_NOT_LOADED = -100; + public static final int ERROR_JAVA_WRONG_ENVIRONMENT = -101; + public static final int ERROR_JAVA_ILEGAL_DEVICE_HANDLE = -102; + + private int code = ERROR_NONE; + + public LibusbError(int code) + { + super("libusb result: " + getStringFromCode(code)); + this.code = code; + } + + public int getErrorCode() + { + return code; + } + + public static String getStringFromCode(int code) + { + String result; + + switch (code) + { + case ERROR_IO: + { + result = "ERROR_IO"; + break; + } + case ERROR_INVALID_PARAM: + { + result = "ERROR_INVALID_PARAM"; + break; + } + case ERROR_ACCESS: + { + result = "ERROR_ACCESS"; + break; + } + case ERROR_NO_DEVICE: + { + result = "ERROR_NO_DEVICE"; + break; + } + case ERROR_NOT_FOUND: + { + result = "ERROR_NOT_FOUND"; + break; + } + case ERROR_BUSY: + { + result = "ERROR_BUSY"; + break; + } + + case ERROR_TIMEOUT: + { + result = "ERROR_TIMEOUT"; + break; + } + + case ERROR_OVERFLOW: + { + result = "ERROR_OVERFLOW"; + break; + } + + case ERROR_PIPE: + { + result = "ERROR_PIPE"; + break; + } + + case ERROR_INTERRUPTED: + { + result = "ERROR_INTERRUPTED"; + break; + } + + case ERROR_NO_MEM: + { + result = "ERROR_NO_MEM"; + break; + } + + case ERROR_NOT_SUPPORTED: + { + result = "ERROR_NOT_SUPPORTED"; + break; + } + + case ERROR_OTHER: + { + result = "ERROR_OTHER"; + break; + } + + case ERROR_JAVA_REFERENCES_NOT_LOADED: + { + result = "ERROR_JAVA_REFERENCES_NOT_LOADED"; + break; + } + + case ERROR_JAVA_WRONG_ENVIRONMENT: + { + result = "ERROR_JAVA_WRONG_ENVIRONMENT"; + break; + } + + case ERROR_JAVA_ILEGAL_DEVICE_HANDLE: + { + result = "ERROR_JAVA_ILEGAL_DEVICE_HANDLE"; + break; + } + + default: + { + result = "ERROR_UNKNWON (" + code + ")"; + break; + } + } + + return result; + } + + public String getErrorString() { + return getStringFromCode(getErrorCode()); + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/logger/LogUtil.java b/src/main/java/ch/ntb/inf/libusbJava/logger/LogUtil.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/logger/LogUtil.java rename to src/main/java/ch/ntb/inf/libusbJava/logger/LogUtil.java index ac18644..32e204a 100644 --- a/java/src/ch/ntb/inf/libusbJava/logger/LogUtil.java +++ b/src/main/java/ch/ntb/inf/libusbJava/logger/LogUtil.java @@ -1,135 +1,135 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.logger; - -import java.io.InputStream; -import java.util.Properties; -import java.util.logging.ConsoleHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.Logger; - -public class LogUtil { - - // debug this class - private static final boolean debugLogUtil = false; - - private static final String PLUGIN_ID = "ch.ntb.inf.libusbJava"; - private static final String PROPERTIES_FILE = ".configure"; - private static final String LOGGER_WARNING = "Warning in class " - + LogUtil.class.getName() - + ": could not load the logger properties file " + PROPERTIES_FILE; - - private static boolean debugEnabled; - - static { - createLoggersFromProperties(); - } - - private static void debugMsg(String method, String message) { - if (debugLogUtil) { - System.out.println(method + ": " + message); - } - } - - public static void setLevel(Logger logger, Level loglevel) { - Handler[] h = logger.getHandlers(); - for (int i = 0; i < h.length; i++) { - System.out.println("setLevel " + loglevel.toString()); - h[i].setLevel(loglevel); - } - logger.setLevel(loglevel); - } - - public static Logger getLogger(String name) { - debugMsg("getLogger", name); - LogManager manager = LogManager.getLogManager(); - // check if logger is already registered - Logger logger = manager.getLogger(name); - if (logger == null) { - logger = Logger.getLogger(name); - setLevel(logger, Level.OFF); - manager.addLogger(logger); - debugMsg("getLogger", "creating new logger"); - } - if (logger.getLevel() == null) { - debugMsg("getLogger", "level == null -> setLevel to OFF "); - setLevel(logger, Level.OFF); - } - debugMsg("getLogger", "logLevel " + logger.getLevel().getName()); - return logger; - } - - private static void initLevel(Logger logger, Level loglevel) { - Handler[] h = logger.getHandlers(); - for (int i = 0; i < h.length; i++) { - logger.removeHandler(h[i]); - } - Handler console = new ConsoleHandler(); - console.setLevel(loglevel); - logger.addHandler(console); - logger.setLevel(loglevel); - logger.setUseParentHandlers(false); - } - - private static void createLoggersFromProperties() { - try { - debugMsg(LogUtil.class.getName(), "createLoggersFromProperties"); - InputStream is = LogUtil.class.getClassLoader() - .getResourceAsStream(PROPERTIES_FILE); - if (is == null) { - System.err.println(LOGGER_WARNING); - } else { - Properties prop = new Properties(); - prop.load(is); - debugMsg("createLoggersFromProperties", - "properties file loaded: " + PROPERTIES_FILE); - debugMsg("createLoggersFromProperties", "file content:\n" - + prop.toString()); - // get global debug enable flag - debugEnabled = Boolean.parseBoolean(prop.getProperty(PLUGIN_ID - + "/debug")); - debugMsg("createLoggersFromProperties", "debuging enabled: " - + debugEnabled); - // get and configure loggers - boolean moreLoggers = true; - int loggerCount = 0; - while (moreLoggers) { - String loggerProp = prop.getProperty(PLUGIN_ID - + "/debug/logger" + loggerCount); - loggerCount++; - if (loggerProp != null) { - // parse string and get logger name and log level - int slashIndex = loggerProp.indexOf('/'); - String loggerName = loggerProp.substring(0, slashIndex) - .trim(); - String logLevel = loggerProp.substring(slashIndex + 1, - loggerProp.length()); - // register logger - Level level; - if (debugEnabled) { - level = Level.parse(logLevel); - } else { - level = Level.OFF; - } - Logger logger = getLogger(loggerName); - initLevel(logger, level); - debugMsg("createLoggersFromProperties", - "create logger " + loggerName + " with level " - + level.toString()); - } else { - moreLoggers = false; - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.logger; + +import java.io.InputStream; +import java.util.Properties; +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.Logger; + +public class LogUtil { + + // debug this class + private static final boolean debugLogUtil = false; + + private static final String PLUGIN_ID = "ch.ntb.inf.libusbJava"; + private static final String PROPERTIES_FILE = ".configure"; + private static final String LOGGER_WARNING = "Warning in class " + + LogUtil.class.getName() + + ": could not load the logger properties file " + PROPERTIES_FILE; + + private static boolean debugEnabled; + + static { + createLoggersFromProperties(); + } + + private static void debugMsg(String method, String message) { + if (debugLogUtil) { + System.out.println(method + ": " + message); + } + } + + public static void setLevel(Logger logger, Level loglevel) { + Handler[] h = logger.getHandlers(); + for (int i = 0; i < h.length; i++) { + System.out.println("setLevel " + loglevel.toString()); + h[i].setLevel(loglevel); + } + logger.setLevel(loglevel); + } + + public static Logger getLogger(String name) { + debugMsg("getLogger", name); + LogManager manager = LogManager.getLogManager(); + // check if logger is already registered + Logger logger = manager.getLogger(name); + if (logger == null) { + logger = Logger.getLogger(name); + setLevel(logger, Level.OFF); + manager.addLogger(logger); + debugMsg("getLogger", "creating new logger"); + } + if (logger.getLevel() == null) { + debugMsg("getLogger", "level == null -> setLevel to OFF "); + setLevel(logger, Level.OFF); + } + debugMsg("getLogger", "logLevel " + logger.getLevel().getName()); + return logger; + } + + private static void initLevel(Logger logger, Level loglevel) { + Handler[] h = logger.getHandlers(); + for (int i = 0; i < h.length; i++) { + logger.removeHandler(h[i]); + } + Handler console = new ConsoleHandler(); + console.setLevel(loglevel); + logger.addHandler(console); + logger.setLevel(loglevel); + logger.setUseParentHandlers(false); + } + + private static void createLoggersFromProperties() { + try { + debugMsg(LogUtil.class.getName(), "createLoggersFromProperties"); + InputStream is = LogUtil.class.getClassLoader() + .getResourceAsStream(PROPERTIES_FILE); + if (is == null) { + System.err.println(LOGGER_WARNING); + } else { + Properties prop = new Properties(); + prop.load(is); + debugMsg("createLoggersFromProperties", + "properties file loaded: " + PROPERTIES_FILE); + debugMsg("createLoggersFromProperties", "file content:\n" + + prop.toString()); + // get global debug enable flag + debugEnabled = Boolean.parseBoolean(prop.getProperty(PLUGIN_ID + + "/debug")); + debugMsg("createLoggersFromProperties", "debuging enabled: " + + debugEnabled); + // get and configure loggers + boolean moreLoggers = true; + int loggerCount = 0; + while (moreLoggers) { + String loggerProp = prop.getProperty(PLUGIN_ID + + "/debug/logger" + loggerCount); + loggerCount++; + if (loggerProp != null) { + // parse string and get logger name and log level + int slashIndex = loggerProp.indexOf('/'); + String loggerName = loggerProp.substring(0, slashIndex) + .trim(); + String logLevel = loggerProp.substring(slashIndex + 1, + loggerProp.length()); + // register logger + Level level; + if (debugEnabled) { + level = Level.parse(logLevel); + } else { + level = Level.OFF; + } + Logger logger = getLogger(loggerName); + initLevel(logger, level); + debugMsg("createLoggersFromProperties", + "create logger " + loggerName + " with level " + + level.toString()); + } else { + moreLoggers = false; + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/logger/package.html b/src/main/java/ch/ntb/inf/libusbJava/logger/package.html similarity index 94% rename from java/src/ch/ntb/inf/libusbJava/logger/package.html rename to src/main/java/ch/ntb/inf/libusbJava/logger/package.html index 0fbe441..fe57a92 100644 --- a/java/src/ch/ntb/inf/libusbJava/logger/package.html +++ b/src/main/java/ch/ntb/inf/libusbJava/logger/package.html @@ -1,16 +1,16 @@ - - - - - -Logging related classes. - -

Related Resources

- -For more information about this project visit -http://libusbjava.sourceforge.net -. - - - + + + + + +Logging related classes. + +

Related Resources

+ +For more information about this project visit +http://libusbjava.sourceforge.net +. + + + diff --git a/java/src/ch/ntb/inf/libusbJava/package.html b/src/main/java/ch/ntb/inf/libusbJava/package.html similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/package.html rename to src/main/java/ch/ntb/inf/libusbJava/package.html index e698310..147866d 100644 --- a/java/src/ch/ntb/inf/libusbJava/package.html +++ b/src/main/java/ch/ntb/inf/libusbJava/package.html @@ -1,26 +1,26 @@ - - - - - -Includes the main classes for the Java libusb wrapper. -
-LibusbJava.java -is the JNI class to the -LibusbJava.dll -. Every class starting with -Usb_ -represents a descriptor of the bus structure which is retrieved by -calling -LibusbJava.usb_get_busses() -. - -

Related Resources

- -For more information about this project visit -http://libusbjava.sourceforge.net -. - - - + + + + + +Includes the main classes for the Java libusb wrapper. +
+LibusbJava.java +is the JNI class to the +LibusbJava.dll +. Every class starting with +Usb_ +represents a descriptor of the bus structure which is retrieved by +calling +LibusbJava.usb_get_busses() +. + +

Related Resources

+ +For more information about this project visit +http://libusbjava.sourceforge.net +. + + + diff --git a/java/src/ch/ntb/inf/libusbJava/testApp/AbstractDeviceInfo.java b/src/main/java/ch/ntb/inf/libusbJava/testApp/AbstractDeviceInfo.java similarity index 94% rename from java/src/ch/ntb/inf/libusbJava/testApp/AbstractDeviceInfo.java rename to src/main/java/ch/ntb/inf/libusbJava/testApp/AbstractDeviceInfo.java index 049edca..ecb4c9f 100644 --- a/java/src/ch/ntb/inf/libusbJava/testApp/AbstractDeviceInfo.java +++ b/src/main/java/ch/ntb/inf/libusbJava/testApp/AbstractDeviceInfo.java @@ -1,211 +1,211 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.testApp; - -public abstract class AbstractDeviceInfo { - - private short idVendor; - - private short idProduct; - - private String filename = null; - - private String busName = null; - - private int timeout; - - private int configuration; - - private int interface_; - - private int altinterface; - - private int outEPBulk = -1; - - private int inEPBulk = -1; - - private int outEPInt = -1; - - private int inEPInt = -1; - - private int sleepTimeout; - - private int maxDataSize; - - private TransferMode mode; - - private boolean compareData = true; - - private String manufacturer = null; - - private String product = null; - - private String serialVersion = null; - - public static enum TransferMode { - Bulk, Interrupt - } - - public AbstractDeviceInfo() { - initValues(); - } - - abstract public void initValues(); - - public int getAltinterface() { - return altinterface; - } - - public int getConfiguration() { - return configuration; - } - - public short getIdProduct() { - return idProduct; - } - - public short getIdVendor() { - return idVendor; - } - - public int getInEPBulk() { - return inEPBulk; - } - - public int getInEPInt() { - return inEPInt; - } - - public int getInterface() { - return interface_; - } - - public int getMaxDataSize() { - return maxDataSize; - } - - public int getOutEPBulk() { - return outEPBulk; - } - - public int getOutEPInt() { - return outEPInt; - } - - public int getSleepTimeout() { - return sleepTimeout; - } - - public int getTimeout() { - return timeout; - } - - public void setAltinterface(int altinterface) { - this.altinterface = altinterface; - } - - public void setConfiguration(int configuration) { - this.configuration = configuration; - } - - public void setIdProduct(short idProduct) { - this.idProduct = idProduct; - } - - public void setIdVendor(short idVendor) { - this.idVendor = idVendor; - } - - public void setInEPBulk(int in_ep_bulk) { - this.inEPBulk = in_ep_bulk; - } - - public void setInEPInt(int in_ep_int) { - this.inEPInt = in_ep_int; - } - - public void setInterface(int interface_) { - this.interface_ = interface_; - } - - public void setMaxDataSize(int maxDataSize) { - this.maxDataSize = maxDataSize; - } - - public void setOutEPBulk(int out_ep_bulk) { - this.outEPBulk = out_ep_bulk; - } - - public void setOutEPInt(int out_ep_int) { - this.outEPInt = out_ep_int; - } - - public void setSleepTimeout(int sleepTimeout) { - this.sleepTimeout = sleepTimeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public TransferMode getMode() { - return mode; - } - - public void setMode(TransferMode mode) { - this.mode = mode; - } - - public boolean doCompareData() { - return compareData; - } - - public void setDoCompareData(boolean compareData) { - this.compareData = compareData; - } - - public String getManufacturer() { - return manufacturer; - } - - public void setManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - } - - public String getProduct() { - return product; - } - - public void setProduct(String product) { - this.product = product; - } - - public String getSerialVersion() { - return serialVersion; - } - - public void setSerialVersion(String serialVersion) { - this.serialVersion = serialVersion; - } - - public String getFilename() { - return filename; - } - - public void setFilename(String filename) { - this.filename = filename; - } - - public String getBusName() { - return busName; - } - - public void setBusName(String busName) { - this.busName = busName; - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.testApp; + +public abstract class AbstractDeviceInfo { + + private short idVendor; + + private short idProduct; + + private String filename = null; + + private String busName = null; + + private int timeout; + + private int configuration; + + private int interface_; + + private int altinterface; + + private int outEPBulk = -1; + + private int inEPBulk = -1; + + private int outEPInt = -1; + + private int inEPInt = -1; + + private int sleepTimeout; + + private int maxDataSize; + + private TransferMode mode; + + private boolean compareData = true; + + private String manufacturer = null; + + private String product = null; + + private String serialVersion = null; + + public static enum TransferMode { + Bulk, Interrupt + } + + public AbstractDeviceInfo() { + initValues(); + } + + abstract public void initValues(); + + public int getAltinterface() { + return altinterface; + } + + public int getConfiguration() { + return configuration; + } + + public short getIdProduct() { + return idProduct; + } + + public short getIdVendor() { + return idVendor; + } + + public int getInEPBulk() { + return inEPBulk; + } + + public int getInEPInt() { + return inEPInt; + } + + public int getInterface() { + return interface_; + } + + public int getMaxDataSize() { + return maxDataSize; + } + + public int getOutEPBulk() { + return outEPBulk; + } + + public int getOutEPInt() { + return outEPInt; + } + + public int getSleepTimeout() { + return sleepTimeout; + } + + public int getTimeout() { + return timeout; + } + + public void setAltinterface(int altinterface) { + this.altinterface = altinterface; + } + + public void setConfiguration(int configuration) { + this.configuration = configuration; + } + + public void setIdProduct(short idProduct) { + this.idProduct = idProduct; + } + + public void setIdVendor(short idVendor) { + this.idVendor = idVendor; + } + + public void setInEPBulk(int in_ep_bulk) { + this.inEPBulk = in_ep_bulk; + } + + public void setInEPInt(int in_ep_int) { + this.inEPInt = in_ep_int; + } + + public void setInterface(int interface_) { + this.interface_ = interface_; + } + + public void setMaxDataSize(int maxDataSize) { + this.maxDataSize = maxDataSize; + } + + public void setOutEPBulk(int out_ep_bulk) { + this.outEPBulk = out_ep_bulk; + } + + public void setOutEPInt(int out_ep_int) { + this.outEPInt = out_ep_int; + } + + public void setSleepTimeout(int sleepTimeout) { + this.sleepTimeout = sleepTimeout; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public TransferMode getMode() { + return mode; + } + + public void setMode(TransferMode mode) { + this.mode = mode; + } + + public boolean doCompareData() { + return compareData; + } + + public void setDoCompareData(boolean compareData) { + this.compareData = compareData; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + + public String getProduct() { + return product; + } + + public void setProduct(String product) { + this.product = product; + } + + public String getSerialVersion() { + return serialVersion; + } + + public void setSerialVersion(String serialVersion) { + this.serialVersion = serialVersion; + } + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public String getBusName() { + return busName; + } + + public void setBusName(String busName) { + this.busName = busName; + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/testApp/TestApp.java b/src/main/java/ch/ntb/inf/libusbJava/testApp/TestApp.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/testApp/TestApp.java rename to src/main/java/ch/ntb/inf/libusbJava/testApp/TestApp.java index 08e98c7..c861dbd 100644 --- a/java/src/ch/ntb/inf/libusbJava/testApp/TestApp.java +++ b/src/main/java/ch/ntb/inf/libusbJava/testApp/TestApp.java @@ -1,709 +1,709 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.testApp; - -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.event.ItemEvent; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.UIManager; -import javax.swing.border.TitledBorder; - -public class TestApp extends JFrame { - - private static final long serialVersionUID = 994508729204158681L; - TestDevice dev; - private JPanel rootPanel = null; - private JPanel sendReceivePanel = null; - private JPanel settingsPanel = null; - private JButton openDeviceButton = null; - private JButton closeDevice = null; - private JButton resetButton = null; - private JPanel settingsPanelTop = null; - private JPanel settingsPanelBottom = null; - JTextField vendorIDText = null; - JTextField productIDText = null; - private JPanel vendorIDPanel = null; - private JPanel productIDPanel = null; - private JPanel configurationPanel = null; - JTextField configurationText = null; - private JPanel interfacePanel = null; - JTextField interfaceText = null; - private JPanel altInterfacePanel = null; - JTextField altInterfaceText = null; - private JPanel settingsPanelTop2Left = null; - private JPanel settingsPanelTop2Right = null; - private JPanel outEpPanel = null; - JTextField outEpText = null; - private JPanel inEpPanel = null; - JTextField inEpText = null; - private JPanel timeoutPanel = null; - private JTextField timeoutText = null; - private JPanel sendDataPanel = null; - private JPanel sendRecButtonsPanel = null; - private JButton sendButton = null; - private JButton recButton = null; - JTextField sendDataText = null; - JComboBox sendTypeComboBox = null; - private JComboBox recTypeComboBox = null; - private JPanel sendRecButtonsPanelTop = null; - private JPanel sendRecButtonsPanelBottom = null; - - public TestApp(TestDevice devInfo) { - super(); - this.dev = devInfo; - initialize(); - } - - private void initialize() { - - this.setTitle("USB Test Application"); - - this.setContentPane(getRootPanel()); - - // read default values - this.vendorIDText.setText(toHexString(dev.getIdVendor() & 0xffff)); - this.productIDText.setText(toHexString(dev.getIdProduct() & 0xffff)); - this.configurationText.setText(new Integer(dev.getConfiguration()) - .toString()); - this.interfaceText.setText(new Integer(dev.getInterface()).toString()); - this.altInterfaceText.setText(new Integer(dev.getAltinterface()) - .toString()); - this.timeoutText.setText(new Integer(dev.getTimeout()).toString()); - this.sendDataText.setText(dev.getSendData()); - setOutEpAddr(); - setInEpAddr(); - - this.pack(); - this.setVisible(true); - } - - void setOutEpAddr() { - switch (dev.getOutMode()) { - case Bulk: - this.outEpText.setText(toHexString(dev.getOutEPBulk())); - break; - case Interrupt: - this.outEpText.setText(toHexString(dev.getOutEPInt())); - break; - default: - break; - } - } - - void setInEpAddr() { - switch (dev.getInMode()) { - case Bulk: - this.inEpText.setText(toHexString(dev.getInEPBulk())); - break; - case Interrupt: - this.inEpText.setText(toHexString(dev.getInEPInt())); - break; - default: - break; - } - } - - private JPanel getRootPanel() { - if (rootPanel == null) { - rootPanel = new JPanel(); - rootPanel - .setLayout(new BoxLayout(getRootPanel(), BoxLayout.Y_AXIS)); - rootPanel.add(getSettingsPanel(), null); - rootPanel.add(getSendReceivePanel(), null); - } - return rootPanel; - } - - private JPanel getSendReceivePanel() { - if (sendReceivePanel == null) { - BorderLayout borderLayout2 = new BorderLayout(); - borderLayout2.setHgap(5); - sendReceivePanel = new JPanel(); - sendReceivePanel.setLayout(borderLayout2); - sendReceivePanel.setBorder(BorderFactory.createTitledBorder(null, - "Send and Receive Data", - TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - sendReceivePanel.add(getSendRecButtonsPanel(), BorderLayout.NORTH); - sendReceivePanel.add(getSendDataPanel(), BorderLayout.SOUTH); - } - return sendReceivePanel; - } - - private JPanel getSettingsPanel() { - if (settingsPanel == null) { - settingsPanel = new JPanel(); - settingsPanel.setLayout(new BoxLayout(getSettingsPanel(), - BoxLayout.Y_AXIS)); - settingsPanel.setBorder(BorderFactory.createTitledBorder(null, - "Device Settings", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - settingsPanel.add(getSettingsPanelTop(), null); - settingsPanel.add(getSettingsPanelBottom(), null); - } - return settingsPanel; - } - - private JButton getOpenDeviceButton() { - if (openDeviceButton == null) { - openDeviceButton = new JButton(); - openDeviceButton.setText("Open Device"); - openDeviceButton - .addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - // update values for the device - dev.setIdVendor((short) parseInt(vendorIDText - .getText().trim())); - dev.setIdProduct((short) parseInt(productIDText - .getText().trim())); - dev.setConfiguration(parseInt(configurationText - .getText().trim())); - dev.setInterface(parseInt(interfaceText.getText() - .trim())); - dev.setAltinterface(parseInt(altInterfaceText - .getText().trim())); - // opent the device - dev.openUsbDevice(); - } - }); - } - return openDeviceButton; - } - - private JButton getCloseDevice() { - if (closeDevice == null) { - closeDevice = new JButton(); - closeDevice.setText("Close Device"); - closeDevice.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - dev.closeUsbDevice(); - } - }); - } - return closeDevice; - } - - private JButton getResetButton() { - if (resetButton == null) { - resetButton = new JButton(); - resetButton.setText("Reset Device"); - resetButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - dev.resetUsbDevice(); - } - }); - } - return resetButton; - } - - private JPanel getSettingsPanelTop() { - if (settingsPanelTop == null) { - FlowLayout flowLayout = new FlowLayout(); - flowLayout.setVgap(1); - flowLayout.setAlignment(FlowLayout.LEFT); - settingsPanelTop = new JPanel(); - settingsPanelTop.setLayout(flowLayout); - settingsPanelTop.add(getVendorIDPanel(), null); - settingsPanelTop.add(getProductIDPanel(), null); - settingsPanelTop.add(getConfigurationPanel(), null); - settingsPanelTop.add(getInterfacePanel(), null); - settingsPanelTop.add(getAltInterfacePanel(), null); - } - return settingsPanelTop; - } - - private JPanel getSettingsPanelBottom() { - if (settingsPanelBottom == null) { - FlowLayout flowLayout1 = new FlowLayout(); - flowLayout1.setVgap(1); - flowLayout1.setHgap(0); - flowLayout1.setAlignment(FlowLayout.LEFT); - GridBagConstraints gridBagConstraints1 = new GridBagConstraints(); - gridBagConstraints1.gridx = -1; - gridBagConstraints1.gridy = -1; - settingsPanelBottom = new JPanel(); - settingsPanelBottom.setLayout(flowLayout1); - settingsPanelBottom.add(getSettingsPanelTop2Left(), null); - settingsPanelBottom.add(getSettingsPanelTop2Right(), null); - } - return settingsPanelBottom; - } - - private JTextField getVendorIDText() { - if (vendorIDText == null) { - vendorIDText = new JTextField(); - vendorIDText.setPreferredSize(new Dimension(100, 20)); - } - return vendorIDText; - } - - private JTextField getProductIDText() { - if (productIDText == null) { - productIDText = new JTextField(); - productIDText.setPreferredSize(new Dimension(100, 20)); - } - return productIDText; - } - - private JPanel getVendorIDPanel() { - if (vendorIDPanel == null) { - GridBagConstraints gridBagConstraints3 = new GridBagConstraints(); - gridBagConstraints3.fill = GridBagConstraints.VERTICAL; - gridBagConstraints3.gridy = -1; - gridBagConstraints3.weightx = 1.0; - gridBagConstraints3.gridx = -1; - GridBagConstraints gridBagConstraints5 = new GridBagConstraints(); - gridBagConstraints5.gridx = -1; - gridBagConstraints5.gridy = -1; - vendorIDPanel = new JPanel(); - vendorIDPanel.setBorder(BorderFactory.createTitledBorder(null, - "VendorID", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - vendorIDPanel.setLayout(new BoxLayout(getVendorIDPanel(), - BoxLayout.X_AXIS)); - vendorIDPanel.add(getVendorIDText(), null); - } - return vendorIDPanel; - } - - private JPanel getProductIDPanel() { - if (productIDPanel == null) { - GridBagConstraints gridBagConstraints4 = new GridBagConstraints(); - gridBagConstraints4.fill = GridBagConstraints.VERTICAL; - gridBagConstraints4.gridy = -1; - gridBagConstraints4.weightx = 1.0; - gridBagConstraints4.gridx = -1; - productIDPanel = new JPanel(); - productIDPanel.setBorder(BorderFactory.createTitledBorder(null, - "ProductID", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - productIDPanel.setLayout(new BoxLayout(getProductIDPanel(), - BoxLayout.X_AXIS)); - productIDPanel.add(getProductIDText(), null); - } - return productIDPanel; - } - - private JPanel getConfigurationPanel() { - if (configurationPanel == null) { - configurationPanel = new JPanel(); - configurationPanel.setLayout(new BoxLayout(getConfigurationPanel(), - BoxLayout.X_AXIS)); - configurationPanel.setBorder(BorderFactory.createTitledBorder(null, - "Configuration", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - configurationPanel.add(getConfigurationText(), null); - } - return configurationPanel; - } - - private JTextField getConfigurationText() { - if (configurationText == null) { - configurationText = new JTextField(); - configurationText.setPreferredSize(new Dimension(100, 20)); - } - return configurationText; - } - - private JPanel getInterfacePanel() { - if (interfacePanel == null) { - interfacePanel = new JPanel(); - interfacePanel.setLayout(new BoxLayout(getInterfacePanel(), - BoxLayout.X_AXIS)); - interfacePanel.setBorder(BorderFactory.createTitledBorder(null, - "Interface", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - interfacePanel.add(getInterfaceText(), null); - } - return interfacePanel; - } - - private JTextField getInterfaceText() { - if (interfaceText == null) { - interfaceText = new JTextField(); - interfaceText.setPreferredSize(new Dimension(100, 20)); - } - return interfaceText; - } - - private JPanel getAltInterfacePanel() { - if (altInterfacePanel == null) { - altInterfacePanel = new JPanel(); - altInterfacePanel.setLayout(new BoxLayout(getAltInterfacePanel(), - BoxLayout.X_AXIS)); - altInterfacePanel.setBorder(BorderFactory.createTitledBorder(null, - "Alternate Int", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - altInterfacePanel.add(getAltInterfaceText(), null); - } - return altInterfacePanel; - } - - private JTextField getAltInterfaceText() { - if (altInterfaceText == null) { - altInterfaceText = new JTextField(); - altInterfaceText.setPreferredSize(new Dimension(100, 20)); - } - return altInterfaceText; - } - - private JPanel getSettingsPanelTop2Left() { - if (settingsPanelTop2Left == null) { - FlowLayout flowLayout2 = new FlowLayout(); - flowLayout2.setVgap(2); - flowLayout2.setAlignment(FlowLayout.LEFT); - flowLayout2.setHgap(5); - settingsPanelTop2Left = new JPanel(); - settingsPanelTop2Left.setLayout(flowLayout2); - settingsPanelTop2Left.add(getOutEpPanel(), null); - settingsPanelTop2Left.add(getInEpPanel(), null); - settingsPanelTop2Left.add(getTimeoutPanel(), null); - } - return settingsPanelTop2Left; - } - - private JPanel getSettingsPanelTop2Right() { - if (settingsPanelTop2Right == null) { - FlowLayout flowLayout3 = new FlowLayout(); - flowLayout3.setVgap(2); - settingsPanelTop2Right = new JPanel(); - settingsPanelTop2Right.setLayout(flowLayout3); - settingsPanelTop2Right.add(getOpenDeviceButton(), null); - settingsPanelTop2Right.add(getCloseDevice(), null); - settingsPanelTop2Right.add(getResetButton(), null); - } - return settingsPanelTop2Right; - } - - private JPanel getOutEpPanel() { - if (outEpPanel == null) { - outEpPanel = new JPanel(); - outEpPanel.setLayout(new BoxLayout(getOutEpPanel(), - BoxLayout.X_AXIS)); - outEpPanel.setBorder(BorderFactory.createTitledBorder(null, - "OUT EP", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - outEpPanel.add(getOutEpText(), null); - } - return outEpPanel; - } - - private JTextField getOutEpText() { - if (outEpText == null) { - outEpText = new JTextField(); - outEpText.setPreferredSize(new Dimension(100, 20)); - } - return outEpText; - } - - private JPanel getInEpPanel() { - if (inEpPanel == null) { - inEpPanel = new JPanel(); - inEpPanel - .setLayout(new BoxLayout(getInEpPanel(), BoxLayout.X_AXIS)); - inEpPanel.setBorder(BorderFactory.createTitledBorder(null, "IN EP", - TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - inEpPanel.add(getInEpText(), null); - } - return inEpPanel; - } - - private JTextField getInEpText() { - if (inEpText == null) { - inEpText = new JTextField(); - inEpText.setPreferredSize(new Dimension(100, 20)); - } - return inEpText; - } - - private JPanel getTimeoutPanel() { - if (timeoutPanel == null) { - timeoutPanel = new JPanel(); - timeoutPanel.setLayout(new BoxLayout(getTimeoutPanel(), - BoxLayout.X_AXIS)); - timeoutPanel.setBorder(BorderFactory.createTitledBorder(null, - "Timeout", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - timeoutPanel.add(getTimeoutText(), null); - } - return timeoutPanel; - } - - private JTextField getTimeoutText() { - if (timeoutText == null) { - timeoutText = new JTextField(); - timeoutText.setPreferredSize(new Dimension(100, 20)); - } - return timeoutText; - } - - private JPanel getSendDataPanel() { - if (sendDataPanel == null) { - FlowLayout flowLayout4 = new FlowLayout(); - flowLayout4.setAlignment(FlowLayout.LEFT); - sendDataPanel = new JPanel(); - sendDataPanel.setLayout(flowLayout4); - sendDataPanel.setBorder(BorderFactory.createTitledBorder(null, - "Data to send [hex]", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - sendDataPanel.add(getSendRecDataText(), null); - } - return sendDataPanel; - } - - private JPanel getSendRecButtonsPanel() { - if (sendRecButtonsPanel == null) { - FlowLayout flowLayout5 = new FlowLayout(); - flowLayout5.setAlignment(FlowLayout.LEFT); - flowLayout5.setVgap(0); - sendRecButtonsPanel = new JPanel(); - sendRecButtonsPanel.setLayout(flowLayout5); - sendRecButtonsPanel.add(getSendRecButtonsPanelTop(), null); - sendRecButtonsPanel.add(getSendRecButtonsPanelBottom(), null); - } - return sendRecButtonsPanel; - } - - private JButton getSendButton() { - if (sendButton == null) { - sendButton = new JButton(); - sendButton.setText("Send"); - sendButton.setName("sendButton"); - sendButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - int index = sendTypeComboBox.getSelectedIndex(); - if (index == TestDevice.TransferMode.Bulk.ordinal()) { - dev.setOutEPBulk(parseInt(outEpText.getText().trim())); - dev.setMode(TestDevice.TransferMode.Bulk); - } else if (index == TestDevice.TransferMode.Interrupt - .ordinal()) { - dev.setOutEPInt(parseInt(outEpText.getText().trim())); - dev.setMode(TestDevice.TransferMode.Interrupt); - } - byte[] data = parseByteArray(sendDataText.getText().trim()); - dev.write(data, data.length); - } - }); - } - return sendButton; - } - - private JButton getRecButton() { - if (recButton == null) { - recButton = new JButton(); - recButton.setText("Receive"); - recButton.setName("recButton"); - recButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - int index = sendTypeComboBox.getSelectedIndex(); - if (index == TestDevice.TransferMode.Bulk.ordinal()) { - dev.setInEPBulk(parseInt(inEpText.getText().trim())); - dev.setMode(TestDevice.TransferMode.Bulk); - } else if (index == TestDevice.TransferMode.Interrupt - .ordinal()) { - dev.setInEPInt(parseInt(inEpText.getText().trim())); - dev.setMode(TestDevice.TransferMode.Interrupt); - } - dev.read(); - } - }); - } - return recButton; - } - - private JTextField getSendRecDataText() { - if (sendDataText == null) { - sendDataText = new JTextField(); - sendDataText.setPreferredSize(new Dimension(650, 20)); - } - return sendDataText; - } - - int parseInt(String s) { - if (s == "") - return 0; - if (s.indexOf('x') > 0) { - // is hex number - if (s.length() <= 2) { // exception for "0x" - return 0; - } - return Integer.parseInt( - s.substring(s.indexOf('x') + 1, s.length()), 16); - } - // is decimal number - return Integer.parseInt(s); - } - - byte[] parseByteArray(String s) { - final int HEX_WIDTH = 5; - - StringBuffer sb = new StringBuffer(); - int stringIndex = 0, spaceIndex = 0; - String ss; - while (stringIndex + 3 < s.length()) { - ss = s.substring(spaceIndex, spaceIndex + 4); - spaceIndex = s.indexOf(' ', stringIndex) + 1; - sb.append((char) parseInt(ss)); - stringIndex += HEX_WIDTH; - } - return sb.toString().getBytes(); - } - - private static String toHexString(int value) { - return "0x" + Integer.toHexString(value); - } - - /** - * This method initializes sendTypeComboBox - * - * @return javax.swing.JComboBox - */ - private JComboBox getSendTypeComboBox() { - if (sendTypeComboBox == null) { - sendTypeComboBox = new JComboBox(dev.getTransferTypes()); - sendTypeComboBox.setSelectedIndex(dev.getOutMode().ordinal()); - sendTypeComboBox.addItemListener(new java.awt.event.ItemListener() { - public void itemStateChanged(java.awt.event.ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - String mode = (String) e.getItem(); - if (mode.equalsIgnoreCase("Bulk")) { - dev.setOutMode(TestDevice.TransferMode.Bulk); - setOutEpAddr(); - } else if (mode.equalsIgnoreCase("Interrupt")) { - dev.setOutMode(TestDevice.TransferMode.Interrupt); - setOutEpAddr(); - } - } - } - }); - } - return sendTypeComboBox; - } - - /** - * This method initializes recTypeComboBox - * - * @return javax.swing.JComboBox - */ - private JComboBox getRecTypeComboBox() { - if (recTypeComboBox == null) { - recTypeComboBox = new JComboBox(dev.getTransferTypes()); - recTypeComboBox.setSelectedIndex(dev.getInMode().ordinal()); - recTypeComboBox.addItemListener(new java.awt.event.ItemListener() { - public void itemStateChanged(java.awt.event.ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - String mode = (String) e.getItem(); - if (mode.equalsIgnoreCase("Bulk")) { - dev.setInMode(TestDevice.TransferMode.Bulk); - setInEpAddr(); - } else if (mode.equalsIgnoreCase("Interrupt")) { - dev.setInMode(TestDevice.TransferMode.Interrupt); - setInEpAddr(); - } - } - } - }); - // recTypeComboBox.addActionListener(new - // java.awt.event.ActionListener() { - // public void actionPerformed(java.awt.event.ActionEvent e) { - // JComboBox source = (JComboBox) e.getSource(); - // String mode = ""; - // } if (mode.equalsIgnoreCase("Bulk")) { - // dev.setInMode(TestDevice.TransferMode.Bulk); - // setInEpAddr(); - // } else if (mode.equalsIgnoreCase("Interrupt")) { - // dev.setInMode(TestDevice.TransferMode.Interrupt); - // setInEpAddr(); - // } - // - // }); - } - return recTypeComboBox; - } - - /** - * This method initializes sendRecButtonsPanelTop - * - * @return javax.swing.JPanel - */ - private JPanel getSendRecButtonsPanelTop() { - if (sendRecButtonsPanelTop == null) { - BorderLayout borderLayout1 = new BorderLayout(); - borderLayout1.setHgap(5); - sendRecButtonsPanelTop = new JPanel(); - sendRecButtonsPanelTop.setBorder(BorderFactory.createTitledBorder( - null, "OUT", TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - sendRecButtonsPanelTop.setLayout(borderLayout1); - sendRecButtonsPanelTop.add(getSendButton(), BorderLayout.EAST); - sendRecButtonsPanelTop - .add(getSendTypeComboBox(), BorderLayout.WEST); - } - return sendRecButtonsPanelTop; - } - - /** - * This method initializes sendRecButtonsPanelBottom - * - * @return javax.swing.JPanel - */ - private JPanel getSendRecButtonsPanelBottom() { - if (sendRecButtonsPanelBottom == null) { - BorderLayout borderLayout = new BorderLayout(); - borderLayout.setHgap(5); - sendRecButtonsPanelBottom = new JPanel(); - sendRecButtonsPanelBottom.setBorder(BorderFactory - .createTitledBorder(null, "IN", - TitledBorder.DEFAULT_JUSTIFICATION, - TitledBorder.DEFAULT_POSITION, new Font("Dialog", - Font.BOLD, 12), new Color(51, 51, 51))); - sendRecButtonsPanelBottom.setLayout(borderLayout); - sendRecButtonsPanelBottom.add(getRecButton(), BorderLayout.EAST); - sendRecButtonsPanelBottom.add(getRecTypeComboBox(), - BorderLayout.WEST); - } - return sendRecButtonsPanelBottom; - } - - public static void main(String[] args) { - // set LookAndFeel - try { - UIManager - .setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); - } catch (Exception e) { - e.printStackTrace(); - } - TestApp app = new TestApp(new TestDevice()); - app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.testApp; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.event.ItemEvent; + +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.UIManager; +import javax.swing.border.TitledBorder; + +public class TestApp extends JFrame { + + private static final long serialVersionUID = 994508729204158681L; + TestDevice dev; + private JPanel rootPanel = null; + private JPanel sendReceivePanel = null; + private JPanel settingsPanel = null; + private JButton openDeviceButton = null; + private JButton closeDevice = null; + private JButton resetButton = null; + private JPanel settingsPanelTop = null; + private JPanel settingsPanelBottom = null; + JTextField vendorIDText = null; + JTextField productIDText = null; + private JPanel vendorIDPanel = null; + private JPanel productIDPanel = null; + private JPanel configurationPanel = null; + JTextField configurationText = null; + private JPanel interfacePanel = null; + JTextField interfaceText = null; + private JPanel altInterfacePanel = null; + JTextField altInterfaceText = null; + private JPanel settingsPanelTop2Left = null; + private JPanel settingsPanelTop2Right = null; + private JPanel outEpPanel = null; + JTextField outEpText = null; + private JPanel inEpPanel = null; + JTextField inEpText = null; + private JPanel timeoutPanel = null; + private JTextField timeoutText = null; + private JPanel sendDataPanel = null; + private JPanel sendRecButtonsPanel = null; + private JButton sendButton = null; + private JButton recButton = null; + JTextField sendDataText = null; + JComboBox sendTypeComboBox = null; + private JComboBox recTypeComboBox = null; + private JPanel sendRecButtonsPanelTop = null; + private JPanel sendRecButtonsPanelBottom = null; + + public TestApp(TestDevice devInfo) { + super(); + this.dev = devInfo; + initialize(); + } + + private void initialize() { + + this.setTitle("USB Test Application"); + + this.setContentPane(getRootPanel()); + + // read default values + this.vendorIDText.setText(toHexString(dev.getIdVendor() & 0xffff)); + this.productIDText.setText(toHexString(dev.getIdProduct() & 0xffff)); + this.configurationText.setText(new Integer(dev.getConfiguration()) + .toString()); + this.interfaceText.setText(new Integer(dev.getInterface()).toString()); + this.altInterfaceText.setText(new Integer(dev.getAltinterface()) + .toString()); + this.timeoutText.setText(new Integer(dev.getTimeout()).toString()); + this.sendDataText.setText(dev.getSendData()); + setOutEpAddr(); + setInEpAddr(); + + this.pack(); + this.setVisible(true); + } + + void setOutEpAddr() { + switch (dev.getOutMode()) { + case Bulk: + this.outEpText.setText(toHexString(dev.getOutEPBulk())); + break; + case Interrupt: + this.outEpText.setText(toHexString(dev.getOutEPInt())); + break; + default: + break; + } + } + + void setInEpAddr() { + switch (dev.getInMode()) { + case Bulk: + this.inEpText.setText(toHexString(dev.getInEPBulk())); + break; + case Interrupt: + this.inEpText.setText(toHexString(dev.getInEPInt())); + break; + default: + break; + } + } + + private JPanel getRootPanel() { + if (rootPanel == null) { + rootPanel = new JPanel(); + rootPanel + .setLayout(new BoxLayout(getRootPanel(), BoxLayout.Y_AXIS)); + rootPanel.add(getSettingsPanel(), null); + rootPanel.add(getSendReceivePanel(), null); + } + return rootPanel; + } + + private JPanel getSendReceivePanel() { + if (sendReceivePanel == null) { + BorderLayout borderLayout2 = new BorderLayout(); + borderLayout2.setHgap(5); + sendReceivePanel = new JPanel(); + sendReceivePanel.setLayout(borderLayout2); + sendReceivePanel.setBorder(BorderFactory.createTitledBorder(null, + "Send and Receive Data", + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + sendReceivePanel.add(getSendRecButtonsPanel(), BorderLayout.NORTH); + sendReceivePanel.add(getSendDataPanel(), BorderLayout.SOUTH); + } + return sendReceivePanel; + } + + private JPanel getSettingsPanel() { + if (settingsPanel == null) { + settingsPanel = new JPanel(); + settingsPanel.setLayout(new BoxLayout(getSettingsPanel(), + BoxLayout.Y_AXIS)); + settingsPanel.setBorder(BorderFactory.createTitledBorder(null, + "Device Settings", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + settingsPanel.add(getSettingsPanelTop(), null); + settingsPanel.add(getSettingsPanelBottom(), null); + } + return settingsPanel; + } + + private JButton getOpenDeviceButton() { + if (openDeviceButton == null) { + openDeviceButton = new JButton(); + openDeviceButton.setText("Open Device"); + openDeviceButton + .addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + // update values for the device + dev.setIdVendor((short) parseInt(vendorIDText + .getText().trim())); + dev.setIdProduct((short) parseInt(productIDText + .getText().trim())); + dev.setConfiguration(parseInt(configurationText + .getText().trim())); + dev.setInterface(parseInt(interfaceText.getText() + .trim())); + dev.setAltinterface(parseInt(altInterfaceText + .getText().trim())); + // opent the device + dev.openUsbDevice(); + } + }); + } + return openDeviceButton; + } + + private JButton getCloseDevice() { + if (closeDevice == null) { + closeDevice = new JButton(); + closeDevice.setText("Close Device"); + closeDevice.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + dev.closeUsbDevice(); + } + }); + } + return closeDevice; + } + + private JButton getResetButton() { + if (resetButton == null) { + resetButton = new JButton(); + resetButton.setText("Reset Device"); + resetButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + dev.resetUsbDevice(); + } + }); + } + return resetButton; + } + + private JPanel getSettingsPanelTop() { + if (settingsPanelTop == null) { + FlowLayout flowLayout = new FlowLayout(); + flowLayout.setVgap(1); + flowLayout.setAlignment(FlowLayout.LEFT); + settingsPanelTop = new JPanel(); + settingsPanelTop.setLayout(flowLayout); + settingsPanelTop.add(getVendorIDPanel(), null); + settingsPanelTop.add(getProductIDPanel(), null); + settingsPanelTop.add(getConfigurationPanel(), null); + settingsPanelTop.add(getInterfacePanel(), null); + settingsPanelTop.add(getAltInterfacePanel(), null); + } + return settingsPanelTop; + } + + private JPanel getSettingsPanelBottom() { + if (settingsPanelBottom == null) { + FlowLayout flowLayout1 = new FlowLayout(); + flowLayout1.setVgap(1); + flowLayout1.setHgap(0); + flowLayout1.setAlignment(FlowLayout.LEFT); + GridBagConstraints gridBagConstraints1 = new GridBagConstraints(); + gridBagConstraints1.gridx = -1; + gridBagConstraints1.gridy = -1; + settingsPanelBottom = new JPanel(); + settingsPanelBottom.setLayout(flowLayout1); + settingsPanelBottom.add(getSettingsPanelTop2Left(), null); + settingsPanelBottom.add(getSettingsPanelTop2Right(), null); + } + return settingsPanelBottom; + } + + private JTextField getVendorIDText() { + if (vendorIDText == null) { + vendorIDText = new JTextField(); + vendorIDText.setPreferredSize(new Dimension(100, 20)); + } + return vendorIDText; + } + + private JTextField getProductIDText() { + if (productIDText == null) { + productIDText = new JTextField(); + productIDText.setPreferredSize(new Dimension(100, 20)); + } + return productIDText; + } + + private JPanel getVendorIDPanel() { + if (vendorIDPanel == null) { + GridBagConstraints gridBagConstraints3 = new GridBagConstraints(); + gridBagConstraints3.fill = GridBagConstraints.VERTICAL; + gridBagConstraints3.gridy = -1; + gridBagConstraints3.weightx = 1.0; + gridBagConstraints3.gridx = -1; + GridBagConstraints gridBagConstraints5 = new GridBagConstraints(); + gridBagConstraints5.gridx = -1; + gridBagConstraints5.gridy = -1; + vendorIDPanel = new JPanel(); + vendorIDPanel.setBorder(BorderFactory.createTitledBorder(null, + "VendorID", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + vendorIDPanel.setLayout(new BoxLayout(getVendorIDPanel(), + BoxLayout.X_AXIS)); + vendorIDPanel.add(getVendorIDText(), null); + } + return vendorIDPanel; + } + + private JPanel getProductIDPanel() { + if (productIDPanel == null) { + GridBagConstraints gridBagConstraints4 = new GridBagConstraints(); + gridBagConstraints4.fill = GridBagConstraints.VERTICAL; + gridBagConstraints4.gridy = -1; + gridBagConstraints4.weightx = 1.0; + gridBagConstraints4.gridx = -1; + productIDPanel = new JPanel(); + productIDPanel.setBorder(BorderFactory.createTitledBorder(null, + "ProductID", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + productIDPanel.setLayout(new BoxLayout(getProductIDPanel(), + BoxLayout.X_AXIS)); + productIDPanel.add(getProductIDText(), null); + } + return productIDPanel; + } + + private JPanel getConfigurationPanel() { + if (configurationPanel == null) { + configurationPanel = new JPanel(); + configurationPanel.setLayout(new BoxLayout(getConfigurationPanel(), + BoxLayout.X_AXIS)); + configurationPanel.setBorder(BorderFactory.createTitledBorder(null, + "Configuration", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + configurationPanel.add(getConfigurationText(), null); + } + return configurationPanel; + } + + private JTextField getConfigurationText() { + if (configurationText == null) { + configurationText = new JTextField(); + configurationText.setPreferredSize(new Dimension(100, 20)); + } + return configurationText; + } + + private JPanel getInterfacePanel() { + if (interfacePanel == null) { + interfacePanel = new JPanel(); + interfacePanel.setLayout(new BoxLayout(getInterfacePanel(), + BoxLayout.X_AXIS)); + interfacePanel.setBorder(BorderFactory.createTitledBorder(null, + "Interface", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + interfacePanel.add(getInterfaceText(), null); + } + return interfacePanel; + } + + private JTextField getInterfaceText() { + if (interfaceText == null) { + interfaceText = new JTextField(); + interfaceText.setPreferredSize(new Dimension(100, 20)); + } + return interfaceText; + } + + private JPanel getAltInterfacePanel() { + if (altInterfacePanel == null) { + altInterfacePanel = new JPanel(); + altInterfacePanel.setLayout(new BoxLayout(getAltInterfacePanel(), + BoxLayout.X_AXIS)); + altInterfacePanel.setBorder(BorderFactory.createTitledBorder(null, + "Alternate Int", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + altInterfacePanel.add(getAltInterfaceText(), null); + } + return altInterfacePanel; + } + + private JTextField getAltInterfaceText() { + if (altInterfaceText == null) { + altInterfaceText = new JTextField(); + altInterfaceText.setPreferredSize(new Dimension(100, 20)); + } + return altInterfaceText; + } + + private JPanel getSettingsPanelTop2Left() { + if (settingsPanelTop2Left == null) { + FlowLayout flowLayout2 = new FlowLayout(); + flowLayout2.setVgap(2); + flowLayout2.setAlignment(FlowLayout.LEFT); + flowLayout2.setHgap(5); + settingsPanelTop2Left = new JPanel(); + settingsPanelTop2Left.setLayout(flowLayout2); + settingsPanelTop2Left.add(getOutEpPanel(), null); + settingsPanelTop2Left.add(getInEpPanel(), null); + settingsPanelTop2Left.add(getTimeoutPanel(), null); + } + return settingsPanelTop2Left; + } + + private JPanel getSettingsPanelTop2Right() { + if (settingsPanelTop2Right == null) { + FlowLayout flowLayout3 = new FlowLayout(); + flowLayout3.setVgap(2); + settingsPanelTop2Right = new JPanel(); + settingsPanelTop2Right.setLayout(flowLayout3); + settingsPanelTop2Right.add(getOpenDeviceButton(), null); + settingsPanelTop2Right.add(getCloseDevice(), null); + settingsPanelTop2Right.add(getResetButton(), null); + } + return settingsPanelTop2Right; + } + + private JPanel getOutEpPanel() { + if (outEpPanel == null) { + outEpPanel = new JPanel(); + outEpPanel.setLayout(new BoxLayout(getOutEpPanel(), + BoxLayout.X_AXIS)); + outEpPanel.setBorder(BorderFactory.createTitledBorder(null, + "OUT EP", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + outEpPanel.add(getOutEpText(), null); + } + return outEpPanel; + } + + private JTextField getOutEpText() { + if (outEpText == null) { + outEpText = new JTextField(); + outEpText.setPreferredSize(new Dimension(100, 20)); + } + return outEpText; + } + + private JPanel getInEpPanel() { + if (inEpPanel == null) { + inEpPanel = new JPanel(); + inEpPanel + .setLayout(new BoxLayout(getInEpPanel(), BoxLayout.X_AXIS)); + inEpPanel.setBorder(BorderFactory.createTitledBorder(null, "IN EP", + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + inEpPanel.add(getInEpText(), null); + } + return inEpPanel; + } + + private JTextField getInEpText() { + if (inEpText == null) { + inEpText = new JTextField(); + inEpText.setPreferredSize(new Dimension(100, 20)); + } + return inEpText; + } + + private JPanel getTimeoutPanel() { + if (timeoutPanel == null) { + timeoutPanel = new JPanel(); + timeoutPanel.setLayout(new BoxLayout(getTimeoutPanel(), + BoxLayout.X_AXIS)); + timeoutPanel.setBorder(BorderFactory.createTitledBorder(null, + "Timeout", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + timeoutPanel.add(getTimeoutText(), null); + } + return timeoutPanel; + } + + private JTextField getTimeoutText() { + if (timeoutText == null) { + timeoutText = new JTextField(); + timeoutText.setPreferredSize(new Dimension(100, 20)); + } + return timeoutText; + } + + private JPanel getSendDataPanel() { + if (sendDataPanel == null) { + FlowLayout flowLayout4 = new FlowLayout(); + flowLayout4.setAlignment(FlowLayout.LEFT); + sendDataPanel = new JPanel(); + sendDataPanel.setLayout(flowLayout4); + sendDataPanel.setBorder(BorderFactory.createTitledBorder(null, + "Data to send [hex]", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + sendDataPanel.add(getSendRecDataText(), null); + } + return sendDataPanel; + } + + private JPanel getSendRecButtonsPanel() { + if (sendRecButtonsPanel == null) { + FlowLayout flowLayout5 = new FlowLayout(); + flowLayout5.setAlignment(FlowLayout.LEFT); + flowLayout5.setVgap(0); + sendRecButtonsPanel = new JPanel(); + sendRecButtonsPanel.setLayout(flowLayout5); + sendRecButtonsPanel.add(getSendRecButtonsPanelTop(), null); + sendRecButtonsPanel.add(getSendRecButtonsPanelBottom(), null); + } + return sendRecButtonsPanel; + } + + private JButton getSendButton() { + if (sendButton == null) { + sendButton = new JButton(); + sendButton.setText("Send"); + sendButton.setName("sendButton"); + sendButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + int index = sendTypeComboBox.getSelectedIndex(); + if (index == TestDevice.TransferMode.Bulk.ordinal()) { + dev.setOutEPBulk(parseInt(outEpText.getText().trim())); + dev.setMode(TestDevice.TransferMode.Bulk); + } else if (index == TestDevice.TransferMode.Interrupt + .ordinal()) { + dev.setOutEPInt(parseInt(outEpText.getText().trim())); + dev.setMode(TestDevice.TransferMode.Interrupt); + } + byte[] data = parseByteArray(sendDataText.getText().trim()); + dev.write(data, data.length); + } + }); + } + return sendButton; + } + + private JButton getRecButton() { + if (recButton == null) { + recButton = new JButton(); + recButton.setText("Receive"); + recButton.setName("recButton"); + recButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + int index = sendTypeComboBox.getSelectedIndex(); + if (index == TestDevice.TransferMode.Bulk.ordinal()) { + dev.setInEPBulk(parseInt(inEpText.getText().trim())); + dev.setMode(TestDevice.TransferMode.Bulk); + } else if (index == TestDevice.TransferMode.Interrupt + .ordinal()) { + dev.setInEPInt(parseInt(inEpText.getText().trim())); + dev.setMode(TestDevice.TransferMode.Interrupt); + } + dev.read(); + } + }); + } + return recButton; + } + + private JTextField getSendRecDataText() { + if (sendDataText == null) { + sendDataText = new JTextField(); + sendDataText.setPreferredSize(new Dimension(650, 20)); + } + return sendDataText; + } + + int parseInt(String s) { + if (s == "") + return 0; + if (s.indexOf('x') > 0) { + // is hex number + if (s.length() <= 2) { // exception for "0x" + return 0; + } + return Integer.parseInt( + s.substring(s.indexOf('x') + 1, s.length()), 16); + } + // is decimal number + return Integer.parseInt(s); + } + + byte[] parseByteArray(String s) { + final int HEX_WIDTH = 5; + + StringBuffer sb = new StringBuffer(); + int stringIndex = 0, spaceIndex = 0; + String ss; + while (stringIndex + 3 < s.length()) { + ss = s.substring(spaceIndex, spaceIndex + 4); + spaceIndex = s.indexOf(' ', stringIndex) + 1; + sb.append((char) parseInt(ss)); + stringIndex += HEX_WIDTH; + } + return sb.toString().getBytes(); + } + + private static String toHexString(int value) { + return "0x" + Integer.toHexString(value); + } + + /** + * This method initializes sendTypeComboBox + * + * @return javax.swing.JComboBox + */ + private JComboBox getSendTypeComboBox() { + if (sendTypeComboBox == null) { + sendTypeComboBox = new JComboBox(dev.getTransferTypes()); + sendTypeComboBox.setSelectedIndex(dev.getOutMode().ordinal()); + sendTypeComboBox.addItemListener(new java.awt.event.ItemListener() { + public void itemStateChanged(java.awt.event.ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + String mode = (String) e.getItem(); + if (mode.equalsIgnoreCase("Bulk")) { + dev.setOutMode(TestDevice.TransferMode.Bulk); + setOutEpAddr(); + } else if (mode.equalsIgnoreCase("Interrupt")) { + dev.setOutMode(TestDevice.TransferMode.Interrupt); + setOutEpAddr(); + } + } + } + }); + } + return sendTypeComboBox; + } + + /** + * This method initializes recTypeComboBox + * + * @return javax.swing.JComboBox + */ + private JComboBox getRecTypeComboBox() { + if (recTypeComboBox == null) { + recTypeComboBox = new JComboBox(dev.getTransferTypes()); + recTypeComboBox.setSelectedIndex(dev.getInMode().ordinal()); + recTypeComboBox.addItemListener(new java.awt.event.ItemListener() { + public void itemStateChanged(java.awt.event.ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + String mode = (String) e.getItem(); + if (mode.equalsIgnoreCase("Bulk")) { + dev.setInMode(TestDevice.TransferMode.Bulk); + setInEpAddr(); + } else if (mode.equalsIgnoreCase("Interrupt")) { + dev.setInMode(TestDevice.TransferMode.Interrupt); + setInEpAddr(); + } + } + } + }); + // recTypeComboBox.addActionListener(new + // java.awt.event.ActionListener() { + // public void actionPerformed(java.awt.event.ActionEvent e) { + // JComboBox source = (JComboBox) e.getSource(); + // String mode = ""; + // } if (mode.equalsIgnoreCase("Bulk")) { + // dev.setInMode(TestDevice.TransferMode.Bulk); + // setInEpAddr(); + // } else if (mode.equalsIgnoreCase("Interrupt")) { + // dev.setInMode(TestDevice.TransferMode.Interrupt); + // setInEpAddr(); + // } + // + // }); + } + return recTypeComboBox; + } + + /** + * This method initializes sendRecButtonsPanelTop + * + * @return javax.swing.JPanel + */ + private JPanel getSendRecButtonsPanelTop() { + if (sendRecButtonsPanelTop == null) { + BorderLayout borderLayout1 = new BorderLayout(); + borderLayout1.setHgap(5); + sendRecButtonsPanelTop = new JPanel(); + sendRecButtonsPanelTop.setBorder(BorderFactory.createTitledBorder( + null, "OUT", TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + sendRecButtonsPanelTop.setLayout(borderLayout1); + sendRecButtonsPanelTop.add(getSendButton(), BorderLayout.EAST); + sendRecButtonsPanelTop + .add(getSendTypeComboBox(), BorderLayout.WEST); + } + return sendRecButtonsPanelTop; + } + + /** + * This method initializes sendRecButtonsPanelBottom + * + * @return javax.swing.JPanel + */ + private JPanel getSendRecButtonsPanelBottom() { + if (sendRecButtonsPanelBottom == null) { + BorderLayout borderLayout = new BorderLayout(); + borderLayout.setHgap(5); + sendRecButtonsPanelBottom = new JPanel(); + sendRecButtonsPanelBottom.setBorder(BorderFactory + .createTitledBorder(null, "IN", + TitledBorder.DEFAULT_JUSTIFICATION, + TitledBorder.DEFAULT_POSITION, new Font("Dialog", + Font.BOLD, 12), new Color(51, 51, 51))); + sendRecButtonsPanelBottom.setLayout(borderLayout); + sendRecButtonsPanelBottom.add(getRecButton(), BorderLayout.EAST); + sendRecButtonsPanelBottom.add(getRecTypeComboBox(), + BorderLayout.WEST); + } + return sendRecButtonsPanelBottom; + } + + public static void main(String[] args) { + // set LookAndFeel + try { + UIManager + .setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception e) { + e.printStackTrace(); + } + TestApp app = new TestApp(new TestDevice()); + app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/testApp/TestDevice.java b/src/main/java/ch/ntb/inf/libusbJava/testApp/TestDevice.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/testApp/TestDevice.java rename to src/main/java/ch/ntb/inf/libusbJava/testApp/TestDevice.java index 89bca5a..d3d92a4 100644 --- a/java/src/ch/ntb/inf/libusbJava/testApp/TestDevice.java +++ b/src/main/java/ch/ntb/inf/libusbJava/testApp/TestDevice.java @@ -1,191 +1,191 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.testApp; - -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import ch.ntb.inf.libusbJava.Device; -import ch.ntb.inf.libusbJava.USB; -import ch.ntb.inf.libusbJava.USBException; -import ch.ntb.inf.libusbJava.logger.LogUtil; - -public class TestDevice extends AbstractDeviceInfo { - - private static final Logger logger = LogUtil.getLogger("ch.ntb.inf.libusbJava.test"); - - private String sendData = "0x5b 0x02 0x01 0x00 0x03 0x03 0xf0 0xf0 0x1f"; - - private Vector transferTypes; - - private static Device dev = null; - - private TransferMode inMode; - private TransferMode outMode; - - public TestDevice() { - logger.setLevel(Level.ALL); - // create a vector for transfer types - transferTypes = new Vector(); - transferTypes - .add(TransferMode.Bulk.ordinal(), TransferMode.Bulk.name()); - transferTypes.add(TransferMode.Interrupt.ordinal(), - TransferMode.Interrupt.name()); - inMode = TransferMode.Bulk; - outMode = TransferMode.Bulk; - } - - @Override - public void initValues() { - setIdVendor((short) 0x8235); - setIdProduct((short) 0x0200); - setTimeout(2000); - setConfiguration(1); - setInterface(0); - setAltinterface(-1); - setOutEPBulk(0x01); - setInEPBulk(0x82); - setOutEPInt(0x01); - setInEPInt(0x82); - setSleepTimeout(2000); - setMaxDataSize(USB.FULLSPEED_MAX_BULK_PACKET_SIZE); - setMode(TransferMode.Bulk); - } - - public void openUsbDevice() { - dev = USB.getDevice(getIdVendor(), getIdProduct()); - try { - dev.open(getConfiguration(), getInterface(), getAltinterface()); - logger.info("device opened, interface claimed"); - } catch (USBException e) { - e.printStackTrace(); - } - } - - public void closeUsbDevice() { - try { - if (dev != null) { - dev.close(); - logger.info("device closed"); - } else { - logger.warning("no device to close -> open first"); - } - } catch (USBException e) { - e.printStackTrace(); - } - } - - public void resetUsbDevice() { - try { - if (dev != null) { - dev.reset(); - logger.info("device reset"); - } else { - logger.warning("no device to reset -> open first"); - } - } catch (USBException e) { - e.printStackTrace(); - } - } - - public void write(byte[] data, int length) { - int lenWritten = 0; - try { - if (dev != null) { - StringBuffer sb = new StringBuffer(); - switch (getOutMode()) { - case Bulk: - lenWritten = dev.writeBulk(getOutEPBulk(), data, length, - getTimeout(), false); - sb.append("write_bulk, ep: 0x" - + Integer.toHexString(getOutEPBulk()) + ", " - + lenWritten + " Bytes sent: "); - break; - case Interrupt: - lenWritten = dev.writeInterrupt(getOutEPInt(), data, - length, getTimeout(), false); - sb.append("write_interrupt, ep: 0x" - + Integer.toHexString(getOutEPInt()) + ", " - + lenWritten + " Bytes sent: "); - break; - } - for (int i = 0; i < lenWritten; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } else { - logger.warning("no device opened"); - } - } catch (USBException e) { - e.printStackTrace(); - } - } - - public void read() { - if (dev != null) { - byte[] data = new byte[dev.getMaxPacketSize()]; - int lenRead = 0; - try { - StringBuffer sb = new StringBuffer(); - switch (getInMode()) { - case Bulk: - lenRead = dev.readBulk(getInEPBulk(), data, dev - .getMaxPacketSize(), getTimeout(), false); - sb.append("read_bulk, ep: 0x" - + Integer.toHexString(getInEPBulk()) + ", " - + lenRead + " Bytes received: Data: "); - break; - case Interrupt: - lenRead = dev.readInterrupt(getInEPInt(), data, dev - .getMaxPacketSize(), getTimeout(), false); - sb.append("read_interrupt, ep: 0x" - + Integer.toHexString(getInEPInt()) + ", " - + lenRead + " Bytes received: Data: "); - break; - } - for (int i = 0; i < lenRead; i++) { - sb.append("0x" + String.format("%1$02X", data[i]) + " "); - } - logger.info(sb.toString()); - } catch (USBException e) { - e.printStackTrace(); - } - } else { - logger.warning("no device opened"); - } - } - - public String getSendData() { - return sendData; - } - - public void setSendData(String sendData) { - this.sendData = sendData; - } - - public Vector getTransferTypes() { - return transferTypes; - } - - public TransferMode getOutMode() { - return outMode; - } - - public void setOutMode(TransferMode outMode) { - this.outMode = outMode; - } - - public TransferMode getInMode() { - return inMode; - } - - public void setInMode(TransferMode inMode) { - this.inMode = inMode; - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.testApp; + +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; + +import ch.ntb.inf.libusbJava.Device; +import ch.ntb.inf.libusbJava.USB; +import ch.ntb.inf.libusbJava.USBException; +import ch.ntb.inf.libusbJava.logger.LogUtil; + +public class TestDevice extends AbstractDeviceInfo { + + private static final Logger logger = LogUtil.getLogger("ch.ntb.inf.libusbJava.test"); + + private String sendData = "0x5b 0x02 0x01 0x00 0x03 0x03 0xf0 0xf0 0x1f"; + + private Vector transferTypes; + + private static Device dev = null; + + private TransferMode inMode; + private TransferMode outMode; + + public TestDevice() { + logger.setLevel(Level.ALL); + // create a vector for transfer types + transferTypes = new Vector(); + transferTypes + .add(TransferMode.Bulk.ordinal(), TransferMode.Bulk.name()); + transferTypes.add(TransferMode.Interrupt.ordinal(), + TransferMode.Interrupt.name()); + inMode = TransferMode.Bulk; + outMode = TransferMode.Bulk; + } + + @Override + public void initValues() { + setIdVendor((short) 0x8235); + setIdProduct((short) 0x0200); + setTimeout(2000); + setConfiguration(1); + setInterface(0); + setAltinterface(-1); + setOutEPBulk(0x01); + setInEPBulk(0x82); + setOutEPInt(0x01); + setInEPInt(0x82); + setSleepTimeout(2000); + setMaxDataSize(USB.FULLSPEED_MAX_BULK_PACKET_SIZE); + setMode(TransferMode.Bulk); + } + + public void openUsbDevice() { + dev = USB.getDevice(getIdVendor(), getIdProduct()); + try { + dev.open(getConfiguration(), getInterface(), getAltinterface()); + logger.info("device opened, interface claimed"); + } catch (USBException e) { + e.printStackTrace(); + } + } + + public void closeUsbDevice() { + try { + if (dev != null) { + dev.close(); + logger.info("device closed"); + } else { + logger.warning("no device to close -> open first"); + } + } catch (USBException e) { + e.printStackTrace(); + } + } + + public void resetUsbDevice() { + try { + if (dev != null) { + dev.reset(); + logger.info("device reset"); + } else { + logger.warning("no device to reset -> open first"); + } + } catch (USBException e) { + e.printStackTrace(); + } + } + + public void write(byte[] data, int length) { + int lenWritten = 0; + try { + if (dev != null) { + StringBuffer sb = new StringBuffer(); + switch (getOutMode()) { + case Bulk: + lenWritten = dev.writeBulk(getOutEPBulk(), data, length, + getTimeout(), false); + sb.append("write_bulk, ep: 0x" + + Integer.toHexString(getOutEPBulk()) + ", " + + lenWritten + " Bytes sent: "); + break; + case Interrupt: + lenWritten = dev.writeInterrupt(getOutEPInt(), data, + length, getTimeout(), false); + sb.append("write_interrupt, ep: 0x" + + Integer.toHexString(getOutEPInt()) + ", " + + lenWritten + " Bytes sent: "); + break; + } + for (int i = 0; i < lenWritten; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } else { + logger.warning("no device opened"); + } + } catch (USBException e) { + e.printStackTrace(); + } + } + + public void read() { + if (dev != null) { + byte[] data = new byte[dev.getMaxPacketSize()]; + int lenRead = 0; + try { + StringBuffer sb = new StringBuffer(); + switch (getInMode()) { + case Bulk: + lenRead = dev.readBulk(getInEPBulk(), data, dev + .getMaxPacketSize(), getTimeout(), false); + sb.append("read_bulk, ep: 0x" + + Integer.toHexString(getInEPBulk()) + ", " + + lenRead + " Bytes received: Data: "); + break; + case Interrupt: + lenRead = dev.readInterrupt(getInEPInt(), data, dev + .getMaxPacketSize(), getTimeout(), false); + sb.append("read_interrupt, ep: 0x" + + Integer.toHexString(getInEPInt()) + ", " + + lenRead + " Bytes received: Data: "); + break; + } + for (int i = 0; i < lenRead; i++) { + sb.append("0x" + String.format("%1$02X", data[i]) + " "); + } + logger.info(sb.toString()); + } catch (USBException e) { + e.printStackTrace(); + } + } else { + logger.warning("no device opened"); + } + } + + public String getSendData() { + return sendData; + } + + public void setSendData(String sendData) { + this.sendData = sendData; + } + + public Vector getTransferTypes() { + return transferTypes; + } + + public TransferMode getOutMode() { + return outMode; + } + + public void setOutMode(TransferMode outMode) { + this.outMode = outMode; + } + + public TransferMode getInMode() { + return inMode; + } + + public void setInMode(TransferMode inMode) { + this.inMode = inMode; + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/testApp/package.html b/src/main/java/ch/ntb/inf/libusbJava/testApp/package.html similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/testApp/package.html rename to src/main/java/ch/ntb/inf/libusbJava/testApp/package.html index bf865ad..84a7b64 100644 --- a/java/src/ch/ntb/inf/libusbJava/testApp/package.html +++ b/src/main/java/ch/ntb/inf/libusbJava/testApp/package.html @@ -1,16 +1,16 @@ - - - - - -A test application with a GUI to write to and read from a device (based on Swing). - -

Related Resources

- -For more information about this project visit -http://libusbjava.sourceforge.net -. - - - + + + + + +A test application with a GUI to write to and read from a device (based on Swing). + +

Related Resources

+ +For more information about this project visit +http://libusbjava.sourceforge.net +. + + + diff --git a/java/src/ch/ntb/inf/libusbJava/usbView/UsbTreeModel.java b/src/main/java/ch/ntb/inf/libusbJava/usbView/UsbTreeModel.java similarity index 97% rename from java/src/ch/ntb/inf/libusbJava/usbView/UsbTreeModel.java rename to src/main/java/ch/ntb/inf/libusbJava/usbView/UsbTreeModel.java index e1bf70f..cb0abde 100644 --- a/java/src/ch/ntb/inf/libusbJava/usbView/UsbTreeModel.java +++ b/src/main/java/ch/ntb/inf/libusbJava/usbView/UsbTreeModel.java @@ -1,525 +1,525 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.usbView; - -import java.util.Vector; - -import javax.swing.JTextArea; -import javax.swing.JTree; -import javax.swing.event.TreeModelEvent; -import javax.swing.event.TreeModelListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; - -import ch.ntb.inf.libusbJava.LibusbJava1; -import ch.ntb.inf.libusbJava.Usb_Bus; -import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Device; -import ch.ntb.inf.libusbJava.Usb_Device_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Endpoint_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Interface; -import ch.ntb.inf.libusbJava.Usb_Interface_Descriptor; -import ch.ntb.inf.libusbJava.exceptions.LibusbError; - -public class UsbTreeModel implements TreeModel, TreeSelectionListener { - - private Usb_Bus rootBus; - - private static final String USB_ROOT = "USB"; - - private JTextArea textArea; - - private Vector treeModelListeners = new Vector(); - - /** - * Default constructor.
- * - * @param rootBus - * the root bus from which the data is read - * @param textArea - * the text area to which the data is written - */ - public UsbTreeModel(Usb_Bus rootBus, JTextArea textArea) { - this.rootBus = rootBus; - this.textArea = textArea; - } - - /** - * Returns the root of the tree. - */ - public Object getRoot() { - return USB_ROOT; - } - - /** - * Returns the child of parent at index index in the parent's child array. - */ - public Object getChild(Object parent, int index) { - - if (parent instanceof String - && ((String) parent).compareTo(USB_ROOT) == 0) { - Usb_Bus curBus = rootBus; - - for (int i = 0; curBus != null; curBus = curBus.getNext(), i++) { - if (i == index) - return curBus; - } - } - - else if (parent instanceof Usb_Bus) { - Usb_Device device = ((Usb_Bus) parent).getDevices(); - int count = 0; - while (device != null) { - if (count == index) - return device; - count++; - device = device.getNext(); - } - return null; - } else if (parent instanceof Usb_Device) { - Usb_Device dev = (Usb_Device) parent; - // return the Usb_Device_Descriptor at index 0 - if (index == 0) { - return dev.getDescriptor(); - } - Usb_Config_Descriptor[] confDescs = dev.getConfig(); - if (index >= confDescs.length + 1) - return null; - return confDescs[index - 1]; - } else if (parent instanceof Usb_Config_Descriptor) { - Usb_Interface[] intDescs = ((Usb_Config_Descriptor) parent) - .getInterface(); - if (index >= intDescs.length) - return null; - return intDescs[index]; - } else if (parent instanceof Usb_Interface) { - Usb_Interface_Descriptor[] altSettings = ((Usb_Interface) parent) - .getAltsetting(); - if (index >= altSettings.length) - return null; - return altSettings[index]; - } else if (parent instanceof Usb_Interface_Descriptor) { - Usb_Endpoint_Descriptor[] endpoints = ((Usb_Interface_Descriptor) parent) - .getEndpoint(); - if (index >= endpoints.length) - return null; - return endpoints[index]; - } - return null; - } - - /** - * Returns the number of children of parent. - */ - public int getChildCount(Object parent) { - if (parent instanceof String - && ((String) parent).compareTo(USB_ROOT) == 0) { - int count = 0; - - Usb_Bus curBus = rootBus; - - for (; curBus != null; curBus = curBus.getNext()) { - count++; - } - - return count; - - } else if (parent instanceof Usb_Bus) { - Usb_Device device = ((Usb_Bus) parent).getDevices(); - int count = 0; - while (device != null) { - count++; - device = device.getNext(); - } - return count; - } else if (parent instanceof Usb_Device) { - // add the Usb_Device_Descriptor - return ((Usb_Device) parent).getConfig().length + 1; - } else if (parent instanceof Usb_Config_Descriptor) { - return ((Usb_Config_Descriptor) parent).getInterface().length; - } else if (parent instanceof Usb_Interface) { - return ((Usb_Interface) parent).getAltsetting().length; - } else if (parent instanceof Usb_Interface_Descriptor) { - return ((Usb_Interface_Descriptor) parent).getEndpoint().length; - } - return 0; - } - - /** - * Returns true if node is a leaf. - */ - public boolean isLeaf(Object node) { - return false; - } - - /** - * Messaged when the user has altered the value for the item identified by - * path to newValue. Not used by this model. - */ - public void valueForPathChanged(TreePath path, Object newValue) { - System.out.println("*** valueForPathChanged : " + path + " --> " - + newValue); - } - - /** - * Returns the index of child in parent. - */ - public int getIndexOfChild(Object parent, Object child) { - return 0; - } - - public void addTreeModelListener(TreeModelListener l) { - treeModelListeners.addElement(l); - } - - public void removeTreeModelListener(TreeModelListener l) { - treeModelListeners.removeElement(l); - } - - /** - * The only event raised by this model is TreeStructureChanged with the root - * as path, i.e. the whole tree has changed. - */ - protected void fireTreeStructureChanged(Usb_Bus newRootBus) { - rootBus = newRootBus; - int len = treeModelListeners.size(); - TreeModelEvent e = new TreeModelEvent(this, new Object[] { newRootBus }); - for (int i = 0; i < len; i++) { - treeModelListeners.elementAt(i).treeStructureChanged(e); - } - } - - public void valueChanged(TreeSelectionEvent e) { - JTree tree = (JTree) e.getSource(); - Object component = tree.getLastSelectedPathComponent(); - if (component instanceof Usb_Bus) { - Usb_Bus bus = (Usb_Bus) component; - StringBuffer sb = new StringBuffer("Usb_Bus\n"); - sb.append("\tdirname: " + bus.getDirname() + "\n"); - sb.append("\tlocation: 0x" + Long.toHexString(bus.getLocation()) - + "\n"); - textArea.setText(sb.toString()); - } else if (component instanceof Usb_Device) { - Usb_Device device = (Usb_Device) component; - StringBuffer sb = new StringBuffer("Usb_Device\n"); - sb.append("\tfilename: " + device.getFilename() + "\n"); - sb.append("\tdevnum: " + device.getDevnum() + "\n"); - sb.append("\tnum_children: " + device.getNumChildren() + "\n"); - textArea.setText(sb.toString()); - } else if (component instanceof Usb_Device_Descriptor) { - Usb_Device_Descriptor devDesc = (Usb_Device_Descriptor) component; - StringBuffer sb = new StringBuffer("Usb_Device_Descriptor\n"); - sb.append("\tblenght: 0x" - + Integer.toHexString(devDesc.getBLength() & 0xFF) + "\n"); - sb.append("\tbDescriptorType: 0x" - + Integer.toHexString(devDesc.getBDescriptorType() & 0xFF) - + "\n"); - sb.append("\tbcdUSB: 0x" - + Integer.toHexString(devDesc.getBcdUSB() & 0xFFFF) + "\n"); - sb.append("\tbDeviceClass: 0x" - + Integer.toHexString(devDesc.getBDeviceClass() & 0xFF) - + "\n"); - sb.append("\tbDeviceSubClass: 0x" - + Integer.toHexString(devDesc.getBDeviceSubClass() & 0xFF) - + "\n"); - sb.append("\tbDeviceProtocol: 0x" - + Integer.toHexString(devDesc.getBDeviceProtocol() & 0xFF) - + "\n"); - sb.append("\tbMaxPacketSize0: 0x" - + Integer.toHexString(devDesc.getBMaxPacketSize0() & 0xFF) - + " (" + devDesc.getBMaxPacketSize0() + ")\n"); - sb.append("\tidVendor: 0x" - + Integer.toHexString(devDesc.getIdVendor() & 0xFFFF) - + "\n"); - sb.append("\tidProduct: 0x" - + Integer.toHexString(devDesc.getIdProduct() & 0xFFFF) - + "\n"); - sb.append("\tbcdDevice: 0x" - + Integer.toHexString(devDesc.getBcdDevice() & 0xFF) + "\n"); - sb.append("\tiManufacturer: 0x" - + Integer.toHexString(devDesc.getIManufacturer() & 0xFF) - + "\n"); - sb.append("\tiProduct: 0x" - + Integer.toHexString(devDesc.getIProduct()) + "\n"); - sb.append("\tiSerialNumber: 0x" - + Integer.toHexString(devDesc.getISerialNumber() & 0xFF) - + "\n"); - sb.append("\tbNumConfigurations: 0x" - + Integer.toHexString(devDesc.getBNumConfigurations() & 0xFF) - + "\n"); - // get device handle to retrieve string descriptors - Usb_Bus bus = rootBus; - while (bus != null) { - Usb_Device dev = bus.getDevices(); - while (dev != null) { - Usb_Device_Descriptor tmpDevDesc = dev.getDescriptor(); - if ((dev.getDescriptor() != null) - && ((dev.getDescriptor().getIManufacturer() > 0) - || (dev.getDescriptor().getIProduct() > 0) || (dev - .getDescriptor().getISerialNumber() > 0))) { - if (tmpDevDesc.equals(devDesc)) { - try { - sb.append("\nString descriptors\n"); - long handle = LibusbJava1.libusb_open(dev); - - try { - if (dev.getDescriptor().getIManufacturer() > 0) { - String manufacturer = LibusbJava1 - .libusb_get_string_descriptor_ascii( - handle, - devDesc.getIManufacturer(), - 255); - if (manufacturer == null) - manufacturer = "unable to fetch manufacturer string"; - sb.append("\tiManufacturer: " - + manufacturer + "\n"); - } - if (dev.getDescriptor().getIProduct() > 0) { - String product = LibusbJava1 - .libusb_get_string_descriptor_ascii( - handle, - devDesc.getIProduct(), - 255); - if (product == null) - product = "unable to fetch product string"; - sb.append("\tiProduct: " + product - + "\n"); - } - if (dev.getDescriptor().getISerialNumber() > 0) { - String serialNumber = LibusbJava1 - .libusb_get_string_descriptor_ascii( - handle, - devDesc.getISerialNumber(), - 255); - if (serialNumber == null) - serialNumber = "unable to fetch serial number string"; - sb.append("\tiSerialNumber: " - + serialNumber + "\n"); - } - } catch (LibusbError ex) { - sb.append("\terror getting descriptors: " - + ex.getErrorString() + "\n"); - } finally { - LibusbJava1.libusb_close(handle); - } - } catch (LibusbError ex) { - sb.append("\terror opening the device" - + ex.getErrorString() + "\n"); - } - } - } - dev = dev.getNext(); - } - bus = bus.getNext(); - } - textArea.setText(sb.toString()); - } else if (component instanceof Usb_Config_Descriptor) { - Usb_Config_Descriptor confDesc = (Usb_Config_Descriptor) component; - StringBuffer sb = new StringBuffer("Usb_Config_Descriptor\n"); - sb.append("\tblenght: 0x" - + Integer.toHexString(confDesc.getBLength()) + "\n"); - sb.append("\tbDescriptorType: 0x" - + Integer.toHexString(confDesc.getBDescriptorType() & 0xFF) - + "\n"); - sb.append("\tbNumInterfaces: 0x" - + Integer.toHexString(confDesc.getBNumInterfaces() & 0xFF) - + "\n"); - sb.append("\tbConfigurationValue: 0x" - + Integer.toHexString(confDesc.getBConfigurationValue() & 0xFF) - + "\n"); - sb.append("\tiConfiguration: 0x" - + Integer.toHexString(confDesc.getIConfiguration() & 0xFF) - + "\n"); - sb.append("\tbmAttributes: 0x" - + Integer.toHexString(confDesc.getBmAttributes() & 0xFF) - + "\n"); - sb.append("\tMaxPower [mA]: 0x" - + Integer.toHexString(confDesc.getMaxPower() & 0xFF) + " (" - + confDesc.getMaxPower() + ")\n"); - sb.append("\textralen: 0x" - + Integer.toHexString(confDesc.getExtralen()) + "\n"); - sb.append("\textra: " - + extraDescriptorToString(confDesc.getExtra()) + "\n"); - // get device handle to retrieve string descriptors - Usb_Bus bus = rootBus; - while (bus != null) { - Usb_Device dev = bus.getDevices(); - while (dev != null) { - Usb_Config_Descriptor[] tmpConfDesc = dev.getConfig(); - for (int i = 0; i < tmpConfDesc.length; i++) { - if ((tmpConfDesc.equals(confDesc)) - && (confDesc.getIConfiguration() > 0)) { - try { - sb.append("\nString descriptors\n"); - long handle = LibusbJava1.libusb_open(dev); - - try { - String configuration = LibusbJava1 - .libusb_get_string_descriptor_ascii( - handle, - confDesc.getIConfiguration(), - 255); - if (configuration == null) - configuration = "unable to fetch configuration string"; - sb.append("\tiConfiguration: " - + configuration + "\n"); - } catch (LibusbError e1) { - sb.append("\terror getting config descriptor: " - + e1.getErrorString() + "\n"); - } finally { - LibusbJava1.libusb_close(handle); - } - } catch (LibusbError e1) { - sb.append("\terror opening the device: " - + e1.getErrorString() + "\n"); - } finally { - } - } - } - dev = dev.getNext(); - } - bus = bus.getNext(); - } - textArea.setText(sb.toString()); - } else if (component instanceof Usb_Interface) { - Usb_Interface int_ = (Usb_Interface) component; - StringBuffer sb = new StringBuffer("Usb_Interface\n"); - sb.append("\tnum_altsetting: 0x" - + Integer.toHexString(int_.getNumAltsetting()) + "\n"); - sb.append("\taltsetting: " + int_.getAltsetting() + "\n"); - textArea.setText(sb.toString()); - } else if (component instanceof Usb_Interface_Descriptor) { - Usb_Interface_Descriptor intDesc = (Usb_Interface_Descriptor) component; - StringBuffer sb = new StringBuffer("Usb_Interface_Descriptor\n"); - sb.append("\tblenght: 0x" - + Integer.toHexString(intDesc.getBLength() & 0xFF) + "\n"); - sb.append("\tbDescriptorType: 0x" - + Integer.toHexString(intDesc.getBDescriptorType() & 0xFF) - + "\n"); - sb.append("\tbInterfaceNumber: 0x" - + Integer.toHexString(intDesc.getBInterfaceNumber() & 0xFF) - + "\n"); - sb.append("\tbAlternateSetting: 0x" - + Integer.toHexString(intDesc.getBAlternateSetting() & 0xFF) - + "\n"); - sb.append("\tbNumEndpoints: 0x" - + Integer.toHexString(intDesc.getBNumEndpoints() & 0xFF) - + "\n"); - sb.append("\tbInterfaceClass: 0x" - + Integer.toHexString(intDesc.getBInterfaceClass() & 0xFF) - + "\n"); - sb.append("\tbInterfaceSubClass: 0x" - + Integer.toHexString(intDesc.getBInterfaceSubClass() & 0xFF) - + "\n"); - sb.append("\tbInterfaceProtocol: 0x" - + Integer.toHexString(intDesc.getBInterfaceProtocol() & 0xFF) - + "\n"); - sb.append("\tiInterface: 0x" - + Integer.toHexString(intDesc.getIInterface()) + "\n"); - sb.append("\textralen: 0x" - + Integer.toHexString(intDesc.getExtralen()) + "\n"); - sb.append("\textra: " + extraDescriptorToString(intDesc.getExtra()) - + "\n"); - // get device handle to retrieve string descriptors - Usb_Bus bus = rootBus; - while (bus != null) { - Usb_Device dev = bus.getDevices(); - while (dev != null) { - try { - long handle = LibusbJava1.libusb_open(dev); - - Usb_Config_Descriptor[] confDescs = dev.getConfig(); - for (int i = 0; i < confDescs.length; i++) { - Usb_Interface[] ints = confDescs[i].getInterface(); - - for (int j = 0; j < ints.length; j++) { - Usb_Interface_Descriptor[] tmpIntDescs = ints[j] - .getAltsetting(); - - for (int k = 0; k < ints.length; k++) { - if (i < tmpIntDescs.length - && tmpIntDescs[i].equals(intDesc) - && (intDesc.getIInterface() > 0)) { - sb.append("\nString descriptors\n"); - try { - String interface_ = LibusbJava1 - .libusb_get_string_descriptor_ascii( - handle, - intDesc.getIInterface(), - 255); - if (interface_ == null) - interface_ = "unable to fetch interface string"; - sb.append("\tiInterface: " - + interface_ + "\n"); - } catch (LibusbError e1) { - sb.append("\terror while reading descriptors: " - + e1.getErrorString() - + "\n"); - } - } - } - } - } - - LibusbJava1.libusb_close(handle); - } catch (LibusbError e1) { - sb.append("\terror opening the device: " - + e1.getErrorString() + "\n"); - } - - dev = dev.getNext(); - } - bus = bus.getNext(); - } - textArea.setText(sb.toString()); - } else if (component instanceof Usb_Endpoint_Descriptor) { - Usb_Endpoint_Descriptor epDesc = (Usb_Endpoint_Descriptor) component; - StringBuffer sb = new StringBuffer("Usb_Endpoint_Descriptor\n"); - sb.append("\tblenght: 0x" - + Integer.toHexString(epDesc.getBLength() & 0xFF) + "\n"); - sb.append("\tbDescriptorType: 0x" - + Integer.toHexString(epDesc.getBDescriptorType() & 0xFF) - + "\n"); - sb.append("\tbEndpointAddress: 0x" - + Integer.toHexString(epDesc.getBEndpointAddress() & 0xFF) - + "\n"); - sb.append("\tbmAttributes: 0x" - + Integer.toHexString(epDesc.getBmAttributes() & 0xFF) - + "\n"); - sb.append("\twMaxPacketSize: 0x" - + Integer.toHexString(epDesc.getWMaxPacketSize() & 0xFFFF) - + " (" + epDesc.getWMaxPacketSize() + ")\n"); - sb.append("\tbInterval: 0x" - + Integer.toHexString(epDesc.getBInterval() & 0xFF) + "\n"); - sb.append("\tbRefresh: 0x" - + Integer.toHexString(epDesc.getBRefresh() & 0xFF) + "\n"); - sb.append("\tbSynchAddress: 0x" - + Integer.toHexString(epDesc.getBSynchAddress()) + "\n"); - sb.append("\textralen: 0x" - + Integer.toHexString(epDesc.getExtralen()) + "\n"); - sb.append("\textra: " + extraDescriptorToString(epDesc.getExtra()) - + "\n"); - textArea.setText(sb.toString()); - } - } - - private String extraDescriptorToString(byte[] extra) { - if (extra != null) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < extra.length; i++) { - sb.append("0x"); - sb.append(Integer.toHexString(extra[i] & 0xff)); - sb.append(' '); - } - return sb.toString(); - } - return null; - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.usbView; + +import java.util.Vector; + +import javax.swing.JTextArea; +import javax.swing.JTree; +import javax.swing.event.TreeModelEvent; +import javax.swing.event.TreeModelListener; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; + +import ch.ntb.inf.libusbJava.LibusbJava1; +import ch.ntb.inf.libusbJava.Usb_Bus; +import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Device; +import ch.ntb.inf.libusbJava.Usb_Device_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Endpoint_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Interface; +import ch.ntb.inf.libusbJava.Usb_Interface_Descriptor; +import ch.ntb.inf.libusbJava.exceptions.LibusbError; + +public class UsbTreeModel implements TreeModel, TreeSelectionListener { + + private Usb_Bus rootBus; + + private static final String USB_ROOT = "USB"; + + private JTextArea textArea; + + private Vector treeModelListeners = new Vector(); + + /** + * Default constructor.
+ * + * @param rootBus + * the root bus from which the data is read + * @param textArea + * the text area to which the data is written + */ + public UsbTreeModel(Usb_Bus rootBus, JTextArea textArea) { + this.rootBus = rootBus; + this.textArea = textArea; + } + + /** + * Returns the root of the tree. + */ + public Object getRoot() { + return USB_ROOT; + } + + /** + * Returns the child of parent at index index in the parent's child array. + */ + public Object getChild(Object parent, int index) { + + if (parent instanceof String + && ((String) parent).compareTo(USB_ROOT) == 0) { + Usb_Bus curBus = rootBus; + + for (int i = 0; curBus != null; curBus = curBus.getNext(), i++) { + if (i == index) + return curBus; + } + } + + else if (parent instanceof Usb_Bus) { + Usb_Device device = ((Usb_Bus) parent).getDevices(); + int count = 0; + while (device != null) { + if (count == index) + return device; + count++; + device = device.getNext(); + } + return null; + } else if (parent instanceof Usb_Device) { + Usb_Device dev = (Usb_Device) parent; + // return the Usb_Device_Descriptor at index 0 + if (index == 0) { + return dev.getDescriptor(); + } + Usb_Config_Descriptor[] confDescs = dev.getConfig(); + if (index >= confDescs.length + 1) + return null; + return confDescs[index - 1]; + } else if (parent instanceof Usb_Config_Descriptor) { + Usb_Interface[] intDescs = ((Usb_Config_Descriptor) parent) + .getInterface(); + if (index >= intDescs.length) + return null; + return intDescs[index]; + } else if (parent instanceof Usb_Interface) { + Usb_Interface_Descriptor[] altSettings = ((Usb_Interface) parent) + .getAltsetting(); + if (index >= altSettings.length) + return null; + return altSettings[index]; + } else if (parent instanceof Usb_Interface_Descriptor) { + Usb_Endpoint_Descriptor[] endpoints = ((Usb_Interface_Descriptor) parent) + .getEndpoint(); + if (index >= endpoints.length) + return null; + return endpoints[index]; + } + return null; + } + + /** + * Returns the number of children of parent. + */ + public int getChildCount(Object parent) { + if (parent instanceof String + && ((String) parent).compareTo(USB_ROOT) == 0) { + int count = 0; + + Usb_Bus curBus = rootBus; + + for (; curBus != null; curBus = curBus.getNext()) { + count++; + } + + return count; + + } else if (parent instanceof Usb_Bus) { + Usb_Device device = ((Usb_Bus) parent).getDevices(); + int count = 0; + while (device != null) { + count++; + device = device.getNext(); + } + return count; + } else if (parent instanceof Usb_Device) { + // add the Usb_Device_Descriptor + return ((Usb_Device) parent).getConfig().length + 1; + } else if (parent instanceof Usb_Config_Descriptor) { + return ((Usb_Config_Descriptor) parent).getInterface().length; + } else if (parent instanceof Usb_Interface) { + return ((Usb_Interface) parent).getAltsetting().length; + } else if (parent instanceof Usb_Interface_Descriptor) { + return ((Usb_Interface_Descriptor) parent).getEndpoint().length; + } + return 0; + } + + /** + * Returns true if node is a leaf. + */ + public boolean isLeaf(Object node) { + return false; + } + + /** + * Messaged when the user has altered the value for the item identified by + * path to newValue. Not used by this model. + */ + public void valueForPathChanged(TreePath path, Object newValue) { + System.out.println("*** valueForPathChanged : " + path + " --> " + + newValue); + } + + /** + * Returns the index of child in parent. + */ + public int getIndexOfChild(Object parent, Object child) { + return 0; + } + + public void addTreeModelListener(TreeModelListener l) { + treeModelListeners.addElement(l); + } + + public void removeTreeModelListener(TreeModelListener l) { + treeModelListeners.removeElement(l); + } + + /** + * The only event raised by this model is TreeStructureChanged with the root + * as path, i.e. the whole tree has changed. + */ + protected void fireTreeStructureChanged(Usb_Bus newRootBus) { + rootBus = newRootBus; + int len = treeModelListeners.size(); + TreeModelEvent e = new TreeModelEvent(this, new Object[] { newRootBus }); + for (int i = 0; i < len; i++) { + treeModelListeners.elementAt(i).treeStructureChanged(e); + } + } + + public void valueChanged(TreeSelectionEvent e) { + JTree tree = (JTree) e.getSource(); + Object component = tree.getLastSelectedPathComponent(); + if (component instanceof Usb_Bus) { + Usb_Bus bus = (Usb_Bus) component; + StringBuffer sb = new StringBuffer("Usb_Bus\n"); + sb.append("\tdirname: " + bus.getDirname() + "\n"); + sb.append("\tlocation: 0x" + Long.toHexString(bus.getLocation()) + + "\n"); + textArea.setText(sb.toString()); + } else if (component instanceof Usb_Device) { + Usb_Device device = (Usb_Device) component; + StringBuffer sb = new StringBuffer("Usb_Device\n"); + sb.append("\tfilename: " + device.getFilename() + "\n"); + sb.append("\tdevnum: " + device.getDevnum() + "\n"); + sb.append("\tnum_children: " + device.getNumChildren() + "\n"); + textArea.setText(sb.toString()); + } else if (component instanceof Usb_Device_Descriptor) { + Usb_Device_Descriptor devDesc = (Usb_Device_Descriptor) component; + StringBuffer sb = new StringBuffer("Usb_Device_Descriptor\n"); + sb.append("\tblenght: 0x" + + Integer.toHexString(devDesc.getBLength() & 0xFF) + "\n"); + sb.append("\tbDescriptorType: 0x" + + Integer.toHexString(devDesc.getBDescriptorType() & 0xFF) + + "\n"); + sb.append("\tbcdUSB: 0x" + + Integer.toHexString(devDesc.getBcdUSB() & 0xFFFF) + "\n"); + sb.append("\tbDeviceClass: 0x" + + Integer.toHexString(devDesc.getBDeviceClass() & 0xFF) + + "\n"); + sb.append("\tbDeviceSubClass: 0x" + + Integer.toHexString(devDesc.getBDeviceSubClass() & 0xFF) + + "\n"); + sb.append("\tbDeviceProtocol: 0x" + + Integer.toHexString(devDesc.getBDeviceProtocol() & 0xFF) + + "\n"); + sb.append("\tbMaxPacketSize0: 0x" + + Integer.toHexString(devDesc.getBMaxPacketSize0() & 0xFF) + + " (" + devDesc.getBMaxPacketSize0() + ")\n"); + sb.append("\tidVendor: 0x" + + Integer.toHexString(devDesc.getIdVendor() & 0xFFFF) + + "\n"); + sb.append("\tidProduct: 0x" + + Integer.toHexString(devDesc.getIdProduct() & 0xFFFF) + + "\n"); + sb.append("\tbcdDevice: 0x" + + Integer.toHexString(devDesc.getBcdDevice() & 0xFF) + "\n"); + sb.append("\tiManufacturer: 0x" + + Integer.toHexString(devDesc.getIManufacturer() & 0xFF) + + "\n"); + sb.append("\tiProduct: 0x" + + Integer.toHexString(devDesc.getIProduct()) + "\n"); + sb.append("\tiSerialNumber: 0x" + + Integer.toHexString(devDesc.getISerialNumber() & 0xFF) + + "\n"); + sb.append("\tbNumConfigurations: 0x" + + Integer.toHexString(devDesc.getBNumConfigurations() & 0xFF) + + "\n"); + // get device handle to retrieve string descriptors + Usb_Bus bus = rootBus; + while (bus != null) { + Usb_Device dev = bus.getDevices(); + while (dev != null) { + Usb_Device_Descriptor tmpDevDesc = dev.getDescriptor(); + if ((dev.getDescriptor() != null) + && ((dev.getDescriptor().getIManufacturer() > 0) + || (dev.getDescriptor().getIProduct() > 0) || (dev + .getDescriptor().getISerialNumber() > 0))) { + if (tmpDevDesc.equals(devDesc)) { + try { + sb.append("\nString descriptors\n"); + long handle = LibusbJava1.libusb_open(dev); + + try { + if (dev.getDescriptor().getIManufacturer() > 0) { + String manufacturer = LibusbJava1 + .libusb_get_string_descriptor_ascii( + handle, + devDesc.getIManufacturer(), + 255); + if (manufacturer == null) + manufacturer = "unable to fetch manufacturer string"; + sb.append("\tiManufacturer: " + + manufacturer + "\n"); + } + if (dev.getDescriptor().getIProduct() > 0) { + String product = LibusbJava1 + .libusb_get_string_descriptor_ascii( + handle, + devDesc.getIProduct(), + 255); + if (product == null) + product = "unable to fetch product string"; + sb.append("\tiProduct: " + product + + "\n"); + } + if (dev.getDescriptor().getISerialNumber() > 0) { + String serialNumber = LibusbJava1 + .libusb_get_string_descriptor_ascii( + handle, + devDesc.getISerialNumber(), + 255); + if (serialNumber == null) + serialNumber = "unable to fetch serial number string"; + sb.append("\tiSerialNumber: " + + serialNumber + "\n"); + } + } catch (LibusbError ex) { + sb.append("\terror getting descriptors: " + + ex.getErrorString() + "\n"); + } finally { + LibusbJava1.libusb_close(handle); + } + } catch (LibusbError ex) { + sb.append("\terror opening the device" + + ex.getErrorString() + "\n"); + } + } + } + dev = dev.getNext(); + } + bus = bus.getNext(); + } + textArea.setText(sb.toString()); + } else if (component instanceof Usb_Config_Descriptor) { + Usb_Config_Descriptor confDesc = (Usb_Config_Descriptor) component; + StringBuffer sb = new StringBuffer("Usb_Config_Descriptor\n"); + sb.append("\tblenght: 0x" + + Integer.toHexString(confDesc.getBLength()) + "\n"); + sb.append("\tbDescriptorType: 0x" + + Integer.toHexString(confDesc.getBDescriptorType() & 0xFF) + + "\n"); + sb.append("\tbNumInterfaces: 0x" + + Integer.toHexString(confDesc.getBNumInterfaces() & 0xFF) + + "\n"); + sb.append("\tbConfigurationValue: 0x" + + Integer.toHexString(confDesc.getBConfigurationValue() & 0xFF) + + "\n"); + sb.append("\tiConfiguration: 0x" + + Integer.toHexString(confDesc.getIConfiguration() & 0xFF) + + "\n"); + sb.append("\tbmAttributes: 0x" + + Integer.toHexString(confDesc.getBmAttributes() & 0xFF) + + "\n"); + sb.append("\tMaxPower [mA]: 0x" + + Integer.toHexString(confDesc.getMaxPower() & 0xFF) + " (" + + confDesc.getMaxPower() + ")\n"); + sb.append("\textralen: 0x" + + Integer.toHexString(confDesc.getExtralen()) + "\n"); + sb.append("\textra: " + + extraDescriptorToString(confDesc.getExtra()) + "\n"); + // get device handle to retrieve string descriptors + Usb_Bus bus = rootBus; + while (bus != null) { + Usb_Device dev = bus.getDevices(); + while (dev != null) { + Usb_Config_Descriptor[] tmpConfDesc = dev.getConfig(); + for (int i = 0; i < tmpConfDesc.length; i++) { + if ((tmpConfDesc.equals(confDesc)) + && (confDesc.getIConfiguration() > 0)) { + try { + sb.append("\nString descriptors\n"); + long handle = LibusbJava1.libusb_open(dev); + + try { + String configuration = LibusbJava1 + .libusb_get_string_descriptor_ascii( + handle, + confDesc.getIConfiguration(), + 255); + if (configuration == null) + configuration = "unable to fetch configuration string"; + sb.append("\tiConfiguration: " + + configuration + "\n"); + } catch (LibusbError e1) { + sb.append("\terror getting config descriptor: " + + e1.getErrorString() + "\n"); + } finally { + LibusbJava1.libusb_close(handle); + } + } catch (LibusbError e1) { + sb.append("\terror opening the device: " + + e1.getErrorString() + "\n"); + } finally { + } + } + } + dev = dev.getNext(); + } + bus = bus.getNext(); + } + textArea.setText(sb.toString()); + } else if (component instanceof Usb_Interface) { + Usb_Interface int_ = (Usb_Interface) component; + StringBuffer sb = new StringBuffer("Usb_Interface\n"); + sb.append("\tnum_altsetting: 0x" + + Integer.toHexString(int_.getNumAltsetting()) + "\n"); + sb.append("\taltsetting: " + int_.getAltsetting() + "\n"); + textArea.setText(sb.toString()); + } else if (component instanceof Usb_Interface_Descriptor) { + Usb_Interface_Descriptor intDesc = (Usb_Interface_Descriptor) component; + StringBuffer sb = new StringBuffer("Usb_Interface_Descriptor\n"); + sb.append("\tblenght: 0x" + + Integer.toHexString(intDesc.getBLength() & 0xFF) + "\n"); + sb.append("\tbDescriptorType: 0x" + + Integer.toHexString(intDesc.getBDescriptorType() & 0xFF) + + "\n"); + sb.append("\tbInterfaceNumber: 0x" + + Integer.toHexString(intDesc.getBInterfaceNumber() & 0xFF) + + "\n"); + sb.append("\tbAlternateSetting: 0x" + + Integer.toHexString(intDesc.getBAlternateSetting() & 0xFF) + + "\n"); + sb.append("\tbNumEndpoints: 0x" + + Integer.toHexString(intDesc.getBNumEndpoints() & 0xFF) + + "\n"); + sb.append("\tbInterfaceClass: 0x" + + Integer.toHexString(intDesc.getBInterfaceClass() & 0xFF) + + "\n"); + sb.append("\tbInterfaceSubClass: 0x" + + Integer.toHexString(intDesc.getBInterfaceSubClass() & 0xFF) + + "\n"); + sb.append("\tbInterfaceProtocol: 0x" + + Integer.toHexString(intDesc.getBInterfaceProtocol() & 0xFF) + + "\n"); + sb.append("\tiInterface: 0x" + + Integer.toHexString(intDesc.getIInterface()) + "\n"); + sb.append("\textralen: 0x" + + Integer.toHexString(intDesc.getExtralen()) + "\n"); + sb.append("\textra: " + extraDescriptorToString(intDesc.getExtra()) + + "\n"); + // get device handle to retrieve string descriptors + Usb_Bus bus = rootBus; + while (bus != null) { + Usb_Device dev = bus.getDevices(); + while (dev != null) { + try { + long handle = LibusbJava1.libusb_open(dev); + + Usb_Config_Descriptor[] confDescs = dev.getConfig(); + for (int i = 0; i < confDescs.length; i++) { + Usb_Interface[] ints = confDescs[i].getInterface(); + + for (int j = 0; j < ints.length; j++) { + Usb_Interface_Descriptor[] tmpIntDescs = ints[j] + .getAltsetting(); + + for (int k = 0; k < ints.length; k++) { + if (i < tmpIntDescs.length + && tmpIntDescs[i].equals(intDesc) + && (intDesc.getIInterface() > 0)) { + sb.append("\nString descriptors\n"); + try { + String interface_ = LibusbJava1 + .libusb_get_string_descriptor_ascii( + handle, + intDesc.getIInterface(), + 255); + if (interface_ == null) + interface_ = "unable to fetch interface string"; + sb.append("\tiInterface: " + + interface_ + "\n"); + } catch (LibusbError e1) { + sb.append("\terror while reading descriptors: " + + e1.getErrorString() + + "\n"); + } + } + } + } + } + + LibusbJava1.libusb_close(handle); + } catch (LibusbError e1) { + sb.append("\terror opening the device: " + + e1.getErrorString() + "\n"); + } + + dev = dev.getNext(); + } + bus = bus.getNext(); + } + textArea.setText(sb.toString()); + } else if (component instanceof Usb_Endpoint_Descriptor) { + Usb_Endpoint_Descriptor epDesc = (Usb_Endpoint_Descriptor) component; + StringBuffer sb = new StringBuffer("Usb_Endpoint_Descriptor\n"); + sb.append("\tblenght: 0x" + + Integer.toHexString(epDesc.getBLength() & 0xFF) + "\n"); + sb.append("\tbDescriptorType: 0x" + + Integer.toHexString(epDesc.getBDescriptorType() & 0xFF) + + "\n"); + sb.append("\tbEndpointAddress: 0x" + + Integer.toHexString(epDesc.getBEndpointAddress() & 0xFF) + + "\n"); + sb.append("\tbmAttributes: 0x" + + Integer.toHexString(epDesc.getBmAttributes() & 0xFF) + + "\n"); + sb.append("\twMaxPacketSize: 0x" + + Integer.toHexString(epDesc.getWMaxPacketSize() & 0xFFFF) + + " (" + epDesc.getWMaxPacketSize() + ")\n"); + sb.append("\tbInterval: 0x" + + Integer.toHexString(epDesc.getBInterval() & 0xFF) + "\n"); + sb.append("\tbRefresh: 0x" + + Integer.toHexString(epDesc.getBRefresh() & 0xFF) + "\n"); + sb.append("\tbSynchAddress: 0x" + + Integer.toHexString(epDesc.getBSynchAddress()) + "\n"); + sb.append("\textralen: 0x" + + Integer.toHexString(epDesc.getExtralen()) + "\n"); + sb.append("\textra: " + extraDescriptorToString(epDesc.getExtra()) + + "\n"); + textArea.setText(sb.toString()); + } + } + + private String extraDescriptorToString(byte[] extra) { + if (extra != null) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < extra.length; i++) { + sb.append("0x"); + sb.append(Integer.toHexString(extra[i] & 0xff)); + sb.append(' '); + } + return sb.toString(); + } + return null; + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/usbView/UsbView.java b/src/main/java/ch/ntb/inf/libusbJava/usbView/UsbView.java similarity index 96% rename from java/src/ch/ntb/inf/libusbJava/usbView/UsbView.java rename to src/main/java/ch/ntb/inf/libusbJava/usbView/UsbView.java index a4fba49..8315417 100644 --- a/java/src/ch/ntb/inf/libusbJava/usbView/UsbView.java +++ b/src/main/java/ch/ntb/inf/libusbJava/usbView/UsbView.java @@ -1,403 +1,403 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.usbView; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTextArea; -import javax.swing.JTree; -import javax.swing.KeyStroke; -import javax.swing.tree.TreePath; - -import ch.ntb.inf.libusbJava.LibusbJava; -import ch.ntb.inf.libusbJava.Usb_Bus; -import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Device; -import ch.ntb.inf.libusbJava.Usb_Device_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Endpoint_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Interface_Descriptor; -import ch.ntb.inf.libusbJava.testApp.TestApp; -import ch.ntb.inf.libusbJava.testApp.TestDevice; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo.TransferMode; - -public class UsbView extends JFrame { - - private static final long serialVersionUID = 4693554326612734263L; - - private static final int APP_WIDTH = 600, APP_HIGHT = 800; - - private JPanel jContentPane = null; - private JMenuBar jJMenuBar = null; - private JMenu commandsMenu = null; - private JMenuItem exitMenuItem = null; - private JMenuItem updateMenuItem = null; - JTree usbTree = null; - private JSplitPane jSplitPane = null; - - private JTextArea jPropertiesArea = null; - - UsbTreeModel treeModel; - - JPopupMenu testAppPopup; - - protected JPopupMenu endpointPopup; - - /** - * This is the default constructor - */ - public UsbView() { - super(); - initialize(); - } - - /** - * This method initializes this - * - * @return void - */ - private void initialize() { - this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - this.setJMenuBar(getJJMenuBar()); - this.setSize(APP_WIDTH, APP_HIGHT); - this.setContentPane(getJContentPane()); - this.setTitle("USB View"); - } - - /** - * This method initializes jContentPane - * - * @return javax.swing.JPanel - */ - private JPanel getJContentPane() { - if (jContentPane == null) { - jContentPane = new JPanel(); - jContentPane.setLayout(new BorderLayout()); - jContentPane.add(getJSplitPane(), java.awt.BorderLayout.CENTER); - } - return jContentPane; - } - - /** - * This method initializes jJMenuBar - * - * @return javax.swing.JMenuBar - */ - private JMenuBar getJJMenuBar() { - if (jJMenuBar == null) { - jJMenuBar = new JMenuBar(); - jJMenuBar.add(getFileMenu()); - } - return jJMenuBar; - } - - /** - * This method initializes jMenu - * - * @return javax.swing.JMenu - */ - private JMenu getFileMenu() { - if (commandsMenu == null) { - commandsMenu = new JMenu(); - commandsMenu.setText("Commands"); - commandsMenu.add(getUpdateMenuItem()); - commandsMenu.add(getExitMenuItem()); - } - return commandsMenu; - } - - /** - * This method initializes jMenuItem - * - * @return javax.swing.JMenuItem - */ - private JMenuItem getExitMenuItem() { - if (exitMenuItem == null) { - exitMenuItem = new JMenuItem(); - exitMenuItem.setText("Exit"); - exitMenuItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - System.exit(0); - } - }); - } - return exitMenuItem; - } - - /** - * This method initializes jMenuItem - * - * @return javax.swing.JMenuItem - */ - private JMenuItem getUpdateMenuItem() { - if (updateMenuItem == null) { - updateMenuItem = new JMenuItem(); - updateMenuItem.setText("Update"); - updateMenuItem.setAccelerator(KeyStroke.getKeyStroke( - KeyEvent.VK_F5, 0, true)); - updateMenuItem - .addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - // open bus - LibusbJava.usb_init(); - LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - - Usb_Bus bus = LibusbJava.usb_get_busses(); - if (bus != null) { - treeModel.fireTreeStructureChanged(bus); - expandAll(usbTree); - } - } - }); - } - return updateMenuItem; - } - - /** - * This method initializes usbTree - * - * @return javax.swing.JTree - */ - private JTree getUsbTree() { - if (usbTree == null) { - // open bus - LibusbJava.usb_init(); - LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - - Usb_Bus bus = LibusbJava.usb_get_busses(); - - treeModel = new UsbTreeModel(bus, jPropertiesArea); - usbTree = new JTree(treeModel); - expandAll(usbTree); - usbTree.addTreeSelectionListener(treeModel); - getJTestAppPopup(); - usbTree.addMouseListener(new MouseAdapter() { - - @Override - public void mousePressed(MouseEvent e) { - if (e.isPopupTrigger()) { - Object source = e.getSource(); - if (source instanceof JTree) { - JTree tree = (JTree) source; - TreePath path = tree.getPathForLocation(e.getX(), e - .getY()); - if (path != null - && (path.getLastPathComponent() instanceof Usb_Interface_Descriptor)) { - usbTree.setSelectionPath(path); - testAppPopup.show(tree, e.getX(), e.getY()); - } - } - } - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.isPopupTrigger()) { - if (e.isPopupTrigger()) { - Object source = e.getSource(); - if (source instanceof JTree) { - JTree tree = (JTree) source; - TreePath path = tree.getPathForLocation(e - .getX(), e.getY()); - if (path != null - && (path.getLastPathComponent() instanceof Usb_Interface_Descriptor)) { - usbTree.setSelectionPath(path); - testAppPopup.show(tree, e.getX(), e.getY()); - } - } - } - } - } - }); - } - return usbTree; - } - - private void getJTestAppPopup() { - // Create the popup menu. - testAppPopup = new JPopupMenu(); - endpointPopup = new JPopupMenu(); - JMenuItem menuItem = new JMenuItem( - "Start a test application using this interface"); - menuItem.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - initAndStartTestApp(); - } - - private void initAndStartTestApp() { - JTree tree = (JTree) testAppPopup.getInvoker(); - TreePath path = tree.getSelectionPath(); - TreePath parent = path; - Usb_Endpoint_Descriptor[] endpoints = null; - int altinterface = -1; - int interface_ = -1; - int configuration = -1; - short vendorId = -1; - short productId = -1; - while (parent != null - && !(parent.getLastPathComponent() instanceof Usb_Bus)) { - Object usbObj = parent.getLastPathComponent(); - if (usbObj instanceof Usb_Interface_Descriptor) { - Usb_Interface_Descriptor usbIntDesc = (Usb_Interface_Descriptor) usbObj; - endpoints = usbIntDesc.getEndpoint(); - interface_ = usbIntDesc.getBInterfaceNumber(); - altinterface = usbIntDesc.getBAlternateSetting(); - } else if (usbObj instanceof Usb_Config_Descriptor) { - configuration = ((Usb_Config_Descriptor) usbObj) - .getBConfigurationValue(); - } else if (usbObj instanceof Usb_Device) { - Usb_Device_Descriptor devDesc = ((Usb_Device) usbObj) - .getDescriptor(); - productId = devDesc.getIdProduct(); - vendorId = devDesc.getIdVendor(); - } - parent = parent.getParentPath(); - } - if (parent != null) { - // present a dialog to select in/out endpoint - // TODO: present dialog to select in/out endpoint - Usb_Endpoint_Descriptor[] outEPs = null; - int nofOutEPs = 0; - Usb_Endpoint_Descriptor[] inEPs = null; - int nofInEPs = 0; - - if (endpoints != null) { - outEPs = new Usb_Endpoint_Descriptor[endpoints.length]; - inEPs = new Usb_Endpoint_Descriptor[endpoints.length]; - for (int i = 0; i < endpoints.length; i++) { - int epAddr = endpoints[i].getBEndpointAddress() & 0xFF; - if ((epAddr & 0x80) > 0) { - // is IN endpoint - inEPs[nofInEPs++] = endpoints[i]; - } else { - // is OUT endpoint - outEPs[nofOutEPs++] = endpoints[i]; - } - } - } - // create a new TestDevice - TestDevice testDevice = new TestDevice(); - testDevice.setIdProduct(productId); - testDevice.setIdVendor(vendorId); - testDevice.setAltinterface(altinterface); - testDevice.setConfiguration(configuration); - testDevice.setInterface(interface_); - if (inEPs != null) { - for (int i = 0; i < nofInEPs; i++) { - int type = inEPs[i].getBmAttributes() & 0x03; - switch (type) { - case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_BULK: - testDevice.setInEPBulk(inEPs[i] - .getBEndpointAddress() & 0xff); - testDevice.setInMode(TransferMode.Bulk); - break; - case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_INTERRUPT: - testDevice.setInEPInt(inEPs[i] - .getBEndpointAddress() & 0xff); - testDevice.setInMode(TransferMode.Interrupt); - break; - default: - break; - } - } - } - if (outEPs != null) { - for (int i = 0; i < nofOutEPs; i++) { - int type = outEPs[i].getBmAttributes() & 0x03; - switch (type) { - case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_BULK: - testDevice.setOutEPBulk(outEPs[i] - .getBEndpointAddress() & 0xff); - testDevice.setOutMode(TransferMode.Bulk); - break; - case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_INTERRUPT: - testDevice.setOutEPInt(outEPs[i] - .getBEndpointAddress() & 0xff); - testDevice.setOutMode(TransferMode.Interrupt); - break; - default: - break; - } - } - } - // open a new testApp - TestApp app = new TestApp(testDevice); - app.setVisible(true); - } else { - System.out.println("error, could not find device node"); - // TODO: handle error - } - } - }); - testAppPopup.add(menuItem); - } - - /** - * This method initializes jSplitPane - * - * @return javax.swing.JSplitPane - */ - private JSplitPane getJSplitPane() { - if (jSplitPane == null) { - jSplitPane = new JSplitPane(); - jSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); - jSplitPane.setContinuousLayout(true); - jSplitPane.setDividerLocation(APP_HIGHT / 2); - jSplitPane - .setBottomComponent(createScrollPane(getJPropertiesArea())); - jSplitPane.setTopComponent(createScrollPane(getUsbTree())); - } - return jSplitPane; - } - - /** - * This method initializes jPropertiesArea - * - * @return javax.swing.JTextArea - */ - private JTextArea getJPropertiesArea() { - if (jPropertiesArea == null) { - jPropertiesArea = new JTextArea(); - } - return jPropertiesArea; - } - - private JScrollPane createScrollPane(Component view) { - JScrollPane scrollPane = new JScrollPane(view); - return scrollPane; - } - - /** - * Launches this application - */ - public static void main(String[] args) { - UsbView application = new UsbView(); - application.setVisible(true); - } - - void expandAll(JTree tree) { - for (int row = 0; row < tree.getRowCount(); row++) { - tree.expandRow(row); - } - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.usbView; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextArea; +import javax.swing.JTree; +import javax.swing.KeyStroke; +import javax.swing.tree.TreePath; + +import ch.ntb.inf.libusbJava.LibusbJava; +import ch.ntb.inf.libusbJava.Usb_Bus; +import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Device; +import ch.ntb.inf.libusbJava.Usb_Device_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Endpoint_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Interface_Descriptor; +import ch.ntb.inf.libusbJava.testApp.TestApp; +import ch.ntb.inf.libusbJava.testApp.TestDevice; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo.TransferMode; + +public class UsbView extends JFrame { + + private static final long serialVersionUID = 4693554326612734263L; + + private static final int APP_WIDTH = 600, APP_HIGHT = 800; + + private JPanel jContentPane = null; + private JMenuBar jJMenuBar = null; + private JMenu commandsMenu = null; + private JMenuItem exitMenuItem = null; + private JMenuItem updateMenuItem = null; + JTree usbTree = null; + private JSplitPane jSplitPane = null; + + private JTextArea jPropertiesArea = null; + + UsbTreeModel treeModel; + + JPopupMenu testAppPopup; + + protected JPopupMenu endpointPopup; + + /** + * This is the default constructor + */ + public UsbView() { + super(); + initialize(); + } + + /** + * This method initializes this + * + * @return void + */ + private void initialize() { + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + this.setJMenuBar(getJJMenuBar()); + this.setSize(APP_WIDTH, APP_HIGHT); + this.setContentPane(getJContentPane()); + this.setTitle("USB View"); + } + + /** + * This method initializes jContentPane + * + * @return javax.swing.JPanel + */ + private JPanel getJContentPane() { + if (jContentPane == null) { + jContentPane = new JPanel(); + jContentPane.setLayout(new BorderLayout()); + jContentPane.add(getJSplitPane(), java.awt.BorderLayout.CENTER); + } + return jContentPane; + } + + /** + * This method initializes jJMenuBar + * + * @return javax.swing.JMenuBar + */ + private JMenuBar getJJMenuBar() { + if (jJMenuBar == null) { + jJMenuBar = new JMenuBar(); + jJMenuBar.add(getFileMenu()); + } + return jJMenuBar; + } + + /** + * This method initializes jMenu + * + * @return javax.swing.JMenu + */ + private JMenu getFileMenu() { + if (commandsMenu == null) { + commandsMenu = new JMenu(); + commandsMenu.setText("Commands"); + commandsMenu.add(getUpdateMenuItem()); + commandsMenu.add(getExitMenuItem()); + } + return commandsMenu; + } + + /** + * This method initializes jMenuItem + * + * @return javax.swing.JMenuItem + */ + private JMenuItem getExitMenuItem() { + if (exitMenuItem == null) { + exitMenuItem = new JMenuItem(); + exitMenuItem.setText("Exit"); + exitMenuItem.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }); + } + return exitMenuItem; + } + + /** + * This method initializes jMenuItem + * + * @return javax.swing.JMenuItem + */ + private JMenuItem getUpdateMenuItem() { + if (updateMenuItem == null) { + updateMenuItem = new JMenuItem(); + updateMenuItem.setText("Update"); + updateMenuItem.setAccelerator(KeyStroke.getKeyStroke( + KeyEvent.VK_F5, 0, true)); + updateMenuItem + .addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + // open bus + LibusbJava.usb_init(); + LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + + Usb_Bus bus = LibusbJava.usb_get_busses(); + if (bus != null) { + treeModel.fireTreeStructureChanged(bus); + expandAll(usbTree); + } + } + }); + } + return updateMenuItem; + } + + /** + * This method initializes usbTree + * + * @return javax.swing.JTree + */ + private JTree getUsbTree() { + if (usbTree == null) { + // open bus + LibusbJava.usb_init(); + LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + + Usb_Bus bus = LibusbJava.usb_get_busses(); + + treeModel = new UsbTreeModel(bus, jPropertiesArea); + usbTree = new JTree(treeModel); + expandAll(usbTree); + usbTree.addTreeSelectionListener(treeModel); + getJTestAppPopup(); + usbTree.addMouseListener(new MouseAdapter() { + + @Override + public void mousePressed(MouseEvent e) { + if (e.isPopupTrigger()) { + Object source = e.getSource(); + if (source instanceof JTree) { + JTree tree = (JTree) source; + TreePath path = tree.getPathForLocation(e.getX(), e + .getY()); + if (path != null + && (path.getLastPathComponent() instanceof Usb_Interface_Descriptor)) { + usbTree.setSelectionPath(path); + testAppPopup.show(tree, e.getX(), e.getY()); + } + } + } + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) { + if (e.isPopupTrigger()) { + Object source = e.getSource(); + if (source instanceof JTree) { + JTree tree = (JTree) source; + TreePath path = tree.getPathForLocation(e + .getX(), e.getY()); + if (path != null + && (path.getLastPathComponent() instanceof Usb_Interface_Descriptor)) { + usbTree.setSelectionPath(path); + testAppPopup.show(tree, e.getX(), e.getY()); + } + } + } + } + } + }); + } + return usbTree; + } + + private void getJTestAppPopup() { + // Create the popup menu. + testAppPopup = new JPopupMenu(); + endpointPopup = new JPopupMenu(); + JMenuItem menuItem = new JMenuItem( + "Start a test application using this interface"); + menuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + initAndStartTestApp(); + } + + private void initAndStartTestApp() { + JTree tree = (JTree) testAppPopup.getInvoker(); + TreePath path = tree.getSelectionPath(); + TreePath parent = path; + Usb_Endpoint_Descriptor[] endpoints = null; + int altinterface = -1; + int interface_ = -1; + int configuration = -1; + short vendorId = -1; + short productId = -1; + while (parent != null + && !(parent.getLastPathComponent() instanceof Usb_Bus)) { + Object usbObj = parent.getLastPathComponent(); + if (usbObj instanceof Usb_Interface_Descriptor) { + Usb_Interface_Descriptor usbIntDesc = (Usb_Interface_Descriptor) usbObj; + endpoints = usbIntDesc.getEndpoint(); + interface_ = usbIntDesc.getBInterfaceNumber(); + altinterface = usbIntDesc.getBAlternateSetting(); + } else if (usbObj instanceof Usb_Config_Descriptor) { + configuration = ((Usb_Config_Descriptor) usbObj) + .getBConfigurationValue(); + } else if (usbObj instanceof Usb_Device) { + Usb_Device_Descriptor devDesc = ((Usb_Device) usbObj) + .getDescriptor(); + productId = devDesc.getIdProduct(); + vendorId = devDesc.getIdVendor(); + } + parent = parent.getParentPath(); + } + if (parent != null) { + // present a dialog to select in/out endpoint + // TODO: present dialog to select in/out endpoint + Usb_Endpoint_Descriptor[] outEPs = null; + int nofOutEPs = 0; + Usb_Endpoint_Descriptor[] inEPs = null; + int nofInEPs = 0; + + if (endpoints != null) { + outEPs = new Usb_Endpoint_Descriptor[endpoints.length]; + inEPs = new Usb_Endpoint_Descriptor[endpoints.length]; + for (int i = 0; i < endpoints.length; i++) { + int epAddr = endpoints[i].getBEndpointAddress() & 0xFF; + if ((epAddr & 0x80) > 0) { + // is IN endpoint + inEPs[nofInEPs++] = endpoints[i]; + } else { + // is OUT endpoint + outEPs[nofOutEPs++] = endpoints[i]; + } + } + } + // create a new TestDevice + TestDevice testDevice = new TestDevice(); + testDevice.setIdProduct(productId); + testDevice.setIdVendor(vendorId); + testDevice.setAltinterface(altinterface); + testDevice.setConfiguration(configuration); + testDevice.setInterface(interface_); + if (inEPs != null) { + for (int i = 0; i < nofInEPs; i++) { + int type = inEPs[i].getBmAttributes() & 0x03; + switch (type) { + case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_BULK: + testDevice.setInEPBulk(inEPs[i] + .getBEndpointAddress() & 0xff); + testDevice.setInMode(TransferMode.Bulk); + break; + case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_INTERRUPT: + testDevice.setInEPInt(inEPs[i] + .getBEndpointAddress() & 0xff); + testDevice.setInMode(TransferMode.Interrupt); + break; + default: + break; + } + } + } + if (outEPs != null) { + for (int i = 0; i < nofOutEPs; i++) { + int type = outEPs[i].getBmAttributes() & 0x03; + switch (type) { + case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_BULK: + testDevice.setOutEPBulk(outEPs[i] + .getBEndpointAddress() & 0xff); + testDevice.setOutMode(TransferMode.Bulk); + break; + case Usb_Endpoint_Descriptor.USB_ENDPOINT_TRANSFER_TYPE_INTERRUPT: + testDevice.setOutEPInt(outEPs[i] + .getBEndpointAddress() & 0xff); + testDevice.setOutMode(TransferMode.Interrupt); + break; + default: + break; + } + } + } + // open a new testApp + TestApp app = new TestApp(testDevice); + app.setVisible(true); + } else { + System.out.println("error, could not find device node"); + // TODO: handle error + } + } + }); + testAppPopup.add(menuItem); + } + + /** + * This method initializes jSplitPane + * + * @return javax.swing.JSplitPane + */ + private JSplitPane getJSplitPane() { + if (jSplitPane == null) { + jSplitPane = new JSplitPane(); + jSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); + jSplitPane.setContinuousLayout(true); + jSplitPane.setDividerLocation(APP_HIGHT / 2); + jSplitPane + .setBottomComponent(createScrollPane(getJPropertiesArea())); + jSplitPane.setTopComponent(createScrollPane(getUsbTree())); + } + return jSplitPane; + } + + /** + * This method initializes jPropertiesArea + * + * @return javax.swing.JTextArea + */ + private JTextArea getJPropertiesArea() { + if (jPropertiesArea == null) { + jPropertiesArea = new JTextArea(); + } + return jPropertiesArea; + } + + private JScrollPane createScrollPane(Component view) { + JScrollPane scrollPane = new JScrollPane(view); + return scrollPane; + } + + /** + * Launches this application + */ + public static void main(String[] args) { + UsbView application = new UsbView(); + application.setVisible(true); + } + + void expandAll(JTree tree) { + for (int row = 0; row < tree.getRowCount(); row++) { + tree.expandRow(row); + } + } +} diff --git a/java/src/ch/ntb/inf/libusbJava/usbView/package.html b/src/main/java/ch/ntb/inf/libusbJava/usbView/package.html similarity index 95% rename from java/src/ch/ntb/inf/libusbJava/usbView/package.html rename to src/main/java/ch/ntb/inf/libusbJava/usbView/package.html index d5f8295..2a64b06 100644 --- a/java/src/ch/ntb/inf/libusbJava/usbView/package.html +++ b/src/main/java/ch/ntb/inf/libusbJava/usbView/package.html @@ -1,17 +1,17 @@ - - - - - -Displays the bus and device information of the currently attached -devices in a tree (based on Swing). - -

Related Resources

- -For more information about this project visit -http://libusbjava.sourceforge.net -. - - - + + + + + +Displays the bus and device information of the currently attached +devices in a tree (based on Swing). + +

Related Resources

+ +For more information about this project visit +http://libusbjava.sourceforge.net +. + + + diff --git a/java/test/ch/ntb/inf/libusbJava/test/DeviceTest.java b/src/test/java/ch/ntb/inf/libusbJava/test/DeviceTest.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/DeviceTest.java rename to src/test/java/ch/ntb/inf/libusbJava/test/DeviceTest.java index 20b3a02..7830970 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/DeviceTest.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/DeviceTest.java @@ -1,626 +1,626 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.util.Properties; -import java.util.logging.Logger; - -import junit.framework.Assert; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import ch.ntb.inf.libusbJava.Device; -import ch.ntb.inf.libusbJava.LibusbJava; -import ch.ntb.inf.libusbJava.USB; -import ch.ntb.inf.libusbJava.USBException; -import ch.ntb.inf.libusbJava.Usb_Bus; -import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Device_Descriptor; -import ch.ntb.inf.libusbJava.Utils; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo.TransferMode; - -@SuppressWarnings("deprecation") -public class DeviceTest { - - private static final String testdevicePropertiesFile = "testdevice.properties"; - private static final String deviceInfoKey = "testdeviceInfo"; - - private static AbstractDeviceInfo devinfo; - - private static byte[] testData; - - private static byte[] readData; - - private static Device dev; - - private static Logger log = Logger.getLogger(DeviceTest.class.getName()); - - @BeforeClass - public static void setUp() throws Exception { - // load the device info class with the key - // from 'testdevice.properties' - InputStream propInputStream = new FileInputStream( - testdevicePropertiesFile); - Properties devInfoProp = new Properties(); - devInfoProp.load(propInputStream); - String devInfoClazzName = devInfoProp.getProperty(deviceInfoKey); - if (devInfoClazzName == null) { - throw new Exception("property " + deviceInfoKey - + " not found in file " + testdevicePropertiesFile); - } - Class devInfoClazz = Class.forName(devInfoClazzName); - devinfo = (AbstractDeviceInfo) devInfoClazz.newInstance(); - // devinfo = new CY7C68013A(); - // setup test data - testData = new byte[devinfo.getMaxDataSize()]; - readData = new byte[testData.length]; - // initialise the device - dev = USB.getDevice(devinfo.getIdVendor(), devinfo.getIdProduct(), - devinfo.getBusName(), devinfo.getFilename()); - assertNotNull(dev); - - // print the devices - LibusbJava.usb_init(); -// LibusbJava.usb_set_debug(255); - LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - Usb_Bus bus = LibusbJava.usb_get_busses(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(baos); - Utils.logBus(bus, ps); - log.info(baos.toString()); - } - - @Test - public void getDescriptors() throws Exception { - dev.updateDescriptors(); - Usb_Device_Descriptor devDescriptor = dev.getDeviceDescriptor(); - assertNotNull(devDescriptor); - assertEquals(devinfo.getIdProduct(), devDescriptor.getIdProduct()); - assertEquals(devinfo.getIdVendor(), devDescriptor.getIdVendor()); - Usb_Config_Descriptor confDescriptors[] = dev.getConfigDescriptors(); - assertNotNull(confDescriptors); - assertTrue(confDescriptors[0].getInterface().length > 0); - } - - @Test - public void initalReset() throws Exception { - doOpen(); - // this may change the bus and file name of the device - dev.reset(); - timeout(); - } - - @Test(expected = USBException.class) - public void testClose() throws Exception { - try { - // this calls must not throw an exception - doOpen(); - doClose(); - } catch (USBException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - // this call must throw an exception, because the device is closed - dev.writeBulk(devinfo.getOutEPBulk(), testData, testData.length, - devinfo.getTimeout(), false); - } - - @Test(expected = USBException.class) - public void testReset1() throws Exception { - try { - // this calls must not throw an exception - doOpen(); - dev.reset(); - timeout(); - } catch (USBException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - // this call must throw an exception, because the device is closed - dev.writeBulk(devinfo.getOutEPBulk(), testData, testData.length, - devinfo.getTimeout(), false); - } - - @Test(expected = USBException.class) - public void testReset2() throws Exception { - try { - // this calls must not throw an exception - doOpen(); - dev.reset(); - timeout(); - } catch (USBException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - // this call must throw an exception, because the device can't be closed - doClose(); - } - - @Test - public void open() throws Exception { - // get device by busname - doOpen(); - assertNotNull(dev.getDevice()); - String oldFilename = dev.getDevice().getFilename(); - String oldBusName = dev.getDevice().getBus().getDirname(); - assertNotNull(oldFilename); - assertNotNull(oldBusName); - log.info("filename: " + oldFilename + ", busName: " + oldBusName); - Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo - .getIdProduct()); - doClose(); - assertEquals(dev, dev2); - } - - @Test - public void openWithBusName() throws Exception { - // get device by busname - doOpen(); - assertNotNull(dev.getDevice()); - String oldFilename = dev.getDevice().getFilename(); - String oldBusName = dev.getDevice().getBus().getDirname(); - assertNotNull(oldFilename); - assertNotNull(oldBusName); - log.info("filename: " + oldFilename + ", busName: " + oldBusName); - Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo - .getIdProduct(), oldBusName, null); - doClose(); - assertEquals(dev, dev2); - } - - @Test - public void openWithFilename() throws Exception { - // get device by busname - doOpen(); - assertNotNull(dev.getDevice()); - String oldFilename = dev.getDevice().getFilename(); - String oldBusName = dev.getDevice().getBus().getDirname(); - assertNotNull(oldFilename); - assertNotNull(oldBusName); - log.info("filename: " + oldFilename + ", busName: " + oldBusName); - Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo - .getIdProduct(), null, oldFilename); - doClose(); - assertEquals(dev, dev2); - } - - @Test - public void openWithBusAndFilename() throws Exception { - // get device by busname and filename - doOpen(); - assertNotNull(dev.getDevice()); - String oldFilename = dev.getDevice().getFilename(); - String oldBusName = dev.getDevice().getBus().getDirname(); - assertNotNull(oldFilename); - assertNotNull(oldBusName); - log.info("filename: " + oldFilename + ", busName: " + oldBusName); - Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo - .getIdProduct(), oldBusName, oldFilename); - doClose(); - assertEquals(dev, dev2); - } - - @Test - public void bulkWriteRead() throws Exception { - checkBulkEndpoints(); - devinfo.setMode(TransferMode.Bulk); - doOpenWriteReadClose(); - } - - private void checkBulkEndpoints() { - if (devinfo.getInEPBulk() == -1 && devinfo.getOutEPBulk() == -1) { - throw new UnsupportedOperationException( - "no bulk endpoints defined in test device definition"); - } - } - - @Test - public void interruptWriteRead() throws Exception { - checkInterruptEndpoints(); - devinfo.setMode(TransferMode.Interrupt); - doOpenWriteReadClose(); - } - - private void checkInterruptEndpoints() { - if (devinfo.getInEPInt() == -1 && devinfo.getOutEPInt() == -1) { - throw new UnsupportedOperationException( - "no interrupt endpoints defined in test device definition"); - } - } - - @Test - public void bulkWriteReadMultiple() throws Exception { - final int NumberOfIterations = 100; - - devinfo.setMode(TransferMode.Bulk); - doOpen(); - for (int i = 0; i < NumberOfIterations; i++) { - doWriteRead(); - } - doClose(); - } - - @Test - public void multipleOpenCloseWithBulkWrite() throws Exception { - devinfo.setMode(TransferMode.Bulk); - for (int i = 0; i < 5; i++) { - doOpen(); - doClose(); - } - doOpenWriteReadClose(); - for (int i = 0; i < 10; i++) { - doOpen(); - doWriteRead(); - doClose(); - } - doOpenWriteReadClose(); - for (int i = 0; i < 5; i++) { - doOpen(); - doClose(); - } - } - - @Test - public void bulkAndInterrupt() throws Exception { - doOpen(); - // BULK - devinfo.setMode(TransferMode.Bulk); - doWriteRead(); - // INTERRUPT - devinfo.setMode(TransferMode.Interrupt); - doWriteRead(); - doClose(); - } - - @Test - public void bulkAndInterruptMultiple() throws Exception { - for (int i = 0; i < 20; i++) { - devinfo.setMode(TransferMode.Bulk); - doOpenWriteReadClose(); - devinfo.setMode(TransferMode.Interrupt); - doOpenWriteReadClose(); - } - } - - @Test - public void controlMsg() throws Exception { - try { - dev.open(devinfo.getConfiguration(), devinfo.getInterface(), - devinfo.getAltinterface()); - // GET STATUS (device) - byte[] data = getTestData(2); - int length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, - USB.REQ_GET_STATUS, 0, 0, data, data.length, devinfo - .getTimeout(), false); - assertTrue(length > 0); - assertEquals((byte) 0x01, data[0]); - assertEquals((byte) 0x00, data[1]); - // GET STATUS (interface) - data = getTestData(2); - length = dev.controlMsg( - USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD - | USB.REQ_TYPE_RECIP_INTERFACE, USB.REQ_GET_STATUS, - 0, 0, data, data.length, devinfo.getTimeout(), false); - assertTrue(length > 0); - assertEquals((byte) 0x00, data[0]); - assertEquals((byte) 0x00, data[1]); - // GET STATUS (endpoint) - data = getTestData(2); - length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_ENDPOINT, - USB.REQ_GET_STATUS, 0, 0, data, data.length, devinfo - .getTimeout(), false); - assertTrue(length > 0); - assertEquals((byte) 0x00, data[0]); - assertEquals((byte) 0x00, data[1]); - // GET CONFIGURATION - data = getTestData(1); - length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, - USB.REQ_GET_CONFIGURATION, 0, 0, data, data.length, devinfo - .getTimeout(), false); - assertTrue(length > 0); - assertEquals((byte) devinfo.getConfiguration(), data[0]); - // // GET INTERFACE - // data = byte[1]; - // length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - // | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_INTERFACE, - // USB.REQ_GET_INTERFACE, 0, devinfo.getInterface(), data, - // data.length, - // devinfo - // .getTimeout(), false); - // logData(data, length); - // GET DESCRIPTOR (device descriptor) - data = getTestData(128); - length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, - USB.REQ_GET_DESCRIPTOR, 1 << 8, 0, data, data.length, - devinfo.getTimeout(), false); - validateDeviceDescriptor(data, length); - // GET DESCRIPTOR (string descriptor (1)) - data = getTestData(128); - length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, - USB.REQ_GET_DESCRIPTOR, (3 << 8) + 1, 0, data, data.length, - devinfo.getTimeout(), false); - String s = getString(data, length); - assertEquals(s, devinfo.getManufacturer()); - // GET DESCRIPTOR (string descriptor (2)) - data = getTestData(128); - length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, - USB.REQ_GET_DESCRIPTOR, (3 << 8) + 2, 0, data, data.length, - devinfo.getTimeout(), false); - s = getString(data, length); - assertEquals(s, devinfo.getProduct()); - // GET DESCRIPTOR (string descriptor (3)) - data = getTestData(128); - length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST - | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, - USB.REQ_GET_DESCRIPTOR, (3 << 8) + 3, 0, data, data.length, - devinfo.getTimeout(), false); - s = getString(data, length); - assertEquals(s, devinfo.getSerialVersion()); - // close the device - dev.close(); - } catch (Exception e) { - closeOnException(); - throw e; - } catch (AssertionError e) { - closeOnException(); - throw e; - } - } - - private void closeOnException() { - try { - dev.close(); - } catch (USBException e1) { - // ignore exceptions - } - } - - private void validateDeviceDescriptor(byte[] data, int length) { - // length read - assertEquals(18, length); - // descriptor length - assertEquals((byte) 18, data[0]); - // descriptor type - assertEquals((byte) 1, data[1]); - // USB specification number LSB - assertEquals((byte) 0, data[2]); - // USB specification number MSB - assertEquals((byte) 0x02, data[3]); - // device class (vendor specific) - assertEquals((byte) 0xff, data[4]); - // device subclass (vendor specific) - assertEquals((byte) 0xff, data[5]); - // device protocol (vendor specific) - assertEquals((byte) 0xff, data[6]); - // maximum packet size for endpoint zero - assertEquals((byte) 64, data[7]); - // Vendor ID (NTB) LSB - assertEquals((byte) 0x35, data[8]); - // Vendor ID (NTB) MSB - assertEquals((byte) 0x82, data[9]); - // Product ID (JUnit test board) LSB - assertEquals((byte) 0x22, data[10]); - // Product ID (JUnit test board) MSB - assertEquals((byte) 0x02, data[11]); - - // Device release number LSB - assertEquals((byte) 0x00, data[12]); - // Device release number MSB - assertEquals((byte) 0x10, data[13]); - // Index of manufacturer string descriptor - assertEquals((byte) 0x01, data[14]); - // Index of product string descriptor - assertEquals((byte) 0x02, data[15]); - // Index of serial number string descriptor - assertEquals((byte) 0x03, data[16]); - // Number of possible configurations - assertEquals((byte) 0x01, data[17]); - } - - private byte[] getTestData(int length) { - byte[] b = new byte[length]; - for (int i = 0; i < b.length; i++) { - b[i] = (byte) (Math.random() * 256); - } - return b; - } - - @SuppressWarnings("unused") - private void logData(byte[] data, int length) { - if (length > 0) { - log.info("length: " + length); - String logData = ""; - for (int i = 0; i < length; i++) { - logData += "0x" + Integer.toHexString(data[i] & 0xff) + "\t"; - } - log.info(logData); - } - } - - private String getString(byte[] data, int length) - throws UnsupportedEncodingException { - // data length - assertTrue(length > 2); - // string length - assertTrue(data[0] > 2); - // string descriptor ident - assertEquals((byte) 3, data[1]); - // create string from data - return new String(data, 2, length - 2, "UTF-16LE"); - } - - @Test - public void invalidConfig() throws Exception { - try { - dev.open(devinfo.getConfiguration() + 5, devinfo.getInterface(), - devinfo.getAltinterface()); - fail("USBException expected"); - } catch (USBException e) { - log.severe("could not set config " - + (devinfo.getConfiguration() + 5)); - } - doOpenWriteReadClose(); - } - - @Test - public void invalidInterface() throws Exception { - try { - dev.open(devinfo.getConfiguration(), devinfo.getInterface() + 5, - devinfo.getAltinterface()); - fail("USBException expected"); - } catch (USBException e) { - log.severe("could not claim interface " - + (devinfo.getInterface() + 5)); - } - doOpenWriteReadClose(); - } - - @Test - public void invalidAltinterface() throws Exception { - try { - dev.open(devinfo.getConfiguration(), devinfo.getInterface(), - devinfo.getAltinterface() + 5); - fail("USBException expected"); - } catch (USBException e) { - log.severe("could not set alt interface " - + (devinfo.getAltinterface() + 5)); - } - doOpenWriteReadClose(); - } - - @Test - public void testGetIdProduct() { - Assert.assertEquals(devinfo.getIdProduct(), dev.getIdProduct()); - } - - @Test - public void testGetIdVendor() { - Assert.assertEquals(devinfo.getIdVendor(), dev.getIdVendor()); - } - - @Test - public void testGetAltinterface() { - Assert.assertEquals(devinfo.getAltinterface(), dev.getAltinterface()); - } - - @Test - public void testGetConfiguration() { - Assert.assertEquals(devinfo.getConfiguration(), dev.getConfiguration()); - } - - @Test - public void testGetInterface() { - Assert.assertEquals(devinfo.getInterface(), dev.getInterface()); - } - - @Test - public void testGetMaxPacketSize() throws USBException { - doOpen(); - Assert.assertEquals(devinfo.getMaxDataSize(), dev.getMaxPacketSize()); - doClose(); - } - - @AfterClass - public static void tearDown() throws Exception { - if (dev != null && dev.isOpen()) { - dev.close(); - } - } - - private void doOpen() throws USBException { - dev.open(devinfo.getConfiguration(), devinfo.getInterface(), devinfo - .getAltinterface()); - } - - private void doClose() throws USBException { - dev.close(); - } - - private void doOpenWriteReadClose() throws Exception { - doOpen(); - doWriteRead(); - doClose(); - } - - private void doWriteRead() throws Exception { - initTestData(); - try { - if (devinfo.getMode().equals(TransferMode.Bulk)) { - if (devinfo.getOutEPBulk() != -1) { - dev.writeBulk(devinfo.getOutEPBulk(), testData, - testData.length, devinfo.getTimeout(), false); - } - if (devinfo.getInEPBulk() != -1) { - dev.readBulk(devinfo.getInEPBulk(), readData, - readData.length, devinfo.getTimeout(), false); - } - } else if (devinfo.getMode().equals(TransferMode.Interrupt)) { - if (devinfo.getOutEPInt() != -1) { - dev.writeInterrupt(devinfo.getOutEPInt(), testData, - testData.length, devinfo.getTimeout(), false); - } - if (devinfo.getInEPInt() != -1) { - dev.readInterrupt(devinfo.getInEPInt(), readData, - readData.length, devinfo.getTimeout(), false); - } - } - if (devinfo.doCompareData()) { - compare(testData, readData); - } - } catch (AssertionError e) { - closeOnException(); - throw e; - } catch (Exception e) { - closeOnException(); - throw e; - } - } - - private static void compare(byte[] d1, byte[] d2) { - int minLength = Math.min(d1.length, d2.length); - for (int i = 0; i < minLength; i++) { - assertEquals(d1[i], d2[i]); - } - } - - private static void timeout() { - try { - Thread.sleep(devinfo.getSleepTimeout()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - private static void initTestData() { - for (int i = 0; i < testData.length; i++) { - testData[i] = (byte) (Math.random() * 0xff); - readData[i] = 0; - } - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.util.Properties; +import java.util.logging.Logger; + +import junit.framework.Assert; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.ntb.inf.libusbJava.Device; +import ch.ntb.inf.libusbJava.LibusbJava; +import ch.ntb.inf.libusbJava.USB; +import ch.ntb.inf.libusbJava.USBException; +import ch.ntb.inf.libusbJava.Usb_Bus; +import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Device_Descriptor; +import ch.ntb.inf.libusbJava.Utils; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo.TransferMode; + +@SuppressWarnings("deprecation") +public class DeviceTest { + + private static final String testdevicePropertiesFile = "testdevice.properties"; + private static final String deviceInfoKey = "testdeviceInfo"; + + private static AbstractDeviceInfo devinfo; + + private static byte[] testData; + + private static byte[] readData; + + private static Device dev; + + private static Logger log = Logger.getLogger(DeviceTest.class.getName()); + + @BeforeClass + public static void setUp() throws Exception { + // load the device info class with the key + // from 'testdevice.properties' + InputStream propInputStream = new FileInputStream( + testdevicePropertiesFile); + Properties devInfoProp = new Properties(); + devInfoProp.load(propInputStream); + String devInfoClazzName = devInfoProp.getProperty(deviceInfoKey); + if (devInfoClazzName == null) { + throw new Exception("property " + deviceInfoKey + + " not found in file " + testdevicePropertiesFile); + } + Class devInfoClazz = Class.forName(devInfoClazzName); + devinfo = (AbstractDeviceInfo) devInfoClazz.newInstance(); + // devinfo = new CY7C68013A(); + // setup test data + testData = new byte[devinfo.getMaxDataSize()]; + readData = new byte[testData.length]; + // initialise the device + dev = USB.getDevice(devinfo.getIdVendor(), devinfo.getIdProduct(), + devinfo.getBusName(), devinfo.getFilename()); + assertNotNull(dev); + + // print the devices + LibusbJava.usb_init(); +// LibusbJava.usb_set_debug(255); + LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + Usb_Bus bus = LibusbJava.usb_get_busses(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + Utils.logBus(bus, ps); + log.info(baos.toString()); + } + + @Test + public void getDescriptors() throws Exception { + dev.updateDescriptors(); + Usb_Device_Descriptor devDescriptor = dev.getDeviceDescriptor(); + assertNotNull(devDescriptor); + assertEquals(devinfo.getIdProduct(), devDescriptor.getIdProduct()); + assertEquals(devinfo.getIdVendor(), devDescriptor.getIdVendor()); + Usb_Config_Descriptor confDescriptors[] = dev.getConfigDescriptors(); + assertNotNull(confDescriptors); + assertTrue(confDescriptors[0].getInterface().length > 0); + } + + @Test + public void initalReset() throws Exception { + doOpen(); + // this may change the bus and file name of the device + dev.reset(); + timeout(); + } + + @Test(expected = USBException.class) + public void testClose() throws Exception { + try { + // this calls must not throw an exception + doOpen(); + doClose(); + } catch (USBException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + // this call must throw an exception, because the device is closed + dev.writeBulk(devinfo.getOutEPBulk(), testData, testData.length, + devinfo.getTimeout(), false); + } + + @Test(expected = USBException.class) + public void testReset1() throws Exception { + try { + // this calls must not throw an exception + doOpen(); + dev.reset(); + timeout(); + } catch (USBException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + // this call must throw an exception, because the device is closed + dev.writeBulk(devinfo.getOutEPBulk(), testData, testData.length, + devinfo.getTimeout(), false); + } + + @Test(expected = USBException.class) + public void testReset2() throws Exception { + try { + // this calls must not throw an exception + doOpen(); + dev.reset(); + timeout(); + } catch (USBException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + // this call must throw an exception, because the device can't be closed + doClose(); + } + + @Test + public void open() throws Exception { + // get device by busname + doOpen(); + assertNotNull(dev.getDevice()); + String oldFilename = dev.getDevice().getFilename(); + String oldBusName = dev.getDevice().getBus().getDirname(); + assertNotNull(oldFilename); + assertNotNull(oldBusName); + log.info("filename: " + oldFilename + ", busName: " + oldBusName); + Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo + .getIdProduct()); + doClose(); + assertEquals(dev, dev2); + } + + @Test + public void openWithBusName() throws Exception { + // get device by busname + doOpen(); + assertNotNull(dev.getDevice()); + String oldFilename = dev.getDevice().getFilename(); + String oldBusName = dev.getDevice().getBus().getDirname(); + assertNotNull(oldFilename); + assertNotNull(oldBusName); + log.info("filename: " + oldFilename + ", busName: " + oldBusName); + Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo + .getIdProduct(), oldBusName, null); + doClose(); + assertEquals(dev, dev2); + } + + @Test + public void openWithFilename() throws Exception { + // get device by busname + doOpen(); + assertNotNull(dev.getDevice()); + String oldFilename = dev.getDevice().getFilename(); + String oldBusName = dev.getDevice().getBus().getDirname(); + assertNotNull(oldFilename); + assertNotNull(oldBusName); + log.info("filename: " + oldFilename + ", busName: " + oldBusName); + Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo + .getIdProduct(), null, oldFilename); + doClose(); + assertEquals(dev, dev2); + } + + @Test + public void openWithBusAndFilename() throws Exception { + // get device by busname and filename + doOpen(); + assertNotNull(dev.getDevice()); + String oldFilename = dev.getDevice().getFilename(); + String oldBusName = dev.getDevice().getBus().getDirname(); + assertNotNull(oldFilename); + assertNotNull(oldBusName); + log.info("filename: " + oldFilename + ", busName: " + oldBusName); + Device dev2 = USB.getDevice(devinfo.getIdVendor(), devinfo + .getIdProduct(), oldBusName, oldFilename); + doClose(); + assertEquals(dev, dev2); + } + + @Test + public void bulkWriteRead() throws Exception { + checkBulkEndpoints(); + devinfo.setMode(TransferMode.Bulk); + doOpenWriteReadClose(); + } + + private void checkBulkEndpoints() { + if (devinfo.getInEPBulk() == -1 && devinfo.getOutEPBulk() == -1) { + throw new UnsupportedOperationException( + "no bulk endpoints defined in test device definition"); + } + } + + @Test + public void interruptWriteRead() throws Exception { + checkInterruptEndpoints(); + devinfo.setMode(TransferMode.Interrupt); + doOpenWriteReadClose(); + } + + private void checkInterruptEndpoints() { + if (devinfo.getInEPInt() == -1 && devinfo.getOutEPInt() == -1) { + throw new UnsupportedOperationException( + "no interrupt endpoints defined in test device definition"); + } + } + + @Test + public void bulkWriteReadMultiple() throws Exception { + final int NumberOfIterations = 100; + + devinfo.setMode(TransferMode.Bulk); + doOpen(); + for (int i = 0; i < NumberOfIterations; i++) { + doWriteRead(); + } + doClose(); + } + + @Test + public void multipleOpenCloseWithBulkWrite() throws Exception { + devinfo.setMode(TransferMode.Bulk); + for (int i = 0; i < 5; i++) { + doOpen(); + doClose(); + } + doOpenWriteReadClose(); + for (int i = 0; i < 10; i++) { + doOpen(); + doWriteRead(); + doClose(); + } + doOpenWriteReadClose(); + for (int i = 0; i < 5; i++) { + doOpen(); + doClose(); + } + } + + @Test + public void bulkAndInterrupt() throws Exception { + doOpen(); + // BULK + devinfo.setMode(TransferMode.Bulk); + doWriteRead(); + // INTERRUPT + devinfo.setMode(TransferMode.Interrupt); + doWriteRead(); + doClose(); + } + + @Test + public void bulkAndInterruptMultiple() throws Exception { + for (int i = 0; i < 20; i++) { + devinfo.setMode(TransferMode.Bulk); + doOpenWriteReadClose(); + devinfo.setMode(TransferMode.Interrupt); + doOpenWriteReadClose(); + } + } + + @Test + public void controlMsg() throws Exception { + try { + dev.open(devinfo.getConfiguration(), devinfo.getInterface(), + devinfo.getAltinterface()); + // GET STATUS (device) + byte[] data = getTestData(2); + int length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, + USB.REQ_GET_STATUS, 0, 0, data, data.length, devinfo + .getTimeout(), false); + assertTrue(length > 0); + assertEquals((byte) 0x01, data[0]); + assertEquals((byte) 0x00, data[1]); + // GET STATUS (interface) + data = getTestData(2); + length = dev.controlMsg( + USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD + | USB.REQ_TYPE_RECIP_INTERFACE, USB.REQ_GET_STATUS, + 0, 0, data, data.length, devinfo.getTimeout(), false); + assertTrue(length > 0); + assertEquals((byte) 0x00, data[0]); + assertEquals((byte) 0x00, data[1]); + // GET STATUS (endpoint) + data = getTestData(2); + length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_ENDPOINT, + USB.REQ_GET_STATUS, 0, 0, data, data.length, devinfo + .getTimeout(), false); + assertTrue(length > 0); + assertEquals((byte) 0x00, data[0]); + assertEquals((byte) 0x00, data[1]); + // GET CONFIGURATION + data = getTestData(1); + length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, + USB.REQ_GET_CONFIGURATION, 0, 0, data, data.length, devinfo + .getTimeout(), false); + assertTrue(length > 0); + assertEquals((byte) devinfo.getConfiguration(), data[0]); + // // GET INTERFACE + // data = byte[1]; + // length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + // | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_INTERFACE, + // USB.REQ_GET_INTERFACE, 0, devinfo.getInterface(), data, + // data.length, + // devinfo + // .getTimeout(), false); + // logData(data, length); + // GET DESCRIPTOR (device descriptor) + data = getTestData(128); + length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, + USB.REQ_GET_DESCRIPTOR, 1 << 8, 0, data, data.length, + devinfo.getTimeout(), false); + validateDeviceDescriptor(data, length); + // GET DESCRIPTOR (string descriptor (1)) + data = getTestData(128); + length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, + USB.REQ_GET_DESCRIPTOR, (3 << 8) + 1, 0, data, data.length, + devinfo.getTimeout(), false); + String s = getString(data, length); + assertEquals(s, devinfo.getManufacturer()); + // GET DESCRIPTOR (string descriptor (2)) + data = getTestData(128); + length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, + USB.REQ_GET_DESCRIPTOR, (3 << 8) + 2, 0, data, data.length, + devinfo.getTimeout(), false); + s = getString(data, length); + assertEquals(s, devinfo.getProduct()); + // GET DESCRIPTOR (string descriptor (3)) + data = getTestData(128); + length = dev.controlMsg(USB.REQ_TYPE_DIR_DEVICE_TO_HOST + | USB.REQ_TYPE_TYPE_STANDARD | USB.REQ_TYPE_RECIP_DEVICE, + USB.REQ_GET_DESCRIPTOR, (3 << 8) + 3, 0, data, data.length, + devinfo.getTimeout(), false); + s = getString(data, length); + assertEquals(s, devinfo.getSerialVersion()); + // close the device + dev.close(); + } catch (Exception e) { + closeOnException(); + throw e; + } catch (AssertionError e) { + closeOnException(); + throw e; + } + } + + private void closeOnException() { + try { + dev.close(); + } catch (USBException e1) { + // ignore exceptions + } + } + + private void validateDeviceDescriptor(byte[] data, int length) { + // length read + assertEquals(18, length); + // descriptor length + assertEquals((byte) 18, data[0]); + // descriptor type + assertEquals((byte) 1, data[1]); + // USB specification number LSB + assertEquals((byte) 0, data[2]); + // USB specification number MSB + assertEquals((byte) 0x02, data[3]); + // device class (vendor specific) + assertEquals((byte) 0xff, data[4]); + // device subclass (vendor specific) + assertEquals((byte) 0xff, data[5]); + // device protocol (vendor specific) + assertEquals((byte) 0xff, data[6]); + // maximum packet size for endpoint zero + assertEquals((byte) 64, data[7]); + // Vendor ID (NTB) LSB + assertEquals((byte) 0x35, data[8]); + // Vendor ID (NTB) MSB + assertEquals((byte) 0x82, data[9]); + // Product ID (JUnit test board) LSB + assertEquals((byte) 0x22, data[10]); + // Product ID (JUnit test board) MSB + assertEquals((byte) 0x02, data[11]); + + // Device release number LSB + assertEquals((byte) 0x00, data[12]); + // Device release number MSB + assertEquals((byte) 0x10, data[13]); + // Index of manufacturer string descriptor + assertEquals((byte) 0x01, data[14]); + // Index of product string descriptor + assertEquals((byte) 0x02, data[15]); + // Index of serial number string descriptor + assertEquals((byte) 0x03, data[16]); + // Number of possible configurations + assertEquals((byte) 0x01, data[17]); + } + + private byte[] getTestData(int length) { + byte[] b = new byte[length]; + for (int i = 0; i < b.length; i++) { + b[i] = (byte) (Math.random() * 256); + } + return b; + } + + @SuppressWarnings("unused") + private void logData(byte[] data, int length) { + if (length > 0) { + log.info("length: " + length); + String logData = ""; + for (int i = 0; i < length; i++) { + logData += "0x" + Integer.toHexString(data[i] & 0xff) + "\t"; + } + log.info(logData); + } + } + + private String getString(byte[] data, int length) + throws UnsupportedEncodingException { + // data length + assertTrue(length > 2); + // string length + assertTrue(data[0] > 2); + // string descriptor ident + assertEquals((byte) 3, data[1]); + // create string from data + return new String(data, 2, length - 2, "UTF-16LE"); + } + + @Test + public void invalidConfig() throws Exception { + try { + dev.open(devinfo.getConfiguration() + 5, devinfo.getInterface(), + devinfo.getAltinterface()); + fail("USBException expected"); + } catch (USBException e) { + log.severe("could not set config " + + (devinfo.getConfiguration() + 5)); + } + doOpenWriteReadClose(); + } + + @Test + public void invalidInterface() throws Exception { + try { + dev.open(devinfo.getConfiguration(), devinfo.getInterface() + 5, + devinfo.getAltinterface()); + fail("USBException expected"); + } catch (USBException e) { + log.severe("could not claim interface " + + (devinfo.getInterface() + 5)); + } + doOpenWriteReadClose(); + } + + @Test + public void invalidAltinterface() throws Exception { + try { + dev.open(devinfo.getConfiguration(), devinfo.getInterface(), + devinfo.getAltinterface() + 5); + fail("USBException expected"); + } catch (USBException e) { + log.severe("could not set alt interface " + + (devinfo.getAltinterface() + 5)); + } + doOpenWriteReadClose(); + } + + @Test + public void testGetIdProduct() { + Assert.assertEquals(devinfo.getIdProduct(), dev.getIdProduct()); + } + + @Test + public void testGetIdVendor() { + Assert.assertEquals(devinfo.getIdVendor(), dev.getIdVendor()); + } + + @Test + public void testGetAltinterface() { + Assert.assertEquals(devinfo.getAltinterface(), dev.getAltinterface()); + } + + @Test + public void testGetConfiguration() { + Assert.assertEquals(devinfo.getConfiguration(), dev.getConfiguration()); + } + + @Test + public void testGetInterface() { + Assert.assertEquals(devinfo.getInterface(), dev.getInterface()); + } + + @Test + public void testGetMaxPacketSize() throws USBException { + doOpen(); + Assert.assertEquals(devinfo.getMaxDataSize(), dev.getMaxPacketSize()); + doClose(); + } + + @AfterClass + public static void tearDown() throws Exception { + if (dev != null && dev.isOpen()) { + dev.close(); + } + } + + private void doOpen() throws USBException { + dev.open(devinfo.getConfiguration(), devinfo.getInterface(), devinfo + .getAltinterface()); + } + + private void doClose() throws USBException { + dev.close(); + } + + private void doOpenWriteReadClose() throws Exception { + doOpen(); + doWriteRead(); + doClose(); + } + + private void doWriteRead() throws Exception { + initTestData(); + try { + if (devinfo.getMode().equals(TransferMode.Bulk)) { + if (devinfo.getOutEPBulk() != -1) { + dev.writeBulk(devinfo.getOutEPBulk(), testData, + testData.length, devinfo.getTimeout(), false); + } + if (devinfo.getInEPBulk() != -1) { + dev.readBulk(devinfo.getInEPBulk(), readData, + readData.length, devinfo.getTimeout(), false); + } + } else if (devinfo.getMode().equals(TransferMode.Interrupt)) { + if (devinfo.getOutEPInt() != -1) { + dev.writeInterrupt(devinfo.getOutEPInt(), testData, + testData.length, devinfo.getTimeout(), false); + } + if (devinfo.getInEPInt() != -1) { + dev.readInterrupt(devinfo.getInEPInt(), readData, + readData.length, devinfo.getTimeout(), false); + } + } + if (devinfo.doCompareData()) { + compare(testData, readData); + } + } catch (AssertionError e) { + closeOnException(); + throw e; + } catch (Exception e) { + closeOnException(); + throw e; + } + } + + private static void compare(byte[] d1, byte[] d2) { + int minLength = Math.min(d1.length, d2.length); + for (int i = 0; i < minLength; i++) { + assertEquals(d1[i], d2[i]); + } + } + + private static void timeout() { + try { + Thread.sleep(devinfo.getSleepTimeout()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private static void initTestData() { + for (int i = 0; i < testData.length; i++) { + testData[i] = (byte) (Math.random() * 0xff); + readData[i] = 0; + } + } +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/LibusbJava1Test.java b/src/test/java/ch/ntb/inf/libusbJava/test/LibusbJava1Test.java similarity index 95% rename from java/test/ch/ntb/inf/libusbJava/test/LibusbJava1Test.java rename to src/test/java/ch/ntb/inf/libusbJava/test/LibusbJava1Test.java index 008649f..1696b95 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/LibusbJava1Test.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/LibusbJava1Test.java @@ -1,334 +1,334 @@ -package ch.ntb.inf.libusbJava.test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import ch.ntb.inf.libusbJava.LibusbJava1; -import ch.ntb.inf.libusbJava.Usb_Device; -import ch.ntb.inf.libusbJava.exceptions.LibusbError; - -public class LibusbJava1Test { - /** - * This method does not need to be tested. This test only exists to document - * the fact that this function has not been forgotten. - */ - @Test - public void testLibusb_set_debug() { - } - - @Test - public void testLibusb_init() { - try { - long handle = LibusbJava1.libusb_init(); - LibusbJava1.libusb_exit(handle); - } catch (LibusbError e) { - fail("Initialization failed, Code: " + e.getErrorString()); - } - } - - /** - * This method can not be tested (yet). This test only exists to document - * the fact that this function has not been forgotten. - */ - @Test - public void testLibusb_exit() { - } - - @Test - public void testLibusb_get_device_list() throws LibusbError { - long handle = LibusbJava1.libusb_init(); - Usb_Device devices = LibusbJava1.libusb_get_device_list(handle); - assertNotNull("Got devices", devices); - System.out.println(devices.toString()); - assertNull("Bus is null", devices.getBus()); - LibusbJava1.libusb_exit(handle); - } - - @Test - public void testLibusb_get_bus_number() throws LibusbError { - long handle = LibusbJava1.libusb_init(); - Usb_Device devices = LibusbJava1.libusb_get_device_list(handle); - assertNotNull("Got devices", devices); - System.out.println(devices.getBus()); - LibusbJava1.libusb_exit(handle); - } - - @Test - public void testLibusb_get_max_iso_packet_size() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_ref_device() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_unref_device() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_open() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_open_device_with_vid_pid() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_close() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_device() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_configuration() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_set_configuration() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_claim_interface() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_release_interface() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_set_interface_alt_setting() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_clear_halt() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_reset_device() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_kernel_driver_active() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_detach_kernel_driver() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_attach_kernel_driver() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_active_config_descriptor() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_string_descriptor_ascii() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_descriptor() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_string_descriptor() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_alloc_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_free_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_submit_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_cancel_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_control_transfer_get_data() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_control_transfer_get_setup() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_fill_control_setup() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_fill_control_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_fill_bulk_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_fill_interrupt_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_fill_iso_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_set_iso_packet_lengths() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_iso_packet_buffer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_iso_packet_buffer_simple() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_try_lock_events() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_lock_events() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_unlock_events() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_event_handling_ok() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_event_handler_active() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_lock_event_waiters() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_unlock_event_waiters() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_wait_for_event() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_handle_events_timeout() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_handle_events() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_handle_events_locked() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_pollfds_handle_timeouts() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_next_timeout() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_set_pollfd_notifiers() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_get_pollfds() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_control_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_bulk_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_interrupt_transfer() { - fail("Not yet implemented"); - } - - @Test - public void testLibusb_strerror() { - fail("Not yet implemented"); - } - - @Test - public void testIsHandleValid() { - fail("Not yet implemented"); - } - -} +package ch.ntb.inf.libusbJava.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import ch.ntb.inf.libusbJava.LibusbJava1; +import ch.ntb.inf.libusbJava.Usb_Device; +import ch.ntb.inf.libusbJava.exceptions.LibusbError; + +public class LibusbJava1Test { + /** + * This method does not need to be tested. This test only exists to document + * the fact that this function has not been forgotten. + */ + @Test + public void testLibusb_set_debug() { + } + + @Test + public void testLibusb_init() { + try { + long handle = LibusbJava1.libusb_init(); + LibusbJava1.libusb_exit(handle); + } catch (LibusbError e) { + fail("Initialization failed, Code: " + e.getErrorString()); + } + } + + /** + * This method can not be tested (yet). This test only exists to document + * the fact that this function has not been forgotten. + */ + @Test + public void testLibusb_exit() { + } + + @Test + public void testLibusb_get_device_list() throws LibusbError { + long handle = LibusbJava1.libusb_init(); + Usb_Device devices = LibusbJava1.libusb_get_device_list(handle); + assertNotNull("Got devices", devices); + System.out.println(devices.toString()); + assertNull("Bus is null", devices.getBus()); + LibusbJava1.libusb_exit(handle); + } + + @Test + public void testLibusb_get_bus_number() throws LibusbError { + long handle = LibusbJava1.libusb_init(); + Usb_Device devices = LibusbJava1.libusb_get_device_list(handle); + assertNotNull("Got devices", devices); + System.out.println(devices.getBus()); + LibusbJava1.libusb_exit(handle); + } + + @Test + public void testLibusb_get_max_iso_packet_size() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_ref_device() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_unref_device() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_open() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_open_device_with_vid_pid() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_close() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_device() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_configuration() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_set_configuration() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_claim_interface() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_release_interface() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_set_interface_alt_setting() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_clear_halt() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_reset_device() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_kernel_driver_active() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_detach_kernel_driver() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_attach_kernel_driver() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_active_config_descriptor() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_string_descriptor_ascii() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_descriptor() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_string_descriptor() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_alloc_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_free_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_submit_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_cancel_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_control_transfer_get_data() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_control_transfer_get_setup() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_fill_control_setup() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_fill_control_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_fill_bulk_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_fill_interrupt_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_fill_iso_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_set_iso_packet_lengths() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_iso_packet_buffer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_iso_packet_buffer_simple() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_try_lock_events() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_lock_events() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_unlock_events() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_event_handling_ok() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_event_handler_active() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_lock_event_waiters() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_unlock_event_waiters() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_wait_for_event() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_handle_events_timeout() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_handle_events() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_handle_events_locked() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_pollfds_handle_timeouts() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_next_timeout() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_set_pollfd_notifiers() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_get_pollfds() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_control_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_bulk_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_interrupt_transfer() { + fail("Not yet implemented"); + } + + @Test + public void testLibusb_strerror() { + fail("Not yet implemented"); + } + + @Test + public void testIsHandleValid() { + fail("Not yet implemented"); + } + +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/MemoryLeakTest.java b/src/test/java/ch/ntb/inf/libusbJava/test/MemoryLeakTest.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/MemoryLeakTest.java rename to src/test/java/ch/ntb/inf/libusbJava/test/MemoryLeakTest.java index e26e7d0..3886583 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/MemoryLeakTest.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/MemoryLeakTest.java @@ -1,199 +1,199 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2008 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.PrintStream; -import java.util.Properties; -import java.util.logging.Logger; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import ch.ntb.inf.libusbJava.Device; -import ch.ntb.inf.libusbJava.LibusbJava; -import ch.ntb.inf.libusbJava.USB; -import ch.ntb.inf.libusbJava.USBException; -import ch.ntb.inf.libusbJava.Usb_Bus; -import ch.ntb.inf.libusbJava.Utils; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo.TransferMode; - -@SuppressWarnings("deprecation") -public class MemoryLeakTest { - - private static final String testdevicePropertiesFile = "testdevice.properties"; - private static final String deviceInfoKey = "testdeviceInfo"; - - private static AbstractDeviceInfo devinfo; - - private static byte[] testData; - - private static byte[] readData; - - private static Device dev; - - private static Logger log = Logger - .getLogger(MemoryLeakTest.class.getName()); - - @BeforeClass - public static void setUp() throws Exception { - // load the device info class with the key - // from 'testdevice.properties' - InputStream propInputStream = new FileInputStream( - testdevicePropertiesFile); - Properties devInfoProp = new Properties(); - devInfoProp.load(propInputStream); - String devInfoClazzName = devInfoProp.getProperty(deviceInfoKey); - if (devInfoClazzName == null) { - throw new Exception("property " + deviceInfoKey - + " not found in file " + testdevicePropertiesFile); - } - Class devInfoClazz = Class.forName(devInfoClazzName); - devinfo = (AbstractDeviceInfo) devInfoClazz.newInstance(); - // setup test data - testData = new byte[devinfo.getMaxDataSize()]; - readData = new byte[testData.length]; - // initialise the device - dev = USB.getDevice(devinfo.getIdVendor(), devinfo.getIdProduct()); - assertNotNull(dev); - - // print the devices - LibusbJava.usb_init(); -// LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - Usb_Bus bus = LibusbJava.usb_get_busses(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(baos); - Utils.logBus(bus, ps); - log.info(baos.toString()); - } - - @Test - public void initalReset() throws Exception { - doOpen(); - dev.reset(); - timeout(); - } - - @Test - public void bulkWriteReadMultiple() throws Exception { - final int NumberOfIterations = 3000; - - devinfo.setMode(TransferMode.Bulk); - doOpen(); - for (int i = 0; i < NumberOfIterations; i++) { - doWriteRead(); - if (i % 1000 == 0) { - System.out.print("."); - } - } - doClose(); - } - - @Test - public void interruptWriteReadMultiple() throws Exception { - final int NumberOfIterations = 3000; - - devinfo.setMode(TransferMode.Interrupt); - doOpen(); - for (int i = 0; i < NumberOfIterations; i++) { - doWriteRead(); - if (i % 1000 == 0) { - System.out.print("."); - } - } - doClose(); - } - - private void closeOnException() { - try { - dev.close(); - } catch (USBException e1) { - // ignore exceptions - } - } - - @AfterClass - public static void tearDown() throws Exception { - if (dev != null && dev.isOpen()) { - dev.close(); - } - } - - private void doOpen() throws USBException { - dev.open(devinfo.getConfiguration(), devinfo.getInterface(), devinfo - .getAltinterface()); - } - - private void doClose() throws USBException { - dev.close(); - } - - private void doWriteRead() throws Exception { - initTestData(); - try { - if (devinfo.getMode().equals(TransferMode.Bulk)) { - if (devinfo.getOutEPBulk() != -1) { - dev.writeBulk(devinfo.getOutEPBulk(), testData, - testData.length, devinfo.getTimeout(), false); - } - if (devinfo.getInEPBulk() != -1) { - dev.readBulk(devinfo.getInEPBulk(), readData, - readData.length, devinfo.getTimeout(), false); - } - } else if (devinfo.getMode().equals(TransferMode.Interrupt)) { - if (devinfo.getOutEPInt() != -1) { - dev.writeInterrupt(devinfo.getOutEPInt(), testData, - testData.length, devinfo.getTimeout(), false); - } - if (devinfo.getInEPInt() != -1) { - dev.readInterrupt(devinfo.getInEPInt(), readData, - readData.length, devinfo.getTimeout(), false); - } - } - if (devinfo.doCompareData()) { - compare(testData, readData); - } - } catch (AssertionError e) { - closeOnException(); - throw e; - } catch (Exception e) { - closeOnException(); - throw e; - } - } - - private static void compare(byte[] d1, byte[] d2) { - final int minLength = Math.min(d1.length, d2.length); - for (int i = 0; i < minLength; i++) { - assertEquals(d1[i], d2[i]); - } - } - - private static void timeout() { - try { - Thread.sleep(devinfo.getSleepTimeout()); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - private static void initTestData() { - for (int i = 0; i < testData.length; i++) { - testData[i] = (byte) (Math.random() * 0xff); - readData[i] = 0; - } - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2008 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.PrintStream; +import java.util.Properties; +import java.util.logging.Logger; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.ntb.inf.libusbJava.Device; +import ch.ntb.inf.libusbJava.LibusbJava; +import ch.ntb.inf.libusbJava.USB; +import ch.ntb.inf.libusbJava.USBException; +import ch.ntb.inf.libusbJava.Usb_Bus; +import ch.ntb.inf.libusbJava.Utils; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo.TransferMode; + +@SuppressWarnings("deprecation") +public class MemoryLeakTest { + + private static final String testdevicePropertiesFile = "testdevice.properties"; + private static final String deviceInfoKey = "testdeviceInfo"; + + private static AbstractDeviceInfo devinfo; + + private static byte[] testData; + + private static byte[] readData; + + private static Device dev; + + private static Logger log = Logger + .getLogger(MemoryLeakTest.class.getName()); + + @BeforeClass + public static void setUp() throws Exception { + // load the device info class with the key + // from 'testdevice.properties' + InputStream propInputStream = new FileInputStream( + testdevicePropertiesFile); + Properties devInfoProp = new Properties(); + devInfoProp.load(propInputStream); + String devInfoClazzName = devInfoProp.getProperty(deviceInfoKey); + if (devInfoClazzName == null) { + throw new Exception("property " + deviceInfoKey + + " not found in file " + testdevicePropertiesFile); + } + Class devInfoClazz = Class.forName(devInfoClazzName); + devinfo = (AbstractDeviceInfo) devInfoClazz.newInstance(); + // setup test data + testData = new byte[devinfo.getMaxDataSize()]; + readData = new byte[testData.length]; + // initialise the device + dev = USB.getDevice(devinfo.getIdVendor(), devinfo.getIdProduct()); + assertNotNull(dev); + + // print the devices + LibusbJava.usb_init(); +// LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + Usb_Bus bus = LibusbJava.usb_get_busses(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + Utils.logBus(bus, ps); + log.info(baos.toString()); + } + + @Test + public void initalReset() throws Exception { + doOpen(); + dev.reset(); + timeout(); + } + + @Test + public void bulkWriteReadMultiple() throws Exception { + final int NumberOfIterations = 3000; + + devinfo.setMode(TransferMode.Bulk); + doOpen(); + for (int i = 0; i < NumberOfIterations; i++) { + doWriteRead(); + if (i % 1000 == 0) { + System.out.print("."); + } + } + doClose(); + } + + @Test + public void interruptWriteReadMultiple() throws Exception { + final int NumberOfIterations = 3000; + + devinfo.setMode(TransferMode.Interrupt); + doOpen(); + for (int i = 0; i < NumberOfIterations; i++) { + doWriteRead(); + if (i % 1000 == 0) { + System.out.print("."); + } + } + doClose(); + } + + private void closeOnException() { + try { + dev.close(); + } catch (USBException e1) { + // ignore exceptions + } + } + + @AfterClass + public static void tearDown() throws Exception { + if (dev != null && dev.isOpen()) { + dev.close(); + } + } + + private void doOpen() throws USBException { + dev.open(devinfo.getConfiguration(), devinfo.getInterface(), devinfo + .getAltinterface()); + } + + private void doClose() throws USBException { + dev.close(); + } + + private void doWriteRead() throws Exception { + initTestData(); + try { + if (devinfo.getMode().equals(TransferMode.Bulk)) { + if (devinfo.getOutEPBulk() != -1) { + dev.writeBulk(devinfo.getOutEPBulk(), testData, + testData.length, devinfo.getTimeout(), false); + } + if (devinfo.getInEPBulk() != -1) { + dev.readBulk(devinfo.getInEPBulk(), readData, + readData.length, devinfo.getTimeout(), false); + } + } else if (devinfo.getMode().equals(TransferMode.Interrupt)) { + if (devinfo.getOutEPInt() != -1) { + dev.writeInterrupt(devinfo.getOutEPInt(), testData, + testData.length, devinfo.getTimeout(), false); + } + if (devinfo.getInEPInt() != -1) { + dev.readInterrupt(devinfo.getInEPInt(), readData, + readData.length, devinfo.getTimeout(), false); + } + } + if (devinfo.doCompareData()) { + compare(testData, readData); + } + } catch (AssertionError e) { + closeOnException(); + throw e; + } catch (Exception e) { + closeOnException(); + throw e; + } + } + + private static void compare(byte[] d1, byte[] d2) { + final int minLength = Math.min(d1.length, d2.length); + for (int i = 0; i < minLength; i++) { + assertEquals(d1[i], d2[i]); + } + } + + private static void timeout() { + try { + Thread.sleep(devinfo.getSleepTimeout()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + private static void initTestData() { + for (int i = 0; i < testData.length; i++) { + testData[i] = (byte) (Math.random() * 0xff); + readData[i] = 0; + } + } +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/TestLibUsbJava.java b/src/test/java/ch/ntb/inf/libusbJava/test/TestLibUsbJava.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/TestLibUsbJava.java rename to src/test/java/ch/ntb/inf/libusbJava/test/TestLibUsbJava.java index 7804611..f1f807f 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/TestLibUsbJava.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/TestLibUsbJava.java @@ -1,239 +1,239 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2007 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test; - -import ch.ntb.inf.libusbJava.LibusbJava; -import ch.ntb.inf.libusbJava.Usb_Bus; -import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Device; -import ch.ntb.inf.libusbJava.Usb_Endpoint_Descriptor; -import ch.ntb.inf.libusbJava.Usb_Interface; -import ch.ntb.inf.libusbJava.Usb_Interface_Descriptor; - -/** - * This class replicates the code from testlibusb.c supplied in the - * libusb-0.1.12 release. - */ -@SuppressWarnings("deprecation") -public class TestLibUsbJava { - static boolean verbose; - - /** - * prints out endpoint info - * - * @param endpoint - * The end point. - */ - private static void printEndpoint(Usb_Endpoint_Descriptor endpoint) { - System.out.print(String.format(" bEndpointAddress: %02xh\n", - endpoint.getBEndpointAddress())); - System.out.print(String.format(" bmAttributes: %02xh\n", - endpoint.getBmAttributes())); - System.out.print(String.format(" wMaxPacketSize: %d\n", endpoint - .getWMaxPacketSize())); - System.out.print(String.format(" bInterval: %d\n", endpoint - .getBInterval())); - System.out.print(String.format(" bRefresh: %d\n", endpoint - .getBRefresh())); - System.out.print(String.format(" bSynchAddress: %d\n", endpoint - .getBSynchAddress())); - } - - /** - * prints out the interface descriptor - * - * @param interfaceDescript - * The interface descriptor. - */ - private static void printAltsetting( - Usb_Interface_Descriptor interfaceDescript) { - System.out.print(String.format(" bInterfaceNumber: %d\n", - interfaceDescript.getBInterfaceNumber())); - System.out.print(String.format(" bAlternateSetting: %d\n", - interfaceDescript.getBAlternateSetting())); - System.out.print(String.format(" bNumEndpoints: %d\n", - interfaceDescript.getBNumEndpoints())); - System.out.print(String.format(" bInterfaceClass: %d\n", - interfaceDescript.getBInterfaceClass())); - System.out.print(String.format(" bInterfaceSubClass: %d\n", - interfaceDescript.getBInterfaceSubClass())); - System.out.print(String.format(" bInterfaceProtocol: %d\n", - interfaceDescript.getBInterfaceProtocol())); - System.out.print(String.format(" iInterface: %d\n", - interfaceDescript.getIInterface())); - - for (int i = 0; i < interfaceDescript.getBNumEndpoints(); i++) { - printEndpoint(interfaceDescript.getEndpoint()[i]); - } - } - - /** - * prints out interface - * - * @param usbInterface - * The interface. - */ - private static void printInterface(Usb_Interface usbInterface) { - for (int i = 0; i < usbInterface.getNumAltsetting(); i++) { - printAltsetting(usbInterface.getAltsetting()[i]); - } - } - - /** - * prints out configuration - * - * @param config - * The configuration. - */ - private static void printConfiguration(Usb_Config_Descriptor config) { - System.out.print(String.format(" wTotalLength: %d\n", config - .getWTotalLength())); - System.out.print(String.format(" bNumInterfaces: %d\n", config - .getBNumInterfaces())); - System.out.print(String.format(" bConfigurationValue: %d\n", config - .getBConfigurationValue())); - System.out.print(String.format(" iConfiguration: %d\n", config - .getIConfiguration())); - System.out.print(String.format(" bmAttributes: %02xh\n", - config.getBmAttributes())); - System.out.print(String.format(" MaxPower: %d\n", config - .getMaxPower())); - - for (int i = 0; i < config.getBNumInterfaces(); i++) { - printInterface(config.getInterface()[i]); - } - } - - private static int printDevice(Usb_Device dev, int level) { - long udev; - String mfr; - String product; - String sn; - String spaces; - String descript; - - spaces = " "; - - udev = LibusbJava.usb_open(dev); - - if (udev != 0) { - if (dev.getDescriptor().getIManufacturer() != 0) { - mfr = LibusbJava.usb_get_string_simple(udev, dev - .getDescriptor().getIManufacturer()); - - if (mfr != null) { - descript = String.format("%s - ", mfr); - } else { - descript = String.format("%04X - ", dev.getDescriptor() - .getIdVendor()); - } - } else { - descript = String.format("%04X - ", dev.getDescriptor() - .getIdVendor()); - } - - if (dev.getDescriptor().getIProduct() != 0) { - product = LibusbJava.usb_get_string_simple(udev, dev - .getDescriptor().getIProduct()); - - if (product != null) { - descript = descript + String.format("%s", product); - } else { - descript = descript - + String.format("%04X", dev.getDescriptor() - .getIdProduct()); - } - } else { - descript = descript - + String.format("%04X", dev.getDescriptor() - .getIdProduct()); - } - } else { - descript = String.format("%04X - %04X", dev.getDescriptor() - .getIdVendor(), dev.getDescriptor().getIdProduct()); - } - - System.out.print(String.format("%sDev #%d: %s\n", spaces.substring(0, - level * 2), dev.getDevnum(), descript)); - - if ((udev != 0) && verbose) { - if (dev.getDescriptor().getISerialNumber() != 0) { - sn = LibusbJava.usb_get_string_simple(udev, dev.getDescriptor() - .getISerialNumber()); - - if (sn != null) { - System.out.print(String.format("%s - Serial Number: %s\n", - spaces.substring(0, level * 2), sn)); - } - } - } - - if (udev != 0) { - LibusbJava.usb_close(udev); - } - - if (verbose) { - if (dev.getConfig().length == 0) { - System.out.print(" Couldn't retrieve descriptors\n"); - - return 0; - } - - for (int i = 0; i < dev.getDescriptor().getBNumConfigurations(); i++) { - printConfiguration(dev.getConfig()[i]); - } - } else { - Usb_Device childDev = null; - - for (int i = 0; i < dev.getNumChildren(); i++) { - if (i == 0) { - childDev = dev.getChildren(); - } else { - childDev = childDev.getNext(); - } - - printDevice(childDev, level + 1); - } - } - - return 0; - } // end of printDevice method - - /** - * The main method. - * - * @param args - * The command line arguments. - */ - public static void main(String args[]) throws Exception { - if ((args.length > 0) && (args[0].equals("-v"))) { - verbose = true; - } else { - verbose = false; - } - - // used for debugging. 0 = no debugging, 255 = with debugging - LibusbJava.usb_init(); - LibusbJava.usb_set_debug(255); - - LibusbJava.usb_find_busses(); - LibusbJava.usb_find_devices(); - - for (Usb_Bus bus = LibusbJava.usb_get_busses(); bus != null; bus = bus - .getNext()) { - if ((bus.getRootDev() != null) && !verbose) { - printDevice(bus.getRootDev(), 0); - } else { - for (Usb_Device dev = bus.getDevices(); dev != null; dev = dev - .getNext()) { - printDevice(dev, 0); - } - } - } - } // end main -} // end of TestLibUsbJava class +/* + * Java libusb wrapper + * Copyright (c) 2005-2007 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test; + +import ch.ntb.inf.libusbJava.LibusbJava; +import ch.ntb.inf.libusbJava.Usb_Bus; +import ch.ntb.inf.libusbJava.Usb_Config_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Device; +import ch.ntb.inf.libusbJava.Usb_Endpoint_Descriptor; +import ch.ntb.inf.libusbJava.Usb_Interface; +import ch.ntb.inf.libusbJava.Usb_Interface_Descriptor; + +/** + * This class replicates the code from testlibusb.c supplied in the + * libusb-0.1.12 release. + */ +@SuppressWarnings("deprecation") +public class TestLibUsbJava { + static boolean verbose; + + /** + * prints out endpoint info + * + * @param endpoint + * The end point. + */ + private static void printEndpoint(Usb_Endpoint_Descriptor endpoint) { + System.out.print(String.format(" bEndpointAddress: %02xh\n", + endpoint.getBEndpointAddress())); + System.out.print(String.format(" bmAttributes: %02xh\n", + endpoint.getBmAttributes())); + System.out.print(String.format(" wMaxPacketSize: %d\n", endpoint + .getWMaxPacketSize())); + System.out.print(String.format(" bInterval: %d\n", endpoint + .getBInterval())); + System.out.print(String.format(" bRefresh: %d\n", endpoint + .getBRefresh())); + System.out.print(String.format(" bSynchAddress: %d\n", endpoint + .getBSynchAddress())); + } + + /** + * prints out the interface descriptor + * + * @param interfaceDescript + * The interface descriptor. + */ + private static void printAltsetting( + Usb_Interface_Descriptor interfaceDescript) { + System.out.print(String.format(" bInterfaceNumber: %d\n", + interfaceDescript.getBInterfaceNumber())); + System.out.print(String.format(" bAlternateSetting: %d\n", + interfaceDescript.getBAlternateSetting())); + System.out.print(String.format(" bNumEndpoints: %d\n", + interfaceDescript.getBNumEndpoints())); + System.out.print(String.format(" bInterfaceClass: %d\n", + interfaceDescript.getBInterfaceClass())); + System.out.print(String.format(" bInterfaceSubClass: %d\n", + interfaceDescript.getBInterfaceSubClass())); + System.out.print(String.format(" bInterfaceProtocol: %d\n", + interfaceDescript.getBInterfaceProtocol())); + System.out.print(String.format(" iInterface: %d\n", + interfaceDescript.getIInterface())); + + for (int i = 0; i < interfaceDescript.getBNumEndpoints(); i++) { + printEndpoint(interfaceDescript.getEndpoint()[i]); + } + } + + /** + * prints out interface + * + * @param usbInterface + * The interface. + */ + private static void printInterface(Usb_Interface usbInterface) { + for (int i = 0; i < usbInterface.getNumAltsetting(); i++) { + printAltsetting(usbInterface.getAltsetting()[i]); + } + } + + /** + * prints out configuration + * + * @param config + * The configuration. + */ + private static void printConfiguration(Usb_Config_Descriptor config) { + System.out.print(String.format(" wTotalLength: %d\n", config + .getWTotalLength())); + System.out.print(String.format(" bNumInterfaces: %d\n", config + .getBNumInterfaces())); + System.out.print(String.format(" bConfigurationValue: %d\n", config + .getBConfigurationValue())); + System.out.print(String.format(" iConfiguration: %d\n", config + .getIConfiguration())); + System.out.print(String.format(" bmAttributes: %02xh\n", + config.getBmAttributes())); + System.out.print(String.format(" MaxPower: %d\n", config + .getMaxPower())); + + for (int i = 0; i < config.getBNumInterfaces(); i++) { + printInterface(config.getInterface()[i]); + } + } + + private static int printDevice(Usb_Device dev, int level) { + long udev; + String mfr; + String product; + String sn; + String spaces; + String descript; + + spaces = " "; + + udev = LibusbJava.usb_open(dev); + + if (udev != 0) { + if (dev.getDescriptor().getIManufacturer() != 0) { + mfr = LibusbJava.usb_get_string_simple(udev, dev + .getDescriptor().getIManufacturer()); + + if (mfr != null) { + descript = String.format("%s - ", mfr); + } else { + descript = String.format("%04X - ", dev.getDescriptor() + .getIdVendor()); + } + } else { + descript = String.format("%04X - ", dev.getDescriptor() + .getIdVendor()); + } + + if (dev.getDescriptor().getIProduct() != 0) { + product = LibusbJava.usb_get_string_simple(udev, dev + .getDescriptor().getIProduct()); + + if (product != null) { + descript = descript + String.format("%s", product); + } else { + descript = descript + + String.format("%04X", dev.getDescriptor() + .getIdProduct()); + } + } else { + descript = descript + + String.format("%04X", dev.getDescriptor() + .getIdProduct()); + } + } else { + descript = String.format("%04X - %04X", dev.getDescriptor() + .getIdVendor(), dev.getDescriptor().getIdProduct()); + } + + System.out.print(String.format("%sDev #%d: %s\n", spaces.substring(0, + level * 2), dev.getDevnum(), descript)); + + if ((udev != 0) && verbose) { + if (dev.getDescriptor().getISerialNumber() != 0) { + sn = LibusbJava.usb_get_string_simple(udev, dev.getDescriptor() + .getISerialNumber()); + + if (sn != null) { + System.out.print(String.format("%s - Serial Number: %s\n", + spaces.substring(0, level * 2), sn)); + } + } + } + + if (udev != 0) { + LibusbJava.usb_close(udev); + } + + if (verbose) { + if (dev.getConfig().length == 0) { + System.out.print(" Couldn't retrieve descriptors\n"); + + return 0; + } + + for (int i = 0; i < dev.getDescriptor().getBNumConfigurations(); i++) { + printConfiguration(dev.getConfig()[i]); + } + } else { + Usb_Device childDev = null; + + for (int i = 0; i < dev.getNumChildren(); i++) { + if (i == 0) { + childDev = dev.getChildren(); + } else { + childDev = childDev.getNext(); + } + + printDevice(childDev, level + 1); + } + } + + return 0; + } // end of printDevice method + + /** + * The main method. + * + * @param args + * The command line arguments. + */ + public static void main(String args[]) throws Exception { + if ((args.length > 0) && (args[0].equals("-v"))) { + verbose = true; + } else { + verbose = false; + } + + // used for debugging. 0 = no debugging, 255 = with debugging + LibusbJava.usb_init(); + LibusbJava.usb_set_debug(255); + + LibusbJava.usb_find_busses(); + LibusbJava.usb_find_devices(); + + for (Usb_Bus bus = LibusbJava.usb_get_busses(); bus != null; bus = bus + .getNext()) { + if ((bus.getRootDev() != null) && !verbose) { + printDevice(bus.getRootDev(), 0); + } else { + for (Usb_Device dev = bus.getDevices(); dev != null; dev = dev + .getNext()) { + printDevice(dev, 0); + } + } + } + } // end main +} // end of TestLibUsbJava class diff --git a/java/test/ch/ntb/inf/libusbJava/test/devices/AT90USB1287.java b/src/test/java/ch/ntb/inf/libusbJava/test/devices/AT90USB1287.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/devices/AT90USB1287.java rename to src/test/java/ch/ntb/inf/libusbJava/test/devices/AT90USB1287.java index 518b7d9..7d2f36a 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/devices/AT90USB1287.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/devices/AT90USB1287.java @@ -1,34 +1,34 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test.devices; - -import ch.ntb.inf.libusbJava.USB; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; - -public class AT90USB1287 extends AbstractDeviceInfo { - - @Override - public void initValues() { - setIdVendor((short) 0x8235); - setIdProduct((short) 0x0200); - setTimeout(2000); - setConfiguration(1); - setInterface(0); - setAltinterface(-1); - setOutEPBulk(0x01); - setInEPBulk(0x82); - setOutEPInt(0x01); - setInEPInt(0x82); - setSleepTimeout(2000); - setMaxDataSize(USB.FULLSPEED_MAX_BULK_PACKET_SIZE); - setMode(TransferMode.Bulk); - setManufacturer("inf.ntb.ch"); - setProduct("JUnit Test Board"); - setSerialVersion("00.10.00"); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test.devices; + +import ch.ntb.inf.libusbJava.USB; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; + +public class AT90USB1287 extends AbstractDeviceInfo { + + @Override + public void initValues() { + setIdVendor((short) 0x8235); + setIdProduct((short) 0x0200); + setTimeout(2000); + setConfiguration(1); + setInterface(0); + setAltinterface(-1); + setOutEPBulk(0x01); + setInEPBulk(0x82); + setOutEPInt(0x01); + setInEPInt(0x82); + setSleepTimeout(2000); + setMaxDataSize(USB.FULLSPEED_MAX_BULK_PACKET_SIZE); + setMode(TransferMode.Bulk); + setManufacturer("inf.ntb.ch"); + setProduct("JUnit Test Board"); + setSerialVersion("00.10.00"); + } +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/devices/CY7C68013A.java b/src/test/java/ch/ntb/inf/libusbJava/test/devices/CY7C68013A.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/devices/CY7C68013A.java rename to src/test/java/ch/ntb/inf/libusbJava/test/devices/CY7C68013A.java index f23f8d6..3b8ee82 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/devices/CY7C68013A.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/devices/CY7C68013A.java @@ -1,31 +1,31 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test.devices; - -import ch.ntb.inf.libusbJava.USB; -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; - -public class CY7C68013A extends AbstractDeviceInfo { - - @Override - public void initValues() { - setIdVendor((short) 0x8235); - setIdProduct((short) 0x0222); - setTimeout(2000); - setConfiguration(1); - setInterface(0); - setAltinterface(-1); - setOutEPInt(0x02); - setInEPInt(0x86); - setOutEPBulk(0x04); - setInEPBulk(0x88); - setSleepTimeout(2000); - setMaxDataSize(USB.HIGHSPEED_MAX_BULK_PACKET_SIZE); - setMode(TransferMode.Bulk); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test.devices; + +import ch.ntb.inf.libusbJava.USB; +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; + +public class CY7C68013A extends AbstractDeviceInfo { + + @Override + public void initValues() { + setIdVendor((short) 0x8235); + setIdProduct((short) 0x0222); + setTimeout(2000); + setConfiguration(1); + setInterface(0); + setAltinterface(-1); + setOutEPInt(0x02); + setInEPInt(0x86); + setOutEPBulk(0x04); + setInEPBulk(0x88); + setSleepTimeout(2000); + setMaxDataSize(USB.HIGHSPEED_MAX_BULK_PACKET_SIZE); + setMode(TransferMode.Bulk); + } +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/devices/MX500.java b/src/test/java/ch/ntb/inf/libusbJava/test/devices/MX500.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/devices/MX500.java rename to src/test/java/ch/ntb/inf/libusbJava/test/devices/MX500.java index bdde469..121dbb8 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/devices/MX500.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/devices/MX500.java @@ -1,32 +1,32 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test.devices; - -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; - -public class MX500 extends AbstractDeviceInfo { - - @Override - public void initValues() { - setIdVendor((short) 0x046d); - setIdProduct((short) 0xc025); - setTimeout(2000); - setConfiguration(1); - setInterface(0); - setAltinterface(0); - setOutEPInt(-1); - setInEPInt(0x81); - setOutEPBulk(-1); - setInEPBulk(-1); - setSleepTimeout(5000); - setMaxDataSize(5); - setMode(TransferMode.Interrupt); - // we only read data -> don't compare - setDoCompareData(false); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test.devices; + +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; + +public class MX500 extends AbstractDeviceInfo { + + @Override + public void initValues() { + setIdVendor((short) 0x046d); + setIdProduct((short) 0xc025); + setTimeout(2000); + setConfiguration(1); + setInterface(0); + setAltinterface(0); + setOutEPInt(-1); + setInEPInt(0x81); + setOutEPBulk(-1); + setInEPBulk(-1); + setSleepTimeout(5000); + setMaxDataSize(5); + setMode(TransferMode.Interrupt); + // we only read data -> don't compare + setDoCompareData(false); + } +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/devices/MousePlus.java b/src/test/java/ch/ntb/inf/libusbJava/test/devices/MousePlus.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/devices/MousePlus.java rename to src/test/java/ch/ntb/inf/libusbJava/test/devices/MousePlus.java index ccc6154..3697c5a 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/devices/MousePlus.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/devices/MousePlus.java @@ -1,34 +1,34 @@ -/* - * Java libusb wrapper - * Copyright (c) 2005-2006 Andreas Schläpfer - * - * http://libusbjava.sourceforge.net - * This library is covered by the LGPL, read LGPL.txt for details. - */ -package ch.ntb.inf.libusbJava.test.devices; - -import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; - -public class MousePlus extends AbstractDeviceInfo { - - @Override - public void initValues() { - setIdVendor((short) 0x046d); - setIdProduct((short) 0xc016); - setBusName("bus-0"); - setFilename("\\\\.\\libusb0-0001--0x046d-0xc016"); - setTimeout(2000); - setConfiguration(1); - setInterface(0); - setAltinterface(0); - setOutEPInt(-1); - setInEPInt(0x81); - setOutEPBulk(-1); - setInEPBulk(-1); - setSleepTimeout(5000); - setMaxDataSize(4); - setMode(TransferMode.Interrupt); - // we only read data -> don't compare - setDoCompareData(false); - } -} +/* + * Java libusb wrapper + * Copyright (c) 2005-2006 Andreas Schläpfer + * + * http://libusbjava.sourceforge.net + * This library is covered by the LGPL, read LGPL.txt for details. + */ +package ch.ntb.inf.libusbJava.test.devices; + +import ch.ntb.inf.libusbJava.testApp.AbstractDeviceInfo; + +public class MousePlus extends AbstractDeviceInfo { + + @Override + public void initValues() { + setIdVendor((short) 0x046d); + setIdProduct((short) 0xc016); + setBusName("bus-0"); + setFilename("\\\\.\\libusb0-0001--0x046d-0xc016"); + setTimeout(2000); + setConfiguration(1); + setInterface(0); + setAltinterface(0); + setOutEPInt(-1); + setInEPInt(0x81); + setOutEPBulk(-1); + setInEPBulk(-1); + setSleepTimeout(5000); + setMaxDataSize(4); + setMode(TransferMode.Interrupt); + // we only read data -> don't compare + setDoCompareData(false); + } +} diff --git a/java/test/ch/ntb/inf/libusbJava/test/exceptions/LibusbErrorTest.java b/src/test/java/ch/ntb/inf/libusbJava/test/exceptions/LibusbErrorTest.java similarity index 96% rename from java/test/ch/ntb/inf/libusbJava/test/exceptions/LibusbErrorTest.java rename to src/test/java/ch/ntb/inf/libusbJava/test/exceptions/LibusbErrorTest.java index db0b2be..c6f3157 100644 --- a/java/test/ch/ntb/inf/libusbJava/test/exceptions/LibusbErrorTest.java +++ b/src/test/java/ch/ntb/inf/libusbJava/test/exceptions/LibusbErrorTest.java @@ -1,76 +1,76 @@ -package ch.ntb.inf.libusbJava.test.exceptions; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import ch.ntb.inf.libusbJava.exceptions.LibusbError; - -@RunWith(Parameterized.class) -public class LibusbErrorTest { - @Parameters - public static Collection codesToTest() { - return Arrays.asList(new Object[][] { {"ERROR_UNKNWON (0)", 0 }, - {"ERROR_IO", -1 }, - {"ERROR_INVALID_PARAM", -2}, - {"ERROR_ACCESS", -3}, - {"ERROR_NO_DEVICE", -4}, - {"ERROR_NOT_FOUND", -5}, - {"ERROR_BUSY", -6}, - {"ERROR_TIMEOUT", -7}, - {"ERROR_OVERFLOW", -8}, - {"ERROR_PIPE", -9}, - {"ERROR_INTERRUPTED", -10}, - {"ERROR_NO_MEM", -11}, - {"ERROR_NOT_SUPPORTED", -12}, - {"ERROR_UNKNWON (-13)", -13}, - {"ERROR_UNKNWON (-98)", -98}, - {"ERROR_JAVA_REFERENCES_NOT_LOADED", -100}, - {"ERROR_JAVA_WRONG_ENVIRONMENT", -101}, - {"ERROR_JAVA_ILEGAL_DEVICE_HANDLE", -102}, - {"ERROR_UNKNWON (-103)", -103}, - {"ERROR_OTHER", -99} }); - } - - private String exp_desc; - private int code; - private LibusbError e; - - public LibusbErrorTest(String exp_desc, int code) { - this.exp_desc = exp_desc; - this.code = code; - try { - throw new LibusbError(code); - } catch (LibusbError e) { - this.e = e; - } - } - - @Test - public void testGetErrorCode() { - assertEquals("Error code is correct", e.getErrorCode(), code); - } - - @Test - public void testGetStringFromCode() { - String gen_desc = LibusbError.getStringFromCode(code); - assertEquals("Correct error description for " + code, exp_desc, gen_desc); - } - - @Test - public void testGetErrorString() { - assertEquals("Correct error string for " + code, e.getErrorString(), exp_desc); - } - - - @Test - public void testGetMessage() { - assertEquals("Correct error string for " + code, e.getMessage(), "libusb result: " + exp_desc); - } -} +package ch.ntb.inf.libusbJava.test.exceptions; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import ch.ntb.inf.libusbJava.exceptions.LibusbError; + +@RunWith(Parameterized.class) +public class LibusbErrorTest { + @Parameters + public static Collection codesToTest() { + return Arrays.asList(new Object[][] { {"ERROR_UNKNWON (0)", 0 }, + {"ERROR_IO", -1 }, + {"ERROR_INVALID_PARAM", -2}, + {"ERROR_ACCESS", -3}, + {"ERROR_NO_DEVICE", -4}, + {"ERROR_NOT_FOUND", -5}, + {"ERROR_BUSY", -6}, + {"ERROR_TIMEOUT", -7}, + {"ERROR_OVERFLOW", -8}, + {"ERROR_PIPE", -9}, + {"ERROR_INTERRUPTED", -10}, + {"ERROR_NO_MEM", -11}, + {"ERROR_NOT_SUPPORTED", -12}, + {"ERROR_UNKNWON (-13)", -13}, + {"ERROR_UNKNWON (-98)", -98}, + {"ERROR_JAVA_REFERENCES_NOT_LOADED", -100}, + {"ERROR_JAVA_WRONG_ENVIRONMENT", -101}, + {"ERROR_JAVA_ILEGAL_DEVICE_HANDLE", -102}, + {"ERROR_UNKNWON (-103)", -103}, + {"ERROR_OTHER", -99} }); + } + + private String exp_desc; + private int code; + private LibusbError e; + + public LibusbErrorTest(String exp_desc, int code) { + this.exp_desc = exp_desc; + this.code = code; + try { + throw new LibusbError(code); + } catch (LibusbError e) { + this.e = e; + } + } + + @Test + public void testGetErrorCode() { + assertEquals("Error code is correct", e.getErrorCode(), code); + } + + @Test + public void testGetStringFromCode() { + String gen_desc = LibusbError.getStringFromCode(code); + assertEquals("Correct error description for " + code, exp_desc, gen_desc); + } + + @Test + public void testGetErrorString() { + assertEquals("Correct error string for " + code, e.getErrorString(), exp_desc); + } + + + @Test + public void testGetMessage() { + assertEquals("Correct error string for " + code, e.getMessage(), "libusb result: " + exp_desc); + } +}