././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0723271 hidapi-0.15.0/0000755000076500000240000000000015115770112012073 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/LICENSE-bsd.txt0000644000076500000240000000275515115610727014502 0ustar00stickstaffCopyright (c) 2011, Gary Bishop All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Signal 11 Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/LICENSE-gpl3.txt0000644000076500000240000010451315115610727014572 0ustar00stickstaff GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/LICENSE-orig.txt0000644000076500000240000000012715115610727014661 0ustar00stickstaff You are free to use cython-hidapi code for any purpose. Copyright 2011, Gary Bishop ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/LICENSE.txt0000644000076500000240000000105615115610727013725 0ustar00stickstaffcython-hidapi can be used under one of three licenses. 1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt 2. A BSD-Style License, in LICENSE-bsd.txt. 3. The more liberal original cython-hidapi license. LICENSE-orig.txt The license chosen is at the discretion of the user of cython-hidapi. For example: 1. An author of GPL software would likely use HIDAPI under the terms of the GPL. 2. An author of commercial closed-source software would likely use HIDAPI under the terms of the BSD-style license or the original cython-hidapi license. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/MANIFEST.in0000644000076500000240000000053315115610727013637 0ustar00stickstaffinclude hidapi/hidapi/*.h include hidapi/libusb/*.c include hidapi/libusb/*.h include hidapi/linux/*.c include hidapi/linux/*.h include hidapi/mac/*.c include hidapi/mac/*.h include hidapi/windows/*.c include hidapi/windows/*.h include LICENSE*.txt include tests.py include try.py include chid.pxd include hid.c include hid.pyx include hidraw.pyx ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0721617 hidapi-0.15.0/PKG-INFO0000644000076500000240000000717515115770112013202 0ustar00stickstaffMetadata-Version: 2.4 Name: hidapi Version: 0.15.0 Summary: A Cython interface to the hidapi from https://github.com/libusb/hidapi Home-page: https://github.com/trezor/cython-hidapi Author: Pavol Rusnak Author-email: pavol@rusnak.io Maintainer: Pavol Rusnak Maintainer-email: pavol@rusnak.io Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: License :: OSI Approved :: BSD License Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 License-File: LICENSE-bsd.txt License-File: LICENSE-gpl3.txt License-File: LICENSE-orig.txt License-File: LICENSE.txt Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: home-page Dynamic: license-file Dynamic: maintainer Dynamic: maintainer-email Dynamic: summary cython-hidapi ============= .. contents:: Description ----------- A Cython interface to `HIDAPI `_ library. This has been tested with: * `TREZOR `_ Hardware Wallet * the PIC18F4550 on the development board from CCS with their example program * the Fine Offset WH3081 Weather Station It works on Linux, Windows and macOS. Software Dependencies --------------------- * `Python `_ * `Cython `_ * hidraw or libusb+libudev on Linux License ------- cython-hidapi may be used by one of three licenses as outlined in LICENSE.txt Install ------- :: $ sudo apt-get install python-dev libusb-1.0-0-dev libudev-dev $ sudo pip install --upgrade setuptools $ sudo pip install hidapi For other download options visit the `PyPi page `_. Build from source ----------------- 1. Download cython-hidapi archive:: $ git clone --recursive https://github.com/trezor/cython-hidapi.git $ cd cython-hidapi 2. Build cython-hidapi extension module:: $ python setup.py build On Linux, the hidraw API is now used by default, and the libusb API is not included. That is, --without-libusb is now the default behavior. To force the use of the libusb API instead, use the --with-libusb option:: $ python setup.py build --with-libusb Or you can also use the environment variable:: $ export HIDAPI_WITH_LIBUSB=1 $ python setup.py build 3. Install cython-hidapi module into your Python distribution:: $ sudo python setup.py install **Alternatively**, you can run pip directly, which will call the necessary build and install commands:: $ pip install -e . 4. Test install:: $ python >>> import hid >>> 5. Try example script:: $ python try.py Udev rules ---------- For correct functionality under Linux, you need to create a rule file similar to `this one `_ in your udev rules directory. Also you might need to call ``udevadm control --reload-rules`` to reload the rules. Documentation ------------- Documentation can be built using Sphinx:: $ cd docs && make html The HTML output will be in ``docs/_build/html``. The documentation is extracted from the code using ``autodoc``. Note that the build output is used. So rebuilt the package before generating documentation. Built documentation is also deployed to: `https://trezor.github.io/cython-hidapi/ `_. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/README.rst0000644000076500000240000000504015115610727013566 0ustar00stickstaffcython-hidapi ============= .. contents:: Description ----------- A Cython interface to `HIDAPI `_ library. This has been tested with: * `TREZOR `_ Hardware Wallet * the PIC18F4550 on the development board from CCS with their example program * the Fine Offset WH3081 Weather Station It works on Linux, Windows and macOS. Software Dependencies --------------------- * `Python `_ * `Cython `_ * hidraw or libusb+libudev on Linux License ------- cython-hidapi may be used by one of three licenses as outlined in LICENSE.txt Install ------- :: $ sudo apt-get install python-dev libusb-1.0-0-dev libudev-dev $ sudo pip install --upgrade setuptools $ sudo pip install hidapi For other download options visit the `PyPi page `_. Build from source ----------------- 1. Download cython-hidapi archive:: $ git clone --recursive https://github.com/trezor/cython-hidapi.git $ cd cython-hidapi 2. Build cython-hidapi extension module:: $ python setup.py build On Linux, the hidraw API is now used by default, and the libusb API is not included. That is, --without-libusb is now the default behavior. To force the use of the libusb API instead, use the --with-libusb option:: $ python setup.py build --with-libusb Or you can also use the environment variable:: $ export HIDAPI_WITH_LIBUSB=1 $ python setup.py build 3. Install cython-hidapi module into your Python distribution:: $ sudo python setup.py install **Alternatively**, you can run pip directly, which will call the necessary build and install commands:: $ pip install -e . 4. Test install:: $ python >>> import hid >>> 5. Try example script:: $ python try.py Udev rules ---------- For correct functionality under Linux, you need to create a rule file similar to `this one `_ in your udev rules directory. Also you might need to call ``udevadm control --reload-rules`` to reload the rules. Documentation ------------- Documentation can be built using Sphinx:: $ cd docs && make html The HTML output will be in ``docs/_build/html``. The documentation is extracted from the code using ``autodoc``. Note that the build output is used. So rebuilt the package before generating documentation. Built documentation is also deployed to: `https://trezor.github.io/cython-hidapi/ `_. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/chid.pxd0000644000076500000240000000407315115610727013530 0ustar00stickstafffrom libc.stddef cimport wchar_t, size_t cdef extern from "": const int HID_API_MAX_REPORT_DESCRIPTOR_SIZE ctypedef struct hid_device: pass ctypedef enum hid_bus_type: HID_API_BUS_UNKNOWN = 0x00, HID_API_BUS_USB = 0x01, HID_API_BUS_BLUETOOTH = 0x02, HID_API_BUS_I2C = 0x03, HID_API_BUS_SPI = 0x04 cdef struct hid_device_info: char *path unsigned short vendor_id unsigned short product_id wchar_t *serial_number unsigned short release_number wchar_t *manufacturer_string wchar_t *product_string unsigned short usage_page unsigned short usage int interface_number hid_device_info *next hid_bus_type bus_type hid_device_info* hid_enumerate(unsigned short, unsigned short) nogil void hid_free_enumeration(hid_device_info*) hid_device* hid_open(unsigned short, unsigned short, const wchar_t*) hid_device* hid_open_path(char *path) void hid_close(hid_device *) int hid_init() int hid_exit() int hid_write(hid_device* device, unsigned char *data, int length) nogil int hid_read(hid_device* device, unsigned char* data, int max_length) nogil int hid_read_timeout(hid_device* device, unsigned char* data, int max_length, int milliseconds) nogil int hid_set_nonblocking(hid_device* device, int value) int hid_get_report_descriptor(hid_device* device, unsigned char *data, int length) nogil int hid_send_feature_report(hid_device* device, unsigned char *data, int length) nogil int hid_get_feature_report(hid_device* device, unsigned char *data, int length) nogil int hid_get_input_report(hid_device* device, unsigned char *data, int length) nogil int hid_get_manufacturer_string(hid_device*, wchar_t *, size_t) int hid_get_product_string(hid_device*, wchar_t *, size_t) int hid_get_serial_number_string(hid_device*, wchar_t *, size_t) int hid_get_indexed_string(hid_device*, int, wchar_t *, size_t) wchar_t *hid_error(hid_device *) char* hid_version_str() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273674.0 hidapi-0.15.0/hid.c0000644000076500000240000246645715115770112013033 0ustar00stickstaff/* Generated by Cython 3.1.4 */ /* BEGIN: Cython Metadata { "distutils": { "depends": [], "extra_compile_args": [ "-isysroot", "/nix/store/npzkc6q10x37mb969v8c19klfsghb70l-apple-sdk-14.4/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.4.sdk", "-Wno-unreachable-code" ], "extra_link_args": [ "-framework", "IOKit", "-framework", "CoreFoundation", "-framework", "AppKit" ], "include_dirs": [ "/Users/stick/work/trezor/cython-hidapi/hidapi/hidapi" ], "name": "hid", "sources": [ "hid.pyx", "/Users/stick/work/trezor/cython-hidapi/hidapi/mac/hid.c" ] }, "module_name": "hid" } END: Cython Metadata */ #ifndef PY_SSIZE_T_CLEAN #define PY_SSIZE_T_CLEAN #endif /* PY_SSIZE_T_CLEAN */ /* InitLimitedAPI */ #if defined(Py_LIMITED_API) && !defined(CYTHON_LIMITED_API) #define CYTHON_LIMITED_API 1 #endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x03080000 #error Cython requires Python 3.8+. #else #define __PYX_ABI_VERSION "3_1_4" #define CYTHON_HEX_VERSION 0x030104F0 #define CYTHON_FUTURE_DIVISION 1 /* CModulePreamble */ #include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #define HAVE_LONG_LONG #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX #if defined(GRAALVM_PYTHON) /* For very preliminary testing purposes. Most variables are set the same as PyPy. The existence of this section does not imply that anything works or is even tested */ #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #define CYTHON_COMPILING_IN_LIMITED_API 0 #define CYTHON_COMPILING_IN_GRAAL 1 #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_TYPE_SPECS #define CYTHON_USE_TYPE_SPECS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_ASSUME_SAFE_SIZE #define CYTHON_ASSUME_SAFE_SIZE 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_GIL #define CYTHON_FAST_GIL 0 #undef CYTHON_METH_FASTCALL #define CYTHON_METH_FASTCALL 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #ifndef CYTHON_PEP487_INIT_SUBCLASS #define CYTHON_PEP487_INIT_SUBCLASS 1 #endif #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 1 #undef CYTHON_USE_MODULE_STATE #define CYTHON_USE_MODULE_STATE 0 #undef CYTHON_USE_SYS_MONITORING #define CYTHON_USE_SYS_MONITORING 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_AM_SEND #define CYTHON_USE_AM_SEND 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 1 #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 #endif #undef CYTHON_USE_FREELISTS #define CYTHON_USE_FREELISTS 0 #elif defined(PYPY_VERSION) #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #define CYTHON_COMPILING_IN_LIMITED_API 0 #define CYTHON_COMPILING_IN_GRAAL 0 #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #ifndef CYTHON_USE_TYPE_SPECS #define CYTHON_USE_TYPE_SPECS 0 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #ifndef CYTHON_ASSUME_SAFE_SIZE #define CYTHON_ASSUME_SAFE_SIZE 1 #endif #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_GIL #define CYTHON_FAST_GIL 0 #undef CYTHON_METH_FASTCALL #define CYTHON_METH_FASTCALL 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #ifndef CYTHON_PEP487_INIT_SUBCLASS #define CYTHON_PEP487_INIT_SUBCLASS 1 #endif #if PY_VERSION_HEX < 0x03090000 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) #define CYTHON_PEP489_MULTI_PHASE_INIT 1 #endif #undef CYTHON_USE_MODULE_STATE #define CYTHON_USE_MODULE_STATE 0 #undef CYTHON_USE_SYS_MONITORING #define CYTHON_USE_SYS_MONITORING 0 #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) #endif #undef CYTHON_USE_AM_SEND #define CYTHON_USE_AM_SEND 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) #endif #undef CYTHON_USE_FREELISTS #define CYTHON_USE_FREELISTS 0 #elif defined(CYTHON_LIMITED_API) #ifdef Py_LIMITED_API #undef __PYX_LIMITED_VERSION_HEX #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API #endif #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #define CYTHON_COMPILING_IN_LIMITED_API 1 #define CYTHON_COMPILING_IN_GRAAL 0 #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 #undef CYTHON_CLINE_IN_TRACEBACK #define CYTHON_CLINE_IN_TRACEBACK 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_TYPE_SPECS #define CYTHON_USE_TYPE_SPECS 1 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #endif #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 #endif #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_ASSUME_SAFE_SIZE #define CYTHON_ASSUME_SAFE_SIZE 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_GIL #define CYTHON_FAST_GIL 0 #undef CYTHON_METH_FASTCALL #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #ifndef CYTHON_PEP487_INIT_SUBCLASS #define CYTHON_PEP487_INIT_SUBCLASS 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 1 #endif #ifndef CYTHON_USE_MODULE_STATE #define CYTHON_USE_MODULE_STATE 0 #endif #undef CYTHON_USE_SYS_MONITORING #define CYTHON_USE_SYS_MONITORING 0 #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #endif #ifndef CYTHON_USE_AM_SEND #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) #endif #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 #endif #undef CYTHON_USE_FREELISTS #define CYTHON_USE_FREELISTS 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #define CYTHON_COMPILING_IN_LIMITED_API 0 #define CYTHON_COMPILING_IN_GRAAL 0 #ifdef Py_GIL_DISABLED #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 #else #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 #endif #if PY_VERSION_HEX < 0x030A0000 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #elif !defined(CYTHON_USE_TYPE_SLOTS) #define CYTHON_USE_TYPE_SLOTS 1 #endif #ifndef CYTHON_USE_TYPE_SPECS #define CYTHON_USE_TYPE_SPECS 0 #endif #ifndef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #ifndef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #elif !defined(CYTHON_USE_PYLIST_INTERNALS) #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_ASSUME_SAFE_SIZE #define CYTHON_ASSUME_SAFE_SIZE 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING #undef CYTHON_FAST_GIL #define CYTHON_FAST_GIL 0 #elif !defined(CYTHON_FAST_GIL) #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) #endif #ifndef CYTHON_METH_FASTCALL #define CYTHON_METH_FASTCALL 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP487_INIT_SUBCLASS #define CYTHON_PEP487_INIT_SUBCLASS 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 1 #endif #ifndef CYTHON_USE_MODULE_STATE #define CYTHON_USE_MODULE_STATE 0 #endif #ifndef CYTHON_USE_SYS_MONITORING #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 1 #endif #ifndef CYTHON_USE_AM_SEND #define CYTHON_USE_AM_SEND 1 #endif #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #elif !defined(CYTHON_USE_DICT_VERSIONS) #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) #endif #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 1 #endif #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 #endif #ifndef CYTHON_USE_FREELISTS #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) #endif #endif #ifndef CYTHON_FAST_PYCCALL #define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL #endif #ifndef CYTHON_VECTORCALL #if CYTHON_COMPILING_IN_LIMITED_API #define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) #else #define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL && PY_VERSION_HEX >= 0x030800B1) #endif #endif #define CYTHON_BACKPORT_VECTORCALL (CYTHON_METH_FASTCALL && PY_VERSION_HEX < 0x030800B1) #if CYTHON_USE_PYLONG_INTERNALS #undef SHIFT #undef BASE #undef MASK #ifdef SIZEOF_VOID_P enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; #endif #endif #ifndef CYTHON_LOCK_AND_GIL_DEADLOCK_AVOIDANCE_TIME #define CYTHON_LOCK_AND_GIL_DEADLOCK_AVOIDANCE_TIME 100 #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED #if defined(__cplusplus) /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 * but leads to warnings with -pedantic, since it is a C++17 feature */ #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) #if __has_cpp_attribute(maybe_unused) #define CYTHON_UNUSED [[maybe_unused]] #endif #endif #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_UNUSED_VAR # if defined(__cplusplus) template void CYTHON_UNUSED_VAR( const T& ) { } # else # define CYTHON_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #ifndef CYTHON_USE_CPP_STD_MOVE #if defined(__cplusplus) && (\ __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) #define CYTHON_USE_CPP_STD_MOVE 1 #else #define CYTHON_USE_CPP_STD_MOVE 0 #endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif #endif #if _MSC_VER < 1300 #ifdef _WIN64 typedef unsigned long long __pyx_uintptr_t; #else typedef unsigned int __pyx_uintptr_t; #endif #else #ifdef _WIN64 typedef unsigned __int64 __pyx_uintptr_t; #else typedef unsigned __int32 __pyx_uintptr_t; #endif #endif #else #include typedef uintptr_t __pyx_uintptr_t; #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 * but leads to warnings with -pedantic, since it is a C++17 feature */ #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef Py_UNREACHABLE #define Py_UNREACHABLE() assert(0); abort() #endif #ifdef __cplusplus template struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) #else #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) #endif #if CYTHON_COMPILING_IN_PYPY == 1 #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x030A0000) #else #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000) #endif #define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) /* CInitCode */ #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif /* PythonCompatibility */ #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_DefaultClassType PyType_Type #if CYTHON_COMPILING_IN_LIMITED_API #ifndef CO_OPTIMIZED static int CO_OPTIMIZED; #endif #ifndef CO_NEWLOCALS static int CO_NEWLOCALS; #endif #ifndef CO_VARARGS static int CO_VARARGS; #endif #ifndef CO_VARKEYWORDS static int CO_VARKEYWORDS; #endif #ifndef CO_ASYNC_GENERATOR static int CO_ASYNC_GENERATOR; #endif #ifndef CO_GENERATOR static int CO_GENERATOR; #endif #ifndef CO_COROUTINE static int CO_COROUTINE; #endif #else #ifndef CO_COROUTINE #define CO_COROUTINE 0x80 #endif #ifndef CO_ASYNC_GENERATOR #define CO_ASYNC_GENERATOR 0x200 #endif #endif static int __Pyx_init_co_variables(void); #if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) #else #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) #endif #if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) #define __Pyx_Py_Is(x, y) Py_Is(x, y) #else #define __Pyx_Py_Is(x, y) ((x) == (y)) #endif #if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) #else #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) #endif #if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) #else #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) #endif #if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) #else #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) #endif #define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) #if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) #else #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef Py_TPFLAGS_SEQUENCE #define Py_TPFLAGS_SEQUENCE 0 #endif #ifndef Py_TPFLAGS_MAPPING #define Py_TPFLAGS_MAPPING 0 #endif #ifndef METH_STACKLESS #define METH_STACKLESS 0 #endif #ifndef METH_FASTCALL #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #else #if PY_VERSION_HEX >= 0x030d00A4 # define __Pyx_PyCFunctionFast PyCFunctionFast # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords #else # define __Pyx_PyCFunctionFast _PyCFunctionFast # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #endif #if CYTHON_METH_FASTCALL #define __Pyx_METH_FASTCALL METH_FASTCALL #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords #else #define __Pyx_METH_FASTCALL METH_VARARGS #define __Pyx_PyCFunction_FastCall PyCFunction #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords #endif #if CYTHON_VECTORCALL #define __pyx_vectorcallfunc vectorcallfunc #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) #elif CYTHON_BACKPORT_VECTORCALL typedef PyObject *(*__pyx_vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames); #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1)) #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(((size_t)(n)) & ~__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)) #else #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) #endif #if PY_VERSION_HEX >= 0x030900B1 #define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) #else #define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) #endif #define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) #elif !CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) #endif #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; } #endif static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { #if CYTHON_COMPILING_IN_LIMITED_API return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; #else return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; #endif } #define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) #if __PYX_LIMITED_VERSION_HEX < 0x03090000 #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); #else #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) #define __Pyx_PyCMethod PyCMethod #endif #ifndef METH_METHOD #define METH_METHOD 0x200 #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_PyFrame_SetLineNumber(frame, lineno) #elif CYTHON_COMPILING_IN_GRAAL #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #if CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_PyThreadState_Current PyThreadState_Get() #elif !CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x030d00A1 #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() #else #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #endif #if CYTHON_USE_MODULE_STATE static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) { void *result; result = PyModule_GetState(op); if (!result) Py_FatalError("Couldn't find the module state"); return result; } #define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) #else #define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) #endif #define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) #define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) #define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) #define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) #if CYTHON_USE_TYPE_SLOTS #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) #else #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) #endif #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS #define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); if (res == NULL) PyErr_Clear(); return res; } #elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 #define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError #define __Pyx_PyDict_GetItemStr PyDict_GetItem #else static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { #if CYTHON_COMPILING_IN_PYPY return PyDict_GetItem(dict, name); #else PyDictEntry *ep; PyDictObject *mp = (PyDictObject*) dict; long hash = ((PyStringObject *) name)->ob_shash; assert(hash != -1); ep = (mp->ma_lookup)(mp, name, hash); if (ep == NULL) { return NULL; } return ep->me_value; #endif } #define __Pyx_PyDict_GetItemStr PyDict_GetItem #endif #if CYTHON_USE_TYPE_SLOTS #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) #else #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) #endif #define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) #if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX >= 0x03080000 #define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ PyTypeObject *type = Py_TYPE((PyObject*)obj);\ assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ PyObject_GC_Del(obj);\ Py_DECREF(type);\ } #else #define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) #endif #if CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) #define __Pyx_PyUnicode_DATA(u) ((void*)u) #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) #else #if PY_VERSION_HEX >= 0x030C0000 #define __Pyx_PyUnicode_READY(op) (0) #else #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #endif #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) #if PY_VERSION_HEX >= 0x030C0000 #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) #else #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #endif #endif #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY #if !defined(PyUnicode_DecodeUnicodeEscape) #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) #endif #if !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #endif #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PySequence_ListKeepNew(obj)\ (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) #else #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) #endif #if PY_VERSION_HEX >= 0x030900A4 #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) #else #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) #endif #if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) #else #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) #endif #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) #else #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) #endif #else #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) #endif #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 #define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) #elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { *result = PyObject_GetItem(dict, key); if (*result == NULL) { if (PyErr_ExceptionMatches(PyExc_KeyError)) { PyErr_Clear(); return 0; } return -1; } return 1; } #else static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { *result = PyDict_GetItemWithError(dict, key); if (*result == NULL) { return PyErr_Occurred() ? -1 : 0; } Py_INCREF(*result); return 1; } #endif #if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) #else #define __Pyx_VISIT_CONST(obj) #endif #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) #else #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) #endif #if CYTHON_ASSUME_SAFE_SIZE #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) #else #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) #endif #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) #else static CYTHON_INLINE PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { PyObject *module = PyImport_AddModule(name); Py_XINCREF(module); return module; } #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t #define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t #if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 #define __Pyx_PySendResult PySendResult #else typedef enum { PYGEN_RETURN = 0, PYGEN_ERROR = -1, PYGEN_NEXT = 1, } __Pyx_PySendResult; #endif #if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); #else #define __Pyx_pyiter_sendfunc sendfunc #endif #if !CYTHON_USE_AM_SEND #define __PYX_HAS_PY_AM_SEND 0 #elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 #define __PYX_HAS_PY_AM_SEND 1 #else #define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation #endif #if __PYX_HAS_PY_AM_SEND < 2 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #else typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; __Pyx_pyiter_sendfunc am_send; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) #endif #if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) #else #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) #endif #if PY_VERSION_HEX >= 0x03090000 #define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() #else #define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp #endif #if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 #ifdef __cplusplus extern "C" #endif PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); #endif #if CYTHON_COMPILING_IN_LIMITED_API static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { int value; PyObject *py_value = PyObject_GetAttrString(inspect, name); if (!py_value) return 0; value = (int) PyLong_AsLong(py_value); Py_DECREF(py_value); *write_to = value; return value != -1 || !PyErr_Occurred(); } static int __Pyx_init_co_variables(void) { PyObject *inspect; int result; inspect = PyImport_ImportModule("inspect"); result = #if !defined(CO_OPTIMIZED) __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && #endif #if !defined(CO_NEWLOCALS) __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && #endif #if !defined(CO_VARARGS) __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && #endif #if !defined(CO_VARKEYWORDS) __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && #endif #if !defined(CO_ASYNC_GENERATOR) __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && #endif #if !defined(CO_GENERATOR) __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && #endif #if !defined(CO_COROUTINE) __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && #endif 1; Py_DECREF(inspect); return result ? 0 : -1; } #else static int __Pyx_init_co_variables(void) { return 0; // It's a limited API-only feature } #endif /* MathInitCode */ #if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #endif #include #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME #define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 #endif #ifndef CYTHON_CLINE_IN_TRACEBACK #define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME #endif #if CYTHON_CLINE_IN_TRACEBACK #define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } #else #define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } #ifdef CYTHON_EXTERN_C #undef __PYX_EXTERN_C #define __PYX_EXTERN_C CYTHON_EXTERN_C #elif defined(__PYX_EXTERN_C) #ifdef _MSC_VER #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") #else #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. #endif #else #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__hid #define __PYX_HAVE_API__hid /* Early includes */ #include #include #include #include #ifdef _OPENMP #include #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { return (size_t) i < (size_t) limit; } #if defined (__cplusplus) && __cplusplus >= 201103L #include #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) #else #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) #endif #define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) return Py_NewRef(obj); #else Py_INCREF(obj); return obj; #endif } static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) return Py_XNewRef(obj); #else Py_XINCREF(obj); return obj; #endif } static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) #else #define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) #endif #define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #if CYTHON_USE_PYLONG_INTERNALS #if PY_VERSION_HEX >= 0x030C00A7 #ifndef _PyLong_SIGN_MASK #define _PyLong_SIGN_MASK 3 #endif #ifndef _PyLong_NON_SIZE_BITS #define _PyLong_NON_SIZE_BITS 3 #endif #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) #define __Pyx_PyLong_SignedDigitCount(x)\ ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) #else #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) #endif typedef Py_ssize_t __Pyx_compact_pylong; typedef size_t __Pyx_compact_upylong; #else #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) #define __Pyx_PyLong_CompactValue(x)\ ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) typedef sdigit __Pyx_compact_pylong; typedef digit __Pyx_compact_upylong; #endif #if PY_VERSION_HEX >= 0x030C00A5 #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) #else #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) #endif #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ /* PretendToInitialize */ #ifdef __cplusplus #if __cplusplus > 201103L #include #endif template static void __Pyx_pretend_to_initialize(T* ptr) { #if __cplusplus > 201103L if ((std::is_trivially_default_constructible::value)) #endif *ptr = T(); (void)ptr; } #else static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } #endif #if !CYTHON_USE_MODULE_STATE static PyObject *__pyx_m = NULL; #endif static int __pyx_lineno; static int __pyx_clineno = 0; static const char * const __pyx_cfilenm = __FILE__; static const char *__pyx_filename; /* #### Code section: filename_table ### */ static const char* const __pyx_f[] = { "hid.pyx", "", }; /* #### Code section: utility_code_proto_before_types ### */ /* IncludeStructmemberH.proto */ #include /* CriticalSections.proto */ #if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING #define __Pyx_PyCriticalSection void* #define __Pyx_PyCriticalSection2 void* #define __Pyx_PyCriticalSection_Begin1(cs, arg) (void)cs #define __Pyx_PyCriticalSection_Begin2(cs, arg1, arg2) (void)cs #define __Pyx_PyCriticalSection_End1(cs) #define __Pyx_PyCriticalSection_End2(cs) #else #define __Pyx_PyCriticalSection PyCriticalSection #define __Pyx_PyCriticalSection2 PyCriticalSection2 #define __Pyx_PyCriticalSection_Begin1 PyCriticalSection_Begin #define __Pyx_PyCriticalSection_Begin2 PyCriticalSection2_Begin #define __Pyx_PyCriticalSection_End1 PyCriticalSection_End #define __Pyx_PyCriticalSection_End2 PyCriticalSection2_End #endif #if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_BEGIN_CRITICAL_SECTION(o) { #define __Pyx_END_CRITICAL_SECTION() } #else #define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION #define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION #endif /* Atomics.proto */ #include #ifndef CYTHON_ATOMICS #define CYTHON_ATOMICS 1 #endif #define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS #define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING #define __pyx_atomic_int_type int #define __pyx_nonatomic_int_type int #if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ (__STDC_VERSION__ >= 201112L) &&\ !defined(__STDC_NO_ATOMICS__)) #include #elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ (__cplusplus >= 201103L) ||\ (defined(_MSC_VER) && _MSC_VER >= 1700))) #include #endif #if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ (__STDC_VERSION__ >= 201112L) &&\ !defined(__STDC_NO_ATOMICS__) &&\ ATOMIC_INT_LOCK_FREE == 2) #undef __pyx_atomic_int_type #define __pyx_atomic_int_type atomic_int #define __pyx_atomic_ptr_type atomic_uintptr_t #define __pyx_nonatomic_ptr_type uintptr_t #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) #define __pyx_atomic_load(value) atomic_load(value) #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) #pragma message ("Using standard C atomics") #elif defined(__PYX_DEBUG_ATOMICS) #warning "Using standard C atomics" #endif #elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ (__cplusplus >= 201103L) ||\ \ (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ ATOMIC_INT_LOCK_FREE == 2) #undef __pyx_atomic_int_type #define __pyx_atomic_int_type std::atomic_int #define __pyx_atomic_ptr_type std::atomic_uintptr_t #define __pyx_nonatomic_ptr_type uintptr_t #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) #define __pyx_atomic_load(value) std::atomic_load(value) #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) #pragma message ("Using standard C++ atomics") #elif defined(__PYX_DEBUG_ATOMICS) #warning "Using standard C++ atomics" #endif #elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ (__GNUC_MINOR__ > 1 ||\ (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) #define __pyx_atomic_ptr_type void* #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); int result = old == *expected; *expected = old; return result; } #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif #elif CYTHON_ATOMICS && defined(_MSC_VER) #include #undef __pyx_atomic_int_type #define __pyx_atomic_int_type long #define __pyx_atomic_ptr_type void* #undef __pyx_nonatomic_int_type #define __pyx_nonatomic_int_type long #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); int result = old == *expected; *expected = old; return result; } #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) #ifdef __PYX_DEBUG_ATOMICS #pragma message ("Using MSVC atomics") #endif #else #undef CYTHON_ATOMICS #define CYTHON_ATOMICS 0 #ifdef __PYX_DEBUG_ATOMICS #warning "Not using atomics" #endif #endif #if CYTHON_ATOMICS #define __pyx_add_acquisition_count(memview)\ __pyx_atomic_incr_relaxed(__pyx_get_slice_count_pointer(memview)) #define __pyx_sub_acquisition_count(memview)\ __pyx_atomic_decr_acq_rel(__pyx_get_slice_count_pointer(memview)) #else #define __pyx_add_acquisition_count(memview)\ __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview)\ __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #endif /* NoFastGil.proto */ #define __Pyx_PyGILState_Ensure PyGILState_Ensure #define __Pyx_PyGILState_Release PyGILState_Release #define __Pyx_FastGIL_Remember() #define __Pyx_FastGIL_Forget() #define __Pyx_FastGilFuncInit() /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* #### Code section: numeric_typedefs ### */ /* #### Code section: complex_type_declarations ### */ /* #### Code section: type_declarations ### */ /*--- Type declarations ---*/ struct __pyx_obj_3hid__closer; struct __pyx_obj_3hid_device; struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_; /* "hid.pyx":85 * return (hid_version_str()).decode('ascii') * * cdef class _closer: # <<<<<<<<<<<<<< * """Wrap a hid_device *ptr and a provide a way to call hid_close() on it. * */ struct __pyx_obj_3hid__closer { PyObject_HEAD struct __pyx_vtabstruct_3hid__closer *__pyx_vtab; hid_device *_ptr; }; /* "hid.pyx":102 * hid_close(self._ptr) * * cdef class device: # <<<<<<<<<<<<<< * """Device class. * */ struct __pyx_obj_3hid_device { PyObject_HEAD hid_device *_c_hid; PyObject *__weakref__; PyObject *_close; }; /* "cfunc.to_py":65 * * * @cname("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_") # <<<<<<<<<<<<<< * cdef object __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*f)() except *): * def wrap(): */ struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ { PyObject_HEAD int (*__pyx_v_f)(void); }; /* "hid.pyx":85 * return (hid_version_str()).decode('ascii') * * cdef class _closer: # <<<<<<<<<<<<<< * """Wrap a hid_device *ptr and a provide a way to call hid_close() on it. * */ struct __pyx_vtabstruct_3hid__closer { PyObject *(*wrap)(hid_device *); }; static struct __pyx_vtabstruct_3hid__closer *__pyx_vtabptr_3hid__closer; /* #### Code section: utility_code_proto ### */ /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, Py_ssize_t); void (*DECREF)(void*, PyObject*, Py_ssize_t); void (*GOTREF)(void*, PyObject*, Py_ssize_t); void (*GIVEREF)(void*, PyObject*, Py_ssize_t); void* (*SetupContext)(const char*, Py_ssize_t, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ } #define __Pyx_RefNannyFinishContextNogil() {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __Pyx_RefNannyFinishContext();\ PyGILState_Release(__pyx_gilstate_save);\ } #define __Pyx_RefNannyFinishContextNogil() {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __Pyx_RefNannyFinishContext();\ PyGILState_Release(__pyx_gilstate_save);\ } #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContextNogil() #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_Py_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; Py_XDECREF(tmp);\ } while (0) #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #if PY_VERSION_HEX >= 0x030C00A6 #define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) #define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) #else #define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) #define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) #endif #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) #define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* PyObjectGetAttrStrNoError.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* TupleAndListFromArray.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); #endif #if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); #endif /* IncludeStringH.proto */ #include /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* fastcall.proto */ #if CYTHON_AVOID_BORROWED_REFS #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) #elif CYTHON_ASSUME_SAFE_MACROS #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) #else #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) #endif #define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) #define __Pyx_KwValues_VARARGS(args, nargs) NULL #define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) #define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) #if CYTHON_METH_FASTCALL #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); #else #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) #endif #else #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS #endif #define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) #if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) #define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) #else #define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) #endif /* LimitedApiGetTypeDict.proto */ #if CYTHON_COMPILING_IN_LIMITED_API static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); #endif /* SetItemOnTypeDict.proto */ static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); #define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) /* FixUpExtensionType.proto */ static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); /* FetchSharedCythonModule.proto */ static PyObject *__Pyx_FetchSharedCythonABIModule(void); /* dict_setdefault.proto */ static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, int is_safe_type); /* FetchCommonType.proto */ static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); /* CommonTypesMetaclass.proto */ static int __pyx_CommonTypesMetaclass_init(PyObject *module); #define __Pyx_CommonTypesMetaclass_USED /* CallTypeTraverse.proto */ #if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) #define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 #else static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); #endif /* PyMethodNew.proto */ static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); /* PyVectorcallFastCallDict.proto */ #if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); #endif /* CythonFunctionShared.proto */ #define __Pyx_CyFunction_USED #define __Pyx_CYFUNCTION_STATICMETHOD 0x01 #define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 #define __Pyx_CYFUNCTION_CCLASS 0x04 #define __Pyx_CYFUNCTION_COROUTINE 0x08 #define __Pyx_CyFunction_GetClosure(f)\ (((__pyx_CyFunctionObject *) (f))->func_closure) #if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_CyFunction_GetClassObj(f)\ (((__pyx_CyFunctionObject *) (f))->func_classobj) #else #define __Pyx_CyFunction_GetClassObj(f)\ ((PyObject*) ((PyCMethodObject *) (f))->mm_class) #endif #define __Pyx_CyFunction_SetClassObj(f, classobj)\ __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) #define __Pyx_CyFunction_Defaults(type, f)\ ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) #define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) typedef struct { #if CYTHON_COMPILING_IN_LIMITED_API PyObject_HEAD PyObject *func; #elif PY_VERSION_HEX < 0x030900B1 PyCFunctionObject func; #else PyCMethodObject func; #endif #if CYTHON_BACKPORT_VECTORCALL ||\ (CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL) __pyx_vectorcallfunc func_vectorcall; #endif #if CYTHON_COMPILING_IN_LIMITED_API PyObject *func_weakreflist; #endif PyObject *func_dict; PyObject *func_name; PyObject *func_qualname; PyObject *func_doc; PyObject *func_globals; PyObject *func_code; PyObject *func_closure; #if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API PyObject *func_classobj; #endif PyObject *defaults; int flags; PyObject *defaults_tuple; PyObject *defaults_kwdict; PyObject *(*defaults_getter)(PyObject *); PyObject *func_annotations; PyObject *func_is_coroutine; } __pyx_CyFunctionObject; #undef __Pyx_CyOrPyCFunction_Check #define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) #define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) #define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); #undef __Pyx_IsSameCFunction #define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject *globals, PyObject* code); static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type); static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, PyObject *tuple); static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, PyObject *dict); static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, PyObject *dict); static int __pyx_CyFunction_init(PyObject *module); #if CYTHON_METH_FASTCALL static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); #if CYTHON_BACKPORT_VECTORCALL || CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) #else #define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) #endif #endif /* CythonFunction.proto */ static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject *globals, PyObject* code); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static CYTHON_INLINE int __Pyx_ParseKeywords( PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, const char* function_name, int ignore_unknown_kwargs ); /* CallCFunction.proto */ #define __Pyx_CallCFunction(cfunc, self, args)\ ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) #define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) #define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) #define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #if !CYTHON_VECTORCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs); #endif #define __Pyx_BUILD_ASSERT_EXPR(cond)\ (sizeof(char [1 - 2*!(cond)]) - 1) #ifndef Py_MEMBER_SIZE #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) #endif #if !CYTHON_VECTORCALL #if PY_VERSION_HEX >= 0x03080000 #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets() #define __Pyx_PyFrame_GetLocalsplus(frame) ((frame)->f_localsplus) #else static size_t __pyx_pyframe_localsplus_offset = 0; #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets()\ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) #define __Pyx_PyFrame_GetLocalsplus(frame)\ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) #endif #endif #endif /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectFastCall.proto */ #define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); /* UnpackUnboundCMethod.proto */ typedef struct { PyObject *type; PyObject **method_name; #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS __pyx_atomic_int_type initialized; #endif PyCFunction func; PyObject *method; int flag; } __Pyx_CachedCFunction; #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { #if !CYTHON_ATOMICS return 1; #else __pyx_nonatomic_int_type expected = 0; if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { return 0; } return expected; #endif } static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { #if CYTHON_ATOMICS __pyx_atomic_store(&cfunc->initialized, 2); #endif } #else #define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 #define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) #endif /* CallUnboundCMethod2.proto */ CYTHON_UNUSED static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); #else #define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) #endif /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* ListAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { Py_INCREF(x); #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 L->ob_item[len] = x; #else PyList_SET_ITEM(list, len, x); #endif __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif /* decode_c_string_utf16.proto */ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 0; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = -1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } /* decode_c_bytes.proto */ static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); /* decode_bytes.proto */ static CYTHON_INLINE PyObject* __Pyx_decode_bytes( PyObject* string, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { char* as_c_string; Py_ssize_t size; #if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE as_c_string = PyBytes_AS_STRING(string); size = PyBytes_GET_SIZE(string); #else if (PyBytes_AsStringAndSize(string, &as_c_string, &size) < 0) { return NULL; } #endif return __Pyx_decode_c_bytes( as_c_string, size, start, stop, encoding, errors, decode_func); } /* RejectKeywords.proto */ static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* ArgTypeTest.proto */ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* SwapException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #endif /* GetTopmostException.proto */ #if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); #endif /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyDictVersioning.proto */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS #define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) #define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ (version_var) = __PYX_GET_DICT_VERSION(dict);\ (cache_var) = (value); #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ (VAR) = __pyx_dict_cached_value;\ } else {\ (VAR) = __pyx_dict_cached_value = (LOOKUP);\ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ }\ } static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); #else #define __PYX_GET_DICT_VERSION(dict) (0) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); #endif /* GetModuleGlobalName.proto */ #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) do {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } while(0) #define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ PY_UINT64_T __pyx_dict_version;\ PyObject *__pyx_dict_cached_value;\ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } while(0) static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); #else #define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); #endif /* PyObjectFastCallMethod.proto */ #if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 #define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) #else static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); #endif /* PyObjectCallNoArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* PyObjectGetMethod.proto */ static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); /* PyObjectCallMethod0.proto */ static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); /* ValidateBasesTuple.proto */ #if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); #endif /* PyType_Ready.proto */ CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); /* SetVTable.proto */ static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); /* GetVTable.proto */ static void* __Pyx_GetVtable(PyTypeObject *type); /* MergeVTables.proto */ static int __Pyx_MergeVtables(PyTypeObject *type); /* DelItemOnTypeDict.proto */ static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); #define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) /* SetupReduce.proto */ static int __Pyx_setup_reduce(PyObject* type_obj); /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* ImportDottedModule.proto */ static PyObject *__Pyx_ImportDottedModule(PyObject *name, PyObject *parts_tuple); static PyObject *__Pyx_ImportDottedModule_WalkParts(PyObject *module, PyObject *name, PyObject *parts_tuple); /* GetItemInt.proto */ #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); /* ObjectGetItem.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key); #else #define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) #endif /* CLineInTraceback.proto */ #if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #else #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #endif /* CodeObjectCache.proto */ #if CYTHON_COMPILING_IN_LIMITED_API typedef PyObject __Pyx_CachedCodeObjectType; #else typedef PyCodeObject __Pyx_CachedCodeObjectType; #endif typedef struct { __Pyx_CachedCodeObjectType* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING __pyx_atomic_int_type accessor_count; #endif }; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* GCCDiagnostics.proto */ #if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) #define __Pyx_HAS_GCC_DIAGNOSTIC #endif /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); /* PyObjectVectorCallKwBuilder.proto */ CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); #if CYTHON_VECTORCALL #if PY_VERSION_HEX >= 0x03090000 #define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall #else #define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall #endif #define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); #else #define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict #define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) #define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) #define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_unsigned_short(unsigned short value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_hid_bus_type(hid_bus_type value); /* CIntFromPy.proto */ static CYTHON_INLINE unsigned char __Pyx_PyLong_As_unsigned_char(PyObject *); /* FormatTypeName.proto */ #if CYTHON_COMPILING_IN_LIMITED_API typedef PyObject *__Pyx_TypeName; #define __Pyx_FMT_TYPENAME "%U" #define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 #define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName #else static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); #endif #else // !LIMITED_API typedef const char *__Pyx_TypeName; #define __Pyx_FMT_TYPENAME "%.200s" #define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) #define __Pyx_DECREF_TypeName(obj) #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) #define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); } #endif #define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #ifdef PyExceptionInstance_Check #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) #else #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) #endif /* GetRuntimeVersion.proto */ static unsigned long __Pyx_get_runtime_version(void); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); /* MultiPhaseInitModuleState.proto */ #if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE static PyObject *__Pyx_State_FindModule(void*); static int __Pyx_State_AddModule(PyObject* module, void*); static int __Pyx_State_RemoveModule(void*); #elif CYTHON_USE_MODULE_STATE #define __Pyx_State_FindModule PyState_FindModule #define __Pyx_State_AddModule PyState_AddModule #define __Pyx_State_RemoveModule PyState_RemoveModule #endif /* #### Code section: module_declarations ### */ /* CythonABIVersion.proto */ #if CYTHON_COMPILING_IN_LIMITED_API #if CYTHON_METH_FASTCALL #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" #else #define __PYX_FASTCALL_ABI_SUFFIX #endif #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX #else #define __PYX_LIMITED_ABI_SUFFIX #endif #if __PYX_HAS_PY_AM_SEND == 1 #define __PYX_AM_SEND_ABI_SUFFIX #elif __PYX_HAS_PY_AM_SEND == 2 #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" #else #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" #endif #ifndef __PYX_MONITORING_ABI_SUFFIX #define __PYX_MONITORING_ABI_SUFFIX #endif #if CYTHON_USE_TP_FINALIZE #define __PYX_TP_FINALIZE_ABI_SUFFIX #else #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" #endif #if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) #define __PYX_FREELISTS_ABI_SUFFIX #else #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" #endif #define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX #define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI #define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." static PyObject *__pyx_f_3hid_7_closer_wrap(hid_device *__pyx_v_ptr); /* proto*/ /* Module declarations from "libc.stddef" */ /* Module declarations from "chid" */ /* Module declarations from "hid" */ static PyObject *__pyx_f_3hid_U(wchar_t *); /*proto*/ static PyObject *__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*)(void)); /*proto*/ /* #### Code section: typeinfo ### */ /* #### Code section: before_global_var ### */ #define __Pyx_MODULE_NAME "hid" extern int __pyx_module_is_main_hid; int __pyx_module_is_main_hid = 0; /* Implementation of "hid" */ /* #### Code section: global_var ### */ static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_IOError; static PyObject *__pyx_builtin_map; /* #### Code section: string_decls ### */ static const char __pyx_k_[] = ""; static const char __pyx_k_Q[] = "\200\001\330\004\n\210+\220Q"; static const char __pyx_k_c[] = "c"; static const char __pyx_k_n[] = "n"; static const char __pyx_k_r[] = "r"; static const char __pyx_k_v[] = "v"; static const char __pyx_k__2[] = "?"; static const char __pyx_k_gc[] = "gc"; static const char __pyx_k_A_a[] = "\200A\330\010\021\220\021\220$\220a"; static const char __pyx_k_A_q[] = "\200A\340\010\017\210q\220\001"; static const char __pyx_k_chr[] = "chr"; static const char __pyx_k_hid[] = "hid"; static const char __pyx_k_map[] = "map"; static const char __pyx_k_pop[] = "pop"; static const char __pyx_k_res[] = "res"; static const char __pyx_k_sys[] = "sys"; static const char __pyx_k_buff[] = "buff"; static const char __pyx_k_func[] = "__func__"; static const char __pyx_k_info[] = "info"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_name[] = "__name__"; static const char __pyx_k_open[] = "open"; static const char __pyx_k_path[] = "path"; static const char __pyx_k_read[] = "read"; static const char __pyx_k_self[] = "self"; static const char __pyx_k_spec[] = "__spec__"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_wrap[] = "wrap"; static const char __pyx_k_G_WAQ[] = "\200\001\360\014\000\005\r\210G\220?\240#\240W\250A\250Q"; static const char __pyx_k_c_hid[] = "c_hid"; static const char __pyx_k_cbuff[] = "cbuff"; static const char __pyx_k_close[] = "close"; static const char __pyx_k_error[] = "error"; static const char __pyx_k_index[] = "index"; static const char __pyx_k_lbuff[] = "lbuff"; static const char __pyx_k_usage[] = "usage"; static const char __pyx_k_write[] = "write"; static const char __pyx_k_0_15_0[] = "0.15.0"; static const char __pyx_k_closer[] = "_closer"; static const char __pyx_k_detach[] = "detach"; static const char __pyx_k_device[] = "device"; static const char __pyx_k_enable[] = "enable"; static const char __pyx_k_module[] = "__module__"; static const char __pyx_k_reduce[] = "__reduce__"; static const char __pyx_k_result[] = "result"; static const char __pyx_k_A_q_9AT[] = "\200A\360\016\000\t\020\210q\220\001\220\032\2309\240A\240T\250\021"; static const char __pyx_k_IOError[] = "IOError"; static const char __pyx_k_c_index[] = "c_index"; static const char __pyx_k_disable[] = "disable"; static const char __pyx_k_hid_pyx[] = "hid.pyx"; static const char __pyx_k_modules[] = "modules"; static const char __pyx_k_version[] = "__version__"; static const char __pyx_k_weakref[] = "weakref"; static const char __pyx_k_add_note[] = "add_note"; static const char __pyx_k_bus_type[] = "bus_type"; static const char __pyx_k_finalize[] = "finalize"; static const char __pyx_k_getstate[] = "__getstate__"; static const char __pyx_k_not_open[] = "not open"; static const char __pyx_k_qualname[] = "__qualname__"; static const char __pyx_k_set_name[] = "__set_name__"; static const char __pyx_k_setstate[] = "__setstate__"; static const char __pyx_k_TypeError[] = "TypeError"; static const char __pyx_k_enumerate[] = "enumerate"; static const char __pyx_k_isenabled[] = "isenabled"; static const char __pyx_k_open_path[] = "open_path"; static const char __pyx_k_pyx_state[] = "__pyx_state"; static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; static const char __pyx_k_vendor_id[] = "vendor_id"; static const char __pyx_k_A_4xs_q_wa[] = "\200A\360\n\000\t\014\2104\210x\220s\230!\330\014\020\220\007\220q\330\014\020\220\007\220w\230a\330\014\020\220\n\230!"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_c_buff_len[] = "c_buff_len"; static const char __pyx_k_max_length[] = "max_length"; static const char __pyx_k_product_id[] = "product_id"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_read_error[] = "read error"; static const char __pyx_k_report_num[] = "report_num"; static const char __pyx_k_serial_len[] = "serial_len"; static const char __pyx_k_timeout_ms[] = "timeout_ms"; static const char __pyx_k_usage_page[] = "usage_page"; static const char __pyx_k_A_4xs_AQ_4y[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\330\010\017\320\017\"\240!\2404\240y\260\001"; static const char __pyx_k_MemoryError[] = "MemoryError"; static const char __pyx_k_cfunc_to_py[] = "cfunc.to_py"; static const char __pyx_k_device_open[] = "device.open"; static const char __pyx_k_device_read[] = "device.read"; static const char __pyx_k_open_failed[] = "open failed"; static const char __pyx_k_version_str[] = "version_str"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_already_open[] = "already open"; static const char __pyx_k_c_max_length[] = "c_max_length"; static const char __pyx_k_c_timeout_ms[] = "c_timeout_ms"; static const char __pyx_k_closer_close[] = "_closer.close"; static const char __pyx_k_device_close[] = "device.close"; static const char __pyx_k_device_error[] = "device.error"; static const char __pyx_k_device_write[] = "device.write"; static const char __pyx_k_initializing[] = "_initializing"; static const char __pyx_k_is_coroutine[] = "_is_coroutine"; static const char __pyx_k_stringsource[] = ""; static const char __pyx_k_version_info[] = "version_info"; static const char __pyx_k_class_getitem[] = "__class_getitem__"; static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; static const char __pyx_k_serial_number[] = "serial_number"; static const char __pyx_k_cserial_number[] = "cserial_number"; static const char __pyx_k_product_string[] = "product_string"; static const char __pyx_k_release_number[] = "release_number"; static const char __pyx_k_set_nonblocking[] = "set_nonblocking"; static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; static const char __pyx_k_device_open_path[] = "device.open_path"; static const char __pyx_k_get_input_report[] = "get_input_report"; static const char __pyx_k_interface_number[] = "interface_number"; static const char __pyx_k_asyncio_coroutines[] = "asyncio.coroutines"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_get_feature_report[] = "get_feature_report"; static const char __pyx_k_get_indexed_string[] = "get_indexed_string"; static const char __pyx_k_get_product_string[] = "get_product_string"; static const char __pyx_k_A_4xs_AQ_1D_q_2Rq_q[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\340\010\025\320\025+\2501\250D\260\t\270\026\270q\330\010\013\2102\210R\210q\330\014\022\220'\230\021\230!\330\010\017\210q\220\001\220\021"; static const char __pyx_k_A_4xs_AQ_Q_1D_2Rq_q[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\340\010%\240Q\330\010\025\320\025+\2501\250D\260\t\270\031\300&\310\001\330\010\013\2102\210R\210q\330\014\022\220'\230\021\230!\330\010\017\210q\220\001\220\021"; static const char __pyx_k_manufacturer_string[] = "manufacturer_string"; static const char __pyx_k_send_feature_report[] = "send_feature_report"; static const char __pyx_k_A_4xs_AQ_0_YfA_2Rq_q[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\340\010\025\320\0250\260\001\260\024\260Y\270f\300A\330\010\013\2102\210R\210q\330\014\022\220'\230\021\230!\330\010\017\210q\220\001\220\021"; static const char __pyx_k_A_4xs_AQ_1_ivQ_2Rq_q[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\340\010\025\320\0251\260\021\260$\260i\270v\300Q\330\010\013\2102\210R\210q\330\014\022\220'\230\021\230!\330\010\017\210q\220\001\220\021"; static const char __pyx_k_get_report_descriptor[] = "get_report_descriptor"; static const char __pyx_k_A_4xs_AQ_a_q_2Rq_t1E_1[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\360\006\000\t#\240$\240a\340\r\016\330\014\020\320\020)\250\021\250'\260\027\270\007\270q\330\010\013\2102\210R\210q\330\014\022\220'\230\021\230!\330\010\017\210t\2201\220E\230\022\2301"; static const char __pyx_k_closer___reduce_cython[] = "_closer.__reduce_cython__"; static const char __pyx_k_device___reduce_cython[] = "device.__reduce_cython__"; static const char __pyx_k_device_set_nonblocking[] = "device.set_nonblocking"; static const char __pyx_k_device_get_input_report[] = "device.get_input_report"; static const char __pyx_k_get_manufacturer_string[] = "get_manufacturer_string"; static const char __pyx_k_closer___setstate_cython[] = "_closer.__setstate_cython__"; static const char __pyx_k_device___setstate_cython[] = "device.__setstate_cython__"; static const char __pyx_k_get_indexed_string_error[] = "get indexed string error"; static const char __pyx_k_get_product_string_error[] = "get product string error"; static const char __pyx_k_get_serial_number_string[] = "get_serial_number_string"; static const char __pyx_k_device_get_feature_report[] = "device.get_feature_report"; static const char __pyx_k_device_get_indexed_string[] = "device.get_indexed_string"; static const char __pyx_k_device_get_product_string[] = "device.get_product_string"; static const char __pyx_k_device_send_feature_report[] = "device.send_feature_report"; static const char __pyx_k_device_get_report_descriptor[] = "device.get_report_descriptor"; static const char __pyx_k_invalid_serial_number_string[] = "invalid serial number string"; static const char __pyx_k_A_1_4xs_aq_Jm1A_4xs_JgYa_E_ha[] = "\200A\360\016\000\t\034\2301\330\010\013\2104\210x\220s\230!\330\014\022\220,\230a\230q\330\010\014\210J\220m\2401\240A\330\010\013\2104\210x\220s\230!\330\014\022\220'\230\021\230!\330\010\014\210J\220g\230Y\240a\240}\260E\270\021\270$\270h\300a"; static const char __pyx_k_get_manufacturer_string_error[] = "get manufacturer string error"; static const char __pyx_k_2_4xs_AQ_1_a_Q_q_A_Q_q_r_Q_gQa[] = "\320\0042\260!\360\024\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\360\006\000\t$\2401\330\010 \240\001\330\010\"\240$\240a\330\010\t\330\014\017\210{\230#\230Q\330\020\030\230\001\340\020\030\320\030)\250\026\250q\260\001\330\014\017\210{\230\"\230A\330\025\026\330\024\030\320\030(\250\001\250\027\260\007\260~\300Q\340\025\026\330\024\030\230\010\240\001\240\027\250\007\250q\330\014\017\210r\220\024\220Q\330\020\026\220g\230Q\230a\330\014\022\220$\220a\220u\230B\230a\340\014\017\210{\230\"\230A\330\020\024\220A\220Q\330\010\017\210q"; static const char __pyx_k_Pyx_CFunc_4chid_int__lParen__r[] = "__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_..wrap"; static const char __pyx_k_device_get_manufacturer_string[] = "device.get_manufacturer_string"; static const char __pyx_k_get_serial_number_string_error[] = "get serial number string error"; static const char __pyx_k_q0_A_a_7_AQ_1_Qaq_aq_1AQa_aq_1[] = "\200\016\320\016\037\230q\3600\000\n\013\330\010\017\210}\230A\230[\250\001\330\004\036\230a\330\004\n\210!\330\004\n\210!\330\010\013\2107\220!\330\014\024\220A\220Q\330\014\031\230\021\230!\330\014\032\230!\2301\330\014\035\230Q\230a\230q\240\001\330\014\036\230a\230q\330\014#\2401\240A\240Q\240a\330\014\036\230a\230q\240\001\240\021\330\014\032\230!\2301\330\014\025\220Q\220a\330\014 \240\001\240\021\330\014\030\230\001\230\021\340\010\014\210A\210Q\330\004\030\230\001\230\021\330\004\013\2101"; static const char __pyx_k_33LA_4xs_aq_WA_S_6_2B_ZqPQ_Q_Qo[] = "\320\004!\320!3\3203L\310A\360\026\000\t)\250\001\360\006\000\t\014\2104\210x\220s\230!\330\014\022\220,\230a\230q\330\010\t\330\014\017\210~\230W\240A\330\020\035\230S\240\001\240\021\330\020!\240\032\2506\260\021\3202B\300#\300Z\310q\320PQ\330\020\023\220?\240#\240Q\330\024\025\330\020\031\320\031-\250Q\250o\320=M\310Q\330\020\023\2207\230$\230a\330\024\032\230*\240A\240Q\330\020\036\230a\230~\250Q\330\014\020\220\n\230(\240!\240;\250l\270!\340\014\017\210\177\230c\240\021\330\020\024\220A\220Q\330\010\013\2104\210x\220s\230!\330\014\022\220'\230\021\230!\330\010\014\210J\220g\230Y\240a\240}\260E\270\021\270$\270h\300a"; static const char __pyx_k_device_get_serial_number_string[] = "device.get_serial_number_string"; static const char __pyx_k_self__c_hid_cannot_be_converted[] = "self._c_hid cannot be converted to a Python object for pickling"; static const char __pyx_k_A_4xs_AQ_3nCs_2U_3auA_5_a_A_AQ_A[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\340\010\013\2103\210n\230C\230s\240!\330\014\023\2202\220U\230!\2303\230a\230u\240A\340\014\023\2205\230\001\230\021\330\010\"\240$\240a\330\010$\240A\330\010!\240\023\240A\240Q\340\r\016\330\014\025\320\025,\250A\250W\260G\2701\330\010\017\210q"; static const char __pyx_k_A_4xs_AQ_3nCs_2U_3auA_5_a_A_AQ_Y[] = "\200A\360\020\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\340\010\013\2103\210n\230C\230s\240!\330\014\023\2202\220U\230!\2303\230a\230u\240A\340\014\023\2205\230\001\230\021\330\010\"\240$\240a\330\010$\240A\330\010!\240\023\240A\240Q\340\r\016\330\014\025\220Y\230a\230w\240g\250Q\330\010\017\210q"; static const char __pyx_k_A_4xs_AQ_a_1_Q_q_q_7_r_1_gQa_auB[] = "\200A\360\030\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\330\010\"\240$\240a\360\006\000\t$\2401\340\010\t\330\014\017\210{\230#\230Q\330\020\030\230\001\340\020\030\320\030)\250\026\250q\260\001\330\014\021\220\021\220%\220q\330\021\022\330\020\024\320\024*\250!\2507\260'\270\021\330\014\017\210r\220\022\2201\330\020\026\220g\230Q\230a\330\014\022\220$\220a\220u\230B\230a\340\014\017\210{\230\"\230A\330\020\024\220A\220Q\330\010\017\210q"; static const char __pyx_k_A_4xs_AQ_a_1_Q_q_q_q_r_1_gQa_auB[] = "\200A\360\030\000\t\014\2104\210x\220s\230!\330\014\022\220*\230A\230Q\330\010\"\240$\240a\360\006\000\t$\2401\340\010\t\330\014\017\210{\230#\230Q\330\020\030\230\001\340\020\030\320\030)\250\026\250q\260\001\330\014\021\220\021\220%\220q\330\021\022\330\020\024\320\024(\250\001\250\027\260\007\260q\330\014\017\210r\220\022\2201\330\020\026\220g\230Q\230a\330\014\022\220$\220a\220u\230B\230a\340\014\017\210{\230\"\230A\330\020\024\220A\220Q\330\010\017\210q"; static const char __pyx_k_Note_that_Cython_is_deliberately[] = "Note that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False."; static const char __pyx_k_self__ptr_cannot_be_converted_to[] = "self._ptr cannot be converted to a Python object for pickling"; /* #### Code section: decls ### */ static PyObject *__pyx_pf_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__wrap(PyObject *__pyx_self); /* proto */ static PyObject *__pyx_pf_3hid_enumerate(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_vendor_id, int __pyx_v_product_id); /* proto */ static PyObject *__pyx_pf_3hid_2version_str(CYTHON_UNUSED PyObject *__pyx_self); /* proto */ static PyObject *__pyx_pf_3hid_7_closer_close(struct __pyx_obj_3hid__closer *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_7_closer_2__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_3hid__closer *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_7_closer_4__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_3hid__closer *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_pf_3hid_6device_open(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_vendor_id, int __pyx_v_product_id, PyObject *__pyx_v_serial_number); /* proto */ static PyObject *__pyx_pf_3hid_6device_2open_path(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_path); /* proto */ static PyObject *__pyx_pf_3hid_6device_4close(struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_6write(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_buff); /* proto */ static PyObject *__pyx_pf_3hid_6device_8set_nonblocking(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_v); /* proto */ static PyObject *__pyx_pf_3hid_6device_10read(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_max_length, int __pyx_v_timeout_ms); /* proto */ static PyObject *__pyx_pf_3hid_6device_12get_manufacturer_string(struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_14get_product_string(struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_16get_serial_number_string(struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_18get_indexed_string(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ static PyObject *__pyx_pf_3hid_6device_20send_feature_report(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_buff); /* proto */ static PyObject *__pyx_pf_3hid_6device_22get_report_descriptor(struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_24get_feature_report(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_report_num, int __pyx_v_max_length); /* proto */ static PyObject *__pyx_pf_3hid_6device_26get_input_report(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_report_num, int __pyx_v_max_length); /* proto */ static PyObject *__pyx_pf_3hid_6device_28error(struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_30__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_3hid_device *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_3hid_6device_32__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_3hid_device *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_tp_new_3hid__closer(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_3hid_device(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ /* #### Code section: late_includes ### */ /* #### Code section: module_state ### */ /* SmallCodeConfig */ #ifndef CYTHON_SMALL_CODE #if defined(__clang__) #define CYTHON_SMALL_CODE #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define CYTHON_SMALL_CODE __attribute__((cold)) #else #define CYTHON_SMALL_CODE #endif #endif typedef struct { PyObject *__pyx_d; PyObject *__pyx_b; PyObject *__pyx_cython_runtime; PyObject *__pyx_empty_tuple; PyObject *__pyx_empty_bytes; PyObject *__pyx_empty_unicode; #ifdef __Pyx_CyFunction_USED PyTypeObject *__pyx_CyFunctionType; #endif #ifdef __Pyx_FusedFunction_USED PyTypeObject *__pyx_FusedFunctionType; #endif #ifdef __Pyx_Generator_USED PyTypeObject *__pyx_GeneratorType; #endif #ifdef __Pyx_IterableCoroutine_USED PyTypeObject *__pyx_IterableCoroutineType; #endif #ifdef __Pyx_Coroutine_USED PyTypeObject *__pyx_CoroutineAwaitType; #endif #ifdef __Pyx_Coroutine_USED PyTypeObject *__pyx_CoroutineType; #endif PyObject *__pyx_type_3hid__closer; PyObject *__pyx_type_3hid_device; PyObject *__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_; PyTypeObject *__pyx_ptype_3hid__closer; PyTypeObject *__pyx_ptype_3hid_device; PyTypeObject *__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_; __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; PyObject *__pyx_tuple[3]; PyObject *__pyx_codeobj_tab[23]; PyObject *__pyx_string_tab[134]; PyObject *__pyx_int_0; PyObject *__pyx_int_3; /* #### Code section: module_state_contents ### */ /* CommonTypesMetaclass.module_state_decls */ PyTypeObject *__pyx_CommonTypesMetaclassType; /* CachedMethodType.module_state_decls */ #if CYTHON_COMPILING_IN_LIMITED_API PyObject *__Pyx_CachedMethodType; #endif #if CYTHON_USE_FREELISTS struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *__pyx_freelist___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_[8]; int __pyx_freecount___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_; #endif /* CodeObjectCache.module_state_decls */ struct __Pyx_CodeObjectCache __pyx_code_cache; /* #### Code section: module_state_end ### */ } __pyx_mstatetype; #if CYTHON_USE_MODULE_STATE #ifdef __cplusplus namespace { extern struct PyModuleDef __pyx_moduledef; } /* anonymous namespace */ #else static struct PyModuleDef __pyx_moduledef; #endif #define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) #define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) #else static __pyx_mstatetype __pyx_mstate_global_static = #ifdef __cplusplus {}; #else {0}; #endif static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; #endif /* #### Code section: constant_name_defines ### */ #define __pyx_kp_u_ __pyx_string_tab[0] #define __pyx_kp_u_0_15_0 __pyx_string_tab[1] #define __pyx_n_u_IOError __pyx_string_tab[2] #define __pyx_n_u_MemoryError __pyx_string_tab[3] #define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[4] #define __pyx_n_u_Pyx_CFunc_4chid_int__lParen__r __pyx_string_tab[5] #define __pyx_n_u_RuntimeError __pyx_string_tab[6] #define __pyx_n_u_TypeError __pyx_string_tab[7] #define __pyx_n_u_ValueError __pyx_string_tab[8] #define __pyx_kp_u__2 __pyx_string_tab[9] #define __pyx_kp_u_add_note __pyx_string_tab[10] #define __pyx_kp_u_already_open __pyx_string_tab[11] #define __pyx_n_u_asyncio_coroutines __pyx_string_tab[12] #define __pyx_n_u_buff __pyx_string_tab[13] #define __pyx_n_u_bus_type __pyx_string_tab[14] #define __pyx_n_u_c __pyx_string_tab[15] #define __pyx_n_u_c_buff_len __pyx_string_tab[16] #define __pyx_n_u_c_hid __pyx_string_tab[17] #define __pyx_n_u_c_index __pyx_string_tab[18] #define __pyx_n_u_c_max_length __pyx_string_tab[19] #define __pyx_n_u_c_timeout_ms __pyx_string_tab[20] #define __pyx_n_u_cbuff __pyx_string_tab[21] #define __pyx_n_u_cfunc_to_py __pyx_string_tab[22] #define __pyx_n_u_chr __pyx_string_tab[23] #define __pyx_n_u_class_getitem __pyx_string_tab[24] #define __pyx_n_u_cline_in_traceback __pyx_string_tab[25] #define __pyx_n_u_close __pyx_string_tab[26] #define __pyx_n_u_closer __pyx_string_tab[27] #define __pyx_n_u_closer___reduce_cython __pyx_string_tab[28] #define __pyx_n_u_closer___setstate_cython __pyx_string_tab[29] #define __pyx_n_u_closer_close __pyx_string_tab[30] #define __pyx_n_u_cserial_number __pyx_string_tab[31] #define __pyx_n_u_detach __pyx_string_tab[32] #define __pyx_n_u_device __pyx_string_tab[33] #define __pyx_n_u_device___reduce_cython __pyx_string_tab[34] #define __pyx_n_u_device___setstate_cython __pyx_string_tab[35] #define __pyx_n_u_device_close __pyx_string_tab[36] #define __pyx_n_u_device_error __pyx_string_tab[37] #define __pyx_n_u_device_get_feature_report __pyx_string_tab[38] #define __pyx_n_u_device_get_indexed_string __pyx_string_tab[39] #define __pyx_n_u_device_get_input_report __pyx_string_tab[40] #define __pyx_n_u_device_get_manufacturer_string __pyx_string_tab[41] #define __pyx_n_u_device_get_product_string __pyx_string_tab[42] #define __pyx_n_u_device_get_report_descriptor __pyx_string_tab[43] #define __pyx_n_u_device_get_serial_number_string __pyx_string_tab[44] #define __pyx_n_u_device_open __pyx_string_tab[45] #define __pyx_n_u_device_open_path __pyx_string_tab[46] #define __pyx_n_u_device_read __pyx_string_tab[47] #define __pyx_n_u_device_send_feature_report __pyx_string_tab[48] #define __pyx_n_u_device_set_nonblocking __pyx_string_tab[49] #define __pyx_n_u_device_write __pyx_string_tab[50] #define __pyx_kp_u_disable __pyx_string_tab[51] #define __pyx_kp_u_enable __pyx_string_tab[52] #define __pyx_n_u_enumerate __pyx_string_tab[53] #define __pyx_n_u_error __pyx_string_tab[54] #define __pyx_n_u_finalize __pyx_string_tab[55] #define __pyx_n_u_func __pyx_string_tab[56] #define __pyx_kp_u_gc __pyx_string_tab[57] #define __pyx_n_u_get_feature_report __pyx_string_tab[58] #define __pyx_n_u_get_indexed_string __pyx_string_tab[59] #define __pyx_kp_u_get_indexed_string_error __pyx_string_tab[60] #define __pyx_n_u_get_input_report __pyx_string_tab[61] #define __pyx_n_u_get_manufacturer_string __pyx_string_tab[62] #define __pyx_kp_u_get_manufacturer_string_error __pyx_string_tab[63] #define __pyx_n_u_get_product_string __pyx_string_tab[64] #define __pyx_kp_u_get_product_string_error __pyx_string_tab[65] #define __pyx_n_u_get_report_descriptor __pyx_string_tab[66] #define __pyx_n_u_get_serial_number_string __pyx_string_tab[67] #define __pyx_kp_u_get_serial_number_string_error __pyx_string_tab[68] #define __pyx_n_u_getstate __pyx_string_tab[69] #define __pyx_n_u_hid __pyx_string_tab[70] #define __pyx_kp_u_hid_pyx __pyx_string_tab[71] #define __pyx_n_u_index __pyx_string_tab[72] #define __pyx_n_u_info __pyx_string_tab[73] #define __pyx_n_u_initializing __pyx_string_tab[74] #define __pyx_n_u_interface_number __pyx_string_tab[75] #define __pyx_kp_u_invalid_serial_number_string __pyx_string_tab[76] #define __pyx_n_u_is_coroutine __pyx_string_tab[77] #define __pyx_kp_u_isenabled __pyx_string_tab[78] #define __pyx_n_u_lbuff __pyx_string_tab[79] #define __pyx_n_u_main __pyx_string_tab[80] #define __pyx_n_u_manufacturer_string __pyx_string_tab[81] #define __pyx_n_u_map __pyx_string_tab[82] #define __pyx_n_u_max_length __pyx_string_tab[83] #define __pyx_n_u_module __pyx_string_tab[84] #define __pyx_n_u_modules __pyx_string_tab[85] #define __pyx_n_u_n __pyx_string_tab[86] #define __pyx_n_u_name __pyx_string_tab[87] #define __pyx_kp_u_not_open __pyx_string_tab[88] #define __pyx_n_u_open __pyx_string_tab[89] #define __pyx_kp_u_open_failed __pyx_string_tab[90] #define __pyx_n_u_open_path __pyx_string_tab[91] #define __pyx_n_u_path __pyx_string_tab[92] #define __pyx_n_u_pop __pyx_string_tab[93] #define __pyx_n_u_product_id __pyx_string_tab[94] #define __pyx_n_u_product_string __pyx_string_tab[95] #define __pyx_n_u_pyx_state __pyx_string_tab[96] #define __pyx_n_u_pyx_vtable __pyx_string_tab[97] #define __pyx_n_u_qualname __pyx_string_tab[98] #define __pyx_n_u_r __pyx_string_tab[99] #define __pyx_n_u_read __pyx_string_tab[100] #define __pyx_kp_u_read_error __pyx_string_tab[101] #define __pyx_n_u_reduce __pyx_string_tab[102] #define __pyx_n_u_reduce_cython __pyx_string_tab[103] #define __pyx_n_u_reduce_ex __pyx_string_tab[104] #define __pyx_n_u_release_number __pyx_string_tab[105] #define __pyx_n_u_report_num __pyx_string_tab[106] #define __pyx_n_u_res __pyx_string_tab[107] #define __pyx_n_u_result __pyx_string_tab[108] #define __pyx_n_u_self __pyx_string_tab[109] #define __pyx_kp_u_self__c_hid_cannot_be_converted __pyx_string_tab[110] #define __pyx_kp_u_self__ptr_cannot_be_converted_to __pyx_string_tab[111] #define __pyx_n_u_send_feature_report __pyx_string_tab[112] #define __pyx_n_u_serial_len __pyx_string_tab[113] #define __pyx_n_u_serial_number __pyx_string_tab[114] #define __pyx_n_u_set_name __pyx_string_tab[115] #define __pyx_n_u_set_nonblocking __pyx_string_tab[116] #define __pyx_n_u_setstate __pyx_string_tab[117] #define __pyx_n_u_setstate_cython __pyx_string_tab[118] #define __pyx_n_u_spec __pyx_string_tab[119] #define __pyx_kp_u_stringsource __pyx_string_tab[120] #define __pyx_n_u_sys __pyx_string_tab[121] #define __pyx_n_u_test __pyx_string_tab[122] #define __pyx_n_u_timeout_ms __pyx_string_tab[123] #define __pyx_n_u_usage __pyx_string_tab[124] #define __pyx_n_u_usage_page __pyx_string_tab[125] #define __pyx_n_u_v __pyx_string_tab[126] #define __pyx_n_u_vendor_id __pyx_string_tab[127] #define __pyx_n_u_version __pyx_string_tab[128] #define __pyx_n_u_version_info __pyx_string_tab[129] #define __pyx_n_u_version_str __pyx_string_tab[130] #define __pyx_n_u_weakref __pyx_string_tab[131] #define __pyx_n_u_wrap __pyx_string_tab[132] #define __pyx_n_u_write __pyx_string_tab[133] /* #### Code section: module_state_clear ### */ #if CYTHON_USE_MODULE_STATE static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); if (!clear_module_state) return 0; Py_CLEAR(clear_module_state->__pyx_d); Py_CLEAR(clear_module_state->__pyx_b); Py_CLEAR(clear_module_state->__pyx_cython_runtime); Py_CLEAR(clear_module_state->__pyx_empty_tuple); Py_CLEAR(clear_module_state->__pyx_empty_bytes); Py_CLEAR(clear_module_state->__pyx_empty_unicode); #ifdef __Pyx_CyFunction_USED Py_CLEAR(clear_module_state->__pyx_CyFunctionType); #endif #ifdef __Pyx_FusedFunction_USED Py_CLEAR(clear_module_state->__pyx_FusedFunctionType); #endif #if CYTHON_PEP489_MULTI_PHASE_INIT __Pyx_State_RemoveModule(NULL); #endif Py_CLEAR(clear_module_state->__pyx_ptype_3hid__closer); Py_CLEAR(clear_module_state->__pyx_type_3hid__closer); Py_CLEAR(clear_module_state->__pyx_ptype_3hid_device); Py_CLEAR(clear_module_state->__pyx_type_3hid_device); Py_CLEAR(clear_module_state->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_); Py_CLEAR(clear_module_state->__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_); for (int i=0; i<3; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } for (int i=0; i<23; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } for (int i=0; i<134; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } Py_CLEAR(clear_module_state->__pyx_int_0); Py_CLEAR(clear_module_state->__pyx_int_3); return 0; } #endif /* #### Code section: module_state_traverse ### */ #if CYTHON_USE_MODULE_STATE static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); if (!traverse_module_state) return 0; Py_VISIT(traverse_module_state->__pyx_d); Py_VISIT(traverse_module_state->__pyx_b); Py_VISIT(traverse_module_state->__pyx_cython_runtime); __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); #ifdef __Pyx_CyFunction_USED Py_VISIT(traverse_module_state->__pyx_CyFunctionType); #endif #ifdef __Pyx_FusedFunction_USED Py_VISIT(traverse_module_state->__pyx_FusedFunctionType); #endif Py_VISIT(traverse_module_state->__pyx_ptype_3hid__closer); Py_VISIT(traverse_module_state->__pyx_type_3hid__closer); Py_VISIT(traverse_module_state->__pyx_ptype_3hid_device); Py_VISIT(traverse_module_state->__pyx_type_3hid_device); Py_VISIT(traverse_module_state->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_); Py_VISIT(traverse_module_state->__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_); for (int i=0; i<3; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } for (int i=0; i<23; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } for (int i=0; i<134; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_0); __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_3); return 0; } #endif /* #### Code section: module_code ### */ /* "cfunc.to_py":67 * @cname("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_") * cdef object __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*f)() except *): * def wrap(): # <<<<<<<<<<<<<< * """wrap() -> 'int'""" * return f() */ /* Python wrapper */ static PyObject *__pyx_pw_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__1wrap(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused); /*proto*/ PyDoc_STRVAR(__pyx_doc_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__wrap, "wrap() -> 'int'"); static PyMethodDef __pyx_mdef_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__1wrap = {"wrap", (PyCFunction)__pyx_pw_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__1wrap, METH_NOARGS, __pyx_doc_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__wrap}; static PyObject *__pyx_pw_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__1wrap(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused) { CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("wrap (wrapper)", 0); __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); __pyx_r = __pyx_pf_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__wrap(__pyx_self); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__wrap(PyObject *__pyx_self) { struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *__pyx_cur_scope; struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *__pyx_outer_scope; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("wrap", 0); __pyx_outer_scope = (struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *) __Pyx_CyFunction_GetClosure(__pyx_self); __pyx_cur_scope = __pyx_outer_scope; /* "cfunc.to_py":69 * def wrap(): * """wrap() -> 'int'""" * return f() # <<<<<<<<<<<<<< * return wrap * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_cur_scope->__pyx_v_f(); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 69, __pyx_L1_error) __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 69, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "cfunc.to_py":67 * @cname("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_") * cdef object __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*f)() except *): * def wrap(): # <<<<<<<<<<<<<< * """wrap() -> 'int'""" * return f() */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("cfunc.to_py.__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_.wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "cfunc.to_py":65 * * * @cname("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_") # <<<<<<<<<<<<<< * cdef object __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*f)() except *): * def wrap(): */ static PyObject *__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*__pyx_v_f)(void)) { struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *__pyx_cur_scope; PyObject *__pyx_v_wrap = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_", 0); __pyx_cur_scope = (struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *)__pyx_tp_new___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(__pyx_mstate_global->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_, __pyx_mstate_global->__pyx_empty_tuple, NULL); if (unlikely(!__pyx_cur_scope)) { __pyx_cur_scope = ((struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *)Py_None); __Pyx_INCREF(Py_None); __PYX_ERR(1, 65, __pyx_L1_error) } else { __Pyx_GOTREF((PyObject *)__pyx_cur_scope); } __pyx_cur_scope->__pyx_v_f = __pyx_v_f; /* "cfunc.to_py":67 * @cname("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_") * cdef object __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*f)() except *): * def wrap(): # <<<<<<<<<<<<<< * """wrap() -> 'int'""" * return f() */ __pyx_t_1 = __Pyx_CyFunction_New(&__pyx_mdef_11cfunc_dot_to_py_52__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__1wrap, 0, __pyx_mstate_global->__pyx_n_u_Pyx_CFunc_4chid_int__lParen__r, ((PyObject*)__pyx_cur_scope), __pyx_mstate_global->__pyx_n_u_cfunc_to_py, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_wrap = __pyx_t_1; __pyx_t_1 = 0; /* "cfunc.to_py":70 * """wrap() -> 'int'""" * return f() * return wrap # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_wrap); __pyx_r = __pyx_v_wrap; goto __pyx_L0; /* "cfunc.to_py":65 * * * @cname("__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_") # <<<<<<<<<<<<<< * cdef object __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(int (*f)() except *): * def wrap(): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("cfunc.to_py.__Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_wrap); __Pyx_DECREF((PyObject *)__pyx_cur_scope); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":25 * Py_ssize_t PyUnicode_AsWideChar(object unicode, wchar_t *w, Py_ssize_t size) * * cdef object U(wchar_t *wcs): # <<<<<<<<<<<<<< * if wcs == NULL: * return '' */ static PyObject *__pyx_f_3hid_U(wchar_t *__pyx_v_wcs) { int __pyx_v_n; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("U", 0); /* "hid.pyx":26 * * cdef object U(wchar_t *wcs): * if wcs == NULL: # <<<<<<<<<<<<<< * return '' * cdef int n = wcslen(wcs) */ __pyx_t_1 = (__pyx_v_wcs == NULL); if (__pyx_t_1) { /* "hid.pyx":27 * cdef object U(wchar_t *wcs): * if wcs == NULL: * return '' # <<<<<<<<<<<<<< * cdef int n = wcslen(wcs) * return PyUnicode_FromWideChar(wcs, n) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_mstate_global->__pyx_kp_u_); __pyx_r = __pyx_mstate_global->__pyx_kp_u_; goto __pyx_L0; /* "hid.pyx":26 * * cdef object U(wchar_t *wcs): * if wcs == NULL: # <<<<<<<<<<<<<< * return '' * cdef int n = wcslen(wcs) */ } /* "hid.pyx":28 * if wcs == NULL: * return '' * cdef int n = wcslen(wcs) # <<<<<<<<<<<<<< * return PyUnicode_FromWideChar(wcs, n) * */ __pyx_v_n = wcslen(__pyx_v_wcs); /* "hid.pyx":29 * return '' * cdef int n = wcslen(wcs) * return PyUnicode_FromWideChar(wcs, n) # <<<<<<<<<<<<<< * * def enumerate(int vendor_id=0, int product_id=0): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyUnicode_FromWideChar(__pyx_v_wcs, __pyx_v_n); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 29, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":25 * Py_ssize_t PyUnicode_AsWideChar(object unicode, wchar_t *w, Py_ssize_t size) * * cdef object U(wchar_t *wcs): # <<<<<<<<<<<<<< * if wcs == NULL: * return '' */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("hid.U", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":31 * return PyUnicode_FromWideChar(wcs, n) * * def enumerate(int vendor_id=0, int product_id=0): # <<<<<<<<<<<<<< * """Return a list of discovered HID devices. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_1enumerate(PyObject *__pyx_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_enumerate, "Return a list of discovered HID devices.\n\n The fields of dict are:\n\n - 'path'\n - 'vendor_id'\n - 'product_id'\n - 'serial_number'\n - 'release_number'\n - 'manufacturer_string'\n - 'product_string'\n - 'usage_page'\n - 'usage'\n - 'interface_number'\n\n :param vendor_id: Vendor id to look for, default = 0\n :type vendor_id: int, optional\n :param product_id: Product id to look for, default = 0\n :type product_id: int, optional\n :return: List of device dictionaries\n :rtype: List[Dict]\n "); static PyMethodDef __pyx_mdef_3hid_1enumerate = {"enumerate", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_1enumerate, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_enumerate}; static PyObject *__pyx_pw_3hid_1enumerate(PyObject *__pyx_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { int __pyx_v_vendor_id; int __pyx_v_product_id; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[2] = {0,0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("enumerate (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_vendor_id,&__pyx_mstate_global->__pyx_n_u_product_id,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 31, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 31, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 31, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "enumerate", 0) < 0) __PYX_ERR(0, 31, __pyx_L3_error) } else { switch (__pyx_nargs) { case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 31, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 31, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } } if (values[0]) { __pyx_v_vendor_id = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_vendor_id == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 31, __pyx_L3_error) } else { __pyx_v_vendor_id = ((int)((int)0)); } if (values[1]) { __pyx_v_product_id = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_product_id == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 31, __pyx_L3_error) } else { __pyx_v_product_id = ((int)((int)0)); } } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("enumerate", 0, 0, 2, __pyx_nargs); __PYX_ERR(0, 31, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.enumerate", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_enumerate(__pyx_self, __pyx_v_vendor_id, __pyx_v_product_id); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_enumerate(CYTHON_UNUSED PyObject *__pyx_self, int __pyx_v_vendor_id, int __pyx_v_product_id) { struct hid_device_info *__pyx_v_info; struct hid_device_info *__pyx_v_c; PyObject *__pyx_v_res = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; struct hid_device_info *__pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("enumerate", 0); /* "hid.pyx":55 * """ * cdef hid_device_info* info * with nogil: # <<<<<<<<<<<<<< * info = hid_enumerate(vendor_id, product_id) * cdef hid_device_info* c = info */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":56 * cdef hid_device_info* info * with nogil: * info = hid_enumerate(vendor_id, product_id) # <<<<<<<<<<<<<< * cdef hid_device_info* c = info * res = [] */ __pyx_v_info = hid_enumerate(__pyx_v_vendor_id, __pyx_v_product_id); } /* "hid.pyx":55 * """ * cdef hid_device_info* info * with nogil: # <<<<<<<<<<<<<< * info = hid_enumerate(vendor_id, product_id) * cdef hid_device_info* c = info */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L5; } __pyx_L5:; } } /* "hid.pyx":57 * with nogil: * info = hid_enumerate(vendor_id, product_id) * cdef hid_device_info* c = info # <<<<<<<<<<<<<< * res = [] * while c: */ __pyx_v_c = __pyx_v_info; /* "hid.pyx":58 * info = hid_enumerate(vendor_id, product_id) * cdef hid_device_info* c = info * res = [] # <<<<<<<<<<<<<< * while c: * res.append({ */ __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 58, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_res = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "hid.pyx":59 * cdef hid_device_info* c = info * res = [] * while c: # <<<<<<<<<<<<<< * res.append({ * 'path': c.path, */ while (1) { __pyx_t_2 = (__pyx_v_c != 0); if (!__pyx_t_2) break; /* "hid.pyx":61 * while c: * res.append({ * 'path': c.path, # <<<<<<<<<<<<<< * 'vendor_id': c.vendor_id, * 'product_id': c.product_id, */ __pyx_t_1 = __Pyx_PyDict_NewPresized(11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_c->path); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_path, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":62 * res.append({ * 'path': c.path, * 'vendor_id': c.vendor_id, # <<<<<<<<<<<<<< * 'product_id': c.product_id, * 'serial_number': U(c.serial_number), */ __pyx_t_3 = __Pyx_PyLong_From_unsigned_short(__pyx_v_c->vendor_id); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 62, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_vendor_id, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":63 * 'path': c.path, * 'vendor_id': c.vendor_id, * 'product_id': c.product_id, # <<<<<<<<<<<<<< * 'serial_number': U(c.serial_number), * 'release_number': c.release_number, */ __pyx_t_3 = __Pyx_PyLong_From_unsigned_short(__pyx_v_c->product_id); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 63, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_product_id, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":64 * 'vendor_id': c.vendor_id, * 'product_id': c.product_id, * 'serial_number': U(c.serial_number), # <<<<<<<<<<<<<< * 'release_number': c.release_number, * 'manufacturer_string': U(c.manufacturer_string), */ __pyx_t_3 = __pyx_f_3hid_U(__pyx_v_c->serial_number); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_serial_number, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":65 * 'product_id': c.product_id, * 'serial_number': U(c.serial_number), * 'release_number': c.release_number, # <<<<<<<<<<<<<< * 'manufacturer_string': U(c.manufacturer_string), * 'product_string': U(c.product_string), */ __pyx_t_3 = __Pyx_PyLong_From_unsigned_short(__pyx_v_c->release_number); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_release_number, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":66 * 'serial_number': U(c.serial_number), * 'release_number': c.release_number, * 'manufacturer_string': U(c.manufacturer_string), # <<<<<<<<<<<<<< * 'product_string': U(c.product_string), * 'usage_page': c.usage_page, */ __pyx_t_3 = __pyx_f_3hid_U(__pyx_v_c->manufacturer_string); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_manufacturer_string, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":67 * 'release_number': c.release_number, * 'manufacturer_string': U(c.manufacturer_string), * 'product_string': U(c.product_string), # <<<<<<<<<<<<<< * 'usage_page': c.usage_page, * 'usage': c.usage, */ __pyx_t_3 = __pyx_f_3hid_U(__pyx_v_c->product_string); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_product_string, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":68 * 'manufacturer_string': U(c.manufacturer_string), * 'product_string': U(c.product_string), * 'usage_page': c.usage_page, # <<<<<<<<<<<<<< * 'usage': c.usage, * 'interface_number': c.interface_number, */ __pyx_t_3 = __Pyx_PyLong_From_unsigned_short(__pyx_v_c->usage_page); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_usage_page, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":69 * 'product_string': U(c.product_string), * 'usage_page': c.usage_page, * 'usage': c.usage, # <<<<<<<<<<<<<< * 'interface_number': c.interface_number, * 'bus_type': c.bus_type, */ __pyx_t_3 = __Pyx_PyLong_From_unsigned_short(__pyx_v_c->usage); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_usage, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":70 * 'usage_page': c.usage_page, * 'usage': c.usage, * 'interface_number': c.interface_number, # <<<<<<<<<<<<<< * 'bus_type': c.bus_type, * }) */ __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_c->interface_number); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 70, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_interface_number, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":71 * 'usage': c.usage, * 'interface_number': c.interface_number, * 'bus_type': c.bus_type, # <<<<<<<<<<<<<< * }) * c = c.next */ __pyx_t_3 = __Pyx_PyLong_From_hid_bus_type(__pyx_v_c->bus_type); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_bus_type, __pyx_t_3) < 0) __PYX_ERR(0, 61, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":60 * res = [] * while c: * res.append({ # <<<<<<<<<<<<<< * 'path': c.path, * 'vendor_id': c.vendor_id, */ __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_res, __pyx_t_1); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 60, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "hid.pyx":73 * 'bus_type': c.bus_type, * }) * c = c.next # <<<<<<<<<<<<<< * hid_free_enumeration(info) * return res */ __pyx_t_5 = __pyx_v_c->next; __pyx_v_c = __pyx_t_5; } /* "hid.pyx":74 * }) * c = c.next * hid_free_enumeration(info) # <<<<<<<<<<<<<< * return res * */ hid_free_enumeration(__pyx_v_info); /* "hid.pyx":75 * c = c.next * hid_free_enumeration(info) * return res # <<<<<<<<<<<<<< * * def version_str(): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_res); __pyx_r = __pyx_v_res; goto __pyx_L0; /* "hid.pyx":31 * return PyUnicode_FromWideChar(wcs, n) * * def enumerate(int vendor_id=0, int product_id=0): # <<<<<<<<<<<<<< * """Return a list of discovered HID devices. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("hid.enumerate", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_res); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":77 * return res * * def version_str(): # <<<<<<<<<<<<<< * """Return a runtime version string of the hidapi C library. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_3version_str(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_2version_str, "Return a runtime version string of the hidapi C library.\n\n :return: version string of library\n :rtype: str\n "); static PyMethodDef __pyx_mdef_3hid_3version_str = {"version_str", (PyCFunction)__pyx_pw_3hid_3version_str, METH_NOARGS, __pyx_doc_3hid_2version_str}; static PyObject *__pyx_pw_3hid_3version_str(PyObject *__pyx_self, CYTHON_UNUSED PyObject *unused) { CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("version_str (wrapper)", 0); __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); __pyx_r = __pyx_pf_3hid_2version_str(__pyx_self); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_2version_str(CYTHON_UNUSED PyObject *__pyx_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("version_str", 0); /* "hid.pyx":83 * :rtype: str * """ * return (hid_version_str()).decode('ascii') # <<<<<<<<<<<<<< * * cdef class _closer: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBytes_FromString(hid_version_str()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (unlikely(__pyx_t_1 == Py_None)) { PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); __PYX_ERR(0, 83, __pyx_L1_error) } __pyx_t_2 = __Pyx_decode_bytes(((PyObject*)__pyx_t_1), 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 83, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":77 * return res * * def version_str(): # <<<<<<<<<<<<<< * """Return a runtime version string of the hidapi C library. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("hid.version_str", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":93 * cdef hid_device *_ptr * * @staticmethod # <<<<<<<<<<<<<< * cdef wrap(hid_device *ptr): * cdef _closer closer = _closer() */ static PyObject *__pyx_f_3hid_7_closer_wrap(hid_device *__pyx_v_ptr) { struct __pyx_obj_3hid__closer *__pyx_v_closer = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; size_t __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("wrap", 0); /* "hid.pyx":95 * @staticmethod * cdef wrap(hid_device *ptr): * cdef _closer closer = _closer() # <<<<<<<<<<<<<< * closer._ptr = ptr * return closer */ __pyx_t_2 = NULL; __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_3hid__closer); __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_3hid__closer); __pyx_t_4 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 95, __pyx_L1_error) __Pyx_GOTREF((PyObject *)__pyx_t_1); } __pyx_v_closer = ((struct __pyx_obj_3hid__closer *)__pyx_t_1); __pyx_t_1 = 0; /* "hid.pyx":96 * cdef wrap(hid_device *ptr): * cdef _closer closer = _closer() * closer._ptr = ptr # <<<<<<<<<<<<<< * return closer * */ __pyx_v_closer->_ptr = __pyx_v_ptr; /* "hid.pyx":97 * cdef _closer closer = _closer() * closer._ptr = ptr * return closer # <<<<<<<<<<<<<< * * def close(self): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF((PyObject *)__pyx_v_closer); __pyx_r = ((PyObject *)__pyx_v_closer); goto __pyx_L0; /* "hid.pyx":93 * cdef hid_device *_ptr * * @staticmethod # <<<<<<<<<<<<<< * cdef wrap(hid_device *ptr): * cdef _closer closer = _closer() */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("hid._closer.wrap", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_closer); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":99 * return closer * * def close(self): # <<<<<<<<<<<<<< * hid_close(self._ptr) * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_7_closer_1close(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ static PyMethodDef __pyx_mdef_3hid_7_closer_1close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_7_closer_1close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3hid_7_closer_1close(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("close (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_7_closer_close(((struct __pyx_obj_3hid__closer *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_7_closer_close(struct __pyx_obj_3hid__closer *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("close", 0); /* "hid.pyx":100 * * def close(self): * hid_close(self._ptr) # <<<<<<<<<<<<<< * * cdef class device: */ hid_close(__pyx_v_self->_ptr); /* "hid.pyx":99 * return closer * * def close(self): # <<<<<<<<<<<<<< * hid_close(self._ptr) * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_7_closer_3__reduce_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ static PyMethodDef __pyx_mdef_3hid_7_closer_3__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_7_closer_3__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3hid_7_closer_3__reduce_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_7_closer_2__reduce_cython__(((struct __pyx_obj_3hid__closer *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_7_closer_2__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_3hid__closer *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" */ __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self__ptr_cannot_be_converted_to, 0, 0); __PYX_ERR(1, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("hid._closer.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_7_closer_5__setstate_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ static PyMethodDef __pyx_mdef_3hid_7_closer_5__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_7_closer_5__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3hid_7_closer_5__setstate_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 3, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 3, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(1, 3, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 3, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 3, __pyx_L3_error) } __pyx_v___pyx_state = values[0]; } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 3, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid._closer.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_7_closer_4__setstate_cython__(((struct __pyx_obj_3hid__closer *)__pyx_v_self), __pyx_v___pyx_state); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_7_closer_4__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_3hid__closer *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< */ __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self__ptr_cannot_be_converted_to, 0, 0); __PYX_ERR(1, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("hid._closer.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":112 * cdef object _close * * def open(self, int vendor_id=0, int product_id=0, unicode serial_number=None): # <<<<<<<<<<<<<< * """Open the connection. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_1open(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_open, "Open the connection.\n\n :param vendor_id: Vendor id to connect to, default = 0\n :type vendor_id: int, optional\n :param product_id: Product id to connect to, default = 0\n :type product_id: int, optional\n :param serial_number:\n :type serial_number: unicode, optional\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_1open = {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_1open, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_open}; static PyObject *__pyx_pw_3hid_6device_1open(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { int __pyx_v_vendor_id; int __pyx_v_product_id; PyObject *__pyx_v_serial_number = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[3] = {0,0,0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("open (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_vendor_id,&__pyx_mstate_global->__pyx_n_u_product_id,&__pyx_mstate_global->__pyx_n_u_serial_number,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 112, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 3: values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 112, __pyx_L3_error) CYTHON_FALLTHROUGH; case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 112, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 112, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "open", 0) < 0) __PYX_ERR(0, 112, __pyx_L3_error) if (!values[2]) values[2] = __Pyx_NewRef(((PyObject*)Py_None)); } else { switch (__pyx_nargs) { case 3: values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 112, __pyx_L3_error) CYTHON_FALLTHROUGH; case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 112, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 112, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } if (!values[2]) values[2] = __Pyx_NewRef(((PyObject*)Py_None)); } if (values[0]) { __pyx_v_vendor_id = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_vendor_id == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 112, __pyx_L3_error) } else { __pyx_v_vendor_id = ((int)0); } if (values[1]) { __pyx_v_product_id = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_product_id == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 112, __pyx_L3_error) } else { __pyx_v_product_id = ((int)0); } __pyx_v_serial_number = ((PyObject*)values[2]); } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("open", 0, 0, 3, __pyx_nargs); __PYX_ERR(0, 112, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.open", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_serial_number), (&PyUnicode_Type), 1, "serial_number", 1))) __PYX_ERR(0, 112, __pyx_L1_error) __pyx_r = __pyx_pf_3hid_6device_open(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_vendor_id, __pyx_v_product_id, __pyx_v_serial_number); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } goto __pyx_L7_cleaned_up; __pyx_L0:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __pyx_L7_cleaned_up:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_open(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_vendor_id, int __pyx_v_product_id, PyObject *__pyx_v_serial_number) { wchar_t *__pyx_v_cserial_number; int __pyx_v_serial_len; Py_ssize_t __pyx_v_result; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; Py_ssize_t __pyx_t_6; int __pyx_t_7; int __pyx_t_8; char const *__pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; PyObject *__pyx_t_13 = NULL; PyObject *__pyx_t_14 = NULL; PyObject *__pyx_t_15 = NULL; PyObject *__pyx_t_16 = NULL; PyObject *__pyx_t_17 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("open", 0); /* "hid.pyx":123 * :raises IOError: * """ * cdef wchar_t * cserial_number = NULL # <<<<<<<<<<<<<< * cdef int serial_len * cdef Py_ssize_t result */ __pyx_v_cserial_number = NULL; /* "hid.pyx":126 * cdef int serial_len * cdef Py_ssize_t result * if self._c_hid != NULL: # <<<<<<<<<<<<<< * raise RuntimeError('already open') * try: */ __pyx_t_1 = (__pyx_v_self->_c_hid != NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":127 * cdef Py_ssize_t result * if self._c_hid != NULL: * raise RuntimeError('already open') # <<<<<<<<<<<<<< * try: * if serial_number is not None: */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_RuntimeError); __pyx_t_4 = __pyx_builtin_RuntimeError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_already_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 127, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 127, __pyx_L1_error) /* "hid.pyx":126 * cdef int serial_len * cdef Py_ssize_t result * if self._c_hid != NULL: # <<<<<<<<<<<<<< * raise RuntimeError('already open') * try: */ } /* "hid.pyx":128 * if self._c_hid != NULL: * raise RuntimeError('already open') * try: # <<<<<<<<<<<<<< * if serial_number is not None: * serial_len = len(serial_number) */ /*try:*/ { /* "hid.pyx":129 * raise RuntimeError('already open') * try: * if serial_number is not None: # <<<<<<<<<<<<<< * serial_len = len(serial_number) * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) */ __pyx_t_1 = (__pyx_v_serial_number != ((PyObject*)Py_None)); if (__pyx_t_1) { /* "hid.pyx":130 * try: * if serial_number is not None: * serial_len = len(serial_number) # <<<<<<<<<<<<<< * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) * if cserial_number == NULL: */ if (unlikely(__pyx_v_serial_number == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(0, 130, __pyx_L5_error) } __pyx_t_6 = __Pyx_PyUnicode_GET_LENGTH(__pyx_v_serial_number); if (unlikely(__pyx_t_6 == ((Py_ssize_t)-1))) __PYX_ERR(0, 130, __pyx_L5_error) __pyx_v_serial_len = __pyx_t_6; /* "hid.pyx":131 * if serial_number is not None: * serial_len = len(serial_number) * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) # <<<<<<<<<<<<<< * if cserial_number == NULL: * raise MemoryError() */ __pyx_v_cserial_number = ((wchar_t *)malloc(((sizeof(wchar_t)) * (__pyx_v_serial_len + 1)))); /* "hid.pyx":132 * serial_len = len(serial_number) * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) * if cserial_number == NULL: # <<<<<<<<<<<<<< * raise MemoryError() * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) */ __pyx_t_1 = (__pyx_v_cserial_number == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":133 * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) * if cserial_number == NULL: * raise MemoryError() # <<<<<<<<<<<<<< * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) * if result == -1: */ PyErr_NoMemory(); __PYX_ERR(0, 133, __pyx_L5_error) /* "hid.pyx":132 * serial_len = len(serial_number) * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) * if cserial_number == NULL: # <<<<<<<<<<<<<< * raise MemoryError() * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) */ } /* "hid.pyx":134 * if cserial_number == NULL: * raise MemoryError() * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) # <<<<<<<<<<<<<< * if result == -1: * raise ValueError("invalid serial number string") */ __pyx_v_result = PyUnicode_AsWideChar(__pyx_v_serial_number, __pyx_v_cserial_number, __pyx_v_serial_len); /* "hid.pyx":135 * raise MemoryError() * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) * if result == -1: # <<<<<<<<<<<<<< * raise ValueError("invalid serial number string") * cserial_number[serial_len] = 0 # Must explicitly null-terminate */ __pyx_t_1 = (__pyx_v_result == -1L); if (unlikely(__pyx_t_1)) { /* "hid.pyx":136 * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) * if result == -1: * raise ValueError("invalid serial number string") # <<<<<<<<<<<<<< * cserial_number[serial_len] = 0 # Must explicitly null-terminate * self._c_hid = hid_open(vendor_id, product_id, cserial_number) */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_3 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_invalid_serial_number_string}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 136, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 136, __pyx_L5_error) /* "hid.pyx":135 * raise MemoryError() * result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) * if result == -1: # <<<<<<<<<<<<<< * raise ValueError("invalid serial number string") * cserial_number[serial_len] = 0 # Must explicitly null-terminate */ } /* "hid.pyx":137 * if result == -1: * raise ValueError("invalid serial number string") * cserial_number[serial_len] = 0 # Must explicitly null-terminate # <<<<<<<<<<<<<< * self._c_hid = hid_open(vendor_id, product_id, cserial_number) * finally: */ (__pyx_v_cserial_number[__pyx_v_serial_len]) = 0; /* "hid.pyx":129 * raise RuntimeError('already open') * try: * if serial_number is not None: # <<<<<<<<<<<<<< * serial_len = len(serial_number) * cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) */ } /* "hid.pyx":138 * raise ValueError("invalid serial number string") * cserial_number[serial_len] = 0 # Must explicitly null-terminate * self._c_hid = hid_open(vendor_id, product_id, cserial_number) # <<<<<<<<<<<<<< * finally: * if cserial_number != NULL: */ __pyx_v_self->_c_hid = hid_open(__pyx_v_vendor_id, __pyx_v_product_id, __pyx_v_cserial_number); } /* "hid.pyx":140 * self._c_hid = hid_open(vendor_id, product_id, cserial_number) * finally: * if cserial_number != NULL: # <<<<<<<<<<<<<< * free(cserial_number) * if self._c_hid == NULL: */ /*finally:*/ { /*normal exit:*/{ __pyx_t_1 = (__pyx_v_cserial_number != NULL); if (__pyx_t_1) { /* "hid.pyx":141 * finally: * if cserial_number != NULL: * free(cserial_number) # <<<<<<<<<<<<<< * if self._c_hid == NULL: * raise IOError('open failed') */ free(__pyx_v_cserial_number); /* "hid.pyx":140 * self._c_hid = hid_open(vendor_id, product_id, cserial_number) * finally: * if cserial_number != NULL: # <<<<<<<<<<<<<< * free(cserial_number) * if self._c_hid == NULL: */ } goto __pyx_L6; } __pyx_L5_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_ExceptionSwap(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); if ( unlikely(__Pyx_GetException(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12) < 0)) __Pyx_ErrFetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __Pyx_XGOTREF(__pyx_t_12); __Pyx_XGOTREF(__pyx_t_13); __Pyx_XGOTREF(__pyx_t_14); __Pyx_XGOTREF(__pyx_t_15); __pyx_t_7 = __pyx_lineno; __pyx_t_8 = __pyx_clineno; __pyx_t_9 = __pyx_filename; { __pyx_t_1 = (__pyx_v_cserial_number != NULL); if (__pyx_t_1) { /* "hid.pyx":141 * finally: * if cserial_number != NULL: * free(cserial_number) # <<<<<<<<<<<<<< * if self._c_hid == NULL: * raise IOError('open failed') */ free(__pyx_v_cserial_number); /* "hid.pyx":140 * self._c_hid = hid_open(vendor_id, product_id, cserial_number) * finally: * if cserial_number != NULL: # <<<<<<<<<<<<<< * free(cserial_number) * if self._c_hid == NULL: */ } } __Pyx_XGIVEREF(__pyx_t_13); __Pyx_XGIVEREF(__pyx_t_14); __Pyx_XGIVEREF(__pyx_t_15); __Pyx_ExceptionReset(__pyx_t_13, __pyx_t_14, __pyx_t_15); __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_XGIVEREF(__pyx_t_12); __Pyx_ErrRestore(__pyx_t_10, __pyx_t_11, __pyx_t_12); __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_lineno = __pyx_t_7; __pyx_clineno = __pyx_t_8; __pyx_filename = __pyx_t_9; goto __pyx_L1_error; } __pyx_L6:; } /* "hid.pyx":142 * if cserial_number != NULL: * free(cserial_number) * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise IOError('open failed') * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":143 * free(cserial_number) * if self._c_hid == NULL: * raise IOError('open failed') # <<<<<<<<<<<<<< * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_4 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_open_failed}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 143, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 143, __pyx_L1_error) /* "hid.pyx":142 * if cserial_number != NULL: * free(cserial_number) * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise IOError('open failed') * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) */ } /* "hid.pyx":144 * if self._c_hid == NULL: * raise IOError('open failed') * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) # <<<<<<<<<<<<<< * * def open_path(self, bytes path): */ __pyx_t_4 = NULL; __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_weakref); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 144, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_16 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_finalize); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 144, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_16); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __pyx_f_3hid_7_closer_wrap(__pyx_v_self->_c_hid); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 144, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_17 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_close); if (unlikely(!__pyx_t_17)) __PYX_ERR(0, 144, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_17); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_5 = 1; #if CYTHON_UNPACK_METHODS if (unlikely(PyMethod_Check(__pyx_t_16))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_16); assert(__pyx_t_4); PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_16); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx__function); __Pyx_DECREF_SET(__pyx_t_16, __pyx__function); __pyx_t_5 = 0; } #endif { PyObject *__pyx_callargs[3] = {__pyx_t_4, ((PyObject *)__pyx_v_self), __pyx_t_17}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_16, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_17); __pyx_t_17 = 0; __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 144, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_self->_close); __Pyx_DECREF(__pyx_v_self->_close); __pyx_v_self->_close = __pyx_t_2; __pyx_t_2 = 0; /* "hid.pyx":112 * cdef object _close * * def open(self, int vendor_id=0, int product_id=0, unicode serial_number=None): # <<<<<<<<<<<<<< * """Open the connection. * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_16); __Pyx_XDECREF(__pyx_t_17); __Pyx_AddTraceback("hid.device.open", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":146 * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * * def open_path(self, bytes path): # <<<<<<<<<<<<<< * """Open connection by path. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_3open_path(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_2open_path, "Open connection by path.\n\n :param path: Path to device\n :type path: bytes\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_3open_path = {"open_path", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_3open_path, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_2open_path}; static PyObject *__pyx_pw_3hid_6device_3open_path(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { PyObject *__pyx_v_path = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("open_path (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_path,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 146, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 146, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "open_path", 0) < 0) __PYX_ERR(0, 146, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("open_path", 1, 1, 1, i); __PYX_ERR(0, 146, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 146, __pyx_L3_error) } __pyx_v_path = ((PyObject*)values[0]); } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("open_path", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 146, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.open_path", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_path), (&PyBytes_Type), 1, "path", 1))) __PYX_ERR(0, 146, __pyx_L1_error) __pyx_r = __pyx_pf_3hid_6device_2open_path(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_path); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } goto __pyx_L7_cleaned_up; __pyx_L0:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __pyx_L7_cleaned_up:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_2open_path(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_path) { char *__pyx_v_cbuff; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations char *__pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; size_t __pyx_t_6; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("open_path", 0); /* "hid.pyx":153 * :raises IOError: * """ * cdef char* cbuff = path # <<<<<<<<<<<<<< * if self._c_hid != NULL: * raise RuntimeError('already open') */ if (unlikely(__pyx_v_path == Py_None)) { PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); __PYX_ERR(0, 153, __pyx_L1_error) } __pyx_t_1 = __Pyx_PyBytes_AsWritableString(__pyx_v_path); if (unlikely((!__pyx_t_1) && PyErr_Occurred())) __PYX_ERR(0, 153, __pyx_L1_error) __pyx_v_cbuff = __pyx_t_1; /* "hid.pyx":154 * """ * cdef char* cbuff = path * if self._c_hid != NULL: # <<<<<<<<<<<<<< * raise RuntimeError('already open') * self._c_hid = hid_open_path(cbuff) */ __pyx_t_2 = (__pyx_v_self->_c_hid != NULL); if (unlikely(__pyx_t_2)) { /* "hid.pyx":155 * cdef char* cbuff = path * if self._c_hid != NULL: * raise RuntimeError('already open') # <<<<<<<<<<<<<< * self._c_hid = hid_open_path(cbuff) * if self._c_hid == NULL: */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_RuntimeError); __pyx_t_5 = __pyx_builtin_RuntimeError; __pyx_t_6 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_already_open}; __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 155, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); } __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(0, 155, __pyx_L1_error) /* "hid.pyx":154 * """ * cdef char* cbuff = path * if self._c_hid != NULL: # <<<<<<<<<<<<<< * raise RuntimeError('already open') * self._c_hid = hid_open_path(cbuff) */ } /* "hid.pyx":156 * if self._c_hid != NULL: * raise RuntimeError('already open') * self._c_hid = hid_open_path(cbuff) # <<<<<<<<<<<<<< * if self._c_hid == NULL: * raise IOError('open failed') */ __pyx_v_self->_c_hid = hid_open_path(__pyx_v_cbuff); /* "hid.pyx":157 * raise RuntimeError('already open') * self._c_hid = hid_open_path(cbuff) * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise IOError('open failed') * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) */ __pyx_t_2 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_2)) { /* "hid.pyx":158 * self._c_hid = hid_open_path(cbuff) * if self._c_hid == NULL: * raise IOError('open failed') # <<<<<<<<<<<<<< * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * */ __pyx_t_5 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_4 = __pyx_builtin_IOError; __pyx_t_6 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_open_failed}; __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 158, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); } __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(0, 158, __pyx_L1_error) /* "hid.pyx":157 * raise RuntimeError('already open') * self._c_hid = hid_open_path(cbuff) * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise IOError('open failed') * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) */ } /* "hid.pyx":159 * if self._c_hid == NULL: * raise IOError('open failed') * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) # <<<<<<<<<<<<<< * * def close(self): */ __pyx_t_4 = NULL; __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_weakref); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 159, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_finalize); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 159, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_5 = __pyx_f_3hid_7_closer_wrap(__pyx_v_self->_c_hid); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 159, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_close); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 159, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_6 = 1; #if CYTHON_UNPACK_METHODS if (unlikely(PyMethod_Check(__pyx_t_7))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_7); assert(__pyx_t_4); PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx__function); __Pyx_DECREF_SET(__pyx_t_7, __pyx__function); __pyx_t_6 = 0; } #endif { PyObject *__pyx_callargs[3] = {__pyx_t_4, ((PyObject *)__pyx_v_self), __pyx_t_8}; __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 159, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); } __Pyx_GIVEREF(__pyx_t_3); __Pyx_GOTREF(__pyx_v_self->_close); __Pyx_DECREF(__pyx_v_self->_close); __pyx_v_self->_close = __pyx_t_3; __pyx_t_3 = 0; /* "hid.pyx":146 * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * * def open_path(self, bytes path): # <<<<<<<<<<<<<< * """Open connection by path. * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("hid.device.open_path", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":161 * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * * def close(self): # <<<<<<<<<<<<<< * """Close connection. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_5close(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_4close, "Close connection.\n\n This should always be called after opening a connection.\n "); static PyMethodDef __pyx_mdef_3hid_6device_5close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_5close, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_4close}; static PyObject *__pyx_pw_3hid_6device_5close(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("close (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_4close(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_4close(struct __pyx_obj_3hid_device *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("close", 0); /* "hid.pyx":166 * This should always be called after opening a connection. * """ * if self._c_hid != NULL: # <<<<<<<<<<<<<< * self._close() * self._close.detach() */ __pyx_t_1 = (__pyx_v_self->_c_hid != NULL); if (__pyx_t_1) { /* "hid.pyx":167 * """ * if self._c_hid != NULL: * self._close() # <<<<<<<<<<<<<< * self._close.detach() * self._c_hid = NULL */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_v_self->_close); __pyx_t_4 = __pyx_v_self->_close; __pyx_t_5 = 1; #if CYTHON_UNPACK_METHODS if (likely(PyMethod_Check(__pyx_t_4))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); assert(__pyx_t_3); PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx__function); __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); __pyx_t_5 = 0; } #endif { PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "hid.pyx":168 * if self._c_hid != NULL: * self._close() * self._close.detach() # <<<<<<<<<<<<<< * self._c_hid = NULL * */ __pyx_t_4 = __pyx_v_self->_close; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; { PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_detach, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 168, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "hid.pyx":169 * self._close() * self._close.detach() * self._c_hid = NULL # <<<<<<<<<<<<<< * * def write(self, buff): */ __pyx_v_self->_c_hid = NULL; /* "hid.pyx":166 * This should always be called after opening a connection. * """ * if self._c_hid != NULL: # <<<<<<<<<<<<<< * self._close() * self._close.detach() */ } /* "hid.pyx":161 * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * * def close(self): # <<<<<<<<<<<<<< * """Close connection. * */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.close", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":171 * self._c_hid = NULL * * def write(self, buff): # <<<<<<<<<<<<<< * """Accept a list of integers (0-255) and send them to the device. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_7write(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_6write, "Accept a list of integers (0-255) and send them to the device.\n\n :param buff: Data to write (must be convertible to `bytes`)\n :type buff: Any\n :return: Write result\n :rtype: int\n "); static PyMethodDef __pyx_mdef_3hid_6device_7write = {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_7write, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_6write}; static PyObject *__pyx_pw_3hid_6device_7write(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { PyObject *__pyx_v_buff = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("write (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buff,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 171, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 171, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write", 0) < 0) __PYX_ERR(0, 171, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, i); __PYX_ERR(0, 171, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 171, __pyx_L3_error) } __pyx_v_buff = values[0]; } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 171, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.write", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_6write(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_buff); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_6write(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_buff) { hid_device *__pyx_v_c_hid; unsigned char *__pyx_v_cbuff; size_t __pyx_v_c_buff_len; int __pyx_v_result; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; PyObject *__pyx_t_6 = NULL; hid_device *__pyx_t_7; unsigned char *__pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("write", 0); __Pyx_INCREF(__pyx_v_buff); /* "hid.pyx":179 * :rtype: int * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * # convert to bytes */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":180 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * # convert to bytes * if sys.version_info < (3, 0): */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 180, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 180, __pyx_L1_error) /* "hid.pyx":179 * :rtype: int * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * # convert to bytes */ } /* "hid.pyx":182 * raise ValueError('not open') * # convert to bytes * if sys.version_info < (3, 0): # <<<<<<<<<<<<<< * buff = ''.join(map(chr, buff)) * else: */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_sys); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_version_info); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyObject_RichCompare(__pyx_t_4, __pyx_mstate_global->__pyx_tuple[0], Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "hid.pyx":183 * # convert to bytes * if sys.version_info < (3, 0): * buff = ''.join(map(chr, buff)) # <<<<<<<<<<<<<< * else: * buff = bytes(buff) */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_map); __pyx_t_3 = __pyx_builtin_map; __pyx_t_6 = __Pyx_GetBuiltinName(__pyx_mstate_global->__pyx_n_u_chr); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_5 = 1; { PyObject *__pyx_callargs[3] = {__pyx_t_4, __pyx_t_6, __pyx_v_buff}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __pyx_t_3 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u_, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 183, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_buff, __pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":182 * raise ValueError('not open') * # convert to bytes * if sys.version_info < (3, 0): # <<<<<<<<<<<<<< * buff = ''.join(map(chr, buff)) * else: */ goto __pyx_L4; } /* "hid.pyx":185 * buff = ''.join(map(chr, buff)) * else: * buff = bytes(buff) # <<<<<<<<<<<<<< * cdef hid_device * c_hid = self._c_hid * cdef unsigned char* cbuff = buff # covert to c string */ /*else*/ { __pyx_t_2 = NULL; __Pyx_INCREF((PyObject *)(&PyBytes_Type)); __pyx_t_6 = ((PyObject *)(&PyBytes_Type)); __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_buff}; __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 185, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); } __Pyx_DECREF_SET(__pyx_v_buff, __pyx_t_3); __pyx_t_3 = 0; } __pyx_L4:; /* "hid.pyx":186 * else: * buff = bytes(buff) * cdef hid_device * c_hid = self._c_hid # <<<<<<<<<<<<<< * cdef unsigned char* cbuff = buff # covert to c string * cdef size_t c_buff_len = len(buff) */ __pyx_t_7 = __pyx_v_self->_c_hid; __pyx_v_c_hid = __pyx_t_7; /* "hid.pyx":187 * buff = bytes(buff) * cdef hid_device * c_hid = self._c_hid * cdef unsigned char* cbuff = buff # covert to c string # <<<<<<<<<<<<<< * cdef size_t c_buff_len = len(buff) * cdef int result */ __pyx_t_8 = __Pyx_PyObject_AsWritableUString(__pyx_v_buff); if (unlikely((!__pyx_t_8) && PyErr_Occurred())) __PYX_ERR(0, 187, __pyx_L1_error) __pyx_v_cbuff = __pyx_t_8; /* "hid.pyx":188 * cdef hid_device * c_hid = self._c_hid * cdef unsigned char* cbuff = buff # covert to c string * cdef size_t c_buff_len = len(buff) # <<<<<<<<<<<<<< * cdef int result * with nogil: */ __pyx_t_9 = PyObject_Length(__pyx_v_buff); if (unlikely(__pyx_t_9 == ((Py_ssize_t)-1))) __PYX_ERR(0, 188, __pyx_L1_error) __pyx_v_c_buff_len = __pyx_t_9; /* "hid.pyx":190 * cdef size_t c_buff_len = len(buff) * cdef int result * with nogil: # <<<<<<<<<<<<<< * result = hid_write(c_hid, cbuff, c_buff_len) * return result */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":191 * cdef int result * with nogil: * result = hid_write(c_hid, cbuff, c_buff_len) # <<<<<<<<<<<<<< * return result * */ __pyx_v_result = hid_write(__pyx_v_c_hid, __pyx_v_cbuff, __pyx_v_c_buff_len); } /* "hid.pyx":190 * cdef size_t c_buff_len = len(buff) * cdef int result * with nogil: # <<<<<<<<<<<<<< * result = hid_write(c_hid, cbuff, c_buff_len) * return result */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L7; } __pyx_L7:; } } /* "hid.pyx":192 * with nogil: * result = hid_write(c_hid, cbuff, c_buff_len) * return result # <<<<<<<<<<<<<< * * def set_nonblocking(self, int v): */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_result); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 192, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "hid.pyx":171 * self._c_hid = NULL * * def write(self, buff): # <<<<<<<<<<<<<< * """Accept a list of integers (0-255) and send them to the device. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("hid.device.write", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_buff); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":194 * return result * * def set_nonblocking(self, int v): # <<<<<<<<<<<<<< * """Set the nonblocking flag. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_9set_nonblocking(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_8set_nonblocking, "Set the nonblocking flag.\n\n :param v: Flag value (1 or 0, True or False)\n :type v: int, bool\n :return: Flag result\n :rtype: int\n "); static PyMethodDef __pyx_mdef_3hid_6device_9set_nonblocking = {"set_nonblocking", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_9set_nonblocking, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_8set_nonblocking}; static PyObject *__pyx_pw_3hid_6device_9set_nonblocking(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { int __pyx_v_v; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_nonblocking (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_v,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 194, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 194, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "set_nonblocking", 0) < 0) __PYX_ERR(0, 194, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("set_nonblocking", 1, 1, 1, i); __PYX_ERR(0, 194, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 194, __pyx_L3_error) } __pyx_v_v = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_v == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 194, __pyx_L3_error) } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("set_nonblocking", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 194, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.set_nonblocking", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_8set_nonblocking(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_v); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_8set_nonblocking(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_v) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("set_nonblocking", 0); /* "hid.pyx":202 * :rtype: int * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * return hid_set_nonblocking(self._c_hid, v) */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":203 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * return hid_set_nonblocking(self._c_hid, v) * */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 203, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 203, __pyx_L1_error) /* "hid.pyx":202 * :rtype: int * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * return hid_set_nonblocking(self._c_hid, v) */ } /* "hid.pyx":204 * if self._c_hid == NULL: * raise ValueError('not open') * return hid_set_nonblocking(self._c_hid, v) # <<<<<<<<<<<<<< * * def read(self, int max_length, int timeout_ms=0): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyLong_From_int(hid_set_nonblocking(__pyx_v_self->_c_hid, __pyx_v_v)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 204, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":194 * return result * * def set_nonblocking(self, int v): # <<<<<<<<<<<<<< * """Set the nonblocking flag. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.set_nonblocking", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":206 * return hid_set_nonblocking(self._c_hid, v) * * def read(self, int max_length, int timeout_ms=0): # <<<<<<<<<<<<<< * """Return a list of integers (0-255) from the device up to max_length bytes. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_11read(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_10read, "Return a list of integers (0-255) from the device up to max_length bytes.\n\n :param max_length: Maximum number of bytes to read\n :type max_length: int\n :param timeout_ms: Number of milliseconds until timeout (default: no timeout)\n :type timeout_ms: int, optional\n :return: Read bytes\n :rtype: List[int]\n "); static PyMethodDef __pyx_mdef_3hid_6device_11read = {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_11read, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_10read}; static PyObject *__pyx_pw_3hid_6device_11read(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { int __pyx_v_max_length; int __pyx_v_timeout_ms; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[2] = {0,0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("read (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_max_length,&__pyx_mstate_global->__pyx_n_u_timeout_ms,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 206, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 206, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 206, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read", 0) < 0) __PYX_ERR(0, 206, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read", 0, 1, 2, i); __PYX_ERR(0, 206, __pyx_L3_error) } } } else { switch (__pyx_nargs) { case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 206, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 206, __pyx_L3_error) break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_max_length = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_max_length == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 206, __pyx_L3_error) if (values[1]) { __pyx_v_timeout_ms = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_timeout_ms == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 206, __pyx_L3_error) } else { __pyx_v_timeout_ms = ((int)0); } } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("read", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 206, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.read", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_10read(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_max_length, __pyx_v_timeout_ms); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_10read(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_max_length, int __pyx_v_timeout_ms) { unsigned char __pyx_v_lbuff[16]; unsigned char *__pyx_v_cbuff; size_t __pyx_v_c_max_length; int __pyx_v_c_timeout_ms; hid_device *__pyx_v_c_hid; int __pyx_v_n; PyObject *__pyx_v_res = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; hid_device *__pyx_t_6; int __pyx_t_7; int __pyx_t_8; char const *__pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; PyObject *__pyx_t_13 = NULL; PyObject *__pyx_t_14 = NULL; PyObject *__pyx_t_15 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("read", 0); /* "hid.pyx":216 * :rtype: List[int] * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef unsigned char lbuff[16] */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":217 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef unsigned char lbuff[16] * cdef unsigned char* cbuff */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 217, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 217, __pyx_L1_error) /* "hid.pyx":216 * :rtype: List[int] * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef unsigned char lbuff[16] */ } /* "hid.pyx":220 * cdef unsigned char lbuff[16] * cdef unsigned char* cbuff * cdef size_t c_max_length = max_length # <<<<<<<<<<<<<< * cdef int c_timeout_ms = timeout_ms * cdef hid_device * c_hid = self._c_hid */ __pyx_v_c_max_length = __pyx_v_max_length; /* "hid.pyx":221 * cdef unsigned char* cbuff * cdef size_t c_max_length = max_length * cdef int c_timeout_ms = timeout_ms # <<<<<<<<<<<<<< * cdef hid_device * c_hid = self._c_hid * try: */ __pyx_v_c_timeout_ms = __pyx_v_timeout_ms; /* "hid.pyx":222 * cdef size_t c_max_length = max_length * cdef int c_timeout_ms = timeout_ms * cdef hid_device * c_hid = self._c_hid # <<<<<<<<<<<<<< * try: * if max_length <= 16: */ __pyx_t_6 = __pyx_v_self->_c_hid; __pyx_v_c_hid = __pyx_t_6; /* "hid.pyx":223 * cdef int c_timeout_ms = timeout_ms * cdef hid_device * c_hid = self._c_hid * try: # <<<<<<<<<<<<<< * if max_length <= 16: * cbuff = lbuff */ /*try:*/ { /* "hid.pyx":224 * cdef hid_device * c_hid = self._c_hid * try: * if max_length <= 16: # <<<<<<<<<<<<<< * cbuff = lbuff * else: */ __pyx_t_1 = (__pyx_v_max_length <= 16); if (__pyx_t_1) { /* "hid.pyx":225 * try: * if max_length <= 16: * cbuff = lbuff # <<<<<<<<<<<<<< * else: * cbuff = malloc(max_length) */ __pyx_v_cbuff = __pyx_v_lbuff; /* "hid.pyx":224 * cdef hid_device * c_hid = self._c_hid * try: * if max_length <= 16: # <<<<<<<<<<<<<< * cbuff = lbuff * else: */ goto __pyx_L7; } /* "hid.pyx":227 * cbuff = lbuff * else: * cbuff = malloc(max_length) # <<<<<<<<<<<<<< * if timeout_ms > 0: * with nogil: */ /*else*/ { __pyx_v_cbuff = ((unsigned char *)malloc(__pyx_v_max_length)); } __pyx_L7:; /* "hid.pyx":228 * else: * cbuff = malloc(max_length) * if timeout_ms > 0: # <<<<<<<<<<<<<< * with nogil: * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) */ __pyx_t_1 = (__pyx_v_timeout_ms > 0); if (__pyx_t_1) { /* "hid.pyx":229 * cbuff = malloc(max_length) * if timeout_ms > 0: * with nogil: # <<<<<<<<<<<<<< * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) * else: */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":230 * if timeout_ms > 0: * with nogil: * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) # <<<<<<<<<<<<<< * else: * with nogil: */ __pyx_v_n = hid_read_timeout(__pyx_v_c_hid, __pyx_v_cbuff, __pyx_v_c_max_length, __pyx_v_c_timeout_ms); } /* "hid.pyx":229 * cbuff = malloc(max_length) * if timeout_ms > 0: * with nogil: # <<<<<<<<<<<<<< * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) * else: */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L11; } __pyx_L11:; } } /* "hid.pyx":228 * else: * cbuff = malloc(max_length) * if timeout_ms > 0: # <<<<<<<<<<<<<< * with nogil: * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) */ goto __pyx_L8; } /* "hid.pyx":232 * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) * else: * with nogil: # <<<<<<<<<<<<<< * n = hid_read(c_hid, cbuff, c_max_length) * if n == -1: */ /*else*/ { { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":233 * else: * with nogil: * n = hid_read(c_hid, cbuff, c_max_length) # <<<<<<<<<<<<<< * if n == -1: * raise IOError('read error') */ __pyx_v_n = hid_read(__pyx_v_c_hid, __pyx_v_cbuff, __pyx_v_c_max_length); } /* "hid.pyx":232 * n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) * else: * with nogil: # <<<<<<<<<<<<<< * n = hid_read(c_hid, cbuff, c_max_length) * if n == -1: */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L14; } __pyx_L14:; } } } __pyx_L8:; /* "hid.pyx":234 * with nogil: * n = hid_read(c_hid, cbuff, c_max_length) * if n == -1: # <<<<<<<<<<<<<< * raise IOError('read error') * res = list(cbuff[:n]) */ __pyx_t_1 = (__pyx_v_n == -1L); if (unlikely(__pyx_t_1)) { /* "hid.pyx":235 * n = hid_read(c_hid, cbuff, c_max_length) * if n == -1: * raise IOError('read error') # <<<<<<<<<<<<<< * res = list(cbuff[:n]) * finally: */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_read_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 235, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 235, __pyx_L5_error) /* "hid.pyx":234 * with nogil: * n = hid_read(c_hid, cbuff, c_max_length) * if n == -1: # <<<<<<<<<<<<<< * raise IOError('read error') * res = list(cbuff[:n]) */ } /* "hid.pyx":236 * if n == -1: * raise IOError('read error') * res = list(cbuff[:n]) # <<<<<<<<<<<<<< * finally: * if max_length > 16: */ __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(((char const *)__pyx_v_cbuff) + 0, __pyx_v_n - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 236, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_List(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 236, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_res = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; } /* "hid.pyx":238 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ /*finally:*/ { /*normal exit:*/{ __pyx_t_1 = (__pyx_v_max_length > 16); if (__pyx_t_1) { /* "hid.pyx":239 * finally: * if max_length > 16: * free(cbuff) # <<<<<<<<<<<<<< * return res * */ free(__pyx_v_cbuff); /* "hid.pyx":238 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ } goto __pyx_L6; } __pyx_L5_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_ExceptionSwap(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); if ( unlikely(__Pyx_GetException(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12) < 0)) __Pyx_ErrFetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __Pyx_XGOTREF(__pyx_t_12); __Pyx_XGOTREF(__pyx_t_13); __Pyx_XGOTREF(__pyx_t_14); __Pyx_XGOTREF(__pyx_t_15); __pyx_t_7 = __pyx_lineno; __pyx_t_8 = __pyx_clineno; __pyx_t_9 = __pyx_filename; { __pyx_t_1 = (__pyx_v_max_length > 16); if (__pyx_t_1) { /* "hid.pyx":239 * finally: * if max_length > 16: * free(cbuff) # <<<<<<<<<<<<<< * return res * */ free(__pyx_v_cbuff); /* "hid.pyx":238 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ } } __Pyx_XGIVEREF(__pyx_t_13); __Pyx_XGIVEREF(__pyx_t_14); __Pyx_XGIVEREF(__pyx_t_15); __Pyx_ExceptionReset(__pyx_t_13, __pyx_t_14, __pyx_t_15); __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_XGIVEREF(__pyx_t_12); __Pyx_ErrRestore(__pyx_t_10, __pyx_t_11, __pyx_t_12); __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_lineno = __pyx_t_7; __pyx_clineno = __pyx_t_8; __pyx_filename = __pyx_t_9; goto __pyx_L1_error; } __pyx_L6:; } /* "hid.pyx":240 * if max_length > 16: * free(cbuff) * return res # <<<<<<<<<<<<<< * * def get_manufacturer_string(self): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_res); __pyx_r = __pyx_v_res; goto __pyx_L0; /* "hid.pyx":206 * return hid_set_nonblocking(self._c_hid, v) * * def read(self, int max_length, int timeout_ms=0): # <<<<<<<<<<<<<< * """Return a list of integers (0-255) from the device up to max_length bytes. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.read", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_res); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":242 * return res * * def get_manufacturer_string(self): # <<<<<<<<<<<<<< * """Return manufacturer string (e.g. vendor name). * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_13get_manufacturer_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_12get_manufacturer_string, "Return manufacturer string (e.g. vendor name).\n\n :return:\n :rtype: str\n :raises ValueError: If connection is not opened.\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_13get_manufacturer_string = {"get_manufacturer_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_13get_manufacturer_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_12get_manufacturer_string}; static PyObject *__pyx_pw_3hid_6device_13get_manufacturer_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_manufacturer_string (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("get_manufacturer_string", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("get_manufacturer_string", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_12get_manufacturer_string(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_12get_manufacturer_string(struct __pyx_obj_3hid_device *__pyx_v_self) { wchar_t __pyx_v_buff[0xFF]; int __pyx_v_r; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_manufacturer_string", 0); /* "hid.pyx":250 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":251 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef wchar_t buff[255] * cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 251, __pyx_L1_error) /* "hid.pyx":250 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ } /* "hid.pyx":253 * raise ValueError('not open') * cdef wchar_t buff[255] * cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) # <<<<<<<<<<<<<< * if r < 0: * raise IOError('get manufacturer string error') */ __pyx_v_r = hid_get_manufacturer_string(__pyx_v_self->_c_hid, __pyx_v_buff, 0xFF); /* "hid.pyx":254 * cdef wchar_t buff[255] * cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get manufacturer string error') * return U(buff) */ __pyx_t_1 = (__pyx_v_r < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":255 * cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) * if r < 0: * raise IOError('get manufacturer string error') # <<<<<<<<<<<<<< * return U(buff) * */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_get_manufacturer_string_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 255, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 255, __pyx_L1_error) /* "hid.pyx":254 * cdef wchar_t buff[255] * cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get manufacturer string error') * return U(buff) */ } /* "hid.pyx":256 * if r < 0: * raise IOError('get manufacturer string error') * return U(buff) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_f_3hid_U(__pyx_v_buff); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 256, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":242 * return res * * def get_manufacturer_string(self): # <<<<<<<<<<<<<< * """Return manufacturer string (e.g. vendor name). * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_manufacturer_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":259 * * * def get_product_string(self): # <<<<<<<<<<<<<< * """Return product string (e.g. device description). * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_15get_product_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_14get_product_string, "Return product string (e.g. device description).\n\n :return:\n :rtype: str\n :raises ValueError: If connection is not opened.\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_15get_product_string = {"get_product_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_15get_product_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_14get_product_string}; static PyObject *__pyx_pw_3hid_6device_15get_product_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_product_string (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("get_product_string", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("get_product_string", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_14get_product_string(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_14get_product_string(struct __pyx_obj_3hid_device *__pyx_v_self) { wchar_t __pyx_v_buff[0xFF]; int __pyx_v_r; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_product_string", 0); /* "hid.pyx":267 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":268 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef wchar_t buff[255] * cdef int r = hid_get_product_string(self._c_hid, buff, 255) */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 268, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 268, __pyx_L1_error) /* "hid.pyx":267 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ } /* "hid.pyx":270 * raise ValueError('not open') * cdef wchar_t buff[255] * cdef int r = hid_get_product_string(self._c_hid, buff, 255) # <<<<<<<<<<<<<< * if r < 0: * raise IOError('get product string error') */ __pyx_v_r = hid_get_product_string(__pyx_v_self->_c_hid, __pyx_v_buff, 0xFF); /* "hid.pyx":271 * cdef wchar_t buff[255] * cdef int r = hid_get_product_string(self._c_hid, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get product string error') * return U(buff) */ __pyx_t_1 = (__pyx_v_r < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":272 * cdef int r = hid_get_product_string(self._c_hid, buff, 255) * if r < 0: * raise IOError('get product string error') # <<<<<<<<<<<<<< * return U(buff) * */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_get_product_string_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 272, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 272, __pyx_L1_error) /* "hid.pyx":271 * cdef wchar_t buff[255] * cdef int r = hid_get_product_string(self._c_hid, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get product string error') * return U(buff) */ } /* "hid.pyx":273 * if r < 0: * raise IOError('get product string error') * return U(buff) # <<<<<<<<<<<<<< * * def get_serial_number_string(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_f_3hid_U(__pyx_v_buff); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 273, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":259 * * * def get_product_string(self): # <<<<<<<<<<<<<< * """Return product string (e.g. device description). * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_product_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":275 * return U(buff) * * def get_serial_number_string(self): # <<<<<<<<<<<<<< * """Return serial number. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_17get_serial_number_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_16get_serial_number_string, "Return serial number.\n\n :return:\n :rtype: str\n :raises ValueError: If connection is not opened.\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_17get_serial_number_string = {"get_serial_number_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_17get_serial_number_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_16get_serial_number_string}; static PyObject *__pyx_pw_3hid_6device_17get_serial_number_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_serial_number_string (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("get_serial_number_string", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("get_serial_number_string", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_16get_serial_number_string(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_16get_serial_number_string(struct __pyx_obj_3hid_device *__pyx_v_self) { wchar_t __pyx_v_buff[0xFF]; int __pyx_v_r; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_serial_number_string", 0); /* "hid.pyx":283 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":284 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef wchar_t buff[255] * cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 284, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 284, __pyx_L1_error) /* "hid.pyx":283 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ } /* "hid.pyx":286 * raise ValueError('not open') * cdef wchar_t buff[255] * cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) # <<<<<<<<<<<<<< * if r < 0: * raise IOError('get serial number string error') */ __pyx_v_r = hid_get_serial_number_string(__pyx_v_self->_c_hid, __pyx_v_buff, 0xFF); /* "hid.pyx":287 * cdef wchar_t buff[255] * cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get serial number string error') * return U(buff) */ __pyx_t_1 = (__pyx_v_r < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":288 * cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) * if r < 0: * raise IOError('get serial number string error') # <<<<<<<<<<<<<< * return U(buff) * */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_get_serial_number_string_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 288, __pyx_L1_error) /* "hid.pyx":287 * cdef wchar_t buff[255] * cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get serial number string error') * return U(buff) */ } /* "hid.pyx":289 * if r < 0: * raise IOError('get serial number string error') * return U(buff) # <<<<<<<<<<<<<< * * def get_indexed_string(self, index): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_f_3hid_U(__pyx_v_buff); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 289, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":275 * return U(buff) * * def get_serial_number_string(self): # <<<<<<<<<<<<<< * """Return serial number. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_serial_number_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":291 * return U(buff) * * def get_indexed_string(self, index): # <<<<<<<<<<<<<< * """Return indexed string. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_19get_indexed_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_18get_indexed_string, "Return indexed string.\n\n :return:\n :rtype: str\n :raises ValueError: If connection is not opened.\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_19get_indexed_string = {"get_indexed_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_19get_indexed_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_18get_indexed_string}; static PyObject *__pyx_pw_3hid_6device_19get_indexed_string(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { PyObject *__pyx_v_index = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_indexed_string (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_index,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 291, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 291, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_indexed_string", 0) < 0) __PYX_ERR(0, 291, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_indexed_string", 1, 1, 1, i); __PYX_ERR(0, 291, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 291, __pyx_L3_error) } __pyx_v_index = values[0]; } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("get_indexed_string", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 291, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.get_indexed_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_18get_indexed_string(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_index); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_18get_indexed_string(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_index) { wchar_t __pyx_v_buff[0xFF]; unsigned char __pyx_v_c_index; int __pyx_v_r; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; unsigned char __pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_indexed_string", 0); /* "hid.pyx":299 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":300 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef wchar_t buff[255] * cdef unsigned char c_index = index */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 300, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 300, __pyx_L1_error) /* "hid.pyx":299 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef wchar_t buff[255] */ } /* "hid.pyx":302 * raise ValueError('not open') * cdef wchar_t buff[255] * cdef unsigned char c_index = index # <<<<<<<<<<<<<< * cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) * if r < 0: */ __pyx_t_6 = __Pyx_PyLong_As_unsigned_char(__pyx_v_index); if (unlikely((__pyx_t_6 == (unsigned char)-1) && PyErr_Occurred())) __PYX_ERR(0, 302, __pyx_L1_error) __pyx_v_c_index = __pyx_t_6; /* "hid.pyx":303 * cdef wchar_t buff[255] * cdef unsigned char c_index = index * cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) # <<<<<<<<<<<<<< * if r < 0: * raise IOError('get indexed string error') */ __pyx_v_r = hid_get_indexed_string(__pyx_v_self->_c_hid, __pyx_v_c_index, __pyx_v_buff, 0xFF); /* "hid.pyx":304 * cdef unsigned char c_index = index * cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get indexed string error') * return U(buff) */ __pyx_t_1 = (__pyx_v_r < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":305 * cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) * if r < 0: * raise IOError('get indexed string error') # <<<<<<<<<<<<<< * return U(buff) * */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_get_indexed_string_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 305, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 305, __pyx_L1_error) /* "hid.pyx":304 * cdef unsigned char c_index = index * cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) * if r < 0: # <<<<<<<<<<<<<< * raise IOError('get indexed string error') * return U(buff) */ } /* "hid.pyx":306 * if r < 0: * raise IOError('get indexed string error') * return U(buff) # <<<<<<<<<<<<<< * * def send_feature_report(self, buff): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_f_3hid_U(__pyx_v_buff); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 306, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "hid.pyx":291 * return U(buff) * * def get_indexed_string(self, index): # <<<<<<<<<<<<<< * """Return indexed string. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_indexed_string", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":308 * return U(buff) * * def send_feature_report(self, buff): # <<<<<<<<<<<<<< * """Accept a list of integers (0-255) and send them to the device. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_21send_feature_report(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_20send_feature_report, "Accept a list of integers (0-255) and send them to the device.\n\n :param buff: Data to send (must be convertible into bytes)\n :type buff: any\n :return: Send result\n :rtype: int\n "); static PyMethodDef __pyx_mdef_3hid_6device_21send_feature_report = {"send_feature_report", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_21send_feature_report, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_20send_feature_report}; static PyObject *__pyx_pw_3hid_6device_21send_feature_report(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { PyObject *__pyx_v_buff = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("send_feature_report (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_buff,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 308, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 308, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "send_feature_report", 0) < 0) __PYX_ERR(0, 308, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("send_feature_report", 1, 1, 1, i); __PYX_ERR(0, 308, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 308, __pyx_L3_error) } __pyx_v_buff = values[0]; } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("send_feature_report", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 308, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.send_feature_report", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_20send_feature_report(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_buff); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_20send_feature_report(struct __pyx_obj_3hid_device *__pyx_v_self, PyObject *__pyx_v_buff) { hid_device *__pyx_v_c_hid; unsigned char *__pyx_v_cbuff; size_t __pyx_v_c_buff_len; int __pyx_v_result; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; PyObject *__pyx_t_6 = NULL; hid_device *__pyx_t_7; unsigned char *__pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("send_feature_report", 0); __Pyx_INCREF(__pyx_v_buff); /* "hid.pyx":316 * :rtype: int * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * # convert to bytes */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":317 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * # convert to bytes * if sys.version_info < (3, 0): */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 317, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 317, __pyx_L1_error) /* "hid.pyx":316 * :rtype: int * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * # convert to bytes */ } /* "hid.pyx":319 * raise ValueError('not open') * # convert to bytes * if sys.version_info < (3, 0): # <<<<<<<<<<<<<< * buff = ''.join(map(chr, buff)) * else: */ __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_sys); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 319, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_version_info); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 319, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyObject_RichCompare(__pyx_t_4, __pyx_mstate_global->__pyx_tuple[0], Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 319, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 319, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "hid.pyx":320 * # convert to bytes * if sys.version_info < (3, 0): * buff = ''.join(map(chr, buff)) # <<<<<<<<<<<<<< * else: * buff = bytes(buff) */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_map); __pyx_t_3 = __pyx_builtin_map; __pyx_t_6 = __Pyx_GetBuiltinName(__pyx_mstate_global->__pyx_n_u_chr); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 320, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_5 = 1; { PyObject *__pyx_callargs[3] = {__pyx_t_4, __pyx_t_6, __pyx_v_buff}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 320, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __pyx_t_3 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u_, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 320, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_buff, __pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":319 * raise ValueError('not open') * # convert to bytes * if sys.version_info < (3, 0): # <<<<<<<<<<<<<< * buff = ''.join(map(chr, buff)) * else: */ goto __pyx_L4; } /* "hid.pyx":322 * buff = ''.join(map(chr, buff)) * else: * buff = bytes(buff) # <<<<<<<<<<<<<< * cdef hid_device * c_hid = self._c_hid * cdef unsigned char* cbuff = buff # covert to c string */ /*else*/ { __pyx_t_2 = NULL; __Pyx_INCREF((PyObject *)(&PyBytes_Type)); __pyx_t_6 = ((PyObject *)(&PyBytes_Type)); __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_buff}; __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 322, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); } __Pyx_DECREF_SET(__pyx_v_buff, __pyx_t_3); __pyx_t_3 = 0; } __pyx_L4:; /* "hid.pyx":323 * else: * buff = bytes(buff) * cdef hid_device * c_hid = self._c_hid # <<<<<<<<<<<<<< * cdef unsigned char* cbuff = buff # covert to c string * cdef size_t c_buff_len = len(buff) */ __pyx_t_7 = __pyx_v_self->_c_hid; __pyx_v_c_hid = __pyx_t_7; /* "hid.pyx":324 * buff = bytes(buff) * cdef hid_device * c_hid = self._c_hid * cdef unsigned char* cbuff = buff # covert to c string # <<<<<<<<<<<<<< * cdef size_t c_buff_len = len(buff) * cdef int result */ __pyx_t_8 = __Pyx_PyObject_AsWritableUString(__pyx_v_buff); if (unlikely((!__pyx_t_8) && PyErr_Occurred())) __PYX_ERR(0, 324, __pyx_L1_error) __pyx_v_cbuff = __pyx_t_8; /* "hid.pyx":325 * cdef hid_device * c_hid = self._c_hid * cdef unsigned char* cbuff = buff # covert to c string * cdef size_t c_buff_len = len(buff) # <<<<<<<<<<<<<< * cdef int result * with nogil: */ __pyx_t_9 = PyObject_Length(__pyx_v_buff); if (unlikely(__pyx_t_9 == ((Py_ssize_t)-1))) __PYX_ERR(0, 325, __pyx_L1_error) __pyx_v_c_buff_len = __pyx_t_9; /* "hid.pyx":327 * cdef size_t c_buff_len = len(buff) * cdef int result * with nogil: # <<<<<<<<<<<<<< * result = hid_send_feature_report(c_hid, cbuff, c_buff_len) * return result */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":328 * cdef int result * with nogil: * result = hid_send_feature_report(c_hid, cbuff, c_buff_len) # <<<<<<<<<<<<<< * return result * */ __pyx_v_result = hid_send_feature_report(__pyx_v_c_hid, __pyx_v_cbuff, __pyx_v_c_buff_len); } /* "hid.pyx":327 * cdef size_t c_buff_len = len(buff) * cdef int result * with nogil: # <<<<<<<<<<<<<< * result = hid_send_feature_report(c_hid, cbuff, c_buff_len) * return result */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L7; } __pyx_L7:; } } /* "hid.pyx":329 * with nogil: * result = hid_send_feature_report(c_hid, cbuff, c_buff_len) * return result # <<<<<<<<<<<<<< * * def get_report_descriptor(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_result); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 329, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "hid.pyx":308 * return U(buff) * * def send_feature_report(self, buff): # <<<<<<<<<<<<<< * """Accept a list of integers (0-255) and send them to the device. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("hid.device.send_feature_report", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_buff); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":331 * return result * * def get_report_descriptor(self): # <<<<<<<<<<<<<< * """Return the HID Report Descriptor for this device. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_23get_report_descriptor(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_22get_report_descriptor, "Return the HID Report Descriptor for this device.\n\n :return:\n :rtype: List[int]\n :raises ValueError: If connection is not opened.\n :raises IOError: If read error\n "); static PyMethodDef __pyx_mdef_3hid_6device_23get_report_descriptor = {"get_report_descriptor", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_23get_report_descriptor, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_22get_report_descriptor}; static PyObject *__pyx_pw_3hid_6device_23get_report_descriptor(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_report_descriptor (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("get_report_descriptor", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("get_report_descriptor", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_22get_report_descriptor(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_22get_report_descriptor(struct __pyx_obj_3hid_device *__pyx_v_self) { unsigned char __pyx_v_cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE]; hid_device *__pyx_v_c_hid; int __pyx_v_n; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; hid_device *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_report_descriptor", 0); /* "hid.pyx":339 * :raises IOError: If read error * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":340 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * * cdef unsigned char cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE] */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 340, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 340, __pyx_L1_error) /* "hid.pyx":339 * :raises IOError: If read error * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * */ } /* "hid.pyx":343 * * cdef unsigned char cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE] * cdef hid_device * c_hid = self._c_hid # <<<<<<<<<<<<<< * cdef int n * with nogil: */ __pyx_t_6 = __pyx_v_self->_c_hid; __pyx_v_c_hid = __pyx_t_6; /* "hid.pyx":345 * cdef hid_device * c_hid = self._c_hid * cdef int n * with nogil: # <<<<<<<<<<<<<< * n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) * if n < 0: */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":346 * cdef int n * with nogil: * n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) # <<<<<<<<<<<<<< * if n < 0: * raise IOError('read error') */ __pyx_v_n = hid_get_report_descriptor(__pyx_v_c_hid, __pyx_v_cbuff, (sizeof(__pyx_v_cbuff))); } /* "hid.pyx":345 * cdef hid_device * c_hid = self._c_hid * cdef int n * with nogil: # <<<<<<<<<<<<<< * n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) * if n < 0: */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L6; } __pyx_L6:; } } /* "hid.pyx":347 * with nogil: * n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) * if n < 0: # <<<<<<<<<<<<<< * raise IOError('read error') * return list(cbuff[:n]) */ __pyx_t_1 = (__pyx_v_n < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":348 * n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) * if n < 0: * raise IOError('read error') # <<<<<<<<<<<<<< * return list(cbuff[:n]) * */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_read_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 348, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 348, __pyx_L1_error) /* "hid.pyx":347 * with nogil: * n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) * if n < 0: # <<<<<<<<<<<<<< * raise IOError('read error') * return list(cbuff[:n]) */ } /* "hid.pyx":349 * if n < 0: * raise IOError('read error') * return list(cbuff[:n]) # <<<<<<<<<<<<<< * * def get_feature_report(self, int report_num, int max_length): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(((char const *)__pyx_v_cbuff) + 0, __pyx_v_n - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 349, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_List(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 349, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "hid.pyx":331 * return result * * def get_report_descriptor(self): # <<<<<<<<<<<<<< * """Return the HID Report Descriptor for this device. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_report_descriptor", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":351 * return list(cbuff[:n]) * * def get_feature_report(self, int report_num, int max_length): # <<<<<<<<<<<<<< * """Receive feature report. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_25get_feature_report(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_24get_feature_report, "Receive feature report.\n\n :param report_num:\n :type report_num: int\n :param max_length:\n :type max_length: int\n :return: Incoming feature report\n :rtype: List[int]\n :raises ValueError: If connection is not opened.\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_25get_feature_report = {"get_feature_report", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_25get_feature_report, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_24get_feature_report}; static PyObject *__pyx_pw_3hid_6device_25get_feature_report(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { int __pyx_v_report_num; int __pyx_v_max_length; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[2] = {0,0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_feature_report (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_report_num,&__pyx_mstate_global->__pyx_n_u_max_length,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 351, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 351, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 351, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_feature_report", 0) < 0) __PYX_ERR(0, 351, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_feature_report", 1, 2, 2, i); __PYX_ERR(0, 351, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 2)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 351, __pyx_L3_error) values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 351, __pyx_L3_error) } __pyx_v_report_num = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_report_num == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 351, __pyx_L3_error) __pyx_v_max_length = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_max_length == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 351, __pyx_L3_error) } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("get_feature_report", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 351, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.get_feature_report", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_24get_feature_report(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_report_num, __pyx_v_max_length); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_24get_feature_report(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_report_num, int __pyx_v_max_length) { hid_device *__pyx_v_c_hid; unsigned char __pyx_v_lbuff[16]; unsigned char *__pyx_v_cbuff; size_t __pyx_v_c_max_length; int __pyx_v_n; PyObject *__pyx_v_res = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; hid_device *__pyx_t_6; int __pyx_t_7; int __pyx_t_8; char const *__pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; PyObject *__pyx_t_13 = NULL; PyObject *__pyx_t_14 = NULL; PyObject *__pyx_t_15 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_feature_report", 0); /* "hid.pyx":363 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef hid_device * c_hid = self._c_hid */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":364 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef hid_device * c_hid = self._c_hid * cdef unsigned char lbuff[16] */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 364, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 364, __pyx_L1_error) /* "hid.pyx":363 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef hid_device * c_hid = self._c_hid */ } /* "hid.pyx":365 * if self._c_hid == NULL: * raise ValueError('not open') * cdef hid_device * c_hid = self._c_hid # <<<<<<<<<<<<<< * cdef unsigned char lbuff[16] * cdef unsigned char* cbuff */ __pyx_t_6 = __pyx_v_self->_c_hid; __pyx_v_c_hid = __pyx_t_6; /* "hid.pyx":368 * cdef unsigned char lbuff[16] * cdef unsigned char* cbuff * cdef size_t c_max_length = max_length # <<<<<<<<<<<<<< * cdef int n * try: */ __pyx_v_c_max_length = __pyx_v_max_length; /* "hid.pyx":370 * cdef size_t c_max_length = max_length * cdef int n * try: # <<<<<<<<<<<<<< * if max_length <= 16: * cbuff = lbuff */ /*try:*/ { /* "hid.pyx":371 * cdef int n * try: * if max_length <= 16: # <<<<<<<<<<<<<< * cbuff = lbuff * else: */ __pyx_t_1 = (__pyx_v_max_length <= 16); if (__pyx_t_1) { /* "hid.pyx":372 * try: * if max_length <= 16: * cbuff = lbuff # <<<<<<<<<<<<<< * else: * cbuff = malloc(max_length) */ __pyx_v_cbuff = __pyx_v_lbuff; /* "hid.pyx":371 * cdef int n * try: * if max_length <= 16: # <<<<<<<<<<<<<< * cbuff = lbuff * else: */ goto __pyx_L7; } /* "hid.pyx":374 * cbuff = lbuff * else: * cbuff = malloc(max_length) # <<<<<<<<<<<<<< * cbuff[0] = report_num * with nogil: */ /*else*/ { __pyx_v_cbuff = ((unsigned char *)malloc(__pyx_v_max_length)); } __pyx_L7:; /* "hid.pyx":375 * else: * cbuff = malloc(max_length) * cbuff[0] = report_num # <<<<<<<<<<<<<< * with nogil: * n = hid_get_feature_report(c_hid, cbuff, c_max_length) */ (__pyx_v_cbuff[0]) = __pyx_v_report_num; /* "hid.pyx":376 * cbuff = malloc(max_length) * cbuff[0] = report_num * with nogil: # <<<<<<<<<<<<<< * n = hid_get_feature_report(c_hid, cbuff, c_max_length) * if n < 0: */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":377 * cbuff[0] = report_num * with nogil: * n = hid_get_feature_report(c_hid, cbuff, c_max_length) # <<<<<<<<<<<<<< * if n < 0: * raise IOError('read error') */ __pyx_v_n = hid_get_feature_report(__pyx_v_c_hid, __pyx_v_cbuff, __pyx_v_c_max_length); } /* "hid.pyx":376 * cbuff = malloc(max_length) * cbuff[0] = report_num * with nogil: # <<<<<<<<<<<<<< * n = hid_get_feature_report(c_hid, cbuff, c_max_length) * if n < 0: */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L10; } __pyx_L10:; } } /* "hid.pyx":378 * with nogil: * n = hid_get_feature_report(c_hid, cbuff, c_max_length) * if n < 0: # <<<<<<<<<<<<<< * raise IOError('read error') * res = list(cbuff[:n]) */ __pyx_t_1 = (__pyx_v_n < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":379 * n = hid_get_feature_report(c_hid, cbuff, c_max_length) * if n < 0: * raise IOError('read error') # <<<<<<<<<<<<<< * res = list(cbuff[:n]) * finally: */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_read_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 379, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 379, __pyx_L5_error) /* "hid.pyx":378 * with nogil: * n = hid_get_feature_report(c_hid, cbuff, c_max_length) * if n < 0: # <<<<<<<<<<<<<< * raise IOError('read error') * res = list(cbuff[:n]) */ } /* "hid.pyx":380 * if n < 0: * raise IOError('read error') * res = list(cbuff[:n]) # <<<<<<<<<<<<<< * finally: * if max_length > 16: */ __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(((char const *)__pyx_v_cbuff) + 0, __pyx_v_n - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 380, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_List(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 380, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_res = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; } /* "hid.pyx":382 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ /*finally:*/ { /*normal exit:*/{ __pyx_t_1 = (__pyx_v_max_length > 16); if (__pyx_t_1) { /* "hid.pyx":383 * finally: * if max_length > 16: * free(cbuff) # <<<<<<<<<<<<<< * return res * */ free(__pyx_v_cbuff); /* "hid.pyx":382 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ } goto __pyx_L6; } __pyx_L5_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_ExceptionSwap(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); if ( unlikely(__Pyx_GetException(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12) < 0)) __Pyx_ErrFetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __Pyx_XGOTREF(__pyx_t_12); __Pyx_XGOTREF(__pyx_t_13); __Pyx_XGOTREF(__pyx_t_14); __Pyx_XGOTREF(__pyx_t_15); __pyx_t_7 = __pyx_lineno; __pyx_t_8 = __pyx_clineno; __pyx_t_9 = __pyx_filename; { __pyx_t_1 = (__pyx_v_max_length > 16); if (__pyx_t_1) { /* "hid.pyx":383 * finally: * if max_length > 16: * free(cbuff) # <<<<<<<<<<<<<< * return res * */ free(__pyx_v_cbuff); /* "hid.pyx":382 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ } } __Pyx_XGIVEREF(__pyx_t_13); __Pyx_XGIVEREF(__pyx_t_14); __Pyx_XGIVEREF(__pyx_t_15); __Pyx_ExceptionReset(__pyx_t_13, __pyx_t_14, __pyx_t_15); __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_XGIVEREF(__pyx_t_12); __Pyx_ErrRestore(__pyx_t_10, __pyx_t_11, __pyx_t_12); __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_lineno = __pyx_t_7; __pyx_clineno = __pyx_t_8; __pyx_filename = __pyx_t_9; goto __pyx_L1_error; } __pyx_L6:; } /* "hid.pyx":384 * if max_length > 16: * free(cbuff) * return res # <<<<<<<<<<<<<< * * def get_input_report(self, int report_num, int max_length): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_res); __pyx_r = __pyx_v_res; goto __pyx_L0; /* "hid.pyx":351 * return list(cbuff[:n]) * * def get_feature_report(self, int report_num, int max_length): # <<<<<<<<<<<<<< * """Receive feature report. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_feature_report", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_res); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":386 * return res * * def get_input_report(self, int report_num, int max_length): # <<<<<<<<<<<<<< * """Get input report * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_27get_input_report(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_26get_input_report, "Get input report\n\n :param report_num:\n :type report_num: int\n :param max_length:\n :type max_length: int\n :return:\n :rtype: List[int]\n :raises ValueError: If connection is not opened.\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_27get_input_report = {"get_input_report", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_27get_input_report, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_26get_input_report}; static PyObject *__pyx_pw_3hid_6device_27get_input_report(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { int __pyx_v_report_num; int __pyx_v_max_length; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[2] = {0,0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("get_input_report (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_report_num,&__pyx_mstate_global->__pyx_n_u_max_length,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 386, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 2: values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 386, __pyx_L3_error) CYTHON_FALLTHROUGH; case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 386, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_input_report", 0) < 0) __PYX_ERR(0, 386, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_input_report", 1, 2, 2, i); __PYX_ERR(0, 386, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 2)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 386, __pyx_L3_error) values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 386, __pyx_L3_error) } __pyx_v_report_num = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_report_num == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 386, __pyx_L3_error) __pyx_v_max_length = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_max_length == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 386, __pyx_L3_error) } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("get_input_report", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 386, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.get_input_report", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_26get_input_report(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v_report_num, __pyx_v_max_length); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_26get_input_report(struct __pyx_obj_3hid_device *__pyx_v_self, int __pyx_v_report_num, int __pyx_v_max_length) { hid_device *__pyx_v_c_hid; unsigned char __pyx_v_lbuff[16]; unsigned char *__pyx_v_cbuff; size_t __pyx_v_c_max_length; int __pyx_v_n; PyObject *__pyx_v_res = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; size_t __pyx_t_5; hid_device *__pyx_t_6; int __pyx_t_7; int __pyx_t_8; char const *__pyx_t_9; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; PyObject *__pyx_t_13 = NULL; PyObject *__pyx_t_14 = NULL; PyObject *__pyx_t_15 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_input_report", 0); /* "hid.pyx":398 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef hid_device * c_hid = self._c_hid */ __pyx_t_1 = (__pyx_v_self->_c_hid == NULL); if (unlikely(__pyx_t_1)) { /* "hid.pyx":399 * """ * if self._c_hid == NULL: * raise ValueError('not open') # <<<<<<<<<<<<<< * cdef hid_device * c_hid = self._c_hid * cdef unsigned char lbuff[16] */ __pyx_t_3 = NULL; __Pyx_INCREF(__pyx_builtin_ValueError); __pyx_t_4 = __pyx_builtin_ValueError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_not_open}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 399, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 399, __pyx_L1_error) /* "hid.pyx":398 * :raises IOError: * """ * if self._c_hid == NULL: # <<<<<<<<<<<<<< * raise ValueError('not open') * cdef hid_device * c_hid = self._c_hid */ } /* "hid.pyx":400 * if self._c_hid == NULL: * raise ValueError('not open') * cdef hid_device * c_hid = self._c_hid # <<<<<<<<<<<<<< * cdef unsigned char lbuff[16] * cdef unsigned char* cbuff */ __pyx_t_6 = __pyx_v_self->_c_hid; __pyx_v_c_hid = __pyx_t_6; /* "hid.pyx":403 * cdef unsigned char lbuff[16] * cdef unsigned char* cbuff * cdef size_t c_max_length = max_length # <<<<<<<<<<<<<< * cdef int n * try: */ __pyx_v_c_max_length = __pyx_v_max_length; /* "hid.pyx":405 * cdef size_t c_max_length = max_length * cdef int n * try: # <<<<<<<<<<<<<< * if max_length <= 16: * cbuff = lbuff */ /*try:*/ { /* "hid.pyx":406 * cdef int n * try: * if max_length <= 16: # <<<<<<<<<<<<<< * cbuff = lbuff * else: */ __pyx_t_1 = (__pyx_v_max_length <= 16); if (__pyx_t_1) { /* "hid.pyx":407 * try: * if max_length <= 16: * cbuff = lbuff # <<<<<<<<<<<<<< * else: * cbuff = malloc(max_length) */ __pyx_v_cbuff = __pyx_v_lbuff; /* "hid.pyx":406 * cdef int n * try: * if max_length <= 16: # <<<<<<<<<<<<<< * cbuff = lbuff * else: */ goto __pyx_L7; } /* "hid.pyx":409 * cbuff = lbuff * else: * cbuff = malloc(max_length) # <<<<<<<<<<<<<< * cbuff[0] = report_num * with nogil: */ /*else*/ { __pyx_v_cbuff = ((unsigned char *)malloc(__pyx_v_max_length)); } __pyx_L7:; /* "hid.pyx":410 * else: * cbuff = malloc(max_length) * cbuff[0] = report_num # <<<<<<<<<<<<<< * with nogil: * n = hid_get_input_report(c_hid, cbuff, c_max_length) */ (__pyx_v_cbuff[0]) = __pyx_v_report_num; /* "hid.pyx":411 * cbuff = malloc(max_length) * cbuff[0] = report_num * with nogil: # <<<<<<<<<<<<<< * n = hid_get_input_report(c_hid, cbuff, c_max_length) * if n < 0: */ { PyThreadState *_save; _save = NULL; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); /*try:*/ { /* "hid.pyx":412 * cbuff[0] = report_num * with nogil: * n = hid_get_input_report(c_hid, cbuff, c_max_length) # <<<<<<<<<<<<<< * if n < 0: * raise IOError('read error') */ __pyx_v_n = hid_get_input_report(__pyx_v_c_hid, __pyx_v_cbuff, __pyx_v_c_max_length); } /* "hid.pyx":411 * cbuff = malloc(max_length) * cbuff[0] = report_num * with nogil: # <<<<<<<<<<<<<< * n = hid_get_input_report(c_hid, cbuff, c_max_length) * if n < 0: */ /*finally:*/ { /*normal exit:*/{ __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS goto __pyx_L10; } __pyx_L10:; } } /* "hid.pyx":413 * with nogil: * n = hid_get_input_report(c_hid, cbuff, c_max_length) * if n < 0: # <<<<<<<<<<<<<< * raise IOError('read error') * res = list(cbuff[:n]) */ __pyx_t_1 = (__pyx_v_n < 0); if (unlikely(__pyx_t_1)) { /* "hid.pyx":414 * n = hid_get_input_report(c_hid, cbuff, c_max_length) * if n < 0: * raise IOError('read error') # <<<<<<<<<<<<<< * res = list(cbuff[:n]) * finally: */ __pyx_t_4 = NULL; __Pyx_INCREF(__pyx_builtin_IOError); __pyx_t_3 = __pyx_builtin_IOError; __pyx_t_5 = 1; { PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_read_error}; __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 414, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); } __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 414, __pyx_L5_error) /* "hid.pyx":413 * with nogil: * n = hid_get_input_report(c_hid, cbuff, c_max_length) * if n < 0: # <<<<<<<<<<<<<< * raise IOError('read error') * res = list(cbuff[:n]) */ } /* "hid.pyx":415 * if n < 0: * raise IOError('read error') * res = list(cbuff[:n]) # <<<<<<<<<<<<<< * finally: * if max_length > 16: */ __pyx_t_2 = __Pyx_PyBytes_FromStringAndSize(((char const *)__pyx_v_cbuff) + 0, __pyx_v_n - 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 415, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_List(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 415, __pyx_L5_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_res = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; } /* "hid.pyx":417 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ /*finally:*/ { /*normal exit:*/{ __pyx_t_1 = (__pyx_v_max_length > 16); if (__pyx_t_1) { /* "hid.pyx":418 * finally: * if max_length > 16: * free(cbuff) # <<<<<<<<<<<<<< * return res * */ free(__pyx_v_cbuff); /* "hid.pyx":417 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ } goto __pyx_L6; } __pyx_L5_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_ExceptionSwap(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); if ( unlikely(__Pyx_GetException(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12) < 0)) __Pyx_ErrFetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __Pyx_XGOTREF(__pyx_t_12); __Pyx_XGOTREF(__pyx_t_13); __Pyx_XGOTREF(__pyx_t_14); __Pyx_XGOTREF(__pyx_t_15); __pyx_t_7 = __pyx_lineno; __pyx_t_8 = __pyx_clineno; __pyx_t_9 = __pyx_filename; { __pyx_t_1 = (__pyx_v_max_length > 16); if (__pyx_t_1) { /* "hid.pyx":418 * finally: * if max_length > 16: * free(cbuff) # <<<<<<<<<<<<<< * return res * */ free(__pyx_v_cbuff); /* "hid.pyx":417 * res = list(cbuff[:n]) * finally: * if max_length > 16: # <<<<<<<<<<<<<< * free(cbuff) * return res */ } } __Pyx_XGIVEREF(__pyx_t_13); __Pyx_XGIVEREF(__pyx_t_14); __Pyx_XGIVEREF(__pyx_t_15); __Pyx_ExceptionReset(__pyx_t_13, __pyx_t_14, __pyx_t_15); __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_XGIVEREF(__pyx_t_12); __Pyx_ErrRestore(__pyx_t_10, __pyx_t_11, __pyx_t_12); __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_lineno = __pyx_t_7; __pyx_clineno = __pyx_t_8; __pyx_filename = __pyx_t_9; goto __pyx_L1_error; } __pyx_L6:; } /* "hid.pyx":419 * if max_length > 16: * free(cbuff) * return res # <<<<<<<<<<<<<< * * def error(self): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_res); __pyx_r = __pyx_v_res; goto __pyx_L0; /* "hid.pyx":386 * return res * * def get_input_report(self, int report_num, int max_length): # <<<<<<<<<<<<<< * """Get input report * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("hid.device.get_input_report", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_res); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "hid.pyx":421 * return res * * def error(self): # <<<<<<<<<<<<<< * """Get error from device, or global error if no device is opened. * */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_29error(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ PyDoc_STRVAR(__pyx_doc_3hid_6device_28error, "Get error from device, or global error if no device is opened.\n\n :return:\n :rtype: str\n :raises IOError:\n "); static PyMethodDef __pyx_mdef_3hid_6device_29error = {"error", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_29error, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_28error}; static PyObject *__pyx_pw_3hid_6device_29error(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("error (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("error", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("error", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_28error(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_28error(struct __pyx_obj_3hid_device *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("error", 0); /* "hid.pyx":428 * :raises IOError: * """ * return U(hid_error(self._c_hid)) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_f_3hid_U(((wchar_t *)hid_error(__pyx_v_self->_c_hid))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 428, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "hid.pyx":421 * return res * * def error(self): # <<<<<<<<<<<<<< * """Get error from device, or global error if no device is opened. * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("hid.device.error", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_31__reduce_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ static PyMethodDef __pyx_mdef_3hid_6device_31__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_31__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3hid_6device_31__reduce_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len < 0)) return NULL; if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} __pyx_r = __pyx_pf_3hid_6device_30__reduce_cython__(((struct __pyx_obj_3hid_device *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_30__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_3hid_device *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" */ __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self__c_hid_cannot_be_converted, 0, 0); __PYX_ERR(1, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("hid.device.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" */ /* Python wrapper */ static PyObject *__pyx_pw_3hid_6device_33__setstate_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ); /*proto*/ static PyMethodDef __pyx_mdef_3hid_6device_33__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_33__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_3hid_6device_33__setstate_cython__(PyObject *__pyx_v_self, #if CYTHON_METH_FASTCALL PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds #else PyObject *__pyx_args, PyObject *__pyx_kwds #endif ) { CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; #if !CYTHON_METH_FASTCALL CYTHON_UNUSED Py_ssize_t __pyx_nargs; #endif CYTHON_UNUSED PyObject *const *__pyx_kwvalues; PyObject* values[1] = {0}; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); #if !CYTHON_METH_FASTCALL #if CYTHON_ASSUME_SAFE_SIZE __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); #else __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; #endif #endif __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); { PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(1, 3, __pyx_L3_error) if (__pyx_kwds_len > 0) { switch (__pyx_nargs) { case 1: values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 3, __pyx_L3_error) CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } const Py_ssize_t kwd_pos_args = __pyx_nargs; if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(1, 3, __pyx_L3_error) for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(1, 3, __pyx_L3_error) } } } else if (unlikely(__pyx_nargs != 1)) { goto __pyx_L5_argtuple_error; } else { values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(1, 3, __pyx_L3_error) } __pyx_v___pyx_state = values[0]; } goto __pyx_L6_skip; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(1, 3, __pyx_L3_error) __pyx_L6_skip:; goto __pyx_L4_argument_unpacking_done; __pyx_L3_error:; for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_AddTraceback("hid.device.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_3hid_6device_32__setstate_cython__(((struct __pyx_obj_3hid_device *)__pyx_v_self), __pyx_v___pyx_state); /* function exit code */ for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { Py_XDECREF(values[__pyx_temp]); } __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_3hid_6device_32__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_3hid_device *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< */ __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self__c_hid_cannot_be_converted, 0, 0); __PYX_ERR(1, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" */ /* function exit code */ __pyx_L1_error:; __Pyx_AddTraceback("hid.device.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* #### Code section: module_exttypes ### */ static struct __pyx_vtabstruct_3hid__closer __pyx_vtable_3hid__closer; static PyObject *__pyx_tp_new_3hid__closer(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_obj_3hid__closer *p; PyObject *o; #if CYTHON_COMPILING_IN_LIMITED_API allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); o = alloc_func(t, 0); #else if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; #endif p = ((struct __pyx_obj_3hid__closer *)o); p->__pyx_vtab = __pyx_vtabptr_3hid__closer; return o; } static void __pyx_tp_dealloc_3hid__closer(PyObject *o) { #if CYTHON_USE_TP_FINALIZE if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_3hid__closer) { if (PyObject_CallFinalizerFromDealloc(o)) return; } } #endif #if CYTHON_USE_TYPE_SLOTS (*Py_TYPE(o)->tp_free)(o); #else { freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); if (tp_free) tp_free(o); } #endif } static PyMethodDef __pyx_methods_3hid__closer[] = { {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_7_closer_1close, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_7_closer_3__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_7_closer_5__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; #if CYTHON_USE_TYPE_SPECS static PyType_Slot __pyx_type_3hid__closer_slots[] = { {Py_tp_dealloc, (void *)__pyx_tp_dealloc_3hid__closer}, {Py_tp_doc, (void *)PyDoc_STR("Wrap a hid_device *ptr and a provide a way to call hid_close() on it.\n\n Used internally for weakref.finalize, which only accepts Python objects.\n ")}, {Py_tp_methods, (void *)__pyx_methods_3hid__closer}, {Py_tp_new, (void *)__pyx_tp_new_3hid__closer}, {0, 0}, }; static PyType_Spec __pyx_type_3hid__closer_spec = { "hid._closer", sizeof(struct __pyx_obj_3hid__closer), 0, Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, __pyx_type_3hid__closer_slots, }; #else static PyTypeObject __pyx_type_3hid__closer = { PyVarObject_HEAD_INIT(0, 0) "hid.""_closer", /*tp_name*/ sizeof(struct __pyx_obj_3hid__closer), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_3hid__closer, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_as_async*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ PyDoc_STR("Wrap a hid_device *ptr and a provide a way to call hid_close() on it.\n\n Used internally for weakref.finalize, which only accepts Python objects.\n "), /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_3hid__closer, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ #if !CYTHON_USE_TYPE_SPECS 0, /*tp_dictoffset*/ #endif 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_3hid__closer, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if CYTHON_USE_TP_FINALIZE 0, /*tp_finalize*/ #else NULL, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) 0, /*tp_vectorcall*/ #endif #if __PYX_NEED_TP_PRINT_SLOT == 1 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030C0000 0, /*tp_watched*/ #endif #if PY_VERSION_HEX >= 0x030d00A4 0, /*tp_versions_used*/ #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 0, /*tp_pypy_flags*/ #endif }; #endif static PyObject *__pyx_tp_new_3hid_device(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_obj_3hid_device *p; PyObject *o; #if CYTHON_COMPILING_IN_LIMITED_API allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); o = alloc_func(t, 0); #else if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; #endif p = ((struct __pyx_obj_3hid_device *)o); p->_close = Py_None; Py_INCREF(Py_None); return o; } static void __pyx_tp_dealloc_3hid_device(PyObject *o) { struct __pyx_obj_3hid_device *p = (struct __pyx_obj_3hid_device *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_3hid_device) { if (PyObject_CallFinalizerFromDealloc(o)) return; } } #endif PyObject_GC_UnTrack(o); if (p->__weakref__) PyObject_ClearWeakRefs(o); Py_CLEAR(p->_close); #if CYTHON_USE_TYPE_SLOTS (*Py_TYPE(o)->tp_free)(o); #else { freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); if (tp_free) tp_free(o); } #endif } static int __pyx_tp_traverse_3hid_device(PyObject *o, visitproc v, void *a) { int e; struct __pyx_obj_3hid_device *p = (struct __pyx_obj_3hid_device *)o; { e = __Pyx_call_type_traverse(o, 1, v, a); if (e) return e; } if (p->_close) { e = (*v)(p->_close, a); if (e) return e; } return 0; } static int __pyx_tp_clear_3hid_device(PyObject *o) { PyObject* tmp; struct __pyx_obj_3hid_device *p = (struct __pyx_obj_3hid_device *)o; tmp = ((PyObject*)p->_close); p->_close = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static PyMethodDef __pyx_methods_3hid_device[] = { {"open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_1open, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_open}, {"open_path", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_3open_path, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_2open_path}, {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_5close, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_4close}, {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_7write, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_6write}, {"set_nonblocking", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_9set_nonblocking, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_8set_nonblocking}, {"read", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_11read, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_10read}, {"get_manufacturer_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_13get_manufacturer_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_12get_manufacturer_string}, {"get_product_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_15get_product_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_14get_product_string}, {"get_serial_number_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_17get_serial_number_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_16get_serial_number_string}, {"get_indexed_string", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_19get_indexed_string, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_18get_indexed_string}, {"send_feature_report", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_21send_feature_report, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_20send_feature_report}, {"get_report_descriptor", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_23get_report_descriptor, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_22get_report_descriptor}, {"get_feature_report", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_25get_feature_report, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_24get_feature_report}, {"get_input_report", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_27get_input_report, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_26get_input_report}, {"error", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_29error, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_3hid_6device_28error}, {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_31__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_3hid_6device_33__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; #if CYTHON_USE_TYPE_SPECS static PyMemberDef __pyx_type_3hid_device_members[] = { #if !CYTHON_USE_TYPE_SLOTS {"__weaklistoffset__", T_PYSSIZET, offsetof(struct __pyx_obj_3hid_device, __weakref__), READONLY, 0}, #endif {0, 0, 0, 0, 0} }; #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 #if defined(__GNUC__) || defined(__clang__) #warning "hid.pyx:109:16: : __weakref__ is unsupported in the Limited API when running on Python <3.9." #elif defined(_MSC_VER) #pragma message("hid.pyx:109:16: : __weakref__ is unsupported in the Limited API when running on Python <3.9.") #endif #endif static PyType_Slot __pyx_type_3hid_device_slots[] = { {Py_tp_dealloc, (void *)__pyx_tp_dealloc_3hid_device}, {Py_tp_doc, (void *)PyDoc_STR("Device class.\n\n A device instance can be used to read from and write to a HID device.\n ")}, {Py_tp_traverse, (void *)__pyx_tp_traverse_3hid_device}, {Py_tp_clear, (void *)__pyx_tp_clear_3hid_device}, {Py_tp_methods, (void *)__pyx_methods_3hid_device}, {Py_tp_new, (void *)__pyx_tp_new_3hid_device}, {Py_tp_members, (void*)__pyx_type_3hid_device_members}, {0, 0}, }; static PyType_Spec __pyx_type_3hid_device_spec = { "hid.device", sizeof(struct __pyx_obj_3hid_device), 0, Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, __pyx_type_3hid_device_slots, }; #else static PyTypeObject __pyx_type_3hid_device = { PyVarObject_HEAD_INIT(0, 0) "hid.""device", /*tp_name*/ sizeof(struct __pyx_obj_3hid_device), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_3hid_device, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_as_async*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ PyDoc_STR("Device class.\n\n A device instance can be used to read from and write to a HID device.\n "), /*tp_doc*/ __pyx_tp_traverse_3hid_device, /*tp_traverse*/ __pyx_tp_clear_3hid_device, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_3hid_device, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ #if !CYTHON_USE_TYPE_SPECS 0, /*tp_dictoffset*/ #endif 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_3hid_device, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if CYTHON_USE_TP_FINALIZE 0, /*tp_finalize*/ #else NULL, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) 0, /*tp_vectorcall*/ #endif #if __PYX_NEED_TP_PRINT_SLOT == 1 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030C0000 0, /*tp_watched*/ #endif #if PY_VERSION_HEX >= 0x030d00A4 0, /*tp_versions_used*/ #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 0, /*tp_pypy_flags*/ #endif }; #endif static PyObject *__pyx_tp_new___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { PyObject *o; #if CYTHON_COMPILING_IN_LIMITED_API allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); o = alloc_func(t, 0); #else #if CYTHON_USE_FREELISTS if (likely((int)(__pyx_mstate_global->__pyx_freecount___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ > 0) & (int)(t->tp_basicsize == sizeof(struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_)))) { o = (PyObject*)__pyx_mstate_global->__pyx_freelist___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_[--__pyx_mstate_global->__pyx_freecount___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_]; memset(o, 0, sizeof(struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_)); (void) PyObject_INIT(o, t); } else #endif { o = (*t->tp_alloc)(t, 0); if (unlikely(!o)) return 0; } #endif return o; } static void __pyx_tp_dealloc___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(PyObject *o) { #if CYTHON_USE_TP_FINALIZE if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_) { if (PyObject_CallFinalizerFromDealloc(o)) return; } } #endif #if CYTHON_USE_FREELISTS if (((int)(__pyx_mstate_global->__pyx_freecount___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ < 8) & (int)(Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_)))) { __pyx_mstate_global->__pyx_freelist___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_[__pyx_mstate_global->__pyx_freecount___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_++] = ((struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ *)o); } else #endif { #if CYTHON_USE_TYPE_SLOTS (*Py_TYPE(o)->tp_free)(o); #else { freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); if (tp_free) tp_free(o); } #endif } } #if CYTHON_USE_TYPE_SPECS static PyType_Slot __pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__slots[] = { {Py_tp_dealloc, (void *)__pyx_tp_dealloc___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_}, {Py_tp_new, (void *)__pyx_tp_new___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_}, {0, 0}, }; static PyType_Spec __pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__spec = { "hid.__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_", sizeof(struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_), 0, Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_FINALIZE, __pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__slots, }; #else static PyTypeObject __pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ = { PyVarObject_HEAD_INIT(0, 0) "hid.""__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_", /*tp_name*/ sizeof(struct __pyx_obj___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_as_async*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ #if !CYTHON_USE_TYPE_SPECS 0, /*tp_dictoffset*/ #endif 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if CYTHON_USE_TP_FINALIZE 0, /*tp_finalize*/ #else NULL, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) 0, /*tp_vectorcall*/ #endif #if __PYX_NEED_TP_PRINT_SLOT == 1 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030C0000 0, /*tp_watched*/ #endif #if PY_VERSION_HEX >= 0x030d00A4 0, /*tp_versions_used*/ #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 0, /*tp_pypy_flags*/ #endif }; #endif static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; /* #### Code section: initfunc_declarations ### */ static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ /* #### Code section: init_module ### */ static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); /*--- Global init code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); /*--- Variable export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); /*--- Function export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); /*--- Type init code ---*/ __pyx_vtabptr_3hid__closer = &__pyx_vtable_3hid__closer; __pyx_vtable_3hid__closer.wrap = (PyObject *(*)(hid_device *))__pyx_f_3hid_7_closer_wrap; #if CYTHON_USE_TYPE_SPECS __pyx_mstate->__pyx_ptype_3hid__closer = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_3hid__closer_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_3hid__closer)) __PYX_ERR(0, 85, __pyx_L1_error) if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_3hid__closer_spec, __pyx_mstate->__pyx_ptype_3hid__closer) < 0) __PYX_ERR(0, 85, __pyx_L1_error) #else __pyx_mstate->__pyx_ptype_3hid__closer = &__pyx_type_3hid__closer; #endif #if !CYTHON_COMPILING_IN_LIMITED_API #endif #if !CYTHON_USE_TYPE_SPECS if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_3hid__closer) < 0) __PYX_ERR(0, 85, __pyx_L1_error) #endif #if !CYTHON_COMPILING_IN_LIMITED_API if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_3hid__closer->tp_dictoffset && __pyx_mstate->__pyx_ptype_3hid__closer->tp_getattro == PyObject_GenericGetAttr)) { __pyx_mstate->__pyx_ptype_3hid__closer->tp_getattro = PyObject_GenericGetAttr; } #endif if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_3hid__closer, __pyx_vtabptr_3hid__closer) < 0) __PYX_ERR(0, 85, __pyx_L1_error) if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_3hid__closer) < 0) __PYX_ERR(0, 85, __pyx_L1_error) if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_closer, (PyObject *) __pyx_mstate->__pyx_ptype_3hid__closer) < 0) __PYX_ERR(0, 85, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_3hid__closer) < 0) __PYX_ERR(0, 85, __pyx_L1_error) #if CYTHON_USE_TYPE_SPECS __pyx_mstate->__pyx_ptype_3hid_device = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_3hid_device_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_3hid_device)) __PYX_ERR(0, 102, __pyx_L1_error) if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_3hid_device_spec, __pyx_mstate->__pyx_ptype_3hid_device) < 0) __PYX_ERR(0, 102, __pyx_L1_error) #else __pyx_mstate->__pyx_ptype_3hid_device = &__pyx_type_3hid_device; #endif #if !CYTHON_COMPILING_IN_LIMITED_API #endif #if !CYTHON_USE_TYPE_SPECS if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_3hid_device) < 0) __PYX_ERR(0, 102, __pyx_L1_error) #endif #if !CYTHON_COMPILING_IN_LIMITED_API if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_3hid_device->tp_dictoffset && __pyx_mstate->__pyx_ptype_3hid_device->tp_getattro == PyObject_GenericGetAttr)) { __pyx_mstate->__pyx_ptype_3hid_device->tp_getattro = PyObject_GenericGetAttr; } #endif if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_device, (PyObject *) __pyx_mstate->__pyx_ptype_3hid_device) < 0) __PYX_ERR(0, 102, __pyx_L1_error) #if CYTHON_USE_TYPE_SLOTS if (__pyx_mstate->__pyx_ptype_3hid_device->tp_weaklistoffset == 0) __pyx_mstate->__pyx_ptype_3hid_device->tp_weaklistoffset = offsetof(struct __pyx_obj_3hid_device, __weakref__); #endif if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_3hid_device) < 0) __PYX_ERR(0, 102, __pyx_L1_error) #if CYTHON_USE_TYPE_SPECS __pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_)) __PYX_ERR(1, 65, __pyx_L1_error) if (__Pyx_fix_up_extension_type_from_spec(&__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py__spec, __pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_) < 0) __PYX_ERR(1, 65, __pyx_L1_error) #else __pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_ = &__pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_; #endif #if !CYTHON_COMPILING_IN_LIMITED_API #endif #if !CYTHON_USE_TYPE_SPECS if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_) < 0) __PYX_ERR(1, 65, __pyx_L1_error) #endif #if !CYTHON_COMPILING_IN_LIMITED_API if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_->tp_dictoffset && __pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_->tp_getattro == PyObject_GenericGetAttr)) { __pyx_mstate->__pyx_ptype___pyx_scope_struct____Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_->tp_getattro = PyObject_GenericGetAttr; } #endif __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); /*--- Variable import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); /*--- Function import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec_hid(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec_hid}, #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING {Py_mod_gil, Py_MOD_GIL_USED}, #endif #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, #endif {0, NULL} }; #endif #ifdef __cplusplus namespace { struct PyModuleDef __pyx_moduledef = #else static struct PyModuleDef __pyx_moduledef = #endif { PyModuleDef_HEAD_INIT, "hid", 0, /* m_doc */ #if CYTHON_USE_MODULE_STATE sizeof(__pyx_mstatetype), /* m_size */ #else (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif #if CYTHON_USE_MODULE_STATE __pyx_m_traverse, /* m_traverse */ __pyx_m_clear, /* m_clear */ NULL /* m_free */ #else NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ #endif }; #ifdef __cplusplus } /* anonymous namespace */ #endif /* PyModInitFuncType */ #ifndef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #else #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * #else #define __Pyx_PyMODINIT_FUNC PyObject * #endif #endif __Pyx_PyMODINIT_FUNC PyInit_hid(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC PyInit_hid(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } /* ModuleCreationPEP489 */ #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { { PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think if (!module) { PyErr_Clear(); // just try the 3.8-3.12 version module = PyImport_ImportModule("_xxsubinterpreters"); if (!module) goto bad; } PyObject *current = PyObject_CallMethod(module, "get_current", NULL); Py_DECREF(module); if (!current) goto bad; if (PyTuple_Check(current)) { PyObject *new_current = PySequence_GetItem(current, 0); Py_DECREF(current); current = new_current; if (!new_current) goto bad; } long long as_c_int = PyLong_AsLongLong(current); Py_DECREF(current); return as_c_int; } bad: PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); return -1; } #endif #if !CYTHON_USE_MODULE_STATE static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { static PY_INT64_T main_interpreter_id = -1; #if CYTHON_COMPILING_IN_GRAAL PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); #elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x03090000 PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); #elif CYTHON_COMPILING_IN_LIMITED_API PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); #else PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); #endif if (unlikely(current_id == -1)) { return -1; } if (main_interpreter_id == -1) { main_interpreter_id = current_id; return 0; } else if (unlikely(main_interpreter_id != current_id)) { PyErr_SetString( PyExc_ImportError, "Interpreter change detected - this module can only be loaded into one interpreter per process."); return -1; } return 0; } #endif static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { if (allow_none || value != Py_None) { result = PyDict_SetItemString(moddict, to_name, value); } Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; CYTHON_UNUSED_VAR(def); #if !CYTHON_USE_MODULE_STATE if (__Pyx_check_single_interpreter()) return NULL; #endif if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static CYTHON_SMALL_CODE int __pyx_pymod_exec_hid(PyObject *__pyx_pyinit_module) #endif { int stringtab_initialized = 0; #if CYTHON_USE_MODULE_STATE int pystate_addmodule_run = 0; #endif __pyx_mstatetype *__pyx_mstate = NULL; PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; size_t __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m) { if (__pyx_m == __pyx_pyinit_module) return 0; PyErr_SetString(PyExc_RuntimeError, "Module 'hid' has already been imported. Re-initialisation is not supported."); return -1; } #else if (__pyx_m) return __Pyx_NewRef(__pyx_m); #endif /*--- Module creation code ---*/ #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_t_1 = __pyx_pyinit_module; Py_INCREF(__pyx_t_1); #else __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) #endif #if CYTHON_USE_MODULE_STATE { int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "hid" pseudovariable */ if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) pystate_addmodule_run = 1; } #else __pyx_m = __pyx_t_1; #endif #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_USED); #endif __pyx_mstate = __pyx_mstate_global; CYTHON_UNUSED_VAR(__pyx_t_1); __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_mstate->__pyx_d); __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) /* ImportRefnannyAPI */ #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyInit_hid", 0); if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pxy_PyFrame_Initialize_Offsets __Pxy_PyFrame_Initialize_Offsets(); #endif __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitConstants(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) stringtab_initialized = 1; if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if 0 || defined(__Pyx_CyFunction_USED) || defined(__Pyx_FusedFunction_USED) || defined(__Pyx_Coroutine_USED) || defined(__Pyx_Generator_USED) || defined(__Pyx_AsyncGen_USED) if (__pyx_CommonTypesMetaclass_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ if (__pyx_module_is_main_hid) { if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name, __pyx_mstate_global->__pyx_n_u_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "hid")) { if (unlikely((PyDict_SetItemString(modules, "hid", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) } } /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_CreateCodeObjects(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(__pyx_mstate); (void)__Pyx_modinit_variable_export_code(__pyx_mstate); (void)__Pyx_modinit_function_export_code(__pyx_mstate); if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) (void)__Pyx_modinit_type_import_code(__pyx_mstate); (void)__Pyx_modinit_variable_import_code(__pyx_mstate); (void)__Pyx_modinit_function_import_code(__pyx_mstate); /*--- Execution code ---*/ /* "hid.pyx":1 * import sys # <<<<<<<<<<<<<< * import weakref * */ __pyx_t_2 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_sys, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_sys, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "hid.pyx":2 * import sys * import weakref # <<<<<<<<<<<<<< * * from chid cimport * */ __pyx_t_2 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_weakref, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_weakref, __pyx_t_2) < 0) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "hid.pyx":8 * * * __version__ = "0.15.0" # <<<<<<<<<<<<<< * * */ if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_version, __pyx_mstate_global->__pyx_kp_u_0_15_0) < 0) __PYX_ERR(0, 8, __pyx_L1_error) /* "hid.pyx":11 * * * hid_init() # <<<<<<<<<<<<<< * * */ (void)(hid_init()); /* "hid.pyx":31 * return PyUnicode_FromWideChar(wcs, n) * * def enumerate(int vendor_id=0, int product_id=0): # <<<<<<<<<<<<<< * """Return a list of discovered HID devices. * */ __pyx_t_2 = __Pyx_PyLong_From_int(((int)0)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyLong_From_int(((int)0)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_Pack(2, __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_1enumerate, 0, __pyx_mstate_global->__pyx_n_u_enumerate, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_3, __pyx_t_4); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_enumerate, __pyx_t_3) < 0) __PYX_ERR(0, 31, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":77 * return res * * def version_str(): # <<<<<<<<<<<<<< * """Return a runtime version string of the hidapi C library. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_3version_str, 0, __pyx_mstate_global->__pyx_n_u_version_str, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_version_str, __pyx_t_3) < 0) __PYX_ERR(0, 77, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":99 * return closer * * def close(self): # <<<<<<<<<<<<<< * hid_close(self._ptr) * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_7_closer_1close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_closer_close, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 99, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid__closer, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_3) < 0) __PYX_ERR(0, 99, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_7_closer_3__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_closer___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_3) < 0) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError, "self._ptr cannot be converted to a Python object for pickling" */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_7_closer_5__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_closer___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 3, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_3) < 0) __PYX_ERR(1, 3, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":112 * cdef object _close * * def open(self, int vendor_id=0, int product_id=0, unicode serial_number=None): # <<<<<<<<<<<<<< * """Open the connection. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_1open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_open, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_3, __pyx_mstate_global->__pyx_tuple[1]); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_open, __pyx_t_3) < 0) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":146 * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * * def open_path(self, bytes path): # <<<<<<<<<<<<<< * """Open connection by path. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_3open_path, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_open_path, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 146, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_open_path, __pyx_t_3) < 0) __PYX_ERR(0, 146, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":161 * self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) * * def close(self): # <<<<<<<<<<<<<< * """Close connection. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_5close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_close, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 161, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_3) < 0) __PYX_ERR(0, 161, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":171 * self._c_hid = NULL * * def write(self, buff): # <<<<<<<<<<<<<< * """Accept a list of integers (0-255) and send them to the device. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_7write, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_write, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 171, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_write, __pyx_t_3) < 0) __PYX_ERR(0, 171, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":194 * return result * * def set_nonblocking(self, int v): # <<<<<<<<<<<<<< * """Set the nonblocking flag. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_9set_nonblocking, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_set_nonblocking, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 194, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_set_nonblocking, __pyx_t_3) < 0) __PYX_ERR(0, 194, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":206 * return hid_set_nonblocking(self._c_hid, v) * * def read(self, int max_length, int timeout_ms=0): # <<<<<<<<<<<<<< * """Return a list of integers (0-255) from the device up to max_length bytes. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_11read, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_read, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[11])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 206, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_3, __pyx_mstate_global->__pyx_tuple[2]); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_read, __pyx_t_3) < 0) __PYX_ERR(0, 206, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":242 * return res * * def get_manufacturer_string(self): # <<<<<<<<<<<<<< * """Return manufacturer string (e.g. vendor name). * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_13get_manufacturer_string, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_manufacturer_string, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[12])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 242, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_manufacturer_string, __pyx_t_3) < 0) __PYX_ERR(0, 242, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":259 * * * def get_product_string(self): # <<<<<<<<<<<<<< * """Return product string (e.g. device description). * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_15get_product_string, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_product_string, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[13])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_product_string, __pyx_t_3) < 0) __PYX_ERR(0, 259, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":275 * return U(buff) * * def get_serial_number_string(self): # <<<<<<<<<<<<<< * """Return serial number. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_17get_serial_number_string, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_serial_number_string, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[14])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 275, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_serial_number_string, __pyx_t_3) < 0) __PYX_ERR(0, 275, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":291 * return U(buff) * * def get_indexed_string(self, index): # <<<<<<<<<<<<<< * """Return indexed string. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_19get_indexed_string, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_indexed_string, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[15])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_indexed_string, __pyx_t_3) < 0) __PYX_ERR(0, 291, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":308 * return U(buff) * * def send_feature_report(self, buff): # <<<<<<<<<<<<<< * """Accept a list of integers (0-255) and send them to the device. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_21send_feature_report, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_send_feature_report, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[16])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 308, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_send_feature_report, __pyx_t_3) < 0) __PYX_ERR(0, 308, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":331 * return result * * def get_report_descriptor(self): # <<<<<<<<<<<<<< * """Return the HID Report Descriptor for this device. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_23get_report_descriptor, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_report_descriptor, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[17])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 331, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_report_descriptor, __pyx_t_3) < 0) __PYX_ERR(0, 331, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":351 * return list(cbuff[:n]) * * def get_feature_report(self, int report_num, int max_length): # <<<<<<<<<<<<<< * """Receive feature report. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_25get_feature_report, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_feature_report, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[18])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 351, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_feature_report, __pyx_t_3) < 0) __PYX_ERR(0, 351, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":386 * return res * * def get_input_report(self, int report_num, int max_length): # <<<<<<<<<<<<<< * """Get input report * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_27get_input_report, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_get_input_report, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[19])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 386, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_get_input_report, __pyx_t_3) < 0) __PYX_ERR(0, 386, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":421 * return res * * def error(self): # <<<<<<<<<<<<<< * """Get error from device, or global error if no device is opened. * */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_29error, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device_error, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[20])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 421, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_3hid_device, __pyx_mstate_global->__pyx_n_u_error, __pyx_t_3) < 0) __PYX_ERR(0, 421, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_31__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[21])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_3) < 0) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError, "self._c_hid cannot be converted to a Python object for pickling" */ __pyx_t_3 = __Pyx_CyFunction_New(&__pyx_mdef_3hid_6device_33__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_device___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_hid, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[22])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 3, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_3) < 0) __PYX_ERR(1, 3, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":433 * # Finalize the HIDAPI library *only* once there are no more references to this * # module, and it is being garbage collected. * weakref.finalize(sys.modules[__name__], hid_exit) # <<<<<<<<<<<<<< */ __pyx_t_4 = NULL; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_weakref); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_finalize); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_sys); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_modules); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_t_6, __pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_CFunc_4chid_int__lParen__rParennoexcept_to_py_(hid_exit); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_8 = 1; { PyObject *__pyx_callargs[3] = {__pyx_t_4, __pyx_t_7, __pyx_t_2}; __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_8, (3-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 433, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "hid.pyx":1 * import sys # <<<<<<<<<<<<<< * import weakref * */ __pyx_t_3 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_3) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); if (__pyx_m) { if (__pyx_mstate->__pyx_d && stringtab_initialized) { __Pyx_AddTraceback("init hid", __pyx_clineno, __pyx_lineno, __pyx_filename); } #if !CYTHON_USE_MODULE_STATE Py_CLEAR(__pyx_m); #else Py_DECREF(__pyx_m); if (pystate_addmodule_run) { PyObject *tp, *value, *tb; PyErr_Fetch(&tp, &value, &tb); PyState_RemoveModule(&__pyx_moduledef); PyErr_Restore(tp, value, tb); } #endif } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init hid"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #else return __pyx_m; #endif } /* #### Code section: pystring_table ### */ typedef struct { const char *s; #if 179 <= 65535 const unsigned short n; #elif 179 / 2 < INT_MAX const unsigned int n; #elif 179 / 2 < LONG_MAX const unsigned long n; #else const Py_ssize_t n; #endif #if 1 <= 31 const unsigned int encoding : 5; #elif 1 <= 255 const unsigned char encoding; #elif 1 <= 65535 const unsigned short encoding; #else const Py_ssize_t encoding; #endif const unsigned int is_unicode : 1; const unsigned int intern : 1; } __Pyx_StringTabEntry; static const char * const __pyx_string_tab_encodings[] = { 0 }; static const __Pyx_StringTabEntry __pyx_string_tab[] = { {__pyx_k_, sizeof(__pyx_k_), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_ */ {__pyx_k_0_15_0, sizeof(__pyx_k_0_15_0), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_0_15_0 */ {__pyx_k_IOError, sizeof(__pyx_k_IOError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IOError */ {__pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_MemoryError */ {__pyx_k_Note_that_Cython_is_deliberately, sizeof(__pyx_k_Note_that_Cython_is_deliberately), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Note_that_Cython_is_deliberately */ {__pyx_k_Pyx_CFunc_4chid_int__lParen__r, sizeof(__pyx_k_Pyx_CFunc_4chid_int__lParen__r), 0, 1, 1}, /* PyObject cname: __pyx_n_u_Pyx_CFunc_4chid_int__lParen__r */ {__pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_RuntimeError */ {__pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_TypeError */ {__pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ValueError */ {__pyx_k__2, sizeof(__pyx_k__2), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__2 */ {__pyx_k_add_note, sizeof(__pyx_k_add_note), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_add_note */ {__pyx_k_already_open, sizeof(__pyx_k_already_open), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_already_open */ {__pyx_k_asyncio_coroutines, sizeof(__pyx_k_asyncio_coroutines), 0, 1, 1}, /* PyObject cname: __pyx_n_u_asyncio_coroutines */ {__pyx_k_buff, sizeof(__pyx_k_buff), 0, 1, 1}, /* PyObject cname: __pyx_n_u_buff */ {__pyx_k_bus_type, sizeof(__pyx_k_bus_type), 0, 1, 1}, /* PyObject cname: __pyx_n_u_bus_type */ {__pyx_k_c, sizeof(__pyx_k_c), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c */ {__pyx_k_c_buff_len, sizeof(__pyx_k_c_buff_len), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c_buff_len */ {__pyx_k_c_hid, sizeof(__pyx_k_c_hid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c_hid */ {__pyx_k_c_index, sizeof(__pyx_k_c_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c_index */ {__pyx_k_c_max_length, sizeof(__pyx_k_c_max_length), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c_max_length */ {__pyx_k_c_timeout_ms, sizeof(__pyx_k_c_timeout_ms), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c_timeout_ms */ {__pyx_k_cbuff, sizeof(__pyx_k_cbuff), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cbuff */ {__pyx_k_cfunc_to_py, sizeof(__pyx_k_cfunc_to_py), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cfunc_to_py */ {__pyx_k_chr, sizeof(__pyx_k_chr), 0, 1, 1}, /* PyObject cname: __pyx_n_u_chr */ {__pyx_k_class_getitem, sizeof(__pyx_k_class_getitem), 0, 1, 1}, /* PyObject cname: __pyx_n_u_class_getitem */ {__pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cline_in_traceback */ {__pyx_k_close, sizeof(__pyx_k_close), 0, 1, 1}, /* PyObject cname: __pyx_n_u_close */ {__pyx_k_closer, sizeof(__pyx_k_closer), 0, 1, 1}, /* PyObject cname: __pyx_n_u_closer */ {__pyx_k_closer___reduce_cython, sizeof(__pyx_k_closer___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_closer___reduce_cython */ {__pyx_k_closer___setstate_cython, sizeof(__pyx_k_closer___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_closer___setstate_cython */ {__pyx_k_closer_close, sizeof(__pyx_k_closer_close), 0, 1, 1}, /* PyObject cname: __pyx_n_u_closer_close */ {__pyx_k_cserial_number, sizeof(__pyx_k_cserial_number), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cserial_number */ {__pyx_k_detach, sizeof(__pyx_k_detach), 0, 1, 1}, /* PyObject cname: __pyx_n_u_detach */ {__pyx_k_device, sizeof(__pyx_k_device), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device */ {__pyx_k_device___reduce_cython, sizeof(__pyx_k_device___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device___reduce_cython */ {__pyx_k_device___setstate_cython, sizeof(__pyx_k_device___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device___setstate_cython */ {__pyx_k_device_close, sizeof(__pyx_k_device_close), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_close */ {__pyx_k_device_error, sizeof(__pyx_k_device_error), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_error */ {__pyx_k_device_get_feature_report, sizeof(__pyx_k_device_get_feature_report), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_feature_report */ {__pyx_k_device_get_indexed_string, sizeof(__pyx_k_device_get_indexed_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_indexed_string */ {__pyx_k_device_get_input_report, sizeof(__pyx_k_device_get_input_report), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_input_report */ {__pyx_k_device_get_manufacturer_string, sizeof(__pyx_k_device_get_manufacturer_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_manufacturer_string */ {__pyx_k_device_get_product_string, sizeof(__pyx_k_device_get_product_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_product_string */ {__pyx_k_device_get_report_descriptor, sizeof(__pyx_k_device_get_report_descriptor), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_report_descriptor */ {__pyx_k_device_get_serial_number_string, sizeof(__pyx_k_device_get_serial_number_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_get_serial_number_string */ {__pyx_k_device_open, sizeof(__pyx_k_device_open), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_open */ {__pyx_k_device_open_path, sizeof(__pyx_k_device_open_path), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_open_path */ {__pyx_k_device_read, sizeof(__pyx_k_device_read), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_read */ {__pyx_k_device_send_feature_report, sizeof(__pyx_k_device_send_feature_report), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_send_feature_report */ {__pyx_k_device_set_nonblocking, sizeof(__pyx_k_device_set_nonblocking), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_set_nonblocking */ {__pyx_k_device_write, sizeof(__pyx_k_device_write), 0, 1, 1}, /* PyObject cname: __pyx_n_u_device_write */ {__pyx_k_disable, sizeof(__pyx_k_disable), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_disable */ {__pyx_k_enable, sizeof(__pyx_k_enable), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_enable */ {__pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_enumerate */ {__pyx_k_error, sizeof(__pyx_k_error), 0, 1, 1}, /* PyObject cname: __pyx_n_u_error */ {__pyx_k_finalize, sizeof(__pyx_k_finalize), 0, 1, 1}, /* PyObject cname: __pyx_n_u_finalize */ {__pyx_k_func, sizeof(__pyx_k_func), 0, 1, 1}, /* PyObject cname: __pyx_n_u_func */ {__pyx_k_gc, sizeof(__pyx_k_gc), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_gc */ {__pyx_k_get_feature_report, sizeof(__pyx_k_get_feature_report), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_feature_report */ {__pyx_k_get_indexed_string, sizeof(__pyx_k_get_indexed_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_indexed_string */ {__pyx_k_get_indexed_string_error, sizeof(__pyx_k_get_indexed_string_error), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_get_indexed_string_error */ {__pyx_k_get_input_report, sizeof(__pyx_k_get_input_report), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_input_report */ {__pyx_k_get_manufacturer_string, sizeof(__pyx_k_get_manufacturer_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_manufacturer_string */ {__pyx_k_get_manufacturer_string_error, sizeof(__pyx_k_get_manufacturer_string_error), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_get_manufacturer_string_error */ {__pyx_k_get_product_string, sizeof(__pyx_k_get_product_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_product_string */ {__pyx_k_get_product_string_error, sizeof(__pyx_k_get_product_string_error), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_get_product_string_error */ {__pyx_k_get_report_descriptor, sizeof(__pyx_k_get_report_descriptor), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_report_descriptor */ {__pyx_k_get_serial_number_string, sizeof(__pyx_k_get_serial_number_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_serial_number_string */ {__pyx_k_get_serial_number_string_error, sizeof(__pyx_k_get_serial_number_string_error), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_get_serial_number_string_error */ {__pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_getstate */ {__pyx_k_hid, sizeof(__pyx_k_hid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_hid */ {__pyx_k_hid_pyx, sizeof(__pyx_k_hid_pyx), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_hid_pyx */ {__pyx_k_index, sizeof(__pyx_k_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_index */ {__pyx_k_info, sizeof(__pyx_k_info), 0, 1, 1}, /* PyObject cname: __pyx_n_u_info */ {__pyx_k_initializing, sizeof(__pyx_k_initializing), 0, 1, 1}, /* PyObject cname: __pyx_n_u_initializing */ {__pyx_k_interface_number, sizeof(__pyx_k_interface_number), 0, 1, 1}, /* PyObject cname: __pyx_n_u_interface_number */ {__pyx_k_invalid_serial_number_string, sizeof(__pyx_k_invalid_serial_number_string), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_invalid_serial_number_string */ {__pyx_k_is_coroutine, sizeof(__pyx_k_is_coroutine), 0, 1, 1}, /* PyObject cname: __pyx_n_u_is_coroutine */ {__pyx_k_isenabled, sizeof(__pyx_k_isenabled), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_isenabled */ {__pyx_k_lbuff, sizeof(__pyx_k_lbuff), 0, 1, 1}, /* PyObject cname: __pyx_n_u_lbuff */ {__pyx_k_main, sizeof(__pyx_k_main), 0, 1, 1}, /* PyObject cname: __pyx_n_u_main */ {__pyx_k_manufacturer_string, sizeof(__pyx_k_manufacturer_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_manufacturer_string */ {__pyx_k_map, sizeof(__pyx_k_map), 0, 1, 1}, /* PyObject cname: __pyx_n_u_map */ {__pyx_k_max_length, sizeof(__pyx_k_max_length), 0, 1, 1}, /* PyObject cname: __pyx_n_u_max_length */ {__pyx_k_module, sizeof(__pyx_k_module), 0, 1, 1}, /* PyObject cname: __pyx_n_u_module */ {__pyx_k_modules, sizeof(__pyx_k_modules), 0, 1, 1}, /* PyObject cname: __pyx_n_u_modules */ {__pyx_k_n, sizeof(__pyx_k_n), 0, 1, 1}, /* PyObject cname: __pyx_n_u_n */ {__pyx_k_name, sizeof(__pyx_k_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_name */ {__pyx_k_not_open, sizeof(__pyx_k_not_open), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_not_open */ {__pyx_k_open, sizeof(__pyx_k_open), 0, 1, 1}, /* PyObject cname: __pyx_n_u_open */ {__pyx_k_open_failed, sizeof(__pyx_k_open_failed), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_open_failed */ {__pyx_k_open_path, sizeof(__pyx_k_open_path), 0, 1, 1}, /* PyObject cname: __pyx_n_u_open_path */ {__pyx_k_path, sizeof(__pyx_k_path), 0, 1, 1}, /* PyObject cname: __pyx_n_u_path */ {__pyx_k_pop, sizeof(__pyx_k_pop), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pop */ {__pyx_k_product_id, sizeof(__pyx_k_product_id), 0, 1, 1}, /* PyObject cname: __pyx_n_u_product_id */ {__pyx_k_product_string, sizeof(__pyx_k_product_string), 0, 1, 1}, /* PyObject cname: __pyx_n_u_product_string */ {__pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_state */ {__pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_vtable */ {__pyx_k_qualname, sizeof(__pyx_k_qualname), 0, 1, 1}, /* PyObject cname: __pyx_n_u_qualname */ {__pyx_k_r, sizeof(__pyx_k_r), 0, 1, 1}, /* PyObject cname: __pyx_n_u_r */ {__pyx_k_read, sizeof(__pyx_k_read), 0, 1, 1}, /* PyObject cname: __pyx_n_u_read */ {__pyx_k_read_error, sizeof(__pyx_k_read_error), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_read_error */ {__pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reduce */ {__pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reduce_cython */ {__pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reduce_ex */ {__pyx_k_release_number, sizeof(__pyx_k_release_number), 0, 1, 1}, /* PyObject cname: __pyx_n_u_release_number */ {__pyx_k_report_num, sizeof(__pyx_k_report_num), 0, 1, 1}, /* PyObject cname: __pyx_n_u_report_num */ {__pyx_k_res, sizeof(__pyx_k_res), 0, 1, 1}, /* PyObject cname: __pyx_n_u_res */ {__pyx_k_result, sizeof(__pyx_k_result), 0, 1, 1}, /* PyObject cname: __pyx_n_u_result */ {__pyx_k_self, sizeof(__pyx_k_self), 0, 1, 1}, /* PyObject cname: __pyx_n_u_self */ {__pyx_k_self__c_hid_cannot_be_converted, sizeof(__pyx_k_self__c_hid_cannot_be_converted), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_self__c_hid_cannot_be_converted */ {__pyx_k_self__ptr_cannot_be_converted_to, sizeof(__pyx_k_self__ptr_cannot_be_converted_to), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_self__ptr_cannot_be_converted_to */ {__pyx_k_send_feature_report, sizeof(__pyx_k_send_feature_report), 0, 1, 1}, /* PyObject cname: __pyx_n_u_send_feature_report */ {__pyx_k_serial_len, sizeof(__pyx_k_serial_len), 0, 1, 1}, /* PyObject cname: __pyx_n_u_serial_len */ {__pyx_k_serial_number, sizeof(__pyx_k_serial_number), 0, 1, 1}, /* PyObject cname: __pyx_n_u_serial_number */ {__pyx_k_set_name, sizeof(__pyx_k_set_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_set_name */ {__pyx_k_set_nonblocking, sizeof(__pyx_k_set_nonblocking), 0, 1, 1}, /* PyObject cname: __pyx_n_u_set_nonblocking */ {__pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setstate */ {__pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setstate_cython */ {__pyx_k_spec, sizeof(__pyx_k_spec), 0, 1, 1}, /* PyObject cname: __pyx_n_u_spec */ {__pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_stringsource */ {__pyx_k_sys, sizeof(__pyx_k_sys), 0, 1, 1}, /* PyObject cname: __pyx_n_u_sys */ {__pyx_k_test, sizeof(__pyx_k_test), 0, 1, 1}, /* PyObject cname: __pyx_n_u_test */ {__pyx_k_timeout_ms, sizeof(__pyx_k_timeout_ms), 0, 1, 1}, /* PyObject cname: __pyx_n_u_timeout_ms */ {__pyx_k_usage, sizeof(__pyx_k_usage), 0, 1, 1}, /* PyObject cname: __pyx_n_u_usage */ {__pyx_k_usage_page, sizeof(__pyx_k_usage_page), 0, 1, 1}, /* PyObject cname: __pyx_n_u_usage_page */ {__pyx_k_v, sizeof(__pyx_k_v), 0, 1, 1}, /* PyObject cname: __pyx_n_u_v */ {__pyx_k_vendor_id, sizeof(__pyx_k_vendor_id), 0, 1, 1}, /* PyObject cname: __pyx_n_u_vendor_id */ {__pyx_k_version, sizeof(__pyx_k_version), 0, 1, 1}, /* PyObject cname: __pyx_n_u_version */ {__pyx_k_version_info, sizeof(__pyx_k_version_info), 0, 1, 1}, /* PyObject cname: __pyx_n_u_version_info */ {__pyx_k_version_str, sizeof(__pyx_k_version_str), 0, 1, 1}, /* PyObject cname: __pyx_n_u_version_str */ {__pyx_k_weakref, sizeof(__pyx_k_weakref), 0, 1, 1}, /* PyObject cname: __pyx_n_u_weakref */ {__pyx_k_wrap, sizeof(__pyx_k_wrap), 0, 1, 1}, /* PyObject cname: __pyx_n_u_wrap */ {__pyx_k_write, sizeof(__pyx_k_write), 0, 1, 1}, /* PyObject cname: __pyx_n_u_write */ {0, 0, 0, 0, 0} }; /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry const *t, PyObject **target, const char* const* encoding_names); /* #### Code section: cached_builtins ### */ static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { CYTHON_UNUSED_VAR(__pyx_mstate); __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(0, 127, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(0, 133, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 136, __pyx_L1_error) __pyx_builtin_IOError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_IOError); if (!__pyx_builtin_IOError) __PYX_ERR(0, 143, __pyx_L1_error) __pyx_builtin_map = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_map); if (!__pyx_builtin_map) __PYX_ERR(0, 183, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } /* #### Code section: cached_constants ### */ static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { __Pyx_RefNannyDeclarations CYTHON_UNUSED_VAR(__pyx_mstate); __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "hid.pyx":182 * raise ValueError('not open') * # convert to bytes * if sys.version_info < (3, 0): # <<<<<<<<<<<<<< * buff = ''.join(map(chr, buff)) * else: */ __pyx_mstate_global->__pyx_tuple[0] = PyTuple_Pack(2, __pyx_mstate_global->__pyx_int_3, __pyx_mstate_global->__pyx_int_0); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 182, __pyx_L1_error) __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); /* "hid.pyx":112 * cdef object _close * * def open(self, int vendor_id=0, int product_id=0, unicode serial_number=None): # <<<<<<<<<<<<<< * """Open the connection. * */ __pyx_mstate_global->__pyx_tuple[1] = PyTuple_Pack(3, __pyx_mstate_global->__pyx_int_0, __pyx_mstate_global->__pyx_int_0, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_tuple[1])) __PYX_ERR(0, 112, __pyx_L1_error) __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[1]); __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); /* "hid.pyx":206 * return hid_set_nonblocking(self._c_hid, v) * * def read(self, int max_length, int timeout_ms=0): # <<<<<<<<<<<<<< * """Return a list of integers (0-255) from the device up to max_length bytes. * */ __pyx_mstate_global->__pyx_tuple[2] = PyTuple_Pack(1, __pyx_mstate_global->__pyx_int_0); if (unlikely(!__pyx_mstate_global->__pyx_tuple[2])) __PYX_ERR(0, 206, __pyx_L1_error) __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[2]); __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[2]); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } /* #### Code section: init_constants ### */ static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { CYTHON_UNUSED_VAR(__pyx_mstate); __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; if (__Pyx_InitStrings(__pyx_string_tab, __pyx_mstate->__pyx_string_tab, __pyx_string_tab_encodings) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_mstate->__pyx_int_0 = PyLong_FromLong(0); if (unlikely(!__pyx_mstate->__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_mstate->__pyx_int_3 = PyLong_FromLong(3); if (unlikely(!__pyx_mstate->__pyx_int_3)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } /* #### Code section: init_codeobjects ### */ \ typedef struct { unsigned int argcount : 3; unsigned int num_posonly_args : 1; unsigned int num_kwonly_args : 1; unsigned int nlocals : 4; unsigned int flags : 10; unsigned int first_line : 9; unsigned int line_table_length : 13; } __Pyx_PyCode_New_function_description; /* NewCodeObj.proto */ static PyObject* __Pyx_PyCode_New( const __Pyx_PyCode_New_function_description descr, PyObject * const *varnames, PyObject *filename, PyObject *funcname, const char *line_table, PyObject *tuple_dedup_map ); static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { PyObject* tuple_dedup_map = PyDict_New(); if (unlikely(!tuple_dedup_map)) return -1; { const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 0, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 67, 9}; PyObject* const varnames[] = {0}; __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_wrap, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 31, 153}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_vendor_id, __pyx_mstate->__pyx_n_u_product_id, __pyx_mstate->__pyx_n_u_info, __pyx_mstate->__pyx_n_u_c, __pyx_mstate->__pyx_n_u_res}; __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_enumerate, __pyx_k_q0_A_a_7_AQ_1_Qaq_aq_1AQa_aq_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {0, 0, 0, 0, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 77, 19}; PyObject* const varnames[] = {0}; __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_version_str, __pyx_k_G_WAQ, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 99, 11}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_close, __pyx_k_A_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 7, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 112, 210}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_vendor_id, __pyx_mstate->__pyx_n_u_product_id, __pyx_mstate->__pyx_n_u_serial_number, __pyx_mstate->__pyx_n_u_cserial_number, __pyx_mstate->__pyx_n_u_serial_len, __pyx_mstate->__pyx_n_u_result}; __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_open, __pyx_k_33LA_4xs_aq_WA_S_6_2B_ZqPQ_Q_Qo, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 146, 83}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_path, __pyx_mstate->__pyx_n_u_cbuff}; __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_open_path, __pyx_k_A_1_4xs_aq_Jm1A_4xs_JgYa_E_ha, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 161, 38}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_close, __pyx_k_A_4xs_q_wa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 171, 105}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buff, __pyx_mstate->__pyx_n_u_c_hid, __pyx_mstate->__pyx_n_u_cbuff, __pyx_mstate->__pyx_n_u_c_buff_len, __pyx_mstate->__pyx_n_u_result}; __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_write, __pyx_k_A_4xs_AQ_3nCs_2U_3auA_5_a_A_AQ_Y, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 194, 38}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_v}; __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_set_nonblocking, __pyx_k_A_4xs_AQ_4y, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 10, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 206, 171}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_max_length, __pyx_mstate->__pyx_n_u_timeout_ms, __pyx_mstate->__pyx_n_u_lbuff, __pyx_mstate->__pyx_n_u_cbuff, __pyx_mstate->__pyx_n_u_c_max_length, __pyx_mstate->__pyx_n_u_c_timeout_ms, __pyx_mstate->__pyx_n_u_c_hid, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_res}; __pyx_mstate_global->__pyx_codeobj_tab[11] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_read, __pyx_k_2_4xs_AQ_1_a_Q_q_A_Q_q_r_Q_gQa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[11])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 242, 67}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buff, __pyx_mstate->__pyx_n_u_r}; __pyx_mstate_global->__pyx_codeobj_tab[12] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_manufacturer_string, __pyx_k_A_4xs_AQ_0_YfA_2Rq_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[12])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 259, 67}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buff, __pyx_mstate->__pyx_n_u_r}; __pyx_mstate_global->__pyx_codeobj_tab[13] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_product_string, __pyx_k_A_4xs_AQ_1D_q_2Rq_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[13])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 275, 67}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buff, __pyx_mstate->__pyx_n_u_r}; __pyx_mstate_global->__pyx_codeobj_tab[14] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_serial_number_string, __pyx_k_A_4xs_AQ_1_ivQ_2Rq_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[14])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 291, 74}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_index, __pyx_mstate->__pyx_n_u_buff, __pyx_mstate->__pyx_n_u_c_index, __pyx_mstate->__pyx_n_u_r}; __pyx_mstate_global->__pyx_codeobj_tab[15] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_indexed_string, __pyx_k_A_4xs_AQ_Q_1D_2Rq_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[15])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 308, 106}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_buff, __pyx_mstate->__pyx_n_u_c_hid, __pyx_mstate->__pyx_n_u_cbuff, __pyx_mstate->__pyx_n_u_c_buff_len, __pyx_mstate->__pyx_n_u_result}; __pyx_mstate_global->__pyx_codeobj_tab[16] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_send_feature_report, __pyx_k_A_4xs_AQ_3nCs_2U_3auA_5_a_A_AQ_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[16])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 331, 83}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_cbuff, __pyx_mstate->__pyx_n_u_c_hid, __pyx_mstate->__pyx_n_u_n}; __pyx_mstate_global->__pyx_codeobj_tab[17] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_report_descriptor, __pyx_k_A_4xs_AQ_a_q_2Rq_t1E_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[17])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 9, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 351, 145}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_report_num, __pyx_mstate->__pyx_n_u_max_length, __pyx_mstate->__pyx_n_u_c_hid, __pyx_mstate->__pyx_n_u_lbuff, __pyx_mstate->__pyx_n_u_cbuff, __pyx_mstate->__pyx_n_u_c_max_length, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_res}; __pyx_mstate_global->__pyx_codeobj_tab[18] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_feature_report, __pyx_k_A_4xs_AQ_a_1_Q_q_q_7_r_1_gQa_auB, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[18])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 9, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 386, 145}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_report_num, __pyx_mstate->__pyx_n_u_max_length, __pyx_mstate->__pyx_n_u_c_hid, __pyx_mstate->__pyx_n_u_lbuff, __pyx_mstate->__pyx_n_u_cbuff, __pyx_mstate->__pyx_n_u_c_max_length, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_res}; __pyx_mstate_global->__pyx_codeobj_tab[19] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_get_input_report, __pyx_k_A_4xs_AQ_a_1_Q_q_q_q_r_1_gQa_auB, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[19])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 421, 21}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; __pyx_mstate_global->__pyx_codeobj_tab[20] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_hid_pyx, __pyx_mstate->__pyx_n_u_error, __pyx_k_A_q_9AT, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[20])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; __pyx_mstate_global->__pyx_codeobj_tab[21] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[21])) goto bad; } { const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; __pyx_mstate_global->__pyx_codeobj_tab[22] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[22])) goto bad; } Py_DECREF(tuple_dedup_map); return 0; bad: Py_DECREF(tuple_dedup_map); return -1; } /* #### Code section: init_globals ### */ static int __Pyx_InitGlobals(void) { /* PythonCompatibility.init */ if (likely(__Pyx_init_co_variables() == 0)); else if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) /* CachedMethodType.init */ #if CYTHON_COMPILING_IN_LIMITED_API { PyObject *typesModule=NULL; typesModule = PyImport_ImportModule("types"); if (typesModule) { __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); Py_DECREF(typesModule); } } // error handling follows #endif if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } /* #### Code section: cleanup_globals ### */ /* #### Code section: cleanup_module ### */ /* #### Code section: main_method ### */ /* #### Code section: utility_code_pragmas ### */ #ifdef _MSC_VER #pragma warning( push ) /* Warning 4127: conditional expression is constant * Cython uses constant conditional expressions to allow in inline functions to be optimized at * compile-time, so this warning is not useful */ #pragma warning( disable : 4127 ) #endif /* #### Code section: utility_code_def ### */ /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule(modname); if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(tuple); for (i=0; i= 0x030C00A6 PyObject *current_exception = tstate->current_exception; if (unlikely(!current_exception)) return 0; exc_type = (PyObject*) Py_TYPE(current_exception); if (exc_type == err) return 1; #else exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; #endif #if CYTHON_AVOID_BORROWED_REFS Py_INCREF(exc_type); #endif if (unlikely(PyTuple_Check(err))) { result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); } else { result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); } #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(exc_type); #endif return result; } #endif /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { #if PY_VERSION_HEX >= 0x030C00A6 PyObject *tmp_value; assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); if (value) { #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) #endif PyException_SetTraceback(value, tb); } tmp_value = tstate->current_exception; tstate->current_exception = value; Py_XDECREF(tmp_value); Py_XDECREF(type); Py_XDECREF(tb); #else PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #endif } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if PY_VERSION_HEX >= 0x030C00A6 PyObject* exc_value; exc_value = tstate->current_exception; tstate->current_exception = 0; *value = exc_value; *type = NULL; *tb = NULL; if (exc_value) { *type = (PyObject*) Py_TYPE(exc_value); Py_INCREF(*type); #if CYTHON_COMPILING_IN_CPYTHON *tb = ((PyBaseExceptionObject*) exc_value)->traceback; Py_XINCREF(*tb); #else *tb = PyException_GetTraceback(exc_value); #endif } #else *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #endif } #endif /* PyObjectGetAttrStr */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); return PyObject_GetAttr(obj, attr_name); } #endif /* PyObjectGetAttrStrNoError */ #if __PYX_LIMITED_VERSION_HEX < 0x030d0000 static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) __Pyx_PyErr_Clear(); } #endif static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { PyObject *result; #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 (void) PyObject_GetOptionalAttr(obj, attr_name, &result); return result; #else #if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); } #endif result = __Pyx_PyObject_GetAttrStr(obj, attr_name); if (unlikely(!result)) { __Pyx_PyObject_GetAttrStr_ClearAttributeError(); } return result; #endif } /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); if (unlikely(!result) && !PyErr_Occurred()) { PyErr_Format(PyExc_NameError, "name '%U' is not defined", name); } return result; } /* TupleAndListFromArray */ #if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL static CYTHON_INLINE PyObject * __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) { PyObject *res; Py_ssize_t i; if (n <= 0) { return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); } res = PyTuple_New(n); if (unlikely(res == NULL)) return NULL; for (i = 0; i < n; i++) { if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < 0)) { Py_DECREF(res); return NULL; } Py_INCREF(src[i]); } return res; } #elif CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { PyObject *v; Py_ssize_t i; for (i = 0; i < length; i++) { v = dest[i] = src[i]; Py_INCREF(v); } } static CYTHON_INLINE PyObject * __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) { PyObject *res; if (n <= 0) { return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); } res = PyTuple_New(n); if (unlikely(res == NULL)) return NULL; __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); return res; } static CYTHON_INLINE PyObject * __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) { PyObject *res; if (n <= 0) { return PyList_New(0); } res = PyList_New(n); if (unlikely(res == NULL)) return NULL; __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); return res; } #endif /* BytesEquals */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result; #if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) Py_hash_t hash1, hash2; hash1 = ((PyBytesObject*)s1)->ob_shash; hash2 = ((PyBytesObject*)s2)->ob_shash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { return (equals == Py_NE); } #endif result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } /* UnicodeEquals */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL return PyObject_RichCompareBool(s1, s2, equals); #else int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length, length2; int kind; void *data1, *data2; #if !CYTHON_COMPILING_IN_LIMITED_API if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; #endif length = __Pyx_PyUnicode_GET_LENGTH(s1); #if !CYTHON_ASSUME_SAFE_SIZE if (unlikely(length < 0)) return -1; #endif length2 = __Pyx_PyUnicode_GET_LENGTH(s2); #if !CYTHON_ASSUME_SAFE_SIZE if (unlikely(length2 < 0)) return -1; #endif if (length != length2) { goto return_ne; } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; hash1 = ((PyASCIIObject*)s1)->hash; hash2 = ((PyASCIIObject*)s2)->hash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { goto return_ne; } } #endif kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: return (equals == Py_EQ); return_ne: return (equals == Py_NE); #endif } /* fastcall */ #if CYTHON_METH_FASTCALL static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) { Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); #if !CYTHON_ASSUME_SAFE_SIZE if (unlikely(n == -1)) return NULL; #endif for (i = 0; i < n; i++) { PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); #if !CYTHON_ASSUME_SAFE_MACROS if (unlikely(!namei)) return NULL; #endif if (s == namei) return kwvalues[i]; } for (i = 0; i < n; i++) { PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); #if !CYTHON_ASSUME_SAFE_MACROS if (unlikely(!namei)) return NULL; #endif int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); if (unlikely(eq != 0)) { if (unlikely(eq < 0)) return NULL; return kwvalues[i]; } } return NULL; } #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { Py_ssize_t i, nkwargs; PyObject *dict; #if !CYTHON_ASSUME_SAFE_SIZE nkwargs = PyTuple_Size(kwnames); if (unlikely(nkwargs < 0)) return NULL; #else nkwargs = PyTuple_GET_SIZE(kwnames); #endif dict = PyDict_New(); if (unlikely(!dict)) return NULL; for (i=0; itp_dict; #endif result = PyDict_SetItem(tp_dict, k, v); if (likely(!result)) { PyType_Modified(tp); if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); if (!setNameResult) return -1; Py_DECREF(setNameResult); } } return result; } /* FixUpExtensionType */ static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { #if __PYX_LIMITED_VERSION_HEX > 0x030900B1 CYTHON_UNUSED_VAR(spec); CYTHON_UNUSED_VAR(type); CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); #else const PyType_Slot *slot = spec->slots; int changed = 0; #if !CYTHON_COMPILING_IN_LIMITED_API while (slot && slot->slot && slot->slot != Py_tp_members) slot++; if (slot && slot->slot == Py_tp_members) { #if !CYTHON_COMPILING_IN_CPYTHON const #endif // !CYTHON_COMPILING_IN_CPYTHON) PyMemberDef *memb = (PyMemberDef*) slot->pfunc; while (memb && memb->name) { if (memb->name[0] == '_' && memb->name[1] == '_') { if (strcmp(memb->name, "__weaklistoffset__") == 0) { assert(memb->type == T_PYSSIZET); assert(memb->flags == READONLY); type->tp_weaklistoffset = memb->offset; changed = 1; } else if (strcmp(memb->name, "__dictoffset__") == 0) { assert(memb->type == T_PYSSIZET); assert(memb->flags == READONLY); type->tp_dictoffset = memb->offset; changed = 1; } #if CYTHON_METH_FASTCALL else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { assert(memb->type == T_PYSSIZET); assert(memb->flags == READONLY); #if PY_VERSION_HEX >= 0x030800b4 type->tp_vectorcall_offset = memb->offset; #else type->tp_print = (printfunc) memb->offset; #endif changed = 1; } #endif // CYTHON_METH_FASTCALL #if !CYTHON_COMPILING_IN_PYPY else if (strcmp(memb->name, "__module__") == 0) { PyObject *descr; assert(memb->type == T_OBJECT); assert(memb->flags == 0 || memb->flags == READONLY); descr = PyDescr_NewMember(type, memb); if (unlikely(!descr)) return -1; int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); Py_DECREF(descr); if (unlikely(set_item_result < 0)) { return -1; } changed = 1; } #endif // !CYTHON_COMPILING_IN_PYPY } memb++; } } #endif // !CYTHON_COMPILING_IN_LIMITED_API #if !CYTHON_COMPILING_IN_PYPY slot = spec->slots; while (slot && slot->slot && slot->slot != Py_tp_getset) slot++; if (slot && slot->slot == Py_tp_getset) { PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; while (getset && getset->name) { if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { PyObject *descr = PyDescr_NewGetSet(type, getset); if (unlikely(!descr)) return -1; #if CYTHON_COMPILING_IN_LIMITED_API PyObject *pyname = PyUnicode_FromString(getset->name); if (unlikely(!pyname)) { Py_DECREF(descr); return -1; } int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); Py_DECREF(pyname); #else CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); #endif Py_DECREF(descr); if (unlikely(set_item_result < 0)) { return -1; } changed = 1; } ++getset; } } #endif // !CYTHON_COMPILING_IN_PYPY if (changed) PyType_Modified(type); #endif // PY_VERSION_HEX > 0x030900B1 return 0; } /* FetchSharedCythonModule */ static PyObject *__Pyx_FetchSharedCythonABIModule(void) { return __Pyx_PyImport_AddModuleRef(__PYX_ABI_MODULE_NAME); } /* dict_setdefault */ static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, int is_safe_type) { PyObject* value; CYTHON_MAYBE_UNUSED_VAR(is_safe_type); #if CYTHON_COMPILING_IN_LIMITED_API value = PyObject_CallMethod(d, "setdefault", "OO", key, default_value); #elif PY_VERSION_HEX >= 0x030d0000 PyDict_SetDefaultRef(d, key, default_value, &value); #else value = PyDict_SetDefault(d, key, default_value); if (unlikely(!value)) return NULL; Py_INCREF(value); #endif return value; } /* FetchCommonType */ #if __PYX_LIMITED_VERSION_HEX < 0x030C0000 static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); if (result && metaclass) { PyObject *old_tp = (PyObject*)Py_TYPE(result); Py_INCREF((PyObject*)metaclass); #if __PYX_LIMITED_VERSION_HEX >= 0x03090000 Py_SET_TYPE(result, metaclass); #else result->ob_type = metaclass; #endif Py_DECREF(old_tp); } return result; } #else #define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) #endif static int __Pyx_VerifyCachedType(PyObject *cached_type, const char *name, Py_ssize_t expected_basicsize) { Py_ssize_t basicsize; if (!PyType_Check(cached_type)) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s is not a type object", name); return -1; } if (expected_basicsize == 0) { return 0; // size is inherited, nothing useful to check } #if CYTHON_COMPILING_IN_LIMITED_API PyObject *py_basicsize; py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); if (unlikely(!py_basicsize)) return -1; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = NULL; if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; #else basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; #endif if (basicsize != expected_basicsize) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s has the wrong size, try recompiling", name); return -1; } return 0; } static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; int get_item_ref_result; const char* object_name = strrchr(spec->name, '.'); object_name = object_name ? object_name+1 : spec->name; py_object_name = PyUnicode_FromString(object_name); if (!py_object_name) return NULL; abi_module = __Pyx_FetchSharedCythonABIModule(); if (!abi_module) goto done; abi_module_dict = PyModule_GetDict(abi_module); if (!abi_module_dict) goto done; get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); if (get_item_ref_result == 1) { if (__Pyx_VerifyCachedType( cached_type, object_name, spec->basicsize) < 0) { goto bad; } goto done; } else if (unlikely(get_item_ref_result == -1)) { goto bad; } CYTHON_UNUSED_VAR(module); cached_type = __Pyx_PyType_FromMetaclass(metaclass, abi_module, spec, bases); if (unlikely(!cached_type)) goto bad; if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type, 1); if (unlikely(new_cached_type != cached_type)) { if (unlikely(!new_cached_type)) goto bad; Py_DECREF(cached_type); cached_type = new_cached_type; if (__Pyx_VerifyCachedType( cached_type, object_name, spec->basicsize) < 0) { goto bad; } goto done; } else { Py_DECREF(new_cached_type); } done: Py_XDECREF(abi_module); Py_DECREF(py_object_name); assert(cached_type == NULL || PyType_Check(cached_type)); return (PyTypeObject *) cached_type; bad: Py_XDECREF(cached_type); cached_type = NULL; goto done; } /* CommonTypesMetaclass */ static PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); } static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, {0, 0, 0, 0, 0} }; static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, {0, 0} }; static PyType_Spec __pyx_CommonTypesMetaclass_spec = { __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", 0, 0, #if PY_VERSION_HEX >= 0x030A0000 Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | #endif Py_TPFLAGS_DEFAULT, __pyx_CommonTypesMetaclass_slots }; static int __pyx_CommonTypesMetaclass_init(PyObject *module) { __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); PyObject *bases = PyTuple_Pack(1, &PyType_Type); if (unlikely(!bases)) { return -1; } mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); Py_DECREF(bases); if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { return -1; } return 0; } /* CallTypeTraverse */ #if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) #else static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 if (__Pyx_get_runtime_version() < 0x03090000) return 0; #endif if (!always_call) { PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); unsigned long flags = PyType_GetFlags(base); if (flags & Py_TPFLAGS_HEAPTYPE) { return 0; } } Py_VISIT((PyObject*)Py_TYPE(o)); return 0; } #endif /* PyMethodNew */ #if CYTHON_COMPILING_IN_LIMITED_API static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { PyObject *result; CYTHON_UNUSED_VAR(typ); if (!self) return __Pyx_NewRef(func); #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 { PyObject *args[] = {func, self}; result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); } #else result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); #endif return result; } #else static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { CYTHON_UNUSED_VAR(typ); if (!self) return __Pyx_NewRef(func); return PyMethod_New(func, self); } #endif /* PyVectorcallFastCallDict */ #if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) { PyObject *res = NULL; PyObject *kwnames; PyObject **newargs; PyObject **kwvalues; Py_ssize_t i, pos; size_t j; PyObject *key, *value; unsigned long keys_are_strings; #if !CYTHON_ASSUME_SAFE_SIZE Py_ssize_t nkw = PyDict_Size(kw); if (unlikely(nkw == -1)) return NULL; #else Py_ssize_t nkw = PyDict_GET_SIZE(kw); #endif newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); if (unlikely(newargs == NULL)) { PyErr_NoMemory(); return NULL; } for (j = 0; j < nargs; j++) newargs[j] = args[j]; kwnames = PyTuple_New(nkw); if (unlikely(kwnames == NULL)) { PyMem_Free(newargs); return NULL; } kwvalues = newargs + nargs; pos = i = 0; keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; while (PyDict_Next(kw, &pos, &key, &value)) { keys_are_strings &= #if CYTHON_COMPILING_IN_LIMITED_API PyType_GetFlags(Py_TYPE(key)); #else Py_TYPE(key)->tp_flags; #endif Py_INCREF(key); Py_INCREF(value); #if !CYTHON_ASSUME_SAFE_MACROS if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; #else PyTuple_SET_ITEM(kwnames, i, key); #endif kwvalues[i] = value; i++; } if (unlikely(!keys_are_strings)) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); goto cleanup; } res = vc(func, newargs, nargs, kwnames); cleanup: Py_DECREF(kwnames); for (i = 0; i < nkw; i++) Py_DECREF(kwvalues[i]); PyMem_Free(newargs); return res; } static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) { Py_ssize_t kw_size = likely(kw == NULL) ? 0 : #if !CYTHON_ASSUME_SAFE_SIZE PyDict_Size(kw); #else PyDict_GET_SIZE(kw); #endif if (kw_size == 0) { return vc(func, args, nargs, NULL); } #if !CYTHON_ASSUME_SAFE_SIZE else if (unlikely(kw_size == -1)) { return NULL; } #endif return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); } #endif /* CythonFunctionShared */ #if CYTHON_COMPILING_IN_LIMITED_API static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { if (__Pyx_CyFunction_Check(func)) { return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; } else if (PyCFunction_Check(func)) { return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; } return 0; } static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { int result; PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); if (unlikely(!newFunc)) { PyErr_Clear(); // It's only an optimization, so don't throw an error return 0; } result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); Py_DECREF(newFunc); return result; } return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); } #else static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { if (PyMethod_Check(func)) { func = PyMethod_GET_FUNCTION(func); } return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; } #endif static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { #if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API __Pyx_Py_XDECREF_SET( __Pyx_CyFunction_GetClassObj(f), ((classobj) ? __Pyx_NewRef(classobj) : NULL)); #else __Pyx_Py_XDECREF_SET( ((PyCMethodObject *) (f))->mm_class, (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); #endif } static PyObject * __Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) { if (unlikely(op->func_doc == NULL)) { #if CYTHON_COMPILING_IN_LIMITED_API op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); if (unlikely(!op->func_doc)) return NULL; #else if (((PyCFunctionObject*)op)->m_ml->ml_doc) { op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); if (unlikely(op->func_doc == NULL)) return NULL; } else { Py_INCREF(Py_None); return Py_None; } #endif } Py_INCREF(op->func_doc); return op->func_doc; } static PyObject * __Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { PyObject *result; CYTHON_UNUSED_VAR(closure); __Pyx_BEGIN_CRITICAL_SECTION(op); result = __Pyx_CyFunction_get_doc_locked(op); __Pyx_END_CRITICAL_SECTION(); return result; } static int __Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) { CYTHON_UNUSED_VAR(context); if (value == NULL) { value = Py_None; } Py_INCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->func_doc, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) { if (unlikely(op->func_name == NULL)) { #if CYTHON_COMPILING_IN_LIMITED_API op->func_name = PyObject_GetAttrString(op->func, "__name__"); #else op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); #endif if (unlikely(op->func_name == NULL)) return NULL; } Py_INCREF(op->func_name); return op->func_name; } static PyObject * __Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) { PyObject *result = NULL; CYTHON_UNUSED_VAR(context); __Pyx_BEGIN_CRITICAL_SECTION(op); result = __Pyx_CyFunction_get_name_locked(op); __Pyx_END_CRITICAL_SECTION(); return result; } static int __Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) { CYTHON_UNUSED_VAR(context); if (unlikely(value == NULL || !PyUnicode_Check(value))) { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } Py_INCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->func_name, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) { CYTHON_UNUSED_VAR(context); PyObject *result; __Pyx_BEGIN_CRITICAL_SECTION(op); Py_INCREF(op->func_qualname); result = op->func_qualname; __Pyx_END_CRITICAL_SECTION(); return result; } static int __Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) { CYTHON_UNUSED_VAR(context); if (unlikely(value == NULL || !PyUnicode_Check(value))) { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } Py_INCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->func_qualname, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_dict_locked(__pyx_CyFunctionObject *op) { if (unlikely(op->func_dict == NULL)) { op->func_dict = PyDict_New(); if (unlikely(op->func_dict == NULL)) return NULL; } Py_INCREF(op->func_dict); return op->func_dict; } static PyObject * __Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) { CYTHON_UNUSED_VAR(context); PyObject *result; __Pyx_BEGIN_CRITICAL_SECTION(op); result = __Pyx_CyFunction_get_dict_locked(op); __Pyx_END_CRITICAL_SECTION(); return result; } static int __Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, void *context) { CYTHON_UNUSED_VAR(context); if (unlikely(value == NULL)) { PyErr_SetString(PyExc_TypeError, "function's dictionary may not be deleted"); return -1; } if (unlikely(!PyDict_Check(value))) { PyErr_SetString(PyExc_TypeError, "setting function's dictionary to a non-dict"); return -1; } Py_INCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->func_dict, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) { CYTHON_UNUSED_VAR(context); Py_INCREF(op->func_globals); return op->func_globals; } static PyObject * __Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) { CYTHON_UNUSED_VAR(op); CYTHON_UNUSED_VAR(context); Py_INCREF(Py_None); return Py_None; } static PyObject * __Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) { PyObject* result = (op->func_code) ? op->func_code : Py_None; CYTHON_UNUSED_VAR(context); Py_INCREF(result); return result; } static int __Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { int result = 0; PyObject *res = op->defaults_getter((PyObject *) op); if (unlikely(!res)) return -1; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS op->defaults_tuple = PyTuple_GET_ITEM(res, 0); Py_INCREF(op->defaults_tuple); op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); Py_INCREF(op->defaults_kwdict); #else op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); if (unlikely(!op->defaults_tuple)) result = -1; else { op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); if (unlikely(!op->defaults_kwdict)) result = -1; } #endif Py_DECREF(res); return result; } static int __Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { CYTHON_UNUSED_VAR(context); if (!value) { value = Py_None; } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { PyErr_SetString(PyExc_TypeError, "__defaults__ must be set to a tuple object"); return -1; } PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " "currently affect the values used in function calls", 1); Py_INCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { PyObject* result = op->defaults_tuple; if (unlikely(!result)) { if (op->defaults_getter) { if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; result = op->defaults_tuple; } else { result = Py_None; } } Py_INCREF(result); return result; } static PyObject * __Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { PyObject* result = NULL; CYTHON_UNUSED_VAR(context); __Pyx_BEGIN_CRITICAL_SECTION(op); result = __Pyx_CyFunction_get_defaults_locked(op); __Pyx_END_CRITICAL_SECTION(); return result; } static int __Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { CYTHON_UNUSED_VAR(context); if (!value) { value = Py_None; } else if (unlikely(value != Py_None && !PyDict_Check(value))) { PyErr_SetString(PyExc_TypeError, "__kwdefaults__ must be set to a dict object"); return -1; } PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " "currently affect the values used in function calls", 1); Py_INCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { PyObject* result = op->defaults_kwdict; if (unlikely(!result)) { if (op->defaults_getter) { if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; result = op->defaults_kwdict; } else { result = Py_None; } } Py_INCREF(result); return result; } static PyObject * __Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { PyObject* result; CYTHON_UNUSED_VAR(context); __Pyx_BEGIN_CRITICAL_SECTION(op); result = __Pyx_CyFunction_get_kwdefaults_locked(op); __Pyx_END_CRITICAL_SECTION(); return result; } static int __Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { CYTHON_UNUSED_VAR(context); if (!value || value == Py_None) { value = NULL; } else if (unlikely(!PyDict_Check(value))) { PyErr_SetString(PyExc_TypeError, "__annotations__ must be set to a dict object"); return -1; } Py_XINCREF(value); __Pyx_BEGIN_CRITICAL_SECTION(op); __Pyx_Py_XDECREF_SET(op->func_annotations, value); __Pyx_END_CRITICAL_SECTION(); return 0; } static PyObject * __Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { PyObject* result = op->func_annotations; if (unlikely(!result)) { result = PyDict_New(); if (unlikely(!result)) return NULL; op->func_annotations = result; } Py_INCREF(result); return result; } static PyObject * __Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { PyObject *result; CYTHON_UNUSED_VAR(context); __Pyx_BEGIN_CRITICAL_SECTION(op); result = __Pyx_CyFunction_get_annotations_locked(op); __Pyx_END_CRITICAL_SECTION(); return result; } static PyObject * __Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; if (is_coroutine) { PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; fromlist = PyList_New(1); if (unlikely(!fromlist)) return NULL; Py_INCREF(marker); #if CYTHON_ASSUME_SAFE_MACROS PyList_SET_ITEM(fromlist, 0, marker); #else if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { Py_DECREF(marker); Py_DECREF(fromlist); return NULL; } #endif module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); Py_DECREF(fromlist); if (unlikely(!module)) goto ignore; is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); Py_DECREF(module); if (likely(is_coroutine_value)) { return is_coroutine_value; } ignore: PyErr_Clear(); } return __Pyx_PyBool_FromLong(is_coroutine); } static PyObject * __Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { PyObject *result; CYTHON_UNUSED_VAR(context); if (op->func_is_coroutine) { return __Pyx_NewRef(op->func_is_coroutine); } result = __Pyx_CyFunction_get_is_coroutine_value(op); if (unlikely(!result)) return NULL; __Pyx_BEGIN_CRITICAL_SECTION(op); if (op->func_is_coroutine) { Py_DECREF(result); result = __Pyx_NewRef(op->func_is_coroutine); } else { op->func_is_coroutine = __Pyx_NewRef(result); } __Pyx_END_CRITICAL_SECTION(); return result; } static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { #if CYTHON_COMPILING_IN_LIMITED_API PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); if (!py_name) return; PyErr_Format(PyExc_TypeError, "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", py_name, message, size); Py_DECREF(py_name); #else const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; PyErr_Format(PyExc_TypeError, "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", name, message, size); #endif } static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { #if CYTHON_COMPILING_IN_LIMITED_API PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); if (!py_name) return; PyErr_Format(PyExc_TypeError, "%.200S() %s", py_name, message); Py_DECREF(py_name); #else const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; PyErr_Format(PyExc_TypeError, "%.200s() %s", name, message); #endif } #if CYTHON_COMPILING_IN_LIMITED_API static PyObject * __Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { CYTHON_UNUSED_VAR(context); return PyObject_GetAttrString(op->func, "__module__"); } static int __Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { CYTHON_UNUSED_VAR(context); return PyObject_SetAttrString(op->func, "__module__", value); } #endif static PyGetSetDef __pyx_CyFunction_getsets[] = { {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, #if CYTHON_COMPILING_IN_LIMITED_API {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, #endif {0, 0, 0, 0, 0} }; static PyMemberDef __pyx_CyFunction_members[] = { #if !CYTHON_COMPILING_IN_LIMITED_API {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, #endif {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, #if CYTHON_METH_FASTCALL #if CYTHON_BACKPORT_VECTORCALL || CYTHON_COMPILING_IN_LIMITED_API {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, #else {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, #endif #if CYTHON_COMPILING_IN_LIMITED_API {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, #else {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, #endif #endif {0, 0, 0, 0, 0} }; static PyObject * __Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) { PyObject *result = NULL; CYTHON_UNUSED_VAR(args); __Pyx_BEGIN_CRITICAL_SECTION(m); Py_INCREF(m->func_qualname); result = m->func_qualname; __Pyx_END_CRITICAL_SECTION(); return result; } static PyMethodDef __pyx_CyFunction_methods[] = { {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, {0, 0, 0, 0} }; #if CYTHON_COMPILING_IN_LIMITED_API #define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) #else #define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) #endif static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { #if !CYTHON_COMPILING_IN_LIMITED_API PyCFunctionObject *cf = (PyCFunctionObject*) op; #endif if (unlikely(op == NULL)) return NULL; #if CYTHON_COMPILING_IN_LIMITED_API op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); if (unlikely(!op->func)) return NULL; #endif op->flags = flags; __Pyx_CyFunction_weakreflist(op) = NULL; #if !CYTHON_COMPILING_IN_LIMITED_API cf->m_ml = ml; cf->m_self = (PyObject *) op; #endif Py_XINCREF(closure); op->func_closure = closure; #if !CYTHON_COMPILING_IN_LIMITED_API Py_XINCREF(module); cf->m_module = module; #endif op->func_dict = NULL; op->func_name = NULL; Py_INCREF(qualname); op->func_qualname = qualname; op->func_doc = NULL; #if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API op->func_classobj = NULL; #else ((PyCMethodObject*)op)->mm_class = NULL; #endif op->func_globals = globals; Py_INCREF(op->func_globals); Py_XINCREF(code); op->func_code = code; op->defaults = NULL; op->defaults_tuple = NULL; op->defaults_kwdict = NULL; op->defaults_getter = NULL; op->func_annotations = NULL; op->func_is_coroutine = NULL; #if CYTHON_METH_FASTCALL switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { case METH_NOARGS: __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; break; case METH_O: __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; break; case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; break; case METH_FASTCALL | METH_KEYWORDS: __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; break; case METH_VARARGS | METH_KEYWORDS: __Pyx_CyFunction_func_vectorcall(op) = NULL; break; default: PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); Py_DECREF(op); return NULL; } #endif return (PyObject *) op; } static int __Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) { Py_CLEAR(m->func_closure); #if CYTHON_COMPILING_IN_LIMITED_API Py_CLEAR(m->func); #else Py_CLEAR(((PyCFunctionObject*)m)->m_module); #endif Py_CLEAR(m->func_dict); Py_CLEAR(m->func_name); Py_CLEAR(m->func_qualname); Py_CLEAR(m->func_doc); Py_CLEAR(m->func_globals); Py_CLEAR(m->func_code); #if !CYTHON_COMPILING_IN_LIMITED_API #if PY_VERSION_HEX < 0x030900B1 Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); #else { PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; ((PyCMethodObject *) (m))->mm_class = NULL; Py_XDECREF(cls); } #endif #endif Py_CLEAR(m->defaults_tuple); Py_CLEAR(m->defaults_kwdict); Py_CLEAR(m->func_annotations); Py_CLEAR(m->func_is_coroutine); Py_CLEAR(m->defaults); return 0; } static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) { if (__Pyx_CyFunction_weakreflist(m) != NULL) PyObject_ClearWeakRefs((PyObject *) m); __Pyx_CyFunction_clear(m); __Pyx_PyHeapTypeObject_GC_Del(m); } static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) { PyObject_GC_UnTrack(m); __Pyx__CyFunction_dealloc(m); } static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) { { int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); if (e) return e; } Py_VISIT(m->func_closure); #if CYTHON_COMPILING_IN_LIMITED_API Py_VISIT(m->func); #else Py_VISIT(((PyCFunctionObject*)m)->m_module); #endif Py_VISIT(m->func_dict); __Pyx_VISIT_CONST(m->func_name); __Pyx_VISIT_CONST(m->func_qualname); Py_VISIT(m->func_doc); Py_VISIT(m->func_globals); __Pyx_VISIT_CONST(m->func_code); #if !CYTHON_COMPILING_IN_LIMITED_API Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); #endif Py_VISIT(m->defaults_tuple); Py_VISIT(m->defaults_kwdict); Py_VISIT(m->func_is_coroutine); Py_VISIT(m->defaults); return 0; } static PyObject* __Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) { PyObject *repr; __Pyx_BEGIN_CRITICAL_SECTION(op); repr = PyUnicode_FromFormat("", op->func_qualname, (void *)op); __Pyx_END_CRITICAL_SECTION(); return repr; } static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { #if CYTHON_COMPILING_IN_LIMITED_API PyObject *f = ((__pyx_CyFunctionObject*)func)->func; PyCFunction meth; int flags; meth = PyCFunction_GetFunction(f); if (unlikely(!meth)) return NULL; flags = PyCFunction_GetFlags(f); if (unlikely(flags < 0)) return NULL; #else PyCFunctionObject* f = (PyCFunctionObject*)func; PyCFunction meth = f->m_ml->ml_meth; int flags = f->m_ml->ml_flags; #endif Py_ssize_t size; switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { case METH_VARARGS: if (likely(kw == NULL || PyDict_Size(kw) == 0)) return (*meth)(self, arg); break; case METH_VARARGS | METH_KEYWORDS: return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); case METH_NOARGS: if (likely(kw == NULL || PyDict_Size(kw) == 0)) { #if CYTHON_ASSUME_SAFE_SIZE size = PyTuple_GET_SIZE(arg); #else size = PyTuple_Size(arg); if (unlikely(size < 0)) return NULL; #endif if (likely(size == 0)) return (*meth)(self, NULL); __Pyx_CyFunction_raise_argument_count_error( (__pyx_CyFunctionObject*)func, "takes no arguments", size); return NULL; } break; case METH_O: if (likely(kw == NULL || PyDict_Size(kw) == 0)) { #if CYTHON_ASSUME_SAFE_SIZE size = PyTuple_GET_SIZE(arg); #else size = PyTuple_Size(arg); if (unlikely(size < 0)) return NULL; #endif if (likely(size == 1)) { PyObject *result, *arg0; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS arg0 = PyTuple_GET_ITEM(arg, 0); #else arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; #endif result = (*meth)(self, arg0); #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_DECREF(arg0); #endif return result; } __Pyx_CyFunction_raise_argument_count_error( (__pyx_CyFunctionObject*)func, "takes exactly one argument", size); return NULL; } break; default: PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); return NULL; } __Pyx_CyFunction_raise_type_error( (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); return NULL; } static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *self, *result; #if CYTHON_COMPILING_IN_LIMITED_API self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); if (unlikely(!self) && PyErr_Occurred()) return NULL; #else self = ((PyCFunctionObject*)func)->m_self; #endif result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); return result; } static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { PyObject *result; __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; #if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); if (vc) { #if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); #else (void) &__Pyx_PyVectorcall_FastCallDict; return PyVectorcall_Call(func, args, kw); #endif } #endif if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { Py_ssize_t argc; PyObject *new_args; PyObject *self; #if CYTHON_ASSUME_SAFE_SIZE argc = PyTuple_GET_SIZE(args); #else argc = PyTuple_Size(args); if (unlikely(argc < 0)) return NULL; #endif new_args = PyTuple_GetSlice(args, 1, argc); if (unlikely(!new_args)) return NULL; self = PyTuple_GetItem(args, 0); if (unlikely(!self)) { Py_DECREF(new_args); PyErr_Format(PyExc_TypeError, "unbound method %.200S() needs an argument", cyfunc->func_qualname); return NULL; } result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); Py_DECREF(new_args); } else { result = __Pyx_CyFunction_Call(func, args, kw); } return result; } #if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) { int ret = 0; if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { if (unlikely(nargs < 1)) { __Pyx_CyFunction_raise_type_error( cyfunc, "needs an argument"); return -1; } ret = 1; } if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { __Pyx_CyFunction_raise_type_error( cyfunc, "takes no keyword arguments"); return -1; } return ret; } static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) { __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; #if CYTHON_BACKPORT_VECTORCALL Py_ssize_t nargs = (Py_ssize_t)nargsf; #else Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); #endif PyObject *self; #if CYTHON_COMPILING_IN_LIMITED_API PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); if (unlikely(!meth)) return NULL; #else PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; #endif switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { case 1: self = args[0]; args += 1; nargs -= 1; break; case 0: #if CYTHON_COMPILING_IN_LIMITED_API self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); if (unlikely(!self) && PyErr_Occurred()) return NULL; #else self = ((PyCFunctionObject*)cyfunc)->m_self; #endif break; default: return NULL; } if (unlikely(nargs != 0)) { __Pyx_CyFunction_raise_argument_count_error( cyfunc, "takes no arguments", nargs); return NULL; } return meth(self, NULL); } static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) { __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; #if CYTHON_BACKPORT_VECTORCALL Py_ssize_t nargs = (Py_ssize_t)nargsf; #else Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); #endif PyObject *self; #if CYTHON_COMPILING_IN_LIMITED_API PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); if (unlikely(!meth)) return NULL; #else PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; #endif switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { case 1: self = args[0]; args += 1; nargs -= 1; break; case 0: #if CYTHON_COMPILING_IN_LIMITED_API self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); if (unlikely(!self) && PyErr_Occurred()) return NULL; #else self = ((PyCFunctionObject*)cyfunc)->m_self; #endif break; default: return NULL; } if (unlikely(nargs != 1)) { __Pyx_CyFunction_raise_argument_count_error( cyfunc, "takes exactly one argument", nargs); return NULL; } return meth(self, args[0]); } static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) { __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; #if CYTHON_BACKPORT_VECTORCALL Py_ssize_t nargs = (Py_ssize_t)nargsf; #else Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); #endif PyObject *self; #if CYTHON_COMPILING_IN_LIMITED_API PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); if (unlikely(!meth)) return NULL; #else PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; #endif switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { case 1: self = args[0]; args += 1; nargs -= 1; break; case 0: #if CYTHON_COMPILING_IN_LIMITED_API self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); if (unlikely(!self) && PyErr_Occurred()) return NULL; #else self = ((PyCFunctionObject*)cyfunc)->m_self; #endif break; default: return NULL; } return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); } static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) { __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); #if CYTHON_BACKPORT_VECTORCALL Py_ssize_t nargs = (Py_ssize_t)nargsf; #else Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); #endif PyObject *self; #if CYTHON_COMPILING_IN_LIMITED_API PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); if (unlikely(!meth)) return NULL; #else PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; #endif switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { case 1: self = args[0]; args += 1; nargs -= 1; break; case 0: #if CYTHON_COMPILING_IN_LIMITED_API self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); if (unlikely(!self) && PyErr_Occurred()) return NULL; #else self = ((PyCFunctionObject*)cyfunc)->m_self; #endif break; default: return NULL; } return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, (size_t)nargs, kwnames); } #endif static PyType_Slot __pyx_CyFunctionType_slots[] = { {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, {Py_tp_methods, (void *)__pyx_CyFunction_methods}, {Py_tp_members, (void *)__pyx_CyFunction_members}, {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, {0, 0}, }; static PyType_Spec __pyx_CyFunctionType_spec = { __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", sizeof(__pyx_CyFunctionObject), 0, #ifdef Py_TPFLAGS_METHOD_DESCRIPTOR Py_TPFLAGS_METHOD_DESCRIPTOR | #endif #if CYTHON_METH_FASTCALL #if defined(Py_TPFLAGS_HAVE_VECTORCALL) Py_TPFLAGS_HAVE_VECTORCALL | #elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) _Py_TPFLAGS_HAVE_VECTORCALL | #endif #endif // CYTHON_METH_FASTCALL #if PY_VERSION_HEX >= 0x030A0000 Py_TPFLAGS_IMMUTABLETYPE | #endif Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, __pyx_CyFunctionType_slots }; static int __pyx_CyFunction_init(PyObject *module) { __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { return -1; } return 0; } static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); if (unlikely(!m->defaults)) return NULL; return m->defaults; } static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults_tuple = tuple; Py_INCREF(tuple); } static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults_kwdict = dict; Py_INCREF(dict); } static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->func_annotations = dict; Py_INCREF(dict); } /* CythonFunction */ static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { PyObject *op = __Pyx_CyFunction_Init( PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), ml, flags, qualname, closure, module, globals, code ); if (likely(op)) { PyObject_GC_Track(op); } return op; } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, "%s() got multiple values for keyword argument '%U'", func_name, kw_name); } /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL && !CYTHON_VECTORCALL static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject *const *args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; PyObject *kwdefs; PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) { return NULL; } if ( co->co_kwonlyargcount == 0 && likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); kwdefs = PyFunction_GET_KW_DEFAULTS(func); if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, kwdefs, closure); Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = Py_TYPE(func)->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallMethO */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); self = __Pyx_CyOrPyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectFastCall */ #if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { PyObject *argstuple; PyObject *result = 0; size_t i; argstuple = PyTuple_New((Py_ssize_t)nargs); if (unlikely(!argstuple)) return NULL; for (i = 0; i < nargs; i++) { Py_INCREF(args[i]); if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; } result = __Pyx_PyObject_Call(func, argstuple, kwargs); bad: Py_DECREF(argstuple); return result; } #endif #if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API #if PY_VERSION_HEX < 0x03090000 #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) #elif CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { PyTypeObject *tp = Py_TYPE(callable); #if defined(__Pyx_CyFunction_USED) if (__Pyx_CyFunction_CheckExact(callable)) { return __Pyx_CyFunction_func_vectorcall(callable); } #endif if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { return NULL; } assert(PyCallable_Check(callable)); Py_ssize_t offset = tp->tp_vectorcall_offset; assert(offset > 0); vectorcallfunc ptr; memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); return ptr; } #else #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) #endif #endif static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); #if CYTHON_COMPILING_IN_CPYTHON if (nargs == 0 && kwargs == NULL) { if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) return __Pyx_PyObject_CallMethO(func, NULL); } else if (nargs == 1 && kwargs == NULL) { if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) return __Pyx_PyObject_CallMethO(func, args[0]); } #endif #if PY_VERSION_HEX < 0x030800B1 #if CYTHON_FAST_PYCCALL if (PyCFunction_Check(func)) { if (kwargs) { return _PyCFunction_FastCallDict(func, args, nargs, kwargs); } else { return _PyCFunction_FastCallKeywords(func, args, nargs, NULL); } } if (!kwargs && __Pyx_IS_TYPE(func, &PyMethodDescr_Type)) { return _PyMethodDescr_FastCallKeywords(func, args, nargs, NULL); } #endif #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs); } #endif #endif if (kwargs == NULL) { #if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API vectorcallfunc f = __Pyx_PyVectorcall_Function(func); if (f) { return f(func, args, _nargs, NULL); } #elif defined(__Pyx_CyFunction_USED) && CYTHON_BACKPORT_VECTORCALL if (__Pyx_CyFunction_CheckExact(func)) { __pyx_vectorcallfunc f = __Pyx_CyFunction_func_vectorcall(func); if (f) return f(func, args, _nargs, NULL); } #elif CYTHON_COMPILING_IN_LIMITED_API && CYTHON_VECTORCALL return PyObject_Vectorcall(func, args, _nargs, NULL); #endif } if (nargs == 0) { return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); } #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); #else return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); #endif } /* UnpackUnboundCMethod */ #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { PyObject *result; PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); if (unlikely(!selfless_args)) return NULL; result = PyObject_Call(method, selfless_args, kwargs); Py_DECREF(selfless_args); return result; } #elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { return _PyObject_Vectorcall (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); } #else static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { return #if PY_VERSION_HEX < 0x03090000 _PyObject_Vectorcall #else PyObject_Vectorcall #endif (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); } #endif static PyMethodDef __Pyx_UnboundCMethod_Def = { "CythonUnboundCMethod", __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 METH_VARARGS | METH_KEYWORDS, #else METH_FASTCALL | METH_KEYWORDS, #endif NULL }; static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { PyObject *method, *result=NULL; method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); if (unlikely(!method)) return -1; result = method; #if CYTHON_COMPILING_IN_CPYTHON if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) { PyMethodDescrObject *descr = (PyMethodDescrObject*) method; target->func = descr->d_method->ml_meth; target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); } else #endif #if CYTHON_COMPILING_IN_PYPY #else if (PyCFunction_Check(method)) #endif { PyObject *self; int self_found; #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY self = PyObject_GetAttrString(method, "__self__"); if (!self) { PyErr_Clear(); } #else self = PyCFunction_GET_SELF(method); #endif self_found = (self && self != Py_None); #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY Py_XDECREF(self); #endif if (self_found) { PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); if (unlikely(!unbound_method)) return -1; Py_DECREF(method); result = unbound_method; } } #if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING if (unlikely(target->method)) { Py_DECREF(result); } else #endif target->method = result; return 0; } /* CallUnboundCMethod2 */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); if (likely(was_initialized == 2 && cfunc->func)) { PyObject *args[2] = {arg1, arg2}; if (cfunc->flag == METH_FASTCALL) { return __Pyx_CallCFunctionFast(cfunc, self, args, 2); } if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); } #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING else if (unlikely(was_initialized == 1)) { __Pyx_CachedCFunction tmp_cfunc = { #ifndef __cplusplus 0 #endif }; tmp_cfunc.type = cfunc->type; tmp_cfunc.method_name = cfunc->method_name; return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); } #endif PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); return result; } #endif static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; #if CYTHON_COMPILING_IN_CPYTHON if (cfunc->func && (cfunc->flag & METH_VARARGS)) { PyObject *result = NULL; PyObject *args = PyTuple_New(2); if (unlikely(!args)) return NULL; Py_INCREF(arg1); PyTuple_SET_ITEM(args, 0, arg1); Py_INCREF(arg2); PyTuple_SET_ITEM(args, 1, arg2); if (cfunc->flag & METH_KEYWORDS) result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); else result = __Pyx_CallCFunction(cfunc, self, args); Py_DECREF(args); return result; } #endif { PyObject *args[4] = {NULL, self, arg1, arg2}; return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); } } /* ParseKeywords */ static int __Pyx_ValidateDuplicatePosArgs( PyObject *kwds, PyObject ** const argnames[], PyObject ** const *first_kw_arg, const char* function_name) { PyObject ** const *name = argnames; while (name != first_kw_arg) { PyObject *key = **name; int found = PyDict_Contains(kwds, key); if (unlikely(found)) { if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; } name++; } return 0; bad: return -1; } #if CYTHON_USE_UNICODE_INTERNALS static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { int kind; Py_ssize_t len = PyUnicode_GET_LENGTH(s1); if (len != PyUnicode_GET_LENGTH(s2)) return 0; kind = PyUnicode_KIND(s1); if (kind != PyUnicode_KIND(s2)) return 0; const void *data1 = PyUnicode_DATA(s1); const void *data2 = PyUnicode_DATA(s2); return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); } #endif static int __Pyx_MatchKeywordArg_str( PyObject *key, PyObject ** const argnames[], PyObject ** const *first_kw_arg, size_t *index_found, const char *function_name) { PyObject ** const *name; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; if (unlikely(key_hash == -1)) { key_hash = PyObject_Hash(key); if (unlikely(key_hash == -1)) goto bad; } #endif name = first_kw_arg; while (*name) { PyObject *name_str = **name; #if CYTHON_USE_UNICODE_INTERNALS if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { *index_found = (size_t) (name - argnames); return 1; } #else #if CYTHON_ASSUME_SAFE_SIZE if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) #endif { int cmp = PyUnicode_Compare(name_str, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { *index_found = (size_t) (name - argnames); return 1; } } #endif name++; } name = argnames; while (name != first_kw_arg) { PyObject *name_str = **name; #if CYTHON_USE_UNICODE_INTERNALS if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { if (__Pyx_UnicodeKeywordsEqual(name_str, key)) goto arg_passed_twice; } #else #if CYTHON_ASSUME_SAFE_SIZE if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) #endif { if (unlikely(name_str == key)) goto arg_passed_twice; int cmp = PyUnicode_Compare(name_str, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; } #endif name++; } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; bad: return -1; } static int __Pyx_MatchKeywordArg_nostr( PyObject *key, PyObject ** const argnames[], PyObject ** const *first_kw_arg, size_t *index_found, const char *function_name) { PyObject ** const *name; if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; name = first_kw_arg; while (*name) { int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); if (cmp == 1) { *index_found = (size_t) (name - argnames); return 1; } if (unlikely(cmp == -1)) goto bad; name++; } name = argnames; while (name != first_kw_arg) { int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); if (unlikely(cmp != 0)) { if (cmp == 1) goto arg_passed_twice; else goto bad; } name++; } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; bad: return -1; } static CYTHON_INLINE int __Pyx_MatchKeywordArg( PyObject *key, PyObject ** const argnames[], PyObject ** const *first_kw_arg, size_t *index_found, const char *function_name) { return likely(PyUnicode_CheckExact(key)) ? __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); } static void __Pyx_RejectUnknownKeyword( PyObject *kwds, PyObject ** const argnames[], PyObject ** const *first_kw_arg, const char *function_name) { Py_ssize_t pos = 0; PyObject *key = NULL; __Pyx_BEGIN_CRITICAL_SECTION(kwds); while (PyDict_Next(kwds, &pos, &key, NULL)) { PyObject** const *name = first_kw_arg; while (*name && (**name != key)) name++; if (!*name) { #if CYTHON_AVOID_BORROWED_REFS Py_INCREF(key); #endif size_t index_found = 0; int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); if (cmp != 1) { if (cmp == 0) { PyErr_Format(PyExc_TypeError, "%s() got an unexpected keyword argument '%U'", function_name, key); } #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(key); #endif break; } #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(key); #endif } } __Pyx_END_CRITICAL_SECTION(); assert(PyErr_Occurred()); } static int __Pyx_ParseKeywordDict( PyObject *kwds, PyObject ** const argnames[], PyObject *values[], Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, const char* function_name, int ignore_unknown_kwargs) { PyObject** const *name; PyObject** const *first_kw_arg = argnames + num_pos_args; Py_ssize_t extracted = 0; #if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; #endif name = first_kw_arg; while (*name && num_kwargs > extracted) { PyObject * key = **name; PyObject *value; int found = 0; #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 found = PyDict_GetItemRef(kwds, key, &value); #else value = PyDict_GetItemWithError(kwds, key); if (value) { Py_INCREF(value); found = 1; } else { if (unlikely(PyErr_Occurred())) goto bad; } #endif if (found) { if (unlikely(found < 0)) goto bad; values[name-argnames] = value; extracted++; } name++; } if (num_kwargs > extracted) { if (ignore_unknown_kwargs) { if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) goto bad; } else { __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); goto bad; } } return 0; bad: return -1; } static int __Pyx_ParseKeywordDictToDict( PyObject *kwds, PyObject ** const argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject** const *name; PyObject** const *first_kw_arg = argnames + num_pos_args; Py_ssize_t len; #if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; #endif if (PyDict_Update(kwds2, kwds) < 0) goto bad; name = first_kw_arg; while (*name) { PyObject *key = **name; PyObject *value; #if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) int found = PyDict_Pop(kwds2, key, &value); if (found) { if (unlikely(found < 0)) goto bad; values[name-argnames] = value; } #elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 int found = PyDict_GetItemRef(kwds2, key, &value); if (found) { if (unlikely(found < 0)) goto bad; values[name-argnames] = value; if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; } #else #if CYTHON_COMPILING_IN_CPYTHON value = _PyDict_Pop(kwds2, key, kwds2); #else value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); #endif if (value == kwds2) { Py_DECREF(value); } else { if (unlikely(!value)) goto bad; values[name-argnames] = value; } #endif name++; } len = PyDict_Size(kwds2); if (len > 0) { return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); } else if (unlikely(len == -1)) { goto bad; } return 0; bad: return -1; } static int __Pyx_ParseKeywordsTuple( PyObject *kwds, PyObject * const *kwvalues, PyObject ** const argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, const char* function_name, int ignore_unknown_kwargs) { PyObject *key = NULL; PyObject** const * name; PyObject** const *first_kw_arg = argnames + num_pos_args; for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { #if CYTHON_AVOID_BORROWED_REFS key = __Pyx_PySequence_ITEM(kwds, pos); #else key = __Pyx_PyTuple_GET_ITEM(kwds, pos); #endif #if !CYTHON_ASSUME_SAFE_MACROS if (unlikely(!key)) goto bad; #endif name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { PyObject *value = kwvalues[pos]; values[name-argnames] = __Pyx_NewRef(value); } else { size_t index_found = 0; int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); if (cmp == 1) { PyObject *value = kwvalues[pos]; values[index_found] = __Pyx_NewRef(value); } else { if (unlikely(cmp == -1)) goto bad; if (kwds2) { PyObject *value = kwvalues[pos]; if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else if (!ignore_unknown_kwargs) { goto invalid_keyword; } } } #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(key); key = NULL; #endif } return 0; invalid_keyword: PyErr_Format(PyExc_TypeError, "%s() got an unexpected keyword argument '%U'", function_name, key); goto bad; bad: #if CYTHON_AVOID_BORROWED_REFS Py_XDECREF(key); #endif return -1; } static int __Pyx_ParseKeywords( PyObject *kwds, PyObject * const *kwvalues, PyObject ** const argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, const char* function_name, int ignore_unknown_kwargs) { if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); else if (kwds2) return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); else return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* decode_c_bytes */ static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { if (unlikely((start < 0) | (stop < 0))) { if (start < 0) { start += length; if (start < 0) start = 0; } if (stop < 0) stop += length; } if (stop > length) stop = length; if (unlikely(stop <= start)) return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_unicode); length = stop - start; cstring += start; if (decode_func) { return decode_func(cstring, length, errors); } else { return PyUnicode_Decode(cstring, length, encoding, errors); } } /* RejectKeywords */ static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { PyObject *key = NULL; if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { key = __Pyx_PySequence_ITEM(kwds, 0); } else { Py_ssize_t pos = 0; #if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; #endif PyDict_Next(kwds, &pos, &key, NULL); Py_INCREF(key); } if (likely(key)) { PyErr_Format(PyExc_TypeError, "%s() got an unexpected keyword argument '%U'", function_name, key); Py_DECREF(key); } } /* RaiseException */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } if (cause) { PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if PY_VERSION_HEX >= 0x030C00A6 PyException_SetTraceback(value, tb); #elif CYTHON_FAST_THREAD_STATE PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #else PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #endif } bad: Py_XDECREF(owned_instance); return; } /* ArgTypeTest */ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) { __Pyx_TypeName type_name; __Pyx_TypeName obj_type_name; PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; int from_annotation_subclass = 0; if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } else if (!exact) { if (likely(__Pyx_TypeCheck(obj, type))) return 1; } else if (exact == 2) { if (__Pyx_TypeCheck(obj, type)) { from_annotation_subclass = 1; extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; } } type_name = __Pyx_PyType_GetFullyQualifiedName(type); obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME ", got " __Pyx_FMT_TYPENAME ")" #if __PYX_LIMITED_VERSION_HEX < 0x030C0000 "%s%U" #endif , name, type_name, obj_type_name #if __PYX_LIMITED_VERSION_HEX < 0x030C0000 , (from_annotation_subclass ? ". " : ""), extra_info #endif ); #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 if (exact == 2 && from_annotation_subclass) { PyObject *res; PyObject *vargs[2]; vargs[0] = PyErr_GetRaisedException(); vargs[1] = extra_info; res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); Py_XDECREF(res); PyErr_SetRaisedException(vargs[0]); } #endif __Pyx_DECREF_TypeName(type_name); __Pyx_DECREF_TypeName(obj_type_name); return 0; } /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { PyObject *local_type = NULL, *local_value, *local_tb = NULL; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; #if PY_VERSION_HEX >= 0x030C0000 local_value = tstate->current_exception; tstate->current_exception = 0; #else local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #endif #elif __PYX_LIMITED_VERSION_HEX > 0x030C0000 local_value = PyErr_GetRaisedException(); #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif #if __PYX_LIMITED_VERSION_HEX > 0x030C0000 if (likely(local_value)) { local_type = (PyObject*) Py_TYPE(local_value); Py_INCREF(local_type); local_tb = PyException_GetTraceback(local_value); } #else PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif // __PYX_LIMITED_VERSION_HEX > 0x030C0000 Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { _PyErr_StackItem *exc_info = tstate->exc_info; #if PY_VERSION_HEX >= 0x030B00a4 tmp_value = exc_info->exc_value; exc_info->exc_value = local_value; tmp_type = NULL; tmp_tb = NULL; Py_XDECREF(local_type); Py_XDECREF(local_tb); #else tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = local_type; exc_info->exc_value = local_value; exc_info->exc_traceback = local_tb; #endif } #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 PyErr_SetHandledException(local_value); Py_XDECREF(local_value); Py_XDECREF(local_type); Py_XDECREF(local_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; #if __PYX_LIMITED_VERSION_HEX <= 0x030C0000 bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; #endif } /* SwapException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 _PyErr_StackItem *exc_info = tstate->exc_info; tmp_value = exc_info->exc_value; exc_info->exc_value = *value; if (tmp_value == NULL || tmp_value == Py_None) { Py_XDECREF(tmp_value); tmp_value = NULL; tmp_type = NULL; tmp_tb = NULL; } else { tmp_type = (PyObject*) Py_TYPE(tmp_value); Py_INCREF(tmp_type); #if CYTHON_COMPILING_IN_CPYTHON tmp_tb = ((PyBaseExceptionObject*) tmp_value)->traceback; Py_XINCREF(tmp_tb); #else tmp_tb = PyException_GetTraceback(tmp_value); #endif } #elif CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = *type; exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #endif /* GetTopmostException */ #if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) { _PyErr_StackItem *exc_info = tstate->exc_info; while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && exc_info->previous_item != NULL) { exc_info = exc_info->previous_item; } return exc_info; } #endif /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); PyObject *exc_value = exc_info->exc_value; if (exc_value == NULL || exc_value == Py_None) { *value = NULL; *type = NULL; *tb = NULL; } else { *value = exc_value; Py_INCREF(*value); *type = (PyObject*) Py_TYPE(exc_value); Py_INCREF(*type); *tb = PyException_GetTraceback(exc_value); } #elif CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); *type = exc_info->exc_type; *value = exc_info->exc_value; *tb = exc_info->exc_traceback; Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); #endif } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 _PyErr_StackItem *exc_info = tstate->exc_info; PyObject *tmp_value = exc_info->exc_value; exc_info->exc_value = value; Py_XDECREF(tmp_value); Py_XDECREF(type); Py_XDECREF(tb); #else PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = type; exc_info->exc_value = value; exc_info->exc_traceback = tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #endif } #endif /* PyDictVersioning */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { PyObject *dict = Py_TYPE(obj)->tp_dict; return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; } static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { PyObject **dictptr = NULL; Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; if (offset) { #if CYTHON_COMPILING_IN_CPYTHON dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); #else dictptr = _PyObject_GetDictPtr(obj); #endif } return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; } static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { PyObject *dict = Py_TYPE(obj)->tp_dict; if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) return 0; return obj_dict_version == __Pyx_get_object_dict_version(obj); } #endif /* GetModuleGlobalName */ #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { PyObject *result; #if CYTHON_COMPILING_IN_LIMITED_API if (unlikely(!__pyx_m)) { if (!PyErr_Occurred()) PyErr_SetNone(PyExc_NameError); return NULL; } result = PyObject_GetAttr(__pyx_m, name); if (likely(result)) { return result; } PyErr_Clear(); #elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return result; } #else result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); } /* PyObjectFastCallMethod */ #if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { PyObject *result; PyObject *attr = PyObject_GetAttr(args[0], name); if (unlikely(!attr)) return NULL; result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); Py_DECREF(attr); return result; } #endif /* PyObjectCallNoArg */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { PyObject *arg[2] = {NULL, NULL}; return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); } /* PyObjectCallOneArg */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *args[2] = {NULL, arg}; return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); } /* PyObjectGetMethod */ static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { PyObject *attr; #if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP __Pyx_TypeName type_name; PyTypeObject *tp = Py_TYPE(obj); PyObject *descr; descrgetfunc f = NULL; PyObject **dictptr, *dict; int meth_found = 0; assert (*method == NULL); if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { attr = __Pyx_PyObject_GetAttrStr(obj, name); goto try_unpack; } if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { return 0; } descr = _PyType_Lookup(tp, name); if (likely(descr != NULL)) { Py_INCREF(descr); #if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) #else #ifdef __Pyx_CyFunction_USED if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) #else if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) #endif #endif { meth_found = 1; } else { f = Py_TYPE(descr)->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); goto try_unpack; } } } dictptr = _PyObject_GetDictPtr(obj); if (dictptr != NULL && (dict = *dictptr) != NULL) { Py_INCREF(dict); attr = __Pyx_PyDict_GetItemStr(dict, name); if (attr != NULL) { Py_INCREF(attr); Py_DECREF(dict); Py_XDECREF(descr); goto try_unpack; } Py_DECREF(dict); } if (meth_found) { *method = descr; return 1; } if (f != NULL) { attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); goto try_unpack; } if (likely(descr != NULL)) { *method = descr; return 0; } type_name = __Pyx_PyType_GetFullyQualifiedName(tp); PyErr_Format(PyExc_AttributeError, "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", type_name, name); __Pyx_DECREF_TypeName(type_name); return 0; #else attr = __Pyx_PyObject_GetAttrStr(obj, name); goto try_unpack; #endif try_unpack: #if CYTHON_UNPACK_METHODS if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { PyObject *function = PyMethod_GET_FUNCTION(attr); Py_INCREF(function); Py_DECREF(attr); *method = function; return 1; } #endif *method = attr; return 0; } /* PyObjectCallMethod0 */ static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { #if CYTHON_VECTORCALL && (__PYX_LIMITED_VERSION_HEX >= 0x030C0000 || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x03090000)) PyObject *args[1] = {obj}; (void) __Pyx_PyObject_GetMethod; (void) __Pyx_PyObject_CallOneArg; (void) __Pyx_PyObject_CallNoArg; return PyObject_VectorcallMethod(method_name, args, 1 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); #else PyObject *method = NULL, *result = NULL; int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); if (likely(is_method)) { result = __Pyx_PyObject_CallOneArg(method, obj); Py_DECREF(method); return result; } if (unlikely(!method)) goto bad; result = __Pyx_PyObject_CallNoArg(method); Py_DECREF(method); bad: return result; #endif } /* ValidateBasesTuple */ #if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { Py_ssize_t i, n; #if CYTHON_ASSUME_SAFE_SIZE n = PyTuple_GET_SIZE(bases); #else n = PyTuple_Size(bases); if (unlikely(n < 0)) return -1; #endif for (i = 1; i < n; i++) { PyTypeObject *b; #if CYTHON_AVOID_BORROWED_REFS PyObject *b0 = PySequence_GetItem(bases, i); if (!b0) return -1; #elif CYTHON_ASSUME_SAFE_MACROS PyObject *b0 = PyTuple_GET_ITEM(bases, i); #else PyObject *b0 = PyTuple_GetItem(bases, i); if (!b0) return -1; #endif b = (PyTypeObject*) b0; if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) { __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); PyErr_Format(PyExc_TypeError, "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); __Pyx_DECREF_TypeName(b_name); #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(b0); #endif return -1; } if (dictoffset == 0) { Py_ssize_t b_dictoffset = 0; #if CYTHON_USE_TYPE_SLOTS b_dictoffset = b->tp_dictoffset; #else PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); if (!py_b_dictoffset) goto dictoffset_return; b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); Py_DECREF(py_b_dictoffset); if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; #endif if (b_dictoffset) { { __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); PyErr_Format(PyExc_TypeError, "extension type '%.200s' has no __dict__ slot, " "but base type '" __Pyx_FMT_TYPENAME "' has: " "either add 'cdef dict __dict__' to the extension type " "or add '__slots__ = [...]' to the base type", type_name, b_name); __Pyx_DECREF_TypeName(b_name); } #if !CYTHON_USE_TYPE_SLOTS dictoffset_return: #endif #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(b0); #endif return -1; } } #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(b0); #endif } return 0; } #endif /* PyType_Ready */ CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { while (t) { PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); if (bases) { return 1; } t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); } return 0; } static int __Pyx_PyType_Ready(PyTypeObject *t) { #if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) (void)__Pyx_PyObject_CallMethod0; #if CYTHON_USE_TYPE_SPECS (void)__Pyx_validate_bases_tuple; #endif return PyType_Ready(t); #else int r; if (!__Pyx_PyType_HasMultipleInheritance(t)) { return PyType_Ready(t); } PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) return -1; #if !defined(PYSTON_MAJOR_VERSION) { int gc_was_enabled; #if PY_VERSION_HEX >= 0x030A00b1 gc_was_enabled = PyGC_Disable(); (void)__Pyx_PyObject_CallMethod0; #else PyObject *ret, *py_status; PyObject *gc = NULL; #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ !CYTHON_COMPILING_IN_GRAAL gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); #endif if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); if (unlikely(!gc)) return -1; py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); if (unlikely(!py_status)) { Py_DECREF(gc); return -1; } gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); Py_DECREF(py_status); if (gc_was_enabled > 0) { ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); if (unlikely(!ret)) { Py_DECREF(gc); return -1; } Py_DECREF(ret); } else if (unlikely(gc_was_enabled == -1)) { Py_DECREF(gc); return -1; } #endif t->tp_flags |= Py_TPFLAGS_HEAPTYPE; #if PY_VERSION_HEX >= 0x030A0000 t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; #endif #else (void)__Pyx_PyObject_CallMethod0; #endif r = PyType_Ready(t); #if !defined(PYSTON_MAJOR_VERSION) t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; #if PY_VERSION_HEX >= 0x030A00b1 if (gc_was_enabled) PyGC_Enable(); #else if (gc_was_enabled) { PyObject *tp, *v, *tb; PyErr_Fetch(&tp, &v, &tb); ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); if (likely(ret || r == -1)) { Py_XDECREF(ret); PyErr_Restore(tp, v, tb); } else { Py_XDECREF(tp); Py_XDECREF(v); Py_XDECREF(tb); r = -1; } } Py_DECREF(gc); #endif } #endif return r; #endif } /* SetVTable */ static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { PyObject *ob = PyCapsule_New(vtable, 0, 0); if (unlikely(!ob)) goto bad; #if CYTHON_COMPILING_IN_LIMITED_API if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) #else if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) #endif goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } /* GetVTable */ static void* __Pyx_GetVtable(PyTypeObject *type) { void* ptr; #if CYTHON_COMPILING_IN_LIMITED_API PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); #else PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); #endif if (!ob) goto bad; ptr = PyCapsule_GetPointer(ob, 0); if (!ptr && !PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); Py_DECREF(ob); return ptr; bad: Py_XDECREF(ob); return NULL; } /* MergeVTables */ static int __Pyx_MergeVtables(PyTypeObject *type) { int i=0; Py_ssize_t size; void** base_vtables; __Pyx_TypeName tp_base_name = NULL; __Pyx_TypeName base_name = NULL; void* unknown = (void*)-1; PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); int base_depth = 0; { PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); while (base) { base_depth += 1; base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); } } base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); base_vtables[0] = unknown; #if CYTHON_COMPILING_IN_LIMITED_API size = PyTuple_Size(bases); if (size < 0) goto other_failure; #else size = PyTuple_GET_SIZE(bases); #endif for (i = 1; i < size; i++) { PyObject *basei; void* base_vtable; #if CYTHON_AVOID_BORROWED_REFS basei = PySequence_GetItem(bases, i); if (unlikely(!basei)) goto other_failure; #elif !CYTHON_ASSUME_SAFE_MACROS basei = PyTuple_GetItem(bases, i); if (unlikely(!basei)) goto other_failure; #else basei = PyTuple_GET_ITEM(bases, i); #endif base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(basei); #endif if (base_vtable != NULL) { int j; PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); for (j = 0; j < base_depth; j++) { if (base_vtables[j] == unknown) { base_vtables[j] = __Pyx_GetVtable(base); base_vtables[j + 1] = unknown; } if (base_vtables[j] == base_vtable) { break; } else if (base_vtables[j] == NULL) { goto bad; } base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); } } } PyErr_Clear(); PyMem_Free(base_vtables); return 0; bad: { PyTypeObject* basei = NULL; PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); #if CYTHON_AVOID_BORROWED_REFS basei = (PyTypeObject*)PySequence_GetItem(bases, i); if (unlikely(!basei)) goto really_bad; #elif !CYTHON_ASSUME_SAFE_MACROS basei = (PyTypeObject*)PyTuple_GetItem(bases, i); if (unlikely(!basei)) goto really_bad; #else basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); #endif base_name = __Pyx_PyType_GetFullyQualifiedName(basei); #if CYTHON_AVOID_BORROWED_REFS Py_DECREF(basei); #endif } PyErr_Format(PyExc_TypeError, "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); #if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS really_bad: // bad has failed! #endif __Pyx_DECREF_TypeName(tp_base_name); __Pyx_DECREF_TypeName(base_name); #if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS other_failure: #endif PyMem_Free(base_vtables); return -1; } /* DelItemOnTypeDict */ static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { int result; PyObject *tp_dict; #if CYTHON_COMPILING_IN_LIMITED_API tp_dict = __Pyx_GetTypeDict(tp); if (unlikely(!tp_dict)) return -1; #else tp_dict = tp->tp_dict; #endif result = PyDict_DelItem(tp_dict, k); if (likely(!result)) PyType_Modified(tp); return result; } /* SetupReduce */ static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { int ret; PyObject *name_attr; name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name); if (likely(name_attr)) { ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); } else { ret = -1; } if (unlikely(ret < 0)) { PyErr_Clear(); ret = 0; } Py_XDECREF(name_attr); return ret; } static int __Pyx_setup_reduce(PyObject* type_obj) { int ret = 0; PyObject *object_reduce = NULL; PyObject *object_getstate = NULL; PyObject *object_reduce_ex = NULL; PyObject *reduce = NULL; PyObject *reduce_ex = NULL; PyObject *reduce_cython = NULL; PyObject *setstate = NULL; PyObject *setstate_cython = NULL; PyObject *getstate = NULL; #if CYTHON_USE_PYTYPE_LOOKUP getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); #else getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); if (!getstate && PyErr_Occurred()) { goto __PYX_BAD; } #endif if (getstate) { #if CYTHON_USE_PYTYPE_LOOKUP object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); #else object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); if (!object_getstate && PyErr_Occurred()) { goto __PYX_BAD; } #endif if (object_getstate != getstate) { goto __PYX_GOOD; } } #if CYTHON_USE_PYTYPE_LOOKUP object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #else object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #endif reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; if (reduce_ex == object_reduce_ex) { #if CYTHON_USE_PYTYPE_LOOKUP object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; #else object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; #endif reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (likely(reduce_cython)) { ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (reduce == object_reduce || PyErr_Occurred()) { goto __PYX_BAD; } setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); if (!setstate) PyErr_Clear(); if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (likely(setstate_cython)) { ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (!setstate || PyErr_Occurred()) { goto __PYX_BAD; } } PyType_Modified((PyTypeObject*)type_obj); } } goto __PYX_GOOD; __PYX_BAD: if (!PyErr_Occurred()) { __Pyx_TypeName type_obj_name = __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); __Pyx_DECREF_TypeName(type_obj_name); } ret = -1; __PYX_GOOD: #if !CYTHON_USE_PYTYPE_LOOKUP Py_XDECREF(object_reduce); Py_XDECREF(object_reduce_ex); Py_XDECREF(object_getstate); Py_XDECREF(getstate); #endif Py_XDECREF(reduce); Py_XDECREF(reduce_ex); Py_XDECREF(reduce_cython); Py_XDECREF(setstate); Py_XDECREF(setstate_cython); return ret; } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *module = 0; PyObject *empty_dict = 0; PyObject *empty_list = 0; empty_dict = PyDict_New(); if (unlikely(!empty_dict)) goto bad; if (level == -1) { const char* package_sep = strchr(__Pyx_MODULE_NAME, '.'); if (package_sep != (0)) { module = PyImport_ImportModuleLevelObject( name, __pyx_mstate_global->__pyx_d, empty_dict, from_list, 1); if (unlikely(!module)) { if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) goto bad; PyErr_Clear(); } } level = 0; } if (!module) { module = PyImport_ImportModuleLevelObject( name, __pyx_mstate_global->__pyx_d, empty_dict, from_list, level); } bad: Py_XDECREF(empty_dict); Py_XDECREF(empty_list); return module; } /* ImportDottedModule */ static PyObject *__Pyx__ImportDottedModule_Error(PyObject *name, PyObject *parts_tuple, Py_ssize_t count) { PyObject *partial_name = NULL, *slice = NULL, *sep = NULL; Py_ssize_t size; if (unlikely(PyErr_Occurred())) { PyErr_Clear(); } #if CYTHON_ASSUME_SAFE_SIZE size = PyTuple_GET_SIZE(parts_tuple); #else size = PyTuple_Size(parts_tuple); if (size < 0) goto bad; #endif if (likely(size == count)) { partial_name = name; } else { slice = PySequence_GetSlice(parts_tuple, 0, count); if (unlikely(!slice)) goto bad; sep = PyUnicode_FromStringAndSize(".", 1); if (unlikely(!sep)) goto bad; partial_name = PyUnicode_Join(sep, slice); } PyErr_Format( PyExc_ModuleNotFoundError, "No module named '%U'", partial_name); bad: Py_XDECREF(sep); Py_XDECREF(slice); Py_XDECREF(partial_name); return NULL; } static PyObject *__Pyx__ImportDottedModule_Lookup(PyObject *name) { PyObject *imported_module; #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ CYTHON_COMPILING_IN_GRAAL PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) return NULL; imported_module = __Pyx_PyDict_GetItemStr(modules, name); Py_XINCREF(imported_module); #else imported_module = PyImport_GetModule(name); #endif return imported_module; } static PyObject *__Pyx_ImportDottedModule_WalkParts(PyObject *module, PyObject *name, PyObject *parts_tuple) { Py_ssize_t i, nparts; #if CYTHON_ASSUME_SAFE_SIZE nparts = PyTuple_GET_SIZE(parts_tuple); #else nparts = PyTuple_Size(parts_tuple); if (nparts < 0) return NULL; #endif for (i=1; i < nparts && module; i++) { PyObject *part, *submodule; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS part = PyTuple_GET_ITEM(parts_tuple, i); #else part = __Pyx_PySequence_ITEM(parts_tuple, i); if (!part) return NULL; #endif submodule = __Pyx_PyObject_GetAttrStrNoError(module, part); #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) Py_DECREF(part); #endif Py_DECREF(module); module = submodule; } if (unlikely(!module)) { return __Pyx__ImportDottedModule_Error(name, parts_tuple, i); } return module; } static PyObject *__Pyx__ImportDottedModule(PyObject *name, PyObject *parts_tuple) { PyObject *imported_module; PyObject *module = __Pyx_Import(name, NULL, 0); if (!parts_tuple || unlikely(!module)) return module; imported_module = __Pyx__ImportDottedModule_Lookup(name); if (likely(imported_module)) { Py_DECREF(module); return imported_module; } PyErr_Clear(); return __Pyx_ImportDottedModule_WalkParts(module, name, parts_tuple); } static PyObject *__Pyx_ImportDottedModule(PyObject *name, PyObject *parts_tuple) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *module = __Pyx__ImportDottedModule_Lookup(name); if (likely(module)) { PyObject *spec = __Pyx_PyObject_GetAttrStrNoError(module, __pyx_mstate_global->__pyx_n_u_spec); if (likely(spec)) { PyObject *unsafe = __Pyx_PyObject_GetAttrStrNoError(spec, __pyx_mstate_global->__pyx_n_u_initializing); if (likely(!unsafe || !__Pyx_PyObject_IsTrue(unsafe))) { Py_DECREF(spec); spec = NULL; } Py_XDECREF(unsafe); } if (likely(!spec)) { PyErr_Clear(); return module; } Py_DECREF(spec); Py_DECREF(module); } else if (PyErr_Occurred()) { PyErr_Clear(); } #endif return __Pyx__ImportDottedModule(name, parts_tuple); } /* GetItemInt */ static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (unlikely(!j)) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS && !CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { return __Pyx_PyList_GetItemRef(o, n); } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; if (mm && mm->mp_subscript) { PyObject *r, *key = PyLong_FromSsize_t(i); if (unlikely(!key)) return NULL; r = mm->mp_subscript(o, key); Py_DECREF(key); return r; } if (likely(sm && sm->sq_item)) { if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { Py_ssize_t l = sm->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) return NULL; PyErr_Clear(); } } return sm->sq_item(o, i); } } #else if (is_list || !PyMapping_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); } /* ObjectGetItem */ #if CYTHON_USE_TYPE_SLOTS static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject *index) { PyObject *runerr = NULL; Py_ssize_t key_value; key_value = __Pyx_PyIndex_AsSsize_t(index); if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); } if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { __Pyx_TypeName index_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(index)); PyErr_Clear(); PyErr_Format(PyExc_IndexError, "cannot fit '" __Pyx_FMT_TYPENAME "' into an index-sized integer", index_type_name); __Pyx_DECREF_TypeName(index_type_name); } return NULL; } static PyObject *__Pyx_PyObject_GetItem_Slow(PyObject *obj, PyObject *key) { __Pyx_TypeName obj_type_name; if (likely(PyType_Check(obj))) { PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(obj, __pyx_mstate_global->__pyx_n_u_class_getitem); if (!meth) { PyErr_Clear(); } else { PyObject *result = __Pyx_PyObject_CallOneArg(meth, key); Py_DECREF(meth); return result; } } obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); PyErr_Format(PyExc_TypeError, "'" __Pyx_FMT_TYPENAME "' object is not subscriptable", obj_type_name); __Pyx_DECREF_TypeName(obj_type_name); return NULL; } static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key) { PyTypeObject *tp = Py_TYPE(obj); PyMappingMethods *mm = tp->tp_as_mapping; PySequenceMethods *sm = tp->tp_as_sequence; if (likely(mm && mm->mp_subscript)) { return mm->mp_subscript(obj, key); } if (likely(sm && sm->sq_item)) { return __Pyx_PyObject_GetIndex(obj, key); } return __Pyx_PyObject_GetItem_Slow(obj, key); } #endif /* CLineInTraceback */ #if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif CYTHON_MAYBE_UNUSED_VAR(tstate); if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { return c_line; } __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_mstate_global->__pyx_cython_runtime); if (likely(cython_runtime_dict)) { __Pyx_BEGIN_CRITICAL_SECTION(*cython_runtime_dict); __PYX_PY_DICT_LOOKUP_IF_MODIFIED( use_cline, *cython_runtime_dict, __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback)) Py_XINCREF(use_cline); __Pyx_END_CRITICAL_SECTION(); } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_cython_runtime, __pyx_mstate_global->__pyx_n_u_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_INCREF(use_cline); Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; (void) PyObject_SetAttr(__pyx_mstate_global->__pyx_cython_runtime, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False); } else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } Py_XDECREF(use_cline); __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { __Pyx_CachedCodeObjectType* code_object; int pos; if (unlikely(!code_line) || unlikely(!code_cache->entries)) { return NULL; } pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { return NULL; } code_object = code_cache->entries[pos].code_object; Py_INCREF(code_object); return code_object; } static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS (void)__pyx__find_code_object; return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. #else struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); if (old_count < 0) { __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); return NULL; } #endif __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); #endif return result; #endif } static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { code_cache->entries = entries; code_cache->max_count = 64; code_cache->count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_INCREF(code_object); Py_DECREF(tmp); return; } if (code_cache->count == code_cache->max_count) { int new_max = code_cache->max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } code_cache->entries = entries; code_cache->max_count = new_max; } for (i=code_cache->count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; code_cache->count++; Py_INCREF(code_object); } static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS (void)__pyx__insert_code_object; return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. #else struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING __pyx_nonatomic_int_type expected = 0; if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { return; } #endif __pyx__insert_code_object(code_cache, code_line, code_object); #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); #endif #endif } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" #if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) #ifndef Py_BUILD_CORE #define Py_BUILD_CORE 1 #endif #include "internal/pycore_frame.h" #endif #if CYTHON_COMPILING_IN_LIMITED_API static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, PyObject *firstlineno, PyObject *name) { PyObject *replace = NULL; if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; replace = PyObject_GetAttrString(code, "replace"); if (likely(replace)) { PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); Py_DECREF(replace); return result; } PyErr_Clear(); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; PyObject *replace = NULL, *getframe = NULL, *frame = NULL; PyObject *exc_type, *exc_value, *exc_traceback; int success = 0; if (c_line) { (void) __pyx_cfilenm; (void) __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); } PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); code_object = __pyx_find_code_object(c_line ? -c_line : py_line); if (!code_object) { code_object = Py_CompileString("_getframe()", filename, Py_eval_input); if (unlikely(!code_object)) goto bad; py_py_line = PyLong_FromLong(py_line); if (unlikely(!py_py_line)) goto bad; py_funcname = PyUnicode_FromString(funcname); if (unlikely(!py_funcname)) goto bad; dict = PyDict_New(); if (unlikely(!dict)) goto bad; { PyObject *old_code_object = code_object; code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); Py_DECREF(old_code_object); } if (unlikely(!code_object)) goto bad; __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); } else { dict = PyDict_New(); } getframe = PySys_GetObject("_getframe"); if (unlikely(!getframe)) goto bad; if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; frame = PyEval_EvalCode(code_object, dict, dict); if (unlikely(!frame) || frame == Py_None) goto bad; success = 1; bad: PyErr_Restore(exc_type, exc_value, exc_traceback); Py_XDECREF(code_object); Py_XDECREF(py_py_line); Py_XDECREF(py_funcname); Py_XDECREF(dict); Py_XDECREF(replace); if (success) { PyTraceBack_Here( (struct _frame*)frame); } Py_XDECREF(frame); } #else static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = NULL; PyObject *py_funcname = NULL; if (c_line) { py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); if (!py_funcname) goto bad; funcname = PyUnicode_AsUTF8(py_funcname); if (!funcname) goto bad; } py_code = PyCode_NewEmpty(filename, funcname, py_line); Py_XDECREF(py_funcname); return py_code; bad: Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject *ptype, *pvalue, *ptraceback; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } py_code = __pyx_find_code_object(c_line ? -c_line : py_line); if (!py_code) { __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) { /* If the code object creation fails, then we should clear the fetched exception references and propagate the new exception */ Py_XDECREF(ptype); Py_XDECREF(pvalue); Py_XDECREF(ptraceback); goto bad; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); } py_frame = PyFrame_New( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #endif /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const int neg_one = (int) -1, const_zero = (int) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (unlikely(!PyLong_Check(x))) { int val; PyObject *tmp = __Pyx_PyNumber_Long(x); if (!tmp) return (int) -1; val = __Pyx_PyLong_As_int(tmp); Py_DECREF(tmp); return val; } if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS if (unlikely(__Pyx_PyLong_IsNeg(x))) { goto raise_neg_overflow; } else if (__Pyx_PyLong_IsCompact(x)) { __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) } else { const digit* digits = __Pyx_PyLong_Digits(x); assert(__Pyx_PyLong_DigitCount(x) > 1); switch (__Pyx_PyLong_DigitCount(x)) { case 2: if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } } #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if ((sizeof(int) <= sizeof(unsigned long))) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS if (__Pyx_PyLong_IsCompact(x)) { __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) } else { const digit* digits = __Pyx_PyLong_Digits(x); assert(__Pyx_PyLong_DigitCount(x) > 1); switch (__Pyx_PyLong_SignedDigitCount(x)) { case -2: if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } } #endif if ((sizeof(int) <= sizeof(long))) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { int val; int ret = -1; #if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API Py_ssize_t bytes_copied = PyLong_AsNativeBytes( x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); if (unlikely(bytes_copied == -1)) { } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { goto raise_overflow; } else { ret = 0; } #elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; ret = _PyLong_AsByteArray((PyLongObject *)x, bytes, sizeof(val), is_little, !is_unsigned); #else PyObject *v; PyObject *stepval = NULL, *mask = NULL, *shift = NULL; int bits, remaining_bits, is_negative = 0; int chunk_size = (sizeof(long) < 8) ? 30 : 62; if (likely(PyLong_CheckExact(x))) { v = __Pyx_NewRef(x); } else { v = PyNumber_Long(x); if (unlikely(!v)) return (int) -1; assert(PyLong_CheckExact(v)); } { int result = PyObject_RichCompareBool(v, Py_False, Py_LT); if (unlikely(result < 0)) { Py_DECREF(v); return (int) -1; } is_negative = result == 1; } if (is_unsigned && unlikely(is_negative)) { Py_DECREF(v); goto raise_neg_overflow; } else if (is_negative) { stepval = PyNumber_Invert(v); Py_DECREF(v); if (unlikely(!stepval)) return (int) -1; } else { stepval = v; } v = NULL; val = (int) 0; mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { PyObject *tmp, *digit; long idigit; digit = PyNumber_And(stepval, mask); if (unlikely(!digit)) goto done; idigit = PyLong_AsLong(digit); Py_DECREF(digit); if (unlikely(idigit < 0)) goto done; val |= ((int) idigit) << bits; tmp = PyNumber_Rshift(stepval, shift); if (unlikely(!tmp)) goto done; Py_DECREF(stepval); stepval = tmp; } Py_DECREF(shift); shift = NULL; Py_DECREF(mask); mask = NULL; { long idigit = PyLong_AsLong(stepval); if (unlikely(idigit < 0)) goto done; remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); if (unlikely(idigit >= (1L << remaining_bits))) goto raise_overflow; val |= ((int) idigit) << bits; } if (!is_unsigned) { if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) goto raise_overflow; if (is_negative) val = ~val; } ret = 0; done: Py_XDECREF(shift); Py_XDECREF(mask); Py_XDECREF(stepval); #endif if (unlikely(ret)) return (int) -1; return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* PyObjectVectorCallKwBuilder */ #if CYTHON_VECTORCALL static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { (void)__Pyx_PyObject_FastCallDict; if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; Py_INCREF(key); args[n] = value; return 0; } CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { (void)__Pyx_VectorcallBuilder_AddArgStr; if (unlikely(!PyUnicode_Check(key))) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); return -1; } return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); } static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { PyObject *pyKey = PyUnicode_FromString(key); if (!pyKey) return -1; return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); } #else // CYTHON_VECTORCALL CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { if (unlikely(!PyUnicode_Check(key))) { PyErr_SetString(PyExc_TypeError, "keywords must be strings"); return -1; } return PyDict_SetItem(builder, key, value); } #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const int neg_one = (int) -1, const_zero = (int) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyLong_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyLong_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { unsigned char *bytes = (unsigned char *)&value; #if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 if (is_unsigned) { return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); } else { return PyLong_FromNativeBytes(bytes, sizeof(value), -1); } #elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 int one = 1; int little = (int)*(unsigned char *)&one; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); #else int one = 1; int little = (int)*(unsigned char *)&one; PyObject *from_bytes, *result = NULL, *kwds = NULL; PyObject *py_bytes = NULL, *order_str = NULL; from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); if (!from_bytes) return NULL; py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); if (!py_bytes) goto limited_bad; order_str = PyUnicode_FromString(little ? "little" : "big"); if (!order_str) goto limited_bad; { PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; if (!is_unsigned) { kwds = __Pyx_MakeVectorcallBuilderKwds(1); if (!kwds) goto limited_bad; if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; } result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); } limited_bad: Py_XDECREF(kwds); Py_XDECREF(order_str); Py_XDECREF(py_bytes); Py_XDECREF(from_bytes); return result; #endif } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_unsigned_short(unsigned short value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const unsigned short neg_one = (unsigned short) -1, const_zero = (unsigned short) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(unsigned short) < sizeof(long)) { return PyLong_FromLong((long) value); } else if (sizeof(unsigned short) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY } else if (sizeof(unsigned short) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(unsigned short) <= sizeof(long)) { return PyLong_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned short) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { unsigned char *bytes = (unsigned char *)&value; #if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 if (is_unsigned) { return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); } else { return PyLong_FromNativeBytes(bytes, sizeof(value), -1); } #elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 int one = 1; int little = (int)*(unsigned char *)&one; return _PyLong_FromByteArray(bytes, sizeof(unsigned short), little, !is_unsigned); #else int one = 1; int little = (int)*(unsigned char *)&one; PyObject *from_bytes, *result = NULL, *kwds = NULL; PyObject *py_bytes = NULL, *order_str = NULL; from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); if (!from_bytes) return NULL; py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(unsigned short)); if (!py_bytes) goto limited_bad; order_str = PyUnicode_FromString(little ? "little" : "big"); if (!order_str) goto limited_bad; { PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; if (!is_unsigned) { kwds = __Pyx_MakeVectorcallBuilderKwds(1); if (!kwds) goto limited_bad; if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; } result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); } limited_bad: Py_XDECREF(kwds); Py_XDECREF(order_str); Py_XDECREF(py_bytes); Py_XDECREF(from_bytes); return result; #endif } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_hid_bus_type(hid_bus_type value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const hid_bus_type neg_one = (hid_bus_type) -1, const_zero = (hid_bus_type) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(hid_bus_type) < sizeof(long)) { return PyLong_FromLong((long) value); } else if (sizeof(hid_bus_type) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY } else if (sizeof(hid_bus_type) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(hid_bus_type) <= sizeof(long)) { return PyLong_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(hid_bus_type) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { unsigned char *bytes = (unsigned char *)&value; #if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 if (is_unsigned) { return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); } else { return PyLong_FromNativeBytes(bytes, sizeof(value), -1); } #elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 int one = 1; int little = (int)*(unsigned char *)&one; return _PyLong_FromByteArray(bytes, sizeof(hid_bus_type), little, !is_unsigned); #else int one = 1; int little = (int)*(unsigned char *)&one; PyObject *from_bytes, *result = NULL, *kwds = NULL; PyObject *py_bytes = NULL, *order_str = NULL; from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); if (!from_bytes) return NULL; py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(hid_bus_type)); if (!py_bytes) goto limited_bad; order_str = PyUnicode_FromString(little ? "little" : "big"); if (!order_str) goto limited_bad; { PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; if (!is_unsigned) { kwds = __Pyx_MakeVectorcallBuilderKwds(1); if (!kwds) goto limited_bad; if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; } result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); } limited_bad: Py_XDECREF(kwds); Py_XDECREF(order_str); Py_XDECREF(py_bytes); Py_XDECREF(from_bytes); return result; #endif } } /* CIntFromPy */ static CYTHON_INLINE unsigned char __Pyx_PyLong_As_unsigned_char(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const unsigned char neg_one = (unsigned char) -1, const_zero = (unsigned char) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (unlikely(!PyLong_Check(x))) { unsigned char val; PyObject *tmp = __Pyx_PyNumber_Long(x); if (!tmp) return (unsigned char) -1; val = __Pyx_PyLong_As_unsigned_char(tmp); Py_DECREF(tmp); return val; } if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS if (unlikely(__Pyx_PyLong_IsNeg(x))) { goto raise_neg_overflow; } else if (__Pyx_PyLong_IsCompact(x)) { __PYX_VERIFY_RETURN_INT(unsigned char, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) } else { const digit* digits = __Pyx_PyLong_Digits(x); assert(__Pyx_PyLong_DigitCount(x) > 1); switch (__Pyx_PyLong_DigitCount(x)) { case 2: if ((8 * sizeof(unsigned char) > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) >= 2 * PyLong_SHIFT)) { return (unsigned char) (((((unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0])); } } break; case 3: if ((8 * sizeof(unsigned char) > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) >= 3 * PyLong_SHIFT)) { return (unsigned char) (((((((unsigned char)digits[2]) << PyLong_SHIFT) | (unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0])); } } break; case 4: if ((8 * sizeof(unsigned char) > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) >= 4 * PyLong_SHIFT)) { return (unsigned char) (((((((((unsigned char)digits[3]) << PyLong_SHIFT) | (unsigned char)digits[2]) << PyLong_SHIFT) | (unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0])); } } break; } } #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (unsigned char) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if ((sizeof(unsigned char) <= sizeof(unsigned long))) { __PYX_VERIFY_RETURN_INT_EXC(unsigned char, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if ((sizeof(unsigned char) <= sizeof(unsigned PY_LONG_LONG))) { __PYX_VERIFY_RETURN_INT_EXC(unsigned char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS if (__Pyx_PyLong_IsCompact(x)) { __PYX_VERIFY_RETURN_INT(unsigned char, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) } else { const digit* digits = __Pyx_PyLong_Digits(x); assert(__Pyx_PyLong_DigitCount(x) > 1); switch (__Pyx_PyLong_SignedDigitCount(x)) { case -2: if ((8 * sizeof(unsigned char) - 1 > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) - 1 > 2 * PyLong_SHIFT)) { return (unsigned char) (((unsigned char)-1)*(((((unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0]))); } } break; case 2: if ((8 * sizeof(unsigned char) > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) - 1 > 2 * PyLong_SHIFT)) { return (unsigned char) ((((((unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0]))); } } break; case -3: if ((8 * sizeof(unsigned char) - 1 > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) - 1 > 3 * PyLong_SHIFT)) { return (unsigned char) (((unsigned char)-1)*(((((((unsigned char)digits[2]) << PyLong_SHIFT) | (unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0]))); } } break; case 3: if ((8 * sizeof(unsigned char) > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) - 1 > 3 * PyLong_SHIFT)) { return (unsigned char) ((((((((unsigned char)digits[2]) << PyLong_SHIFT) | (unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0]))); } } break; case -4: if ((8 * sizeof(unsigned char) - 1 > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) - 1 > 4 * PyLong_SHIFT)) { return (unsigned char) (((unsigned char)-1)*(((((((((unsigned char)digits[3]) << PyLong_SHIFT) | (unsigned char)digits[2]) << PyLong_SHIFT) | (unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0]))); } } break; case 4: if ((8 * sizeof(unsigned char) > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(unsigned char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(unsigned char) - 1 > 4 * PyLong_SHIFT)) { return (unsigned char) ((((((((((unsigned char)digits[3]) << PyLong_SHIFT) | (unsigned char)digits[2]) << PyLong_SHIFT) | (unsigned char)digits[1]) << PyLong_SHIFT) | (unsigned char)digits[0]))); } } break; } } #endif if ((sizeof(unsigned char) <= sizeof(long))) { __PYX_VERIFY_RETURN_INT_EXC(unsigned char, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if ((sizeof(unsigned char) <= sizeof(PY_LONG_LONG))) { __PYX_VERIFY_RETURN_INT_EXC(unsigned char, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { unsigned char val; int ret = -1; #if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API Py_ssize_t bytes_copied = PyLong_AsNativeBytes( x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); if (unlikely(bytes_copied == -1)) { } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { goto raise_overflow; } else { ret = 0; } #elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; ret = _PyLong_AsByteArray((PyLongObject *)x, bytes, sizeof(val), is_little, !is_unsigned); #else PyObject *v; PyObject *stepval = NULL, *mask = NULL, *shift = NULL; int bits, remaining_bits, is_negative = 0; int chunk_size = (sizeof(long) < 8) ? 30 : 62; if (likely(PyLong_CheckExact(x))) { v = __Pyx_NewRef(x); } else { v = PyNumber_Long(x); if (unlikely(!v)) return (unsigned char) -1; assert(PyLong_CheckExact(v)); } { int result = PyObject_RichCompareBool(v, Py_False, Py_LT); if (unlikely(result < 0)) { Py_DECREF(v); return (unsigned char) -1; } is_negative = result == 1; } if (is_unsigned && unlikely(is_negative)) { Py_DECREF(v); goto raise_neg_overflow; } else if (is_negative) { stepval = PyNumber_Invert(v); Py_DECREF(v); if (unlikely(!stepval)) return (unsigned char) -1; } else { stepval = v; } v = NULL; val = (unsigned char) 0; mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; for (bits = 0; bits < (int) sizeof(unsigned char) * 8 - chunk_size; bits += chunk_size) { PyObject *tmp, *digit; long idigit; digit = PyNumber_And(stepval, mask); if (unlikely(!digit)) goto done; idigit = PyLong_AsLong(digit); Py_DECREF(digit); if (unlikely(idigit < 0)) goto done; val |= ((unsigned char) idigit) << bits; tmp = PyNumber_Rshift(stepval, shift); if (unlikely(!tmp)) goto done; Py_DECREF(stepval); stepval = tmp; } Py_DECREF(shift); shift = NULL; Py_DECREF(mask); mask = NULL; { long idigit = PyLong_AsLong(stepval); if (unlikely(idigit < 0)) goto done; remaining_bits = ((int) sizeof(unsigned char) * 8) - bits - (is_unsigned ? 0 : 1); if (unlikely(idigit >= (1L << remaining_bits))) goto raise_overflow; val |= ((unsigned char) idigit) << bits; } if (!is_unsigned) { if (unlikely(val & (((unsigned char) 1) << (sizeof(unsigned char) * 8 - 1)))) goto raise_overflow; if (is_negative) val = ~val; } ret = 0; done: Py_XDECREF(shift); Py_XDECREF(mask); Py_XDECREF(stepval); #endif if (unlikely(ret)) return (unsigned char) -1; return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned char"); return (unsigned char) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned char"); return (unsigned char) -1; } /* FormatTypeName */ #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) { PyObject *module = NULL, *name = NULL, *result = NULL; #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, __pyx_mstate_global->__pyx_n_u_qualname); #else name = PyType_GetQualName(tp); #endif if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, __pyx_mstate_global->__pyx_n_u_module); if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { result = name; name = NULL; goto done; } result = PyUnicode_FromFormat("%U.%U", module, name); if (unlikely(result == NULL)) goto bad; done: Py_XDECREF(name); Py_XDECREF(module); return result; bad: PyErr_Clear(); if (name) { result = name; name = NULL; } else { result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__2); } goto done; } #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const long neg_one = (long) -1, const_zero = (long) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyLong_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyLong_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { unsigned char *bytes = (unsigned char *)&value; #if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 if (is_unsigned) { return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); } else { return PyLong_FromNativeBytes(bytes, sizeof(value), -1); } #elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 int one = 1; int little = (int)*(unsigned char *)&one; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); #else int one = 1; int little = (int)*(unsigned char *)&one; PyObject *from_bytes, *result = NULL, *kwds = NULL; PyObject *py_bytes = NULL, *order_str = NULL; from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); if (!from_bytes) return NULL; py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); if (!py_bytes) goto limited_bad; order_str = PyUnicode_FromString(little ? "little" : "big"); if (!order_str) goto limited_bad; { PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; if (!is_unsigned) { kwds = __Pyx_MakeVectorcallBuilderKwds(1); if (!kwds) goto limited_bad; if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; } result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); } limited_bad: Py_XDECREF(kwds); Py_XDECREF(order_str); Py_XDECREF(py_bytes); Py_XDECREF(from_bytes); return result; #endif } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const long neg_one = (long) -1, const_zero = (long) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (unlikely(!PyLong_Check(x))) { long val; PyObject *tmp = __Pyx_PyNumber_Long(x); if (!tmp) return (long) -1; val = __Pyx_PyLong_As_long(tmp); Py_DECREF(tmp); return val; } if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS if (unlikely(__Pyx_PyLong_IsNeg(x))) { goto raise_neg_overflow; } else if (__Pyx_PyLong_IsCompact(x)) { __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) } else { const digit* digits = __Pyx_PyLong_Digits(x); assert(__Pyx_PyLong_DigitCount(x) > 1); switch (__Pyx_PyLong_DigitCount(x)) { case 2: if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } } #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if ((sizeof(long) <= sizeof(unsigned long))) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS if (__Pyx_PyLong_IsCompact(x)) { __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) } else { const digit* digits = __Pyx_PyLong_Digits(x); assert(__Pyx_PyLong_DigitCount(x) > 1); switch (__Pyx_PyLong_SignedDigitCount(x)) { case -2: if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } } #endif if ((sizeof(long) <= sizeof(long))) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { long val; int ret = -1; #if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API Py_ssize_t bytes_copied = PyLong_AsNativeBytes( x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); if (unlikely(bytes_copied == -1)) { } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { goto raise_overflow; } else { ret = 0; } #elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; ret = _PyLong_AsByteArray((PyLongObject *)x, bytes, sizeof(val), is_little, !is_unsigned); #else PyObject *v; PyObject *stepval = NULL, *mask = NULL, *shift = NULL; int bits, remaining_bits, is_negative = 0; int chunk_size = (sizeof(long) < 8) ? 30 : 62; if (likely(PyLong_CheckExact(x))) { v = __Pyx_NewRef(x); } else { v = PyNumber_Long(x); if (unlikely(!v)) return (long) -1; assert(PyLong_CheckExact(v)); } { int result = PyObject_RichCompareBool(v, Py_False, Py_LT); if (unlikely(result < 0)) { Py_DECREF(v); return (long) -1; } is_negative = result == 1; } if (is_unsigned && unlikely(is_negative)) { Py_DECREF(v); goto raise_neg_overflow; } else if (is_negative) { stepval = PyNumber_Invert(v); Py_DECREF(v); if (unlikely(!stepval)) return (long) -1; } else { stepval = v; } v = NULL; val = (long) 0; mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { PyObject *tmp, *digit; long idigit; digit = PyNumber_And(stepval, mask); if (unlikely(!digit)) goto done; idigit = PyLong_AsLong(digit); Py_DECREF(digit); if (unlikely(idigit < 0)) goto done; val |= ((long) idigit) << bits; tmp = PyNumber_Rshift(stepval, shift); if (unlikely(!tmp)) goto done; Py_DECREF(stepval); stepval = tmp; } Py_DECREF(shift); shift = NULL; Py_DECREF(mask); mask = NULL; { long idigit = PyLong_AsLong(stepval); if (unlikely(idigit < 0)) goto done; remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); if (unlikely(idigit >= (1L << remaining_bits))) goto raise_overflow; val |= ((long) idigit) << bits; } if (!is_unsigned) { if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) goto raise_overflow; if (is_negative) val = ~val; } ret = 0; done: Py_XDECREF(shift); Py_XDECREF(mask); Py_XDECREF(stepval); #endif if (unlikely(ret)) return (long) -1; return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (cls == a || cls == b) return 1; mro = cls->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { PyObject *base = PyTuple_GET_ITEM(mro, i); if (base == (PyObject *)a || base == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); } static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { if (exc_type1) { return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); } else { return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } } static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; assert(PyExceptionClass_Check(exc_type)); n = PyTuple_GET_SIZE(tuple); for (i=0; i= 0x030b0000 return Py_Version & ~0xFFUL; #else static unsigned long __Pyx_cached_runtime_version = 0; if (__Pyx_cached_runtime_version == 0) { const char* rt_version = Py_GetVersion(); unsigned long version = 0; unsigned long factor = 0x01000000UL; unsigned int digit = 0; int i = 0; while (factor) { while ('0' <= rt_version[i] && rt_version[i] <= '9') { digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); ++i; } version += factor * digit; if (rt_version[i] != '.') break; digit = 0; factor >>= 8; ++i; } __Pyx_cached_runtime_version = version; } return __Pyx_cached_runtime_version; #endif } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { const unsigned long MAJOR_MINOR = 0xFFFF0000UL; if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) return 0; if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) return 1; { char message[200]; PyOS_snprintf(message, sizeof(message), "compile time Python version %d.%d " "of module '%.100s' " "%s " "runtime version %d.%d", (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), __Pyx_MODULE_NAME, (allow_newer) ? "was newer than" : "does not match", (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) ); return PyErr_WarnEx(NULL, message, 1); } } /* NewCodeObj */ #if CYTHON_COMPILING_IN_LIMITED_API static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, PyObject *code, PyObject *c, PyObject* n, PyObject *v, PyObject *fv, PyObject *cell, PyObject* fn, PyObject *name, int fline, PyObject *lnos) { PyObject *exception_table = NULL; PyObject *types_module=NULL, *code_type=NULL, *result=NULL; #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 PyObject *version_info; PyObject *py_minor_version = NULL; #endif long minor_version = 0; PyObject *type, *value, *traceback; PyErr_Fetch(&type, &value, &traceback); #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 minor_version = 11; #else if (!(version_info = PySys_GetObject("version_info"))) goto end; if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; minor_version = PyLong_AsLong(py_minor_version); Py_DECREF(py_minor_version); if (minor_version == -1 && PyErr_Occurred()) goto end; #endif if (!(types_module = PyImport_ImportModule("types"))) goto end; if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; if (minor_version <= 7) { (void)p; result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, c, n, v, fn, name, fline, lnos, fv, cell); } else if (minor_version <= 10) { result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, c, n, v, fn, name, fline, lnos, fv, cell); } else { if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); } end: Py_XDECREF(code_type); Py_XDECREF(exception_table); Py_XDECREF(types_module); if (type) { PyErr_Restore(type, value, traceback); } return result; } #elif PY_VERSION_HEX >= 0x030B0000 static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, PyObject *code, PyObject *c, PyObject* n, PyObject *v, PyObject *fv, PyObject *cell, PyObject* fn, PyObject *name, int fline, PyObject *lnos) { PyCodeObject *result; result = #if PY_VERSION_HEX >= 0x030C0000 PyUnstable_Code_NewWithPosOnlyArgs #else PyCode_NewWithPosOnlyArgs #endif (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030c00A1 if (likely(result)) result->_co_firsttraceable = 0; #endif return result; } #elif PY_VERSION_HEX >= 0x030800B2 && !CYTHON_COMPILING_IN_PYPY #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif static PyObject* __Pyx_PyCode_New( const __Pyx_PyCode_New_function_description descr, PyObject * const *varnames, PyObject *filename, PyObject *funcname, const char *line_table, PyObject *tuple_dedup_map ) { PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL, *line_table_bytes = NULL; Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; PyObject *varnames_tuple = PyTuple_New(var_count); if (unlikely(!varnames_tuple)) return NULL; for (Py_ssize_t i=0; i < var_count; i++) { Py_INCREF(varnames[i]); if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; } #if CYTHON_COMPILING_IN_LIMITED_API varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); if (!varnames_tuple_dedup) { if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; varnames_tuple_dedup = varnames_tuple; } #else varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); if (unlikely(!varnames_tuple_dedup)) goto done; #endif #if CYTHON_AVOID_BORROWED_REFS Py_INCREF(varnames_tuple_dedup); #endif if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL && !CYTHON_COMPILING_IN_GRAAL) { line_table_bytes = PyBytes_FromStringAndSize(line_table, descr.line_table_length); if (unlikely(!line_table_bytes)) goto done; Py_ssize_t code_len = (descr.line_table_length * 2 + 4) & ~3; code_bytes = PyBytes_FromStringAndSize(NULL, code_len); if (unlikely(!code_bytes)) goto done; char* c_code_bytes = PyBytes_AsString(code_bytes); if (unlikely(!c_code_bytes)) goto done; memset(c_code_bytes, 0, (size_t) code_len); } code_obj = (PyObject*) __Pyx__PyCode_New( (int) descr.argcount, (int) descr.num_posonly_args, (int) descr.num_kwonly_args, (int) descr.nlocals, 0, (int) descr.flags, code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, __pyx_mstate_global->__pyx_empty_tuple, __pyx_mstate_global->__pyx_empty_tuple, varnames_tuple_dedup, __pyx_mstate_global->__pyx_empty_tuple, __pyx_mstate_global->__pyx_empty_tuple, filename, funcname, (int) descr.first_line, (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table_bytes) ? line_table_bytes : __pyx_mstate_global->__pyx_empty_bytes ); done: Py_XDECREF(code_bytes); Py_XDECREF(line_table_bytes); #if CYTHON_AVOID_BORROWED_REFS Py_XDECREF(varnames_tuple_dedup); #endif Py_DECREF(varnames_tuple); return code_obj; } /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry const *t, PyObject **target, const char* const* encoding_names) { while (t->s) { PyObject *str; if (t->is_unicode) { if (t->intern) { str = PyUnicode_InternFromString(t->s); } else if (t->encoding) { str = PyUnicode_Decode(t->s, t->n - 1, encoding_names[t->encoding], NULL); } else { str = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { str = PyBytes_FromStringAndSize(t->s, t->n - 1); } if (!str) return -1; *target = str; if (PyObject_Hash(str) == -1) return -1; ++t; ++target; } return 0; } #include static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { size_t len = strlen(s); if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { PyErr_SetString(PyExc_OverflowError, "byte string is too long"); return -1; } return (Py_ssize_t) len; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { Py_ssize_t len = __Pyx_ssize_strlen(c_str); if (unlikely(len < 0)) return NULL; return __Pyx_PyUnicode_FromStringAndSize(c_str, len); } static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { Py_ssize_t len = __Pyx_ssize_strlen(c_str); if (unlikely(len < 0)) return NULL; return PyByteArray_FromStringAndSize(c_str, len); } static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if CYTHON_COMPILING_IN_LIMITED_API { const char* result; Py_ssize_t unicode_length; CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; #else result = PyUnicode_AsUTF8AndSize(o, length); #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII unicode_length = PyUnicode_GetLength(o); if (unlikely(unicode_length < 0)) return NULL; if (unlikely(unicode_length != *length)) { PyUnicode_AsASCIIString(o); return NULL; } #endif return result; } #else #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(PyUnicode_IS_ASCII(o))) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 if (PyUnicode_Check(o)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif if (PyByteArray_Check(o)) { #if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); #else *length = PyByteArray_Size(o); if (*length == -1) return NULL; return PyByteArray_AsString(o); #endif } else { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; retval = __Pyx_PyObject_IsTrue(x); Py_DECREF(x); return retval; } static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " "The ability to return an instance of a strict subclass of int is deprecated, " "and may be removed in a future version of Python.", result_type_name)) { __Pyx_DECREF_TypeName(result_type_name); Py_DECREF(result); return NULL; } __Pyx_DECREF_TypeName(result_type_name); return result; } PyErr_Format(PyExc_TypeError, "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", result_type_name); __Pyx_DECREF_TypeName(result_type_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif PyObject *res = NULL; if (likely(PyLong_Check(x))) return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; if (likely(m && m->nb_int)) { res = m->nb_int(x); } #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Long(x); } #endif if (likely(res)) { if (unlikely(!PyLong_CheckExact(res))) { return __Pyx_PyNumber_LongWrongResultType(res); } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS if (likely(__Pyx_PyLong_IsCompact(b))) { return __Pyx_PyLong_CompactValue(b); } else { const digit* digits = __Pyx_PyLong_Digits(b); const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyLong_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); } else { Py_ssize_t ival; PyObject *x; x = PyNumber_Index(o); if (!x) return -1; ival = PyLong_AsLong(x); Py_DECREF(x); return ival; } } static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { CYTHON_UNUSED_VAR(b); return __Pyx_NewRef(Py_None); } static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); } static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { return PyLong_FromSize_t(ival); } /* MultiPhaseInitModuleState */ #if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE #ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE #if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 #else #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 #endif #endif #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS #error "Module state with PEP489 requires atomics. Currently that's one of\ C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" #endif #if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE #define __Pyx_ModuleStateLookup_Lock() #define __Pyx_ModuleStateLookup_Unlock() #elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; #define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) #define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) #elif defined(__cplusplus) && __cplusplus >= 201103L #include static std::mutex __Pyx_ModuleStateLookup_mutex; #define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() #define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) #include static mtx_t __Pyx_ModuleStateLookup_mutex; static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; static void __Pyx_ModuleStateLookup_initialize_mutex(void) { mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); } #define __Pyx_ModuleStateLookup_Lock()\ call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ mtx_lock(&__Pyx_ModuleStateLookup_mutex) #define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) #elif defined(HAVE_PTHREAD_H) #include static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; #define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) #define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) #elif defined(_WIN32) #include // synchapi.h on its own doesn't work static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; #define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) #define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) #else #error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ Requires C standard >= C11, or C++ standard >= C++11,\ or pthreads, or the Windows 32 API, or Python >= 3.13." #endif typedef struct { int64_t id; PyObject *module; } __Pyx_InterpreterIdAndModule; typedef struct { char interpreter_id_as_index; Py_ssize_t count; Py_ssize_t allocated; __Pyx_InterpreterIdAndModule table[1]; } __Pyx_ModuleStateLookupData; #define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; #endif #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; #else static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; #endif static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( __Pyx_InterpreterIdAndModule* table, Py_ssize_t count, int64_t interpreterId) { __Pyx_InterpreterIdAndModule* begin = table; __Pyx_InterpreterIdAndModule* end = begin + count; if (begin->id == interpreterId) { return begin; } while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; if (halfway->id == interpreterId) { return halfway; } if (halfway->id < interpreterId) { begin = halfway; } else { end = halfway; } } for (; begin < end; ++begin) { if (begin->id >= interpreterId) return begin; } return begin; } static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); if (interpreter_id == -1) return NULL; #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); { __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); if (likely(data)) { __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); if (likely(data == new_data)) { goto read_finished; } } __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); __Pyx_ModuleStateLookup_Lock(); __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); __Pyx_ModuleStateLookup_Unlock(); } read_finished:; #else __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; #endif __Pyx_InterpreterIdAndModule* found = NULL; if (unlikely(!data)) goto end; if (data->interpreter_id_as_index) { if (interpreter_id < data->count) { found = data->table+interpreter_id; } } else { found = __Pyx_State_FindModuleStateLookupTableLowerBound( data->table, data->count, interpreter_id); } end: { PyObject *result=NULL; if (found && found->id == interpreter_id) { result = found->module; } #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); #endif return result; } } #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); } #else #define __Pyx_ModuleStateLookup_wait_until_no_readers() #endif static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { Py_ssize_t to_allocate = (*old_data)->allocated; while (to_allocate <= interpreter_id) { if (to_allocate == 0) to_allocate = 1; else to_allocate *= 2; } __Pyx_ModuleStateLookupData *new_data = *old_data; if (to_allocate != (*old_data)->allocated) { new_data = (__Pyx_ModuleStateLookupData *)realloc( *old_data, sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); if (!new_data) { PyErr_NoMemory(); return -1; } for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { new_data->table[i].id = i; new_data->table[i].module = NULL; } new_data->allocated = to_allocate; } new_data->table[interpreter_id].module = module; if (new_data->count < interpreter_id+1) { new_data->count = interpreter_id+1; } *old_data = new_data; return 0; } static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { __Pyx_InterpreterIdAndModule *read = data->table; __Pyx_InterpreterIdAndModule *write = data->table; __Pyx_InterpreterIdAndModule *end = read + data->count; for (; readmodule) { write->id = read->id; write->module = read->module; ++write; } } data->count = write - data->table; for (; writeid = 0; write->module = NULL; } data->interpreter_id_as_index = 0; } static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); if (interpreter_id == -1) return -1; int result = 0; __Pyx_ModuleStateLookup_Lock(); #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); #else __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; #endif __Pyx_ModuleStateLookupData *new_data = old_data; if (!new_data) { new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); if (!new_data) { result = -1; PyErr_NoMemory(); goto end; } new_data->allocated = 1; new_data->interpreter_id_as_index = 1; } __Pyx_ModuleStateLookup_wait_until_no_readers(); if (new_data->interpreter_id_as_index) { if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); goto end; } __Pyx_State_ConvertFromInterpIdAsIndex(new_data); } { Py_ssize_t insert_at = 0; { __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( new_data->table, new_data->count, interpreter_id); assert(lower_bound); insert_at = lower_bound - new_data->table; if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { lower_bound->module = module; goto end; // already in table, nothing more to do } } if (new_data->count+1 >= new_data->allocated) { Py_ssize_t to_allocate = (new_data->count+1)*2; new_data = (__Pyx_ModuleStateLookupData*)realloc( new_data, sizeof(__Pyx_ModuleStateLookupData) + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); if (!new_data) { result = -1; new_data = old_data; PyErr_NoMemory(); goto end; } new_data->allocated = to_allocate; } ++new_data->count; int64_t last_id = interpreter_id; PyObject *last_module = module; for (Py_ssize_t i=insert_at; icount; ++i) { int64_t current_id = new_data->table[i].id; new_data->table[i].id = last_id; last_id = current_id; PyObject *current_module = new_data->table[i].module; new_data->table[i].module = last_module; last_module = current_module; } } end: #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); #else __Pyx_ModuleStateLookup_data = new_data; #endif __Pyx_ModuleStateLookup_Unlock(); return result; } static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); if (interpreter_id == -1) return -1; __Pyx_ModuleStateLookup_Lock(); #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); #else __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; #endif if (data->interpreter_id_as_index) { if (interpreter_id < data->count) { data->table[interpreter_id].module = NULL; } goto done; } { __Pyx_ModuleStateLookup_wait_until_no_readers(); __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( data->table, data->count, interpreter_id); if (!lower_bound) goto done; if (lower_bound->id != interpreter_id) goto done; __Pyx_InterpreterIdAndModule *end = data->table+data->count; for (;lower_boundid = (lower_bound+1)->id; lower_bound->module = (lower_bound+1)->module; } } --data->count; if (data->count == 0) { free(data); data = NULL; } done: #if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); #else __Pyx_ModuleStateLookup_data = data; #endif __Pyx_ModuleStateLookup_Unlock(); return 0; } #endif /* #### Code section: utility_code_pragmas_end ### */ #ifdef _MSC_VER #pragma warning( pop ) #endif /* #### Code section: end ### */ #endif /* Py_PYTHON_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273139.0 hidapi-0.15.0/hid.pyx0000644000076500000240000003211515115767063013416 0ustar00stickstaffimport sys import weakref from chid cimport * from libc.stddef cimport wchar_t, size_t __version__ = "0.15.0" hid_init() cdef extern from "": int wcslen(wchar_t*) cdef extern from "": void free(void* ptr) void* malloc(size_t size) cdef extern from *: object PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) Py_ssize_t PyUnicode_AsWideChar(object unicode, wchar_t *w, Py_ssize_t size) cdef object U(wchar_t *wcs): if wcs == NULL: return '' cdef int n = wcslen(wcs) return PyUnicode_FromWideChar(wcs, n) def enumerate(int vendor_id=0, int product_id=0): """Return a list of discovered HID devices. The fields of dict are: - 'path' - 'vendor_id' - 'product_id' - 'serial_number' - 'release_number' - 'manufacturer_string' - 'product_string' - 'usage_page' - 'usage' - 'interface_number' :param vendor_id: Vendor id to look for, default = 0 :type vendor_id: int, optional :param product_id: Product id to look for, default = 0 :type product_id: int, optional :return: List of device dictionaries :rtype: List[Dict] """ cdef hid_device_info* info with nogil: info = hid_enumerate(vendor_id, product_id) cdef hid_device_info* c = info res = [] while c: res.append({ 'path': c.path, 'vendor_id': c.vendor_id, 'product_id': c.product_id, 'serial_number': U(c.serial_number), 'release_number': c.release_number, 'manufacturer_string': U(c.manufacturer_string), 'product_string': U(c.product_string), 'usage_page': c.usage_page, 'usage': c.usage, 'interface_number': c.interface_number, 'bus_type': c.bus_type, }) c = c.next hid_free_enumeration(info) return res def version_str(): """Return a runtime version string of the hidapi C library. :return: version string of library :rtype: str """ return (hid_version_str()).decode('ascii') cdef class _closer: """Wrap a hid_device *ptr and a provide a way to call hid_close() on it. Used internally for weakref.finalize, which only accepts Python objects. """ cdef hid_device *_ptr @staticmethod cdef wrap(hid_device *ptr): cdef _closer closer = _closer() closer._ptr = ptr return closer def close(self): hid_close(self._ptr) cdef class device: """Device class. A device instance can be used to read from and write to a HID device. """ cdef hid_device *_c_hid cdef object __weakref__ # enable weak-reference support cdef object _close def open(self, int vendor_id=0, int product_id=0, unicode serial_number=None): """Open the connection. :param vendor_id: Vendor id to connect to, default = 0 :type vendor_id: int, optional :param product_id: Product id to connect to, default = 0 :type product_id: int, optional :param serial_number: :type serial_number: unicode, optional :raises IOError: """ cdef wchar_t * cserial_number = NULL cdef int serial_len cdef Py_ssize_t result if self._c_hid != NULL: raise RuntimeError('already open') try: if serial_number is not None: serial_len = len(serial_number) cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) if cserial_number == NULL: raise MemoryError() result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) if result == -1: raise ValueError("invalid serial number string") cserial_number[serial_len] = 0 # Must explicitly null-terminate self._c_hid = hid_open(vendor_id, product_id, cserial_number) finally: if cserial_number != NULL: free(cserial_number) if self._c_hid == NULL: raise IOError('open failed') self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) def open_path(self, bytes path): """Open connection by path. :param path: Path to device :type path: bytes :raises IOError: """ cdef char* cbuff = path if self._c_hid != NULL: raise RuntimeError('already open') self._c_hid = hid_open_path(cbuff) if self._c_hid == NULL: raise IOError('open failed') self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) def close(self): """Close connection. This should always be called after opening a connection. """ if self._c_hid != NULL: self._close() self._close.detach() self._c_hid = NULL def write(self, buff): """Accept a list of integers (0-255) and send them to the device. :param buff: Data to write (must be convertible to `bytes`) :type buff: Any :return: Write result :rtype: int """ if self._c_hid == NULL: raise ValueError('not open') # convert to bytes if sys.version_info < (3, 0): buff = ''.join(map(chr, buff)) else: buff = bytes(buff) cdef hid_device * c_hid = self._c_hid cdef unsigned char* cbuff = buff # covert to c string cdef size_t c_buff_len = len(buff) cdef int result with nogil: result = hid_write(c_hid, cbuff, c_buff_len) return result def set_nonblocking(self, int v): """Set the nonblocking flag. :param v: Flag value (1 or 0, True or False) :type v: int, bool :return: Flag result :rtype: int """ if self._c_hid == NULL: raise ValueError('not open') return hid_set_nonblocking(self._c_hid, v) def read(self, int max_length, int timeout_ms=0): """Return a list of integers (0-255) from the device up to max_length bytes. :param max_length: Maximum number of bytes to read :type max_length: int :param timeout_ms: Number of milliseconds until timeout (default: no timeout) :type timeout_ms: int, optional :return: Read bytes :rtype: List[int] """ if self._c_hid == NULL: raise ValueError('not open') cdef unsigned char lbuff[16] cdef unsigned char* cbuff cdef size_t c_max_length = max_length cdef int c_timeout_ms = timeout_ms cdef hid_device * c_hid = self._c_hid try: if max_length <= 16: cbuff = lbuff else: cbuff = malloc(max_length) if timeout_ms > 0: with nogil: n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) else: with nogil: n = hid_read(c_hid, cbuff, c_max_length) if n == -1: raise IOError('read error') res = list(cbuff[:n]) finally: if max_length > 16: free(cbuff) return res def get_manufacturer_string(self): """Return manufacturer string (e.g. vendor name). :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) if r < 0: raise IOError('get manufacturer string error') return U(buff) def get_product_string(self): """Return product string (e.g. device description). :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef int r = hid_get_product_string(self._c_hid, buff, 255) if r < 0: raise IOError('get product string error') return U(buff) def get_serial_number_string(self): """Return serial number. :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) if r < 0: raise IOError('get serial number string error') return U(buff) def get_indexed_string(self, index): """Return indexed string. :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef unsigned char c_index = index cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) if r < 0: raise IOError('get indexed string error') return U(buff) def send_feature_report(self, buff): """Accept a list of integers (0-255) and send them to the device. :param buff: Data to send (must be convertible into bytes) :type buff: any :return: Send result :rtype: int """ if self._c_hid == NULL: raise ValueError('not open') # convert to bytes if sys.version_info < (3, 0): buff = ''.join(map(chr, buff)) else: buff = bytes(buff) cdef hid_device * c_hid = self._c_hid cdef unsigned char* cbuff = buff # covert to c string cdef size_t c_buff_len = len(buff) cdef int result with nogil: result = hid_send_feature_report(c_hid, cbuff, c_buff_len) return result def get_report_descriptor(self): """Return the HID Report Descriptor for this device. :return: :rtype: List[int] :raises ValueError: If connection is not opened. :raises IOError: If read error """ if self._c_hid == NULL: raise ValueError('not open') cdef unsigned char cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE] cdef hid_device * c_hid = self._c_hid cdef int n with nogil: n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) if n < 0: raise IOError('read error') return list(cbuff[:n]) def get_feature_report(self, int report_num, int max_length): """Receive feature report. :param report_num: :type report_num: int :param max_length: :type max_length: int :return: Incoming feature report :rtype: List[int] :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef hid_device * c_hid = self._c_hid cdef unsigned char lbuff[16] cdef unsigned char* cbuff cdef size_t c_max_length = max_length cdef int n try: if max_length <= 16: cbuff = lbuff else: cbuff = malloc(max_length) cbuff[0] = report_num with nogil: n = hid_get_feature_report(c_hid, cbuff, c_max_length) if n < 0: raise IOError('read error') res = list(cbuff[:n]) finally: if max_length > 16: free(cbuff) return res def get_input_report(self, int report_num, int max_length): """Get input report :param report_num: :type report_num: int :param max_length: :type max_length: int :return: :rtype: List[int] :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef hid_device * c_hid = self._c_hid cdef unsigned char lbuff[16] cdef unsigned char* cbuff cdef size_t c_max_length = max_length cdef int n try: if max_length <= 16: cbuff = lbuff else: cbuff = malloc(max_length) cbuff[0] = report_num with nogil: n = hid_get_input_report(c_hid, cbuff, c_max_length) if n < 0: raise IOError('read error') res = list(cbuff[:n]) finally: if max_length > 16: free(cbuff) return res def error(self): """Get error from device, or global error if no device is opened. :return: :rtype: str :raises IOError: """ return U(hid_error(self._c_hid)) # Finalize the HIDAPI library *only* once there are no more references to this # module, and it is being garbage collected. weakref.finalize(sys.modules[__name__], hid_exit) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0581722 hidapi-0.15.0/hidapi/0000755000076500000240000000000015115770112013331 5ustar00stickstaff././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1765273674.062661 hidapi-0.15.0/hidapi/hidapi/0000755000076500000240000000000015115770112014567 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/hidapi/hidapi.h0000644000076500000240000005650215115611013016200 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software libusb/hidapi Team Copyright 2023, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /** @file * @defgroup API hidapi API */ #ifndef HIDAPI_H__ #define HIDAPI_H__ #include /* #480: this is to be refactored properly for v1.0 */ #ifdef _WIN32 #ifndef HID_API_NO_EXPORT_DEFINE #define HID_API_EXPORT __declspec(dllexport) #endif #endif #ifndef HID_API_EXPORT #define HID_API_EXPORT /**< API export macro */ #endif /* To be removed in v1.0 */ #define HID_API_CALL /**< API call macro */ #define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/ /** @brief Static/compile-time major version of the library. @ingroup API */ #define HID_API_VERSION_MAJOR 0 /** @brief Static/compile-time minor version of the library. @ingroup API */ #define HID_API_VERSION_MINOR 15 /** @brief Static/compile-time patch version of the library. @ingroup API */ #define HID_API_VERSION_PATCH 0 /* Helper macros */ #define HID_API_AS_STR_IMPL(x) #x #define HID_API_AS_STR(x) HID_API_AS_STR_IMPL(x) #define HID_API_TO_VERSION_STR(v1, v2, v3) HID_API_AS_STR(v1.v2.v3) /** @brief Coverts a version as Major/Minor/Patch into a number: <8 bit major><16 bit minor><8 bit patch>. This macro was added in version 0.12.0. Convenient function to be used for compile-time checks, like: @code{.c} #if HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) @endcode @ingroup API */ #define HID_API_MAKE_VERSION(mj, mn, p) (((mj) << 24) | ((mn) << 8) | (p)) /** @brief Static/compile-time version of the library. This macro was added in version 0.12.0. @see @ref HID_API_MAKE_VERSION. @ingroup API */ #define HID_API_VERSION HID_API_MAKE_VERSION(HID_API_VERSION_MAJOR, HID_API_VERSION_MINOR, HID_API_VERSION_PATCH) /** @brief Static/compile-time string version of the library. @ingroup API */ #define HID_API_VERSION_STR HID_API_TO_VERSION_STR(HID_API_VERSION_MAJOR, HID_API_VERSION_MINOR, HID_API_VERSION_PATCH) /** @brief Maximum expected HID Report descriptor size in bytes. Since version 0.13.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 13, 0) @ingroup API */ #define HID_API_MAX_REPORT_DESCRIPTOR_SIZE 4096 #ifdef __cplusplus extern "C" { #endif /** A structure to hold the version numbers. */ struct hid_api_version { int major; /**< major version number */ int minor; /**< minor version number */ int patch; /**< patch version number */ }; struct hid_device_; typedef struct hid_device_ hid_device; /**< opaque hidapi structure */ /** @brief HID underlying bus types. @ingroup API */ typedef enum { /** Unknown bus type */ HID_API_BUS_UNKNOWN = 0x00, /** USB bus Specifications: https://usb.org/hid */ HID_API_BUS_USB = 0x01, /** Bluetooth or Bluetooth LE bus Specifications: https://www.bluetooth.com/specifications/specs/human-interface-device-profile-1-1-1/ https://www.bluetooth.com/specifications/specs/hid-service-1-0/ https://www.bluetooth.com/specifications/specs/hid-over-gatt-profile-1-0/ */ HID_API_BUS_BLUETOOTH = 0x02, /** I2C bus Specifications: https://docs.microsoft.com/previous-versions/windows/hardware/design/dn642101(v=vs.85) */ HID_API_BUS_I2C = 0x03, /** SPI bus Specifications: https://www.microsoft.com/download/details.aspx?id=103325 */ HID_API_BUS_SPI = 0x04, } hid_bus_type; /** hidapi info structure */ struct hid_device_info { /** Platform-specific device path */ char *path; /** Device Vendor ID */ unsigned short vendor_id; /** Device Product ID */ unsigned short product_id; /** Serial Number */ wchar_t *serial_number; /** Device Release Number in binary-coded decimal, also known as Device Version Number */ unsigned short release_number; /** Manufacturer String */ wchar_t *manufacturer_string; /** Product string */ wchar_t *product_string; /** Usage Page for this Device/Interface (Windows/Mac/hidraw only) */ unsigned short usage_page; /** Usage for this Device/Interface (Windows/Mac/hidraw only) */ unsigned short usage; /** The USB interface which this logical device represents. Valid only if the device is a USB HID device. Set to -1 in all other cases. */ int interface_number; /** Pointer to the next device */ struct hid_device_info *next; /** Underlying bus type Since version 0.13.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 13, 0) */ hid_bus_type bus_type; }; /** @brief Initialize the HIDAPI library. This function initializes the HIDAPI library. Calling it is not strictly necessary, as it will be called automatically by hid_enumerate() and any of the hid_open_*() functions if it is needed. This function should be called at the beginning of execution however, if there is a chance of HIDAPI handles being opened by different threads simultaneously. @ingroup API @returns This function returns 0 on success and -1 on error. Call hid_error(NULL) to get the failure reason. */ int HID_API_EXPORT HID_API_CALL hid_init(void); /** @brief Finalize the HIDAPI library. This function frees all of the static data associated with HIDAPI. It should be called at the end of execution to avoid memory leaks. @ingroup API @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT HID_API_CALL hid_exit(void); /** @brief Enumerate the HID Devices. This function returns a linked list of all the HID devices attached to the system which match vendor_id and product_id. If @p vendor_id is set to 0 then any vendor matches. If @p product_id is set to 0 then any product matches. If @p vendor_id and @p product_id are both set to 0, then all HID devices will be returned. @ingroup API @param vendor_id The Vendor ID (VID) of the types of device to open. @param product_id The Product ID (PID) of the types of device to open. @returns This function returns a pointer to a linked list of type struct #hid_device_info, containing information about the HID devices attached to the system, or NULL in the case of failure or if no HID devices present in the system. Call hid_error(NULL) to get the failure reason. @note The returned value by this function must to be freed by calling hid_free_enumeration(), when not needed anymore. */ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id); /** @brief Free an enumeration Linked List This function frees a linked list created by hid_enumerate(). @ingroup API @param devs Pointer to a list of struct_device returned from hid_enumerate(). */ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs); /** @brief Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number. If @p serial_number is NULL, the first device with the specified VID and PID is opened. @ingroup API @param vendor_id The Vendor ID (VID) of the device to open. @param product_id The Product ID (PID) of the device to open. @param serial_number The Serial Number of the device to open (Optionally NULL). @returns This function returns a pointer to a #hid_device object on success or NULL on failure. Call hid_error(NULL) to get the failure reason. @note The returned object must be freed by calling hid_close(), when not needed anymore. */ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); /** @brief Open a HID device by its path name. The path name be determined by calling hid_enumerate(), or a platform-specific path name can be used (eg: /dev/hidraw0 on Linux). @ingroup API @param path The path name of the device to open @returns This function returns a pointer to a #hid_device object on success or NULL on failure. Call hid_error(NULL) to get the failure reason. @note The returned object must be freed by calling hid_close(), when not needed anymore. */ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path); /** @brief Write an Output report to a HID device. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_write() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_write(), the Report ID (or 0x0, for devices with a single report), followed by the report data (16 bytes). In this example, the length passed in would be 17. hid_write() will send the data on the first interrupt OUT endpoint, if one exists. If it does not the behaviour is as @ref hid_send_output_report @ingroup API @param dev A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send. @returns This function returns the actual number of bytes written and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length); /** @brief Read an Input report from a HID device with timeout. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param dev A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @param milliseconds timeout in milliseconds or -1 for blocking wait. @returns This function returns the actual number of bytes read and -1 on error. Call hid_read_error(dev) to get the failure reason. If no packet was available to be read within the timeout period, this function returns 0. @note This function doesn't change the buffer returned by the hid_error(dev). */ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds); /** @brief Read an Input report from a HID device. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param dev A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @returns This function returns the actual number of bytes read and -1 on error. Call hid_read_error(dev) to get the failure reason. If no packet was available to be read and the handle is in non-blocking mode, this function returns 0. @note This function doesn't change the buffer returned by the hid_error(dev). */ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length); /** @brief Get a string describing the last error which occurred during hid_read/hid_read_timeout. Since version 0.15.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 15, 0) This function is intended for logging/debugging purposes. This function guarantees to never return NULL for a valid @ref dev. If there was no error in the last call to hid_read/hid_read_error - the returned string clearly indicates that. Strings returned from hid_read_error() must not be freed by the user, i.e. owned by HIDAPI library. Device-specific error string may remain allocated at most until hid_close() is called. @ingroup API @param dev A device handle. Shall never be NULL. @returns A string describing the hid_read/hid_read_timeout error (if any). */ HID_API_EXPORT const wchar_t* HID_API_CALL hid_read_error(hid_device *dev); /** @brief Set the device handle to be non-blocking. In non-blocking mode calls to hid_read() will return immediately with a value of 0 if there is no data to be read. In blocking mode, hid_read() will wait (block) until there is data to read before returning. Nonblocking can be turned on and off at any time. @ingroup API @param dev A device handle returned from hid_open(). @param nonblock enable or not the nonblocking reads - 1 to enable nonblocking - 0 to disable nonblocking. @returns This function returns 0 on success and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock); /** @brief Send a Feature report to the device. Feature reports are sent over the Control endpoint as a Set_Report transfer. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_send_feature_report(): the Report ID (or 0x0, for devices which do not use numbered reports), followed by the report data (16 bytes). In this example, the length passed in would be 17. @ingroup API @param dev A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send, including the report number. @returns This function returns the actual number of bytes written and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length); /** @brief Get a feature report from a HID device. Set the first byte of @p data[] to the Report ID of the report to be read. Make sure to allow space for this extra byte in @p data[]. Upon return, the first byte will still contain the Report ID, and the report data will start in data[1]. @ingroup API @param dev A device handle returned from hid_open(). @param data A buffer to put the read data into, including the Report ID. Set the first byte of @p data[] to the Report ID of the report to be read, or set it to zero if your device does not use numbered reports. @param length The number of bytes to read, including an extra byte for the report ID. The buffer can be longer than the actual report. @returns This function returns the number of bytes read plus one for the report ID (which is still in the first byte), or -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length); /** @brief Send a Output report to the device. Since version 0.15.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 15, 0) Output reports are sent over the Control endpoint as a Set_Report transfer. The first byte of @p data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. The remaining bytes contain the report data. Since the Report ID is mandatory, calls to hid_send_output_report() will always contain one more byte than the report contains. For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_send_output_report(): the Report ID (or 0x0, for devices which do not use numbered reports), followed by the report data (16 bytes). In this example, the length passed in would be 17. This function sets the return value of hid_error(). @ingroup API @param dev A device handle returned from hid_open(). @param data The data to send, including the report number as the first byte. @param length The length in bytes of the data to send, including the report number. @returns This function returns the actual number of bytes written and -1 on error. @see @ref hid_write */ int HID_API_EXPORT HID_API_CALL hid_send_output_report(hid_device* dev, const unsigned char* data, size_t length); /** @brief Get a input report from a HID device. Since version 0.10.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 10, 0) Set the first byte of @p data[] to the Report ID of the report to be read. Make sure to allow space for this extra byte in @p data[]. Upon return, the first byte will still contain the Report ID, and the report data will start in data[1]. @ingroup API @param dev A device handle returned from hid_open(). @param data A buffer to put the read data into, including the Report ID. Set the first byte of @p data[] to the Report ID of the report to be read, or set it to zero if your device does not use numbered reports. @param length The number of bytes to read, including an extra byte for the report ID. The buffer can be longer than the actual report. @returns This function returns the number of bytes read plus one for the report ID (which is still in the first byte), or -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length); /** @brief Close a HID device. @ingroup API @param dev A device handle returned from hid_open(). */ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev); /** @brief Get The Manufacturer String from a HID device. @ingroup API @param dev A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen); /** @brief Get The Product String from a HID device. @ingroup API @param dev A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen); /** @brief Get The Serial Number String from a HID device. @ingroup API @param dev A device handle returned from hid_open(). @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen); /** @brief Get The struct #hid_device_info from a HID device. Since version 0.13.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 13, 0) @ingroup API @param dev A device handle returned from hid_open(). @returns This function returns a pointer to the struct #hid_device_info for this hid_device, or NULL in the case of failure. Call hid_error(dev) to get the failure reason. This struct is valid until the device is closed with hid_close(). @note The returned object is owned by the @p dev, and SHOULD NOT be freed by the user. */ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_get_device_info(hid_device *dev); /** @brief Get a string from a HID device, based on its string index. @ingroup API @param dev A device handle returned from hid_open(). @param string_index The index of the string to get. @param string A wide string buffer to put the data into. @param maxlen The length of the buffer in multiples of wchar_t. @returns This function returns 0 on success and -1 on error. Call hid_error(dev) to get the failure reason. */ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen); /** @brief Get a report descriptor from a HID device. Since version 0.14.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 14, 0) User has to provide a preallocated buffer where descriptor will be copied to. The recommended size for preallocated buffer is @ref HID_API_MAX_REPORT_DESCRIPTOR_SIZE bytes. @ingroup API @param dev A device handle returned from hid_open(). @param buf The buffer to copy descriptor into. @param buf_size The size of the buffer in bytes. @returns This function returns non-negative number of bytes actually copied, or -1 on error. */ int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size); /** @brief Get a string describing the last error which occurred. This function is intended for logging/debugging purposes. This function guarantees to never return NULL. If there was no error in the last function call - the returned string clearly indicates that. Any HIDAPI function that can explicitly indicate an execution failure (e.g. by an error code, or by returning NULL) - may set the error string, to be returned by this function. Strings returned from hid_error() must not be freed by the user, i.e. owned by HIDAPI library. Device-specific error string may remain allocated at most until hid_close() is called. Global error string may remain allocated at most until hid_exit() is called. @ingroup API @param dev A device handle returned from hid_open(), or NULL to get the last non-device-specific error (e.g. for errors in hid_open() or hid_enumerate()). @returns A string describing the last error (if any). */ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *dev); /** @brief Get a runtime version of the library. This function is thread-safe. @ingroup API @returns Pointer to statically allocated struct, that contains version. */ HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void); /** @brief Get a runtime version string of the library. This function is thread-safe. @ingroup API @returns Pointer to statically allocated string, that contains version string. */ HID_API_EXPORT const char* HID_API_CALL hid_version_str(void); #ifdef __cplusplus } #endif #endif ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1765273674.065409 hidapi-0.15.0/hidapi/libusb/0000755000076500000240000000000015115770112014611 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/libusb/hid.c0000644000076500000240000015755615115611013015536 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #define _GNU_SOURCE /* needed for wcsdup() before glibc 2.10 */ /* C */ #include #include #include #include #include #include /* Unix */ #include #include #include #include #include #include #include /* GNU / LibUSB */ #include #if !defined(__ANDROID__) && !defined(NO_ICONV) #include #ifndef ICONV_CONST #define ICONV_CONST #endif #endif #include "hidapi_libusb.h" #ifndef HIDAPI_THREAD_MODEL_INCLUDE #define HIDAPI_THREAD_MODEL_INCLUDE "hidapi_thread_pthread.h" #endif #include HIDAPI_THREAD_MODEL_INCLUDE #ifdef __cplusplus extern "C" { #endif #ifdef DEBUG_PRINTF #define LOG(...) fprintf(stderr, __VA_ARGS__) #else #define LOG(...) do {} while (0) #endif #ifndef __FreeBSD__ #define DETACH_KERNEL_DRIVER #endif /* Uncomment to enable the retrieval of Usage and Usage Page in hid_enumerate(). Warning, on platforms different from FreeBSD this is very invasive as it requires the detach and re-attach of the kernel driver. See comments inside hid_enumerate(). libusb HIDAPI programs are encouraged to use the interface number instead to differentiate between interfaces on a composite HID device. */ /*#define INVASIVE_GET_USAGE*/ /* Linked List of input reports received from the device. */ struct input_report { uint8_t *data; size_t len; struct input_report *next; }; struct hid_device_ { /* Handle to the actual device. */ libusb_device_handle *device_handle; /* USB Configuration Number of the device */ int config_number; /* The interface number of the HID */ int interface; uint16_t report_descriptor_size; /* Endpoint information */ int input_endpoint; int output_endpoint; int input_ep_max_packet_size; /* Indexes of Strings */ int manufacturer_index; int product_index; int serial_index; struct hid_device_info* device_info; /* Whether blocking reads are used */ int blocking; /* boolean */ /* Read thread objects */ hidapi_thread_state thread_state; int shutdown_thread; int transfer_loop_finished; struct libusb_transfer *transfer; /* List of received input reports. */ struct input_report *input_reports; /* Was kernel driver detached by libusb */ #ifdef DETACH_KERNEL_DRIVER int is_driver_detached; #endif }; static struct hid_api_version api_version = { .major = HID_API_VERSION_MAJOR, .minor = HID_API_VERSION_MINOR, .patch = HID_API_VERSION_PATCH }; static libusb_context *usb_context = NULL; uint16_t get_usb_code_for_current_locale(void); static int return_data(hid_device *dev, unsigned char *data, size_t length); static hid_device *new_hid_device(void) { hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); if (!dev) return NULL; dev->blocking = 1; hidapi_thread_state_init(&dev->thread_state); return dev; } static void free_hid_device(hid_device *dev) { /* Clean up the thread objects */ hidapi_thread_state_destroy(&dev->thread_state); hid_free_enumeration(dev->device_info); /* Free the device itself */ free(dev); } #if 0 /*TODO: Implement this function on hidapi/libusb.. */ static void register_error(hid_device *dev, const char *op) { } #endif /* Get bytes from a HID Report Descriptor. Only call with a num_bytes of 0, 1, 2, or 4. */ static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur) { /* Return if there aren't enough bytes. */ if (cur + num_bytes >= len) return 0; if (num_bytes == 0) return 0; else if (num_bytes == 1) { return rpt[cur+1]; } else if (num_bytes == 2) { return (rpt[cur+2] * 256 + rpt[cur+1]); } else if (num_bytes == 4) { return (rpt[cur+4] * 0x01000000 + rpt[cur+3] * 0x00010000 + rpt[cur+2] * 0x00000100 + rpt[cur+1] * 0x00000001); } else return 0; } /* Retrieves the device's Usage Page and Usage from the report descriptor. The algorithm is simple, as it just returns the first Usage and Usage Page that it finds in the descriptor. The return value is 0 on success and -1 on failure. */ static int get_usage(uint8_t *report_descriptor, size_t size, unsigned short *usage_page, unsigned short *usage) { unsigned int i = 0; int size_code; int data_len, key_size; int usage_found = 0, usage_page_found = 0; while (i < size) { int key = report_descriptor[i]; int key_cmd = key & 0xfc; //printf("key: %02hhx\n", key); if ((key & 0xf0) == 0xf0) { /* This is a Long Item. The next byte contains the length of the data section (value) for this key. See the HID specification, version 1.11, section 6.2.2.3, titled "Long Items." */ if (i+1 < size) data_len = report_descriptor[i+1]; else data_len = 0; /* malformed report */ key_size = 3; } else { /* This is a Short Item. The bottom two bits of the key contain the size code for the data section (value) for this key. Refer to the HID specification, version 1.11, section 6.2.2.2, titled "Short Items." */ size_code = key & 0x3; switch (size_code) { case 0: case 1: case 2: data_len = size_code; break; case 3: data_len = 4; break; default: /* Can't ever happen since size_code is & 0x3 */ data_len = 0; break; }; key_size = 1; } if (key_cmd == 0x4) { *usage_page = get_bytes(report_descriptor, size, data_len, i); usage_page_found = 1; //printf("Usage Page: %x\n", (uint32_t)*usage_page); } if (key_cmd == 0x8) { if (data_len == 4) { /* Usages 5.5 / Usage Page 6.2.2.7 */ *usage_page = get_bytes(report_descriptor, size, 2, i + 2); usage_page_found = 1; *usage = get_bytes(report_descriptor, size, 2, i); usage_found = 1; } else { *usage = get_bytes(report_descriptor, size, data_len, i); usage_found = 1; } //printf("Usage: %x\n", (uint32_t)*usage); } if (usage_page_found && usage_found) return 0; /* success */ /* Skip over this key and it's associated data */ i += data_len + key_size; } return -1; /* failure */ } #if defined(__FreeBSD__) && __FreeBSD__ < 10 /* The libusb version included in FreeBSD < 10 doesn't have this function. In mainline libusb, it's inlined in libusb.h. This function will bear a striking resemblance to that one, because there's about one way to code it. Note that the data parameter is Unicode in UTF-16LE encoding. Return value is the number of bytes in data, or LIBUSB_ERROR_*. */ static inline int libusb_get_string_descriptor(libusb_device_handle *dev, uint8_t descriptor_index, uint16_t lang_id, unsigned char *data, int length) { return libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */ LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | descriptor_index, lang_id, data, (uint16_t) length, 1000); } #endif /* Get the first language the device says it reports. This comes from USB string #0. */ static uint16_t get_first_language(libusb_device_handle *dev) { uint16_t buf[32]; int len; /* Get the string from libusb. */ len = libusb_get_string_descriptor(dev, 0x0, /* String ID */ 0x0, /* Language */ (unsigned char*)buf, sizeof(buf)); if (len < 4) return 0x0; return buf[1]; /* First two bytes are len and descriptor type. */ } static int is_language_supported(libusb_device_handle *dev, uint16_t lang) { uint16_t buf[32]; int len; int i; /* Get the string from libusb. */ len = libusb_get_string_descriptor(dev, 0x0, /* String ID */ 0x0, /* Language */ (unsigned char*)buf, sizeof(buf)); if (len < 4) return 0x0; len /= 2; /* language IDs are two-bytes each. */ /* Start at index 1 because there are two bytes of protocol data. */ for (i = 1; i < len; i++) { if (buf[i] == lang) return 1; } return 0; } /* This function returns a newly allocated wide string containing the USB device string numbered by the index. The returned string must be freed by using free(). */ static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx) { char buf[512]; int len; wchar_t *str = NULL; #if !defined(__ANDROID__) && !defined(NO_ICONV) /* we don't use iconv on Android, or when it is explicitly disabled */ wchar_t wbuf[256]; /* iconv variables */ iconv_t ic; size_t inbytes; size_t outbytes; size_t res; ICONV_CONST char *inptr; char *outptr; #endif /* Determine which language to use. */ uint16_t lang; lang = get_usb_code_for_current_locale(); if (!is_language_supported(dev, lang)) lang = get_first_language(dev); /* Get the string from libusb. */ len = libusb_get_string_descriptor(dev, idx, lang, (unsigned char*)buf, sizeof(buf)); if (len < 2) /* we always skip first 2 bytes */ return NULL; #if defined(__ANDROID__) || defined(NO_ICONV) /* Bionic does not have iconv support nor wcsdup() function, so it has to be done manually. The following code will only work for code points that can be represented as a single UTF-16 character, and will incorrectly convert any code points which require more than one UTF-16 character. Skip over the first character (2-bytes). */ len -= 2; str = (wchar_t*) malloc((len / 2 + 1) * sizeof(wchar_t)); int i; for (i = 0; i < len / 2; i++) { str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8); } str[len / 2] = 0x00000000; #else /* buf does not need to be explicitly NULL-terminated because it is only passed into iconv() which does not need it. */ /* Initialize iconv. */ ic = iconv_open("WCHAR_T", "UTF-16LE"); if (ic == (iconv_t)-1) { LOG("iconv_open() failed\n"); return NULL; } /* Convert to native wchar_t (UTF-32 on glibc/BSD systems). Skip the first character (2-bytes). */ inptr = buf+2; inbytes = len-2; outptr = (char*) wbuf; outbytes = sizeof(wbuf); res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes); if (res == (size_t)-1) { LOG("iconv() failed\n"); goto err; } /* Write the terminating NULL. */ wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000; if (outbytes >= sizeof(wbuf[0])) *((wchar_t*)outptr) = 0x00000000; /* Allocate and copy the string. */ str = wcsdup(wbuf); err: iconv_close(ic); #endif return str; } /** Max length of the result: "000-000.000.000.000.000.000.000:000.000" (39 chars). 64 is used for simplicity/alignment. */ static void get_path(char (*result)[64], libusb_device *dev, int config_number, int interface_number) { char *str = *result; /* Note that USB3 port count limit is 7; use 8 here for alignment */ uint8_t port_numbers[8] = {0, 0, 0, 0, 0, 0, 0, 0}; int num_ports = libusb_get_port_numbers(dev, port_numbers, 8); if (num_ports > 0) { int n = snprintf(str, sizeof("000-000"), "%u-%u", libusb_get_bus_number(dev), port_numbers[0]); for (uint8_t i = 1; i < num_ports; i++) { n += snprintf(&str[n], sizeof(".000"), ".%u", port_numbers[i]); } n += snprintf(&str[n], sizeof(":000.000"), ":%u.%u", (uint8_t)config_number, (uint8_t)interface_number); str[n] = '\0'; } else { /* Likely impossible, but check: USB3.0 specs limit number of ports to 7 and buffer size here is 8 */ if (num_ports == LIBUSB_ERROR_OVERFLOW) { LOG("make_path() failed. buffer overflow error\n"); } else { LOG("make_path() failed. unknown error\n"); } str[0] = '\0'; } } static char *make_path(libusb_device *dev, int config_number, int interface_number) { char str[64]; get_path(&str, dev, config_number, interface_number); return strdup(str); } HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) { return &api_version; } HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) { return HID_API_VERSION_STR; } int HID_API_EXPORT hid_init(void) { if (!usb_context) { const char *locale; /* Init Libusb */ if (libusb_init(&usb_context)) return -1; /* Set the locale if it's not set. */ locale = setlocale(LC_CTYPE, NULL); if (!locale) setlocale(LC_CTYPE, ""); } return 0; } int HID_API_EXPORT hid_exit(void) { if (usb_context) { libusb_exit(usb_context); usb_context = NULL; } return 0; } static int hid_get_report_descriptor_libusb(libusb_device_handle *handle, int interface_num, uint16_t expected_report_descriptor_size, unsigned char *buf, size_t buf_size) { unsigned char tmp[HID_API_MAX_REPORT_DESCRIPTOR_SIZE]; if (expected_report_descriptor_size > HID_API_MAX_REPORT_DESCRIPTOR_SIZE) expected_report_descriptor_size = HID_API_MAX_REPORT_DESCRIPTOR_SIZE; /* Get the HID Report Descriptor. See USB HID Specification, section 7.1.1 */ int res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8), interface_num, tmp, expected_report_descriptor_size, 5000); if (res < 0) { LOG("libusb_control_transfer() for getting the HID Report descriptor failed with %d: %s\n", res, libusb_error_name(res)); return -1; } if (res > (int)buf_size) res = (int)buf_size; memcpy(buf, tmp, (size_t)res); return res; } /** * Requires an opened device with *claimed interface*. */ static void fill_device_info_usage(struct hid_device_info *cur_dev, libusb_device_handle *handle, int interface_num, uint16_t expected_report_descriptor_size) { unsigned char hid_report_descriptor[HID_API_MAX_REPORT_DESCRIPTOR_SIZE]; unsigned short page = 0, usage = 0; int res = hid_get_report_descriptor_libusb(handle, interface_num, expected_report_descriptor_size, hid_report_descriptor, sizeof(hid_report_descriptor)); if (res >= 0) { /* Parse the usage and usage page out of the report descriptor. */ get_usage(hid_report_descriptor, res, &page, &usage); } cur_dev->usage_page = page; cur_dev->usage = usage; } #ifdef INVASIVE_GET_USAGE static void invasive_fill_device_info_usage(struct hid_device_info *cur_dev, libusb_device_handle *handle, int interface_num, uint16_t report_descriptor_size) { int res = 0; #ifdef DETACH_KERNEL_DRIVER int detached = 0; /* Usage Page and Usage */ res = libusb_kernel_driver_active(handle, interface_num); if (res == 1) { res = libusb_detach_kernel_driver(handle, interface_num); if (res < 0) LOG("Couldn't detach kernel driver, even though a kernel driver was attached.\n"); else detached = 1; } #endif res = libusb_claim_interface(handle, interface_num); if (res >= 0) { fill_device_info_usage(cur_dev, handle, interface_num, report_descriptor_size); /* Release the interface */ res = libusb_release_interface(handle, interface_num); if (res < 0) LOG("Can't release the interface.\n"); } else LOG("Can't claim interface: (%d) %s\n", res, libusb_error_name(res)); #ifdef DETACH_KERNEL_DRIVER /* Re-attach kernel driver if necessary. */ if (detached) { res = libusb_attach_kernel_driver(handle, interface_num); if (res < 0) LOG("Couldn't re-attach kernel driver.\n"); } #endif } #endif /* INVASIVE_GET_USAGE */ /** * Create and fill up most of hid_device_info fields. * usage_page/usage is not filled up. */ static struct hid_device_info * create_device_info_for_device(libusb_device *device, libusb_device_handle *handle, struct libusb_device_descriptor *desc, int config_number, int interface_num) { struct hid_device_info *cur_dev = calloc(1, sizeof(struct hid_device_info)); if (cur_dev == NULL) { return NULL; } /* VID/PID */ cur_dev->vendor_id = desc->idVendor; cur_dev->product_id = desc->idProduct; cur_dev->release_number = desc->bcdDevice; cur_dev->interface_number = interface_num; cur_dev->bus_type = HID_API_BUS_USB; cur_dev->path = make_path(device, config_number, interface_num); if (!handle) { return cur_dev; } if (desc->iSerialNumber > 0) cur_dev->serial_number = get_usb_string(handle, desc->iSerialNumber); /* Manufacturer and Product strings */ if (desc->iManufacturer > 0) cur_dev->manufacturer_string = get_usb_string(handle, desc->iManufacturer); if (desc->iProduct > 0) cur_dev->product_string = get_usb_string(handle, desc->iProduct); return cur_dev; } static uint16_t get_report_descriptor_size_from_interface_descriptors(const struct libusb_interface_descriptor *intf_desc) { int i = 0; int found_hid_report_descriptor = 0; uint16_t result = HID_API_MAX_REPORT_DESCRIPTOR_SIZE; const unsigned char *extra = intf_desc->extra; int extra_length = intf_desc->extra_length; /* "extra" contains a HID descriptor See section 6.2.1 of HID 1.1 specification. */ while (extra_length >= 2) { /* Descriptor header: bLength/bDescriptorType */ if (extra[1] == LIBUSB_DT_HID) { /* bDescriptorType */ if (extra_length < 6) { LOG("Broken HID descriptor: not enough data\n"); break; } unsigned char bNumDescriptors = extra[5]; if (extra_length < (6 + 3 * bNumDescriptors)) { LOG("Broken HID descriptor: not enough data for Report metadata\n"); break; } for (i = 0; i < bNumDescriptors; i++) { if (extra[6 + 3 * i] == LIBUSB_DT_REPORT) { result = (uint16_t)extra[6 + 3 * i + 2] << 8 | extra[6 + 3 * i + 1]; found_hid_report_descriptor = 1; break; } } if (!found_hid_report_descriptor) { /* We expect to find exactly 1 HID descriptor (LIBUSB_DT_HID) which should contain exactly one HID Report Descriptor metadata (LIBUSB_DT_REPORT). */ LOG("Broken HID descriptor: missing Report descriptor\n"); } break; } if (extra[0] == 0) { /* bLength */ LOG("Broken HID Interface descriptors: zero-sized descriptor\n"); break; } /* Iterate over to the next Descriptor */ extra_length -= extra[0]; extra += extra[0]; } return result; } static int is_xbox360(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc) { static const int xb360_iface_subclass = 93; static const int xb360_iface_protocol = 1; /* Wired */ static const int xb360w_iface_protocol = 129; /* Wireless */ static const int supported_vendors[] = { 0x0079, /* GPD Win 2 */ 0x044f, /* Thrustmaster */ 0x045e, /* Microsoft */ 0x046d, /* Logitech */ 0x056e, /* Elecom */ 0x06a3, /* Saitek */ 0x0738, /* Mad Catz */ 0x07ff, /* Mad Catz */ 0x0e6f, /* PDP */ 0x0f0d, /* Hori */ 0x1038, /* SteelSeries */ 0x11c9, /* Nacon */ 0x12ab, /* Unknown */ 0x1430, /* RedOctane */ 0x146b, /* BigBen */ 0x1532, /* Razer Sabertooth */ 0x15e4, /* Numark */ 0x162e, /* Joytech */ 0x1689, /* Razer Onza */ 0x1949, /* Lab126, Inc. */ 0x1bad, /* Harmonix */ 0x20d6, /* PowerA */ 0x24c6, /* PowerA */ 0x2c22, /* Qanba */ 0x2dc8, /* 8BitDo */ 0x9886, /* ASTRO Gaming */ }; if (intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC && intf_desc->bInterfaceSubClass == xb360_iface_subclass && (intf_desc->bInterfaceProtocol == xb360_iface_protocol || intf_desc->bInterfaceProtocol == xb360w_iface_protocol)) { size_t i; for (i = 0; i < sizeof(supported_vendors)/sizeof(supported_vendors[0]); ++i) { if (vendor_id == supported_vendors[i]) { return 1; } } } return 0; } static int is_xboxone(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc) { static const int xb1_iface_subclass = 71; static const int xb1_iface_protocol = 208; static const int supported_vendors[] = { 0x044f, /* Thrustmaster */ 0x045e, /* Microsoft */ 0x0738, /* Mad Catz */ 0x0e6f, /* PDP */ 0x0f0d, /* Hori */ 0x10f5, /* Turtle Beach */ 0x1532, /* Razer Wildcat */ 0x20d6, /* PowerA */ 0x24c6, /* PowerA */ 0x2dc8, /* 8BitDo */ 0x2e24, /* Hyperkin */ 0x3537, /* GameSir */ }; if (intf_desc->bInterfaceNumber == 0 && intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC && intf_desc->bInterfaceSubClass == xb1_iface_subclass && intf_desc->bInterfaceProtocol == xb1_iface_protocol) { size_t i; for (i = 0; i < sizeof(supported_vendors)/sizeof(supported_vendors[0]); ++i) { if (vendor_id == supported_vendors[i]) { return 1; } } } return 0; } static int should_enumerate_interface(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc) { #if 0 printf("Checking interface 0x%x %d/%d/%d/%d\n", vendor_id, intf_desc->bInterfaceNumber, intf_desc->bInterfaceClass, intf_desc->bInterfaceSubClass, intf_desc->bInterfaceProtocol); #endif if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) return 1; /* Also enumerate Xbox 360 controllers */ if (is_xbox360(vendor_id, intf_desc)) return 1; /* Also enumerate Xbox One controllers */ if (is_xboxone(vendor_id, intf_desc)) return 1; return 0; } struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) { libusb_device **devs; libusb_device *dev; libusb_device_handle *handle = NULL; ssize_t num_devs; int i = 0; struct hid_device_info *root = NULL; /* return object */ struct hid_device_info *cur_dev = NULL; if(hid_init() < 0) return NULL; num_devs = libusb_get_device_list(usb_context, &devs); if (num_devs < 0) return NULL; while ((dev = devs[i++]) != NULL) { struct libusb_device_descriptor desc; struct libusb_config_descriptor *conf_desc = NULL; int j, k; int res = libusb_get_device_descriptor(dev, &desc); if (res < 0) continue; unsigned short dev_vid = desc.idVendor; unsigned short dev_pid = desc.idProduct; if ((vendor_id != 0x0 && vendor_id != dev_vid) || (product_id != 0x0 && product_id != dev_pid)) { continue; } res = libusb_get_active_config_descriptor(dev, &conf_desc); if (res < 0) libusb_get_config_descriptor(dev, 0, &conf_desc); if (conf_desc) { for (j = 0; j < conf_desc->bNumInterfaces; j++) { const struct libusb_interface *intf = &conf_desc->interface[j]; for (k = 0; k < intf->num_altsetting; k++) { const struct libusb_interface_descriptor *intf_desc; intf_desc = &intf->altsetting[k]; if (should_enumerate_interface(dev_vid, intf_desc)) { struct hid_device_info *tmp; res = libusb_open(dev, &handle); #ifdef __ANDROID__ if (handle) { /* There is (a potential) libusb Android backend, in which device descriptor is not accurate up until the device is opened. https://github.com/libusb/libusb/pull/874#discussion_r632801373 A workaround is to re-read the descriptor again. Even if it is not going to be accepted into libusb master, having it here won't do any harm, since reading the device descriptor is as cheap as copy 18 bytes of data. */ libusb_get_device_descriptor(dev, &desc); } #endif tmp = create_device_info_for_device(dev, handle, &desc, conf_desc->bConfigurationValue, intf_desc->bInterfaceNumber); if (tmp) { #ifdef INVASIVE_GET_USAGE /* TODO: have a runtime check for this section. */ /* This section is removed because it is too invasive on the system. Getting a Usage Page and Usage requires parsing the HID Report descriptor. Getting a HID Report descriptor involves claiming the interface. Claiming the interface involves detaching the kernel driver. Detaching the kernel driver is hard on the system because it will unclaim interfaces (if another app has them claimed) and the re-attachment of the driver will sometimes change /dev entry names. It is for these reasons that this section is optional. For composite devices, use the interface field in the hid_device_info struct to distinguish between interfaces. */ if (handle) { uint16_t report_descriptor_size = get_report_descriptor_size_from_interface_descriptors(intf_desc); invasive_fill_device_info_usage(tmp, handle, intf_desc->bInterfaceNumber, report_descriptor_size); } #endif /* INVASIVE_GET_USAGE */ if (cur_dev) { cur_dev->next = tmp; } else { root = tmp; } cur_dev = tmp; } if (res >= 0) { libusb_close(handle); handle = NULL; } break; } } /* altsettings */ } /* interfaces */ libusb_free_config_descriptor(conf_desc); } } libusb_free_device_list(devs, 1); return root; } void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) { struct hid_device_info *d = devs; while (d) { struct hid_device_info *next = d->next; free(d->path); free(d->serial_number); free(d->manufacturer_string); free(d->product_string); free(d); d = next; } } hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { struct hid_device_info *devs, *cur_dev; const char *path_to_open = NULL; hid_device *handle = NULL; devs = hid_enumerate(vendor_id, product_id); cur_dev = devs; while (cur_dev) { if (cur_dev->vendor_id == vendor_id && cur_dev->product_id == product_id) { if (serial_number) { if (cur_dev->serial_number && wcscmp(serial_number, cur_dev->serial_number) == 0) { path_to_open = cur_dev->path; break; } } else { path_to_open = cur_dev->path; break; } } cur_dev = cur_dev->next; } if (path_to_open) { /* Open the device */ handle = hid_open_path(path_to_open); } hid_free_enumeration(devs); return handle; } static void LIBUSB_CALL read_callback(struct libusb_transfer *transfer) { hid_device *dev = transfer->user_data; int res; if (transfer->status == LIBUSB_TRANSFER_COMPLETED) { struct input_report *rpt = (struct input_report*) malloc(sizeof(*rpt)); rpt->data = (uint8_t*) malloc(transfer->actual_length); memcpy(rpt->data, transfer->buffer, transfer->actual_length); rpt->len = transfer->actual_length; rpt->next = NULL; hidapi_thread_mutex_lock(&dev->thread_state); /* Attach the new report object to the end of the list. */ if (dev->input_reports == NULL) { /* The list is empty. Put it at the root. */ dev->input_reports = rpt; hidapi_thread_cond_signal(&dev->thread_state); } else { /* Find the end of the list and attach. */ struct input_report *cur = dev->input_reports; int num_queued = 0; while (cur->next != NULL) { cur = cur->next; num_queued++; } cur->next = rpt; /* Pop one off if we've reached 30 in the queue. This way we don't grow forever if the user never reads anything from the device. */ if (num_queued > 30) { return_data(dev, NULL, 0); } } hidapi_thread_mutex_unlock(&dev->thread_state); } else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { dev->shutdown_thread = 1; } else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) { dev->shutdown_thread = 1; } else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) { //LOG("Timeout (normal)\n"); } else { LOG("Unknown transfer code: %d\n", transfer->status); } if (dev->shutdown_thread) { dev->transfer_loop_finished = 1; return; } /* Re-submit the transfer object. */ res = libusb_submit_transfer(transfer); if (res != 0) { LOG("Unable to submit URB: (%d) %s\n", res, libusb_error_name(res)); dev->shutdown_thread = 1; dev->transfer_loop_finished = 1; } } static void *read_thread(void *param) { int res; hid_device *dev = param; uint8_t *buf; const size_t length = dev->input_ep_max_packet_size; /* Set up the transfer object. */ buf = (uint8_t*) malloc(length); dev->transfer = libusb_alloc_transfer(0); libusb_fill_interrupt_transfer(dev->transfer, dev->device_handle, dev->input_endpoint, buf, (int)length, read_callback, dev, 5000/*timeout*/); /* Make the first submission. Further submissions are made from inside read_callback() */ res = libusb_submit_transfer(dev->transfer); if(res < 0) { LOG("libusb_submit_transfer failed: %d %s. Stopping read_thread from running\n", res, libusb_error_name(res)); dev->shutdown_thread = 1; dev->transfer_loop_finished = 1; } /* Notify the main thread that the read thread is up and running. */ hidapi_thread_barrier_wait(&dev->thread_state); /* Handle all the events. */ while (!dev->shutdown_thread) { res = libusb_handle_events(usb_context); if (res < 0) { /* There was an error. */ LOG("read_thread(): (%d) %s\n", res, libusb_error_name(res)); /* Break out of this loop only on fatal error.*/ if (res != LIBUSB_ERROR_BUSY && res != LIBUSB_ERROR_TIMEOUT && res != LIBUSB_ERROR_OVERFLOW && res != LIBUSB_ERROR_INTERRUPTED) { dev->shutdown_thread = 1; break; } } } /* Cancel any transfer that may be pending. This call will fail if no transfers are pending, but that's OK. */ libusb_cancel_transfer(dev->transfer); while (!dev->transfer_loop_finished) libusb_handle_events_completed(usb_context, &dev->transfer_loop_finished); /* Now that the read thread is stopping, Wake any threads which are waiting on data (in hid_read_timeout()). Do this under a mutex to make sure that a thread which is about to go to sleep waiting on the condition actually will go to sleep before the condition is signaled. */ hidapi_thread_mutex_lock(&dev->thread_state); hidapi_thread_cond_broadcast(&dev->thread_state); hidapi_thread_mutex_unlock(&dev->thread_state); /* The dev->transfer->buffer and dev->transfer objects are cleaned up in hid_close(). They are not cleaned up here because this thread could end either due to a disconnect or due to a user call to hid_close(). In both cases the objects can be safely cleaned up after the call to hidapi_thread_join() (in hid_close()), but since hid_close() calls libusb_cancel_transfer(), on these objects, they can not be cleaned up here. */ return NULL; } static void init_xbox360(libusb_device_handle *device_handle, unsigned short idVendor, unsigned short idProduct, const struct libusb_config_descriptor *conf_desc) { (void)conf_desc; if ((idVendor == 0x05ac && idProduct == 0x055b) /* Gamesir-G3w */ || idVendor == 0x0f0d /* Hori Xbox controllers */) { unsigned char data[20]; /* The HORIPAD FPS for Nintendo Switch requires this to enable input reports. This VID/PID is also shared with other HORI controllers, but they all seem to be fine with this as well. */ memset(data, 0, sizeof(data)); libusb_control_transfer(device_handle, 0xC1, 0x01, 0x100, 0x0, data, sizeof(data), 100); } } static void init_xboxone(libusb_device_handle *device_handle, unsigned short idVendor, unsigned short idProduct, const struct libusb_config_descriptor *conf_desc) { static const int vendor_microsoft = 0x045e; static const int xb1_iface_subclass = 71; static const int xb1_iface_protocol = 208; int j, k, res; (void)idProduct; for (j = 0; j < conf_desc->bNumInterfaces; j++) { const struct libusb_interface *intf = &conf_desc->interface[j]; for (k = 0; k < intf->num_altsetting; k++) { const struct libusb_interface_descriptor *intf_desc = &intf->altsetting[k]; if (intf_desc->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC && intf_desc->bInterfaceSubClass == xb1_iface_subclass && intf_desc->bInterfaceProtocol == xb1_iface_protocol) { int bSetAlternateSetting = 0; /* Newer Microsoft Xbox One controllers have a high speed alternate setting */ if (idVendor == vendor_microsoft && intf_desc->bInterfaceNumber == 0 && intf_desc->bAlternateSetting == 1) { bSetAlternateSetting = 1; } else if (intf_desc->bInterfaceNumber != 0 && intf_desc->bAlternateSetting == 0) { bSetAlternateSetting = 1; } if (bSetAlternateSetting) { res = libusb_claim_interface(device_handle, intf_desc->bInterfaceNumber); if (res < 0) { LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res); continue; } LOG("Setting alternate setting for VID/PID 0x%x/0x%x interface %d to %d\n", idVendor, idProduct, intf_desc->bInterfaceNumber, intf_desc->bAlternateSetting); res = libusb_set_interface_alt_setting(device_handle, intf_desc->bInterfaceNumber, intf_desc->bAlternateSetting); if (res < 0) { LOG("xbox init: can't set alt setting %d: %d\n", intf_desc->bInterfaceNumber, res); } libusb_release_interface(device_handle, intf_desc->bInterfaceNumber); } } } } } static int hidapi_initialize_device(hid_device *dev, const struct libusb_interface_descriptor *intf_desc, const struct libusb_config_descriptor *conf_desc) { int i =0; int res = 0; struct libusb_device_descriptor desc; libusb_get_device_descriptor(libusb_get_device(dev->device_handle), &desc); #ifdef DETACH_KERNEL_DRIVER /* Detach the kernel driver, but only if the device is managed by the kernel */ dev->is_driver_detached = 0; if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) { res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber); if (res < 0) { LOG("Unable to detach Kernel Driver: (%d) %s\n", res, libusb_error_name(res)); return 0; } else { dev->is_driver_detached = 1; LOG("Driver successfully detached from kernel.\n"); } } #endif res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber); if (res < 0) { LOG("can't claim interface %d: (%d) %s\n", intf_desc->bInterfaceNumber, res, libusb_error_name(res)); #ifdef DETACH_KERNEL_DRIVER if (dev->is_driver_detached) { res = libusb_attach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber); if (res < 0) LOG("Failed to reattach the driver to kernel: (%d) %s\n", res, libusb_error_name(res)); } #endif return 0; } /* Initialize XBox 360 controllers */ if (is_xbox360(desc.idVendor, intf_desc)) { init_xbox360(dev->device_handle, desc.idVendor, desc.idProduct, conf_desc); } /* Initialize XBox One controllers */ if (is_xboxone(desc.idVendor, intf_desc)) { init_xboxone(dev->device_handle, desc.idVendor, desc.idProduct, conf_desc); } /* Store off the string descriptor indexes */ dev->manufacturer_index = desc.iManufacturer; dev->product_index = desc.iProduct; dev->serial_index = desc.iSerialNumber; /* Store off the USB information */ dev->config_number = conf_desc->bConfigurationValue; dev->interface = intf_desc->bInterfaceNumber; dev->report_descriptor_size = get_report_descriptor_size_from_interface_descriptors(intf_desc); dev->input_endpoint = 0; dev->input_ep_max_packet_size = 0; dev->output_endpoint = 0; /* Find the INPUT and OUTPUT endpoints. An OUTPUT endpoint is not required. */ for (i = 0; i < intf_desc->bNumEndpoints; i++) { const struct libusb_endpoint_descriptor *ep = &intf_desc->endpoint[i]; /* Determine the type and direction of this endpoint. */ int is_interrupt = (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) == LIBUSB_TRANSFER_TYPE_INTERRUPT; int is_output = (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT; int is_input = (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN; /* Decide whether to use it for input or output. */ if (dev->input_endpoint == 0 && is_interrupt && is_input) { /* Use this endpoint for INPUT */ dev->input_endpoint = ep->bEndpointAddress; dev->input_ep_max_packet_size = ep->wMaxPacketSize; } if (dev->output_endpoint == 0 && is_interrupt && is_output) { /* Use this endpoint for OUTPUT */ dev->output_endpoint = ep->bEndpointAddress; } } hidapi_thread_create(&dev->thread_state, read_thread, dev); /* Wait here for the read thread to be initialized. */ hidapi_thread_barrier_wait(&dev->thread_state); return 1; } hid_device * HID_API_EXPORT hid_open_path(const char *path) { hid_device *dev = NULL; libusb_device **devs = NULL; libusb_device *usb_dev = NULL; int res = 0; int d = 0; int good_open = 0; if(hid_init() < 0) return NULL; dev = new_hid_device(); if (!dev) { LOG("hid_open_path failed: Couldn't allocate memory\n"); return NULL; } libusb_get_device_list(usb_context, &devs); while ((usb_dev = devs[d++]) != NULL && !good_open) { struct libusb_device_descriptor desc; struct libusb_config_descriptor *conf_desc = NULL; int j,k; res = libusb_get_device_descriptor(usb_dev, &desc); if (res < 0) continue; res = libusb_get_active_config_descriptor(usb_dev, &conf_desc); if (res < 0) libusb_get_config_descriptor(usb_dev, 0, &conf_desc); if (!conf_desc) continue; for (j = 0; j < conf_desc->bNumInterfaces && !good_open; j++) { const struct libusb_interface *intf = &conf_desc->interface[j]; for (k = 0; k < intf->num_altsetting && !good_open; k++) { const struct libusb_interface_descriptor *intf_desc = &intf->altsetting[k]; if (should_enumerate_interface(desc.idVendor, intf_desc)) { char dev_path[64]; get_path(&dev_path, usb_dev, conf_desc->bConfigurationValue, intf_desc->bInterfaceNumber); if (!strcmp(dev_path, path)) { /* Matched Paths. Open this device */ /* OPEN HERE */ res = libusb_open(usb_dev, &dev->device_handle); if (res < 0) { LOG("can't open device\n"); break; } good_open = hidapi_initialize_device(dev, intf_desc, conf_desc); if (!good_open) libusb_close(dev->device_handle); } } } } libusb_free_config_descriptor(conf_desc); } libusb_free_device_list(devs, 1); /* If we have a good handle, return it. */ if (good_open) { return dev; } else { /* Unable to open any devices. */ free_hid_device(dev); return NULL; } } HID_API_EXPORT hid_device * HID_API_CALL hid_libusb_wrap_sys_device(intptr_t sys_dev, int interface_num) { /* 0x01000107 is a LIBUSB_API_VERSION for 1.0.23 - version when libusb_wrap_sys_device was introduced */ #if (!defined(HIDAPI_TARGET_LIBUSB_API_VERSION) || HIDAPI_TARGET_LIBUSB_API_VERSION >= 0x01000107) && (LIBUSB_API_VERSION >= 0x01000107) hid_device *dev = NULL; struct libusb_config_descriptor *conf_desc = NULL; const struct libusb_interface_descriptor *selected_intf_desc = NULL; int res = 0; int j = 0, k = 0; if(hid_init() < 0) return NULL; dev = new_hid_device(); if (!dev) { LOG("libusb_wrap_sys_device failed: Couldn't allocate memory\n"); return NULL; } res = libusb_wrap_sys_device(usb_context, sys_dev, &dev->device_handle); if (res < 0) { LOG("libusb_wrap_sys_device failed: %d %s\n", res, libusb_error_name(res)); goto err; } res = libusb_get_active_config_descriptor(libusb_get_device(dev->device_handle), &conf_desc); if (res < 0) libusb_get_config_descriptor(libusb_get_device(dev->device_handle), 0, &conf_desc); if (!conf_desc) { LOG("Failed to get configuration descriptor: %d %s\n", res, libusb_error_name(res)); goto err; } /* find matching HID interface */ for (j = 0; j < conf_desc->bNumInterfaces && !selected_intf_desc; j++) { const struct libusb_interface *intf = &conf_desc->interface[j]; for (k = 0; k < intf->num_altsetting; k++) { const struct libusb_interface_descriptor *intf_desc = &intf->altsetting[k]; if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { if (interface_num < 0 || interface_num == intf_desc->bInterfaceNumber) { selected_intf_desc = intf_desc; break; } } } } if (!selected_intf_desc) { if (interface_num < 0) { LOG("Sys USB device doesn't contain a HID interface\n"); } else { LOG("Sys USB device doesn't contain a HID interface with number %d\n", interface_num); } goto err; } if (!hidapi_initialize_device(dev, selected_intf_desc, conf_desc)) goto err; return dev; err: if (conf_desc) libusb_free_config_descriptor(conf_desc); if (dev->device_handle) libusb_close(dev->device_handle); free_hid_device(dev); #else (void)sys_dev; (void)interface_num; LOG("libusb_wrap_sys_device is not available\n"); #endif return NULL; } int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) { int res; int report_number; int skipped_report_id = 0; if (dev->output_endpoint <= 0) { /* No interrupt out endpoint. Use the Control Endpoint */ return hid_send_output_report(dev, data, length); } if (!data || (length ==0)) { return -1; } report_number = data[0]; if (report_number == 0x0) { data++; length--; skipped_report_id = 1; } /* Use the interrupt out endpoint */ int actual_length; res = libusb_interrupt_transfer(dev->device_handle, dev->output_endpoint, (unsigned char*)data, (int)length, &actual_length, 1000); if (res < 0) return -1; if (skipped_report_id) actual_length++; return actual_length; } /* Helper function, to simplify hid_read(). This should be called with dev->mutex locked. */ static int return_data(hid_device *dev, unsigned char *data, size_t length) { /* Copy the data out of the linked list item (rpt) into the return buffer (data), and delete the liked list item. */ struct input_report *rpt = dev->input_reports; size_t len = (length < rpt->len)? length: rpt->len; if (len > 0) memcpy(data, rpt->data, len); dev->input_reports = rpt->next; free(rpt->data); free(rpt); return (int)len; } static void cleanup_mutex(void *param) { hid_device *dev = param; hidapi_thread_mutex_unlock(&dev->thread_state); } int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) { #if 0 int transferred; int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000); LOG("transferred: %d\n", transferred); return transferred; #endif /* by initialising this variable right here, GCC gives a compilation warning/error: */ /* error: variable ‘bytes_read’ might be clobbered by ‘longjmp’ or ‘vfork’ [-Werror=clobbered] */ int bytes_read; /* = -1; */ hidapi_thread_mutex_lock(&dev->thread_state); hidapi_thread_cleanup_push(cleanup_mutex, dev); bytes_read = -1; /* There's an input report queued up. Return it. */ if (dev->input_reports) { /* Return the first one */ bytes_read = return_data(dev, data, length); goto ret; } if (dev->shutdown_thread) { /* This means the device has been disconnected. An error code of -1 should be returned. */ bytes_read = -1; goto ret; } if (milliseconds == -1) { /* Blocking */ while (!dev->input_reports && !dev->shutdown_thread) { hidapi_thread_cond_wait(&dev->thread_state); } if (dev->input_reports) { bytes_read = return_data(dev, data, length); } } else if (milliseconds > 0) { /* Non-blocking, but called with timeout. */ int res; hidapi_timespec ts; hidapi_thread_gettime(&ts); hidapi_thread_addtime(&ts, milliseconds); while (!dev->input_reports && !dev->shutdown_thread) { res = hidapi_thread_cond_timedwait(&dev->thread_state, &ts); if (res == 0) { if (dev->input_reports) { bytes_read = return_data(dev, data, length); break; } /* If we're here, there was a spurious wake up or the read thread was shutdown. Run the loop again (ie: don't break). */ } else if (res == HIDAPI_THREAD_TIMED_OUT) { /* Timed out. */ bytes_read = 0; break; } else { /* Error. */ bytes_read = -1; break; } } } else { /* Purely non-blocking */ bytes_read = 0; } ret: hidapi_thread_mutex_unlock(&dev->thread_state); hidapi_thread_cleanup_pop(0); return bytes_read; } int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) { return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0); } HID_API_EXPORT const wchar_t * HID_API_CALL hid_read_error(hid_device *dev) { (void)dev; return L"hid_read_error is not implemented yet"; } int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) { dev->blocking = !nonblock; return 0; } int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) { int res = -1; int skipped_report_id = 0; int report_number = data[0]; if (report_number == 0x0) { data++; length--; skipped_report_id = 1; } res = libusb_control_transfer(dev->device_handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, 0x09/*HID set_report*/, (3/*HID feature*/ << 8) | report_number, dev->interface, (unsigned char *)data, length, 1000/*timeout millis*/); if (res < 0) return -1; /* Account for the report ID */ if (skipped_report_id) length++; return (int)length; } int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) { int res = -1; int skipped_report_id = 0; int report_number = data[0]; if (report_number == 0x0) { /* Offset the return buffer by 1, so that the report ID will remain in byte 0. */ data++; length--; skipped_report_id = 1; } res = libusb_control_transfer(dev->device_handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN, 0x01/*HID get_report*/, (3/*HID feature*/ << 8) | report_number, dev->interface, (unsigned char *)data, length, 1000/*timeout millis*/); if (res < 0) return -1; if (skipped_report_id) res++; return res; } int HID_API_EXPORT hid_send_output_report(hid_device *dev, const unsigned char *data, size_t length) { int res = -1; int skipped_report_id = 0; int report_number = data[0]; if (report_number == 0x0) { data++; length--; skipped_report_id = 1; } res = libusb_control_transfer(dev->device_handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, 0x09/*HID set_report*/, (2/*HID output*/ << 8) | report_number, dev->interface, (unsigned char *)data, length, 1000/*timeout millis*/); if (res < 0) return -1; /* Account for the report ID */ if (skipped_report_id) length++; return length; } int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) { int res = -1; int skipped_report_id = 0; int report_number = data[0]; if (report_number == 0x0) { /* Offset the return buffer by 1, so that the report ID will remain in byte 0. */ data++; length--; skipped_report_id = 1; } res = libusb_control_transfer(dev->device_handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN, 0x01/*HID get_report*/, (1/*HID Input*/ << 8) | report_number, dev->interface, (unsigned char *)data, length, 1000/*timeout millis*/); if (res < 0) return -1; if (skipped_report_id) res++; return res; } void HID_API_EXPORT hid_close(hid_device *dev) { if (!dev) return; /* Cause read_thread() to stop. */ dev->shutdown_thread = 1; libusb_cancel_transfer(dev->transfer); /* Wait for read_thread() to end. */ hidapi_thread_join(&dev->thread_state); /* Clean up the Transfer objects allocated in read_thread(). */ free(dev->transfer->buffer); dev->transfer->buffer = NULL; libusb_free_transfer(dev->transfer); /* release the interface */ libusb_release_interface(dev->device_handle, dev->interface); /* reattach the kernel driver if it was detached */ #ifdef DETACH_KERNEL_DRIVER if (dev->is_driver_detached) { int res = libusb_attach_kernel_driver(dev->device_handle, dev->interface); if (res < 0) LOG("Failed to reattach the driver to kernel.\n"); } #endif /* Close the handle */ libusb_close(dev->device_handle); /* Clear out the queue of received reports. */ hidapi_thread_mutex_lock(&dev->thread_state); while (dev->input_reports) { return_data(dev, NULL, 0); } hidapi_thread_mutex_unlock(&dev->thread_state); free_hid_device(dev); } int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) { return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen); } int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) { return hid_get_indexed_string(dev, dev->product_index, string, maxlen); } int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) { return hid_get_indexed_string(dev, dev->serial_index, string, maxlen); } HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) { if (!dev->device_info) { struct libusb_device_descriptor desc; libusb_device *usb_device = libusb_get_device(dev->device_handle); libusb_get_device_descriptor(usb_device, &desc); dev->device_info = create_device_info_for_device(usb_device, dev->device_handle, &desc, dev->config_number, dev->interface); // device error already set by create_device_info_for_device, if any if (dev->device_info) { fill_device_info_usage(dev->device_info, dev->device_handle, dev->interface, dev->report_descriptor_size); } } return dev->device_info; } int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { wchar_t *str; str = get_usb_string(dev->device_handle, string_index); if (str) { wcsncpy(string, str, maxlen); string[maxlen-1] = L'\0'; free(str); return 0; } else return -1; } int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) { return hid_get_report_descriptor_libusb(dev->device_handle, dev->interface, dev->report_descriptor_size, buf, buf_size); } HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) { (void)dev; return L"hid_error is not implemented yet"; } struct lang_map_entry { const char *name; const char *string_code; uint16_t usb_code; }; #define LANG(name,code,usb_code) { name, code, usb_code } static struct lang_map_entry lang_map[] = { LANG("Afrikaans", "af", 0x0436), LANG("Albanian", "sq", 0x041C), LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801), LANG("Arabic - Bahrain", "ar_bh", 0x3C01), LANG("Arabic - Algeria", "ar_dz", 0x1401), LANG("Arabic - Egypt", "ar_eg", 0x0C01), LANG("Arabic - Iraq", "ar_iq", 0x0801), LANG("Arabic - Jordan", "ar_jo", 0x2C01), LANG("Arabic - Kuwait", "ar_kw", 0x3401), LANG("Arabic - Lebanon", "ar_lb", 0x3001), LANG("Arabic - Libya", "ar_ly", 0x1001), LANG("Arabic - Morocco", "ar_ma", 0x1801), LANG("Arabic - Oman", "ar_om", 0x2001), LANG("Arabic - Qatar", "ar_qa", 0x4001), LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401), LANG("Arabic - Syria", "ar_sy", 0x2801), LANG("Arabic - Tunisia", "ar_tn", 0x1C01), LANG("Arabic - Yemen", "ar_ye", 0x2401), LANG("Armenian", "hy", 0x042B), LANG("Azeri - Latin", "az_az", 0x042C), LANG("Azeri - Cyrillic", "az_az", 0x082C), LANG("Basque", "eu", 0x042D), LANG("Belarusian", "be", 0x0423), LANG("Bulgarian", "bg", 0x0402), LANG("Catalan", "ca", 0x0403), LANG("Chinese - China", "zh_cn", 0x0804), LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04), LANG("Chinese - Macau SAR", "zh_mo", 0x1404), LANG("Chinese - Singapore", "zh_sg", 0x1004), LANG("Chinese - Taiwan", "zh_tw", 0x0404), LANG("Croatian", "hr", 0x041A), LANG("Czech", "cs", 0x0405), LANG("Danish", "da", 0x0406), LANG("Dutch - Netherlands", "nl_nl", 0x0413), LANG("Dutch - Belgium", "nl_be", 0x0813), LANG("English - Australia", "en_au", 0x0C09), LANG("English - Belize", "en_bz", 0x2809), LANG("English - Canada", "en_ca", 0x1009), LANG("English - Caribbean", "en_cb", 0x2409), LANG("English - Ireland", "en_ie", 0x1809), LANG("English - Jamaica", "en_jm", 0x2009), LANG("English - New Zealand", "en_nz", 0x1409), LANG("English - Philippines", "en_ph", 0x3409), LANG("English - Southern Africa", "en_za", 0x1C09), LANG("English - Trinidad", "en_tt", 0x2C09), LANG("English - Great Britain", "en_gb", 0x0809), LANG("English - United States", "en_us", 0x0409), LANG("Estonian", "et", 0x0425), LANG("Farsi", "fa", 0x0429), LANG("Finnish", "fi", 0x040B), LANG("Faroese", "fo", 0x0438), LANG("French - France", "fr_fr", 0x040C), LANG("French - Belgium", "fr_be", 0x080C), LANG("French - Canada", "fr_ca", 0x0C0C), LANG("French - Luxembourg", "fr_lu", 0x140C), LANG("French - Switzerland", "fr_ch", 0x100C), LANG("Gaelic - Ireland", "gd_ie", 0x083C), LANG("Gaelic - Scotland", "gd", 0x043C), LANG("German - Germany", "de_de", 0x0407), LANG("German - Austria", "de_at", 0x0C07), LANG("German - Liechtenstein", "de_li", 0x1407), LANG("German - Luxembourg", "de_lu", 0x1007), LANG("German - Switzerland", "de_ch", 0x0807), LANG("Greek", "el", 0x0408), LANG("Hebrew", "he", 0x040D), LANG("Hindi", "hi", 0x0439), LANG("Hungarian", "hu", 0x040E), LANG("Icelandic", "is", 0x040F), LANG("Indonesian", "id", 0x0421), LANG("Italian - Italy", "it_it", 0x0410), LANG("Italian - Switzerland", "it_ch", 0x0810), LANG("Japanese", "ja", 0x0411), LANG("Korean", "ko", 0x0412), LANG("Latvian", "lv", 0x0426), LANG("Lithuanian", "lt", 0x0427), LANG("F.Y.R.O. Macedonia", "mk", 0x042F), LANG("Malay - Malaysia", "ms_my", 0x043E), LANG("Malay – Brunei", "ms_bn", 0x083E), LANG("Maltese", "mt", 0x043A), LANG("Marathi", "mr", 0x044E), LANG("Norwegian - Bokml", "no_no", 0x0414), LANG("Norwegian - Nynorsk", "no_no", 0x0814), LANG("Polish", "pl", 0x0415), LANG("Portuguese - Portugal", "pt_pt", 0x0816), LANG("Portuguese - Brazil", "pt_br", 0x0416), LANG("Raeto-Romance", "rm", 0x0417), LANG("Romanian - Romania", "ro", 0x0418), LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818), LANG("Russian", "ru", 0x0419), LANG("Russian - Republic of Moldova", "ru_mo", 0x0819), LANG("Sanskrit", "sa", 0x044F), LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A), LANG("Serbian - Latin", "sr_sp", 0x081A), LANG("Setsuana", "tn", 0x0432), LANG("Slovenian", "sl", 0x0424), LANG("Slovak", "sk", 0x041B), LANG("Sorbian", "sb", 0x042E), LANG("Spanish - Spain (Traditional)", "es_es", 0x040A), LANG("Spanish - Argentina", "es_ar", 0x2C0A), LANG("Spanish - Bolivia", "es_bo", 0x400A), LANG("Spanish - Chile", "es_cl", 0x340A), LANG("Spanish - Colombia", "es_co", 0x240A), LANG("Spanish - Costa Rica", "es_cr", 0x140A), LANG("Spanish - Dominican Republic", "es_do", 0x1C0A), LANG("Spanish - Ecuador", "es_ec", 0x300A), LANG("Spanish - Guatemala", "es_gt", 0x100A), LANG("Spanish - Honduras", "es_hn", 0x480A), LANG("Spanish - Mexico", "es_mx", 0x080A), LANG("Spanish - Nicaragua", "es_ni", 0x4C0A), LANG("Spanish - Panama", "es_pa", 0x180A), LANG("Spanish - Peru", "es_pe", 0x280A), LANG("Spanish - Puerto Rico", "es_pr", 0x500A), LANG("Spanish - Paraguay", "es_py", 0x3C0A), LANG("Spanish - El Salvador", "es_sv", 0x440A), LANG("Spanish - Uruguay", "es_uy", 0x380A), LANG("Spanish - Venezuela", "es_ve", 0x200A), LANG("Southern Sotho", "st", 0x0430), LANG("Swahili", "sw", 0x0441), LANG("Swedish - Sweden", "sv_se", 0x041D), LANG("Swedish - Finland", "sv_fi", 0x081D), LANG("Tamil", "ta", 0x0449), LANG("Tatar", "tt", 0X0444), LANG("Thai", "th", 0x041E), LANG("Turkish", "tr", 0x041F), LANG("Tsonga", "ts", 0x0431), LANG("Ukrainian", "uk", 0x0422), LANG("Urdu", "ur", 0x0420), LANG("Uzbek - Cyrillic", "uz_uz", 0x0843), LANG("Uzbek – Latin", "uz_uz", 0x0443), LANG("Vietnamese", "vi", 0x042A), LANG("Xhosa", "xh", 0x0434), LANG("Yiddish", "yi", 0x043D), LANG("Zulu", "zu", 0x0435), LANG(NULL, NULL, 0x0), }; uint16_t get_usb_code_for_current_locale(void) { char *locale; char search_string[64]; char *ptr; struct lang_map_entry *lang; /* Get the current locale. */ locale = setlocale(0, NULL); if (!locale) return 0x0; /* Make a copy of the current locale string. */ strncpy(search_string, locale, sizeof(search_string)-1); search_string[sizeof(search_string)-1] = '\0'; /* Chop off the encoding part, and make it lower case. */ ptr = search_string; while (*ptr) { *ptr = tolower(*ptr); if (*ptr == '.') { *ptr = '\0'; break; } ptr++; } /* Find the entry which matches the string code of our locale. */ lang = lang_map; while (lang->string_code) { if (!strcmp(lang->string_code, search_string)) { return lang->usb_code; } lang++; } /* There was no match. Find with just the language only. */ /* Chop off the variant. Chop it off at the '_'. */ ptr = search_string; while (*ptr) { *ptr = tolower(*ptr); if (*ptr == '_') { *ptr = '\0'; break; } ptr++; } #if 0 /* TODO: Do we need this? */ /* Find the entry which matches the string code of our language. */ lang = lang_map; while (lang->string_code) { if (!strcmp(lang->string_code, search_string)) { return lang->usb_code; } lang++; } #endif /* Found nothing. */ return 0x0; } #ifdef __cplusplus } #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216765.0 hidapi-0.15.0/hidapi/libusb/hidapi_libusb.h0000644000076500000240000000321315115610775017567 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2021, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /** @file * @defgroup API hidapi API * Since version 0.11.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 11, 0). */ #ifndef HIDAPI_LIBUSB_H__ #define HIDAPI_LIBUSB_H__ #include #include "hidapi.h" #ifdef __cplusplus extern "C" { #endif /** @brief Open a HID device using libusb_wrap_sys_device. See https://libusb.sourceforge.io/api-1.0/group__libusb__dev.html#ga98f783e115ceff4eaf88a60e6439563c, for details on libusb_wrap_sys_device. @ingroup API @param sys_dev Platform-specific file descriptor that can be recognised by libusb. @param interface_num USB interface number of the device to be used as HID interface. Pass -1 to select first HID interface of the device. @returns This function returns a pointer to a #hid_device object on success or NULL on failure. */ HID_API_EXPORT hid_device * HID_API_CALL hid_libusb_wrap_sys_device(intptr_t sys_dev, int interface_num); #ifdef __cplusplus } #endif #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/libusb/hidapi_thread_pthread.h0000644000076500000240000001056315115611013021255 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software libusb/hidapi Team Sam Lantinga Copyright 2023, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #include #if defined(__ANDROID__) && __ANDROID_API__ < __ANDROID_API_N__ /* Barrier implementation because Android/Bionic don't have pthread_barrier. This implementation came from Brent Priddy and was posted on StackOverflow. It is used with his permission. */ typedef int pthread_barrierattr_t; typedef struct pthread_barrier { pthread_mutex_t mutex; pthread_cond_t cond; int count; int trip_count; } pthread_barrier_t; static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) { if(count == 0) { errno = EINVAL; return -1; } if(pthread_mutex_init(&barrier->mutex, 0) < 0) { return -1; } if(pthread_cond_init(&barrier->cond, 0) < 0) { pthread_mutex_destroy(&barrier->mutex); return -1; } barrier->trip_count = count; barrier->count = 0; return 0; } static int pthread_barrier_destroy(pthread_barrier_t *barrier) { pthread_cond_destroy(&barrier->cond); pthread_mutex_destroy(&barrier->mutex); return 0; } static int pthread_barrier_wait(pthread_barrier_t *barrier) { pthread_mutex_lock(&barrier->mutex); ++(barrier->count); if(barrier->count >= barrier->trip_count) { barrier->count = 0; pthread_cond_broadcast(&barrier->cond); pthread_mutex_unlock(&barrier->mutex); return 1; } else { pthread_cond_wait(&barrier->cond, &(barrier->mutex)); pthread_mutex_unlock(&barrier->mutex); return 0; } } #endif #define HIDAPI_THREAD_TIMED_OUT ETIMEDOUT typedef struct timespec hidapi_timespec; typedef struct { pthread_t thread; pthread_mutex_t mutex; /* Protects input_reports */ pthread_cond_t condition; pthread_barrier_t barrier; /* Ensures correct startup sequence */ } hidapi_thread_state; static void hidapi_thread_state_init(hidapi_thread_state *state) { pthread_mutex_init(&state->mutex, NULL); pthread_cond_init(&state->condition, NULL); pthread_barrier_init(&state->barrier, NULL, 2); } static void hidapi_thread_state_destroy(hidapi_thread_state *state) { pthread_barrier_destroy(&state->barrier); pthread_cond_destroy(&state->condition); pthread_mutex_destroy(&state->mutex); } #define hidapi_thread_cleanup_push pthread_cleanup_push #define hidapi_thread_cleanup_pop pthread_cleanup_pop static void hidapi_thread_mutex_lock(hidapi_thread_state *state) { pthread_mutex_lock(&state->mutex); } static void hidapi_thread_mutex_unlock(hidapi_thread_state *state) { pthread_mutex_unlock(&state->mutex); } static void hidapi_thread_cond_wait(hidapi_thread_state *state) { pthread_cond_wait(&state->condition, &state->mutex); } static int hidapi_thread_cond_timedwait(hidapi_thread_state *state, hidapi_timespec *ts) { return pthread_cond_timedwait(&state->condition, &state->mutex, ts); } static void hidapi_thread_cond_signal(hidapi_thread_state *state) { pthread_cond_signal(&state->condition); } static void hidapi_thread_cond_broadcast(hidapi_thread_state *state) { pthread_cond_broadcast(&state->condition); } static void hidapi_thread_barrier_wait(hidapi_thread_state *state) { pthread_barrier_wait(&state->barrier); } static void hidapi_thread_create(hidapi_thread_state *state, void *(*func)(void*), void *func_arg) { pthread_create(&state->thread, NULL, func, func_arg); } static void hidapi_thread_join(hidapi_thread_state *state) { pthread_join(state->thread, NULL); } static void hidapi_thread_gettime(hidapi_timespec *ts) { clock_gettime(CLOCK_REALTIME, ts); } static void hidapi_thread_addtime(hidapi_timespec *ts, int milliseconds) { ts->tv_sec += milliseconds / 1000; ts->tv_nsec += (milliseconds % 1000) * 1000000; if (ts->tv_nsec >= 1000000000L) { ts->tv_sec++; ts->tv_nsec -= 1000000000L; } } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0656502 hidapi-0.15.0/hidapi/linux/0000755000076500000240000000000015115770112014470 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/linux/hid.c0000644000076500000240000011172115115611013015375 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /* C */ #include #include #include #include #include /* Unix */ #include #include #include #include #include #include #include /* Linux */ #include #include #include #include #include "hidapi.h" #ifdef HIDAPI_ALLOW_BUILD_WORKAROUND_KERNEL_2_6_39 /* This definitions first appeared in Linux Kernel 2.6.39 in linux/hidraw.h. hidapi doesn't support kernels older than that, so we don't define macros below explicitly, to fail builds on old kernels. For those who really need this as a workaround (e.g. to be able to build on old build machines), can workaround by defining the macro above. */ #ifndef HIDIOCSFEATURE #define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len) #endif #ifndef HIDIOCGFEATURE #define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len) #endif #endif // HIDIOCGINPUT and HIDIOCSOUTPUT are not defined in Linux kernel headers < 5.11. // These definitions are from hidraw.h in Linux >= 5.11. // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f43d3870cafa2a0f3854c1819c8385733db8f9ae #ifndef HIDIOCGINPUT #define HIDIOCGINPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0A, len) #endif #ifndef HIDIOCSOUTPUT #define HIDIOCSOUTPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0B, len) #endif struct hid_device_ { int device_handle; int blocking; wchar_t *last_error_str; wchar_t *last_read_error_str; struct hid_device_info* device_info; }; static struct hid_api_version api_version = { .major = HID_API_VERSION_MAJOR, .minor = HID_API_VERSION_MINOR, .patch = HID_API_VERSION_PATCH }; static wchar_t *last_global_error_str = NULL; static hid_device *new_hid_device(void) { hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); if (dev == NULL) { return NULL; } dev->device_handle = -1; dev->blocking = 1; dev->last_error_str = NULL; dev->last_read_error_str = NULL; dev->device_info = NULL; return dev; } /* The caller must free the returned string with free(). */ static wchar_t *utf8_to_wchar_t(const char *utf8) { wchar_t *ret = NULL; if (utf8) { size_t wlen = mbstowcs(NULL, utf8, 0); if ((size_t) -1 == wlen) { return wcsdup(L""); } ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t)); if (ret == NULL) { /* as much as we can do at this point */ return NULL; } mbstowcs(ret, utf8, wlen+1); ret[wlen] = 0x0000; } return ret; } /* Makes a copy of the given error message (and decoded according to the * currently locale) into the wide string pointer pointed by error_str. * The last stored error string is freed. * Use register_error_str(NULL) to free the error message completely. */ static void register_error_str(wchar_t **error_str, const char *msg) { free(*error_str); *error_str = utf8_to_wchar_t(msg); } /* Semilar to register_error_str, but allows passing a format string with va_list args into this function. */ static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args) { char msg[256]; vsnprintf(msg, sizeof(msg), format, args); register_error_str(error_str, msg); } /* Set the last global error to be reported by hid_error(NULL). * The given error message will be copied (and decoded according to the * currently locale, so do not pass in string constants). * The last stored global error message is freed. * Use register_global_error(NULL) to indicate "no error". */ static void register_global_error(const char *msg) { register_error_str(&last_global_error_str, msg); } /* Similar to register_global_error, but allows passing a format string into this function. */ static void register_global_error_format(const char *format, ...) { va_list args; va_start(args, format); register_error_str_vformat(&last_global_error_str, format, args); va_end(args); } /* Set the last error for a device to be reported by hid_error(dev). * The given error message will be copied (and decoded according to the * currently locale, so do not pass in string constants). * The last stored device error message is freed. * Use register_device_error(dev, NULL) to indicate "no error". */ static void register_device_error(hid_device *dev, const char *msg) { register_error_str(&dev->last_error_str, msg); } /* Similar to register_device_error, but you can pass a format string into this function. */ static void register_device_error_format(hid_device *dev, const char *format, ...) { va_list args; va_start(args, format); register_error_str_vformat(&dev->last_error_str, format, args); va_end(args); } /* Get an attribute value from a udev_device and return it as a whar_t string. The returned string must be freed with free() when done.*/ static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name) { return utf8_to_wchar_t(udev_device_get_sysattr_value(dev, udev_name)); } /* * Gets the size of the HID item at the given position * Returns 1 if successful, 0 if an invalid key * Sets data_len and key_size when successful */ static int get_hid_item_size(const __u8 *report_descriptor, __u32 size, unsigned int pos, int *data_len, int *key_size) { int key = report_descriptor[pos]; int size_code; /* * This is a Long Item. The next byte contains the * length of the data section (value) for this key. * See the HID specification, version 1.11, section * 6.2.2.3, titled "Long Items." */ if ((key & 0xf0) == 0xf0) { if (pos + 1 < size) { *data_len = report_descriptor[pos + 1]; *key_size = 3; return 1; } *data_len = 0; /* malformed report */ *key_size = 0; } /* * This is a Short Item. The bottom two bits of the * key contain the size code for the data section * (value) for this key. Refer to the HID * specification, version 1.11, section 6.2.2.2, * titled "Short Items." */ size_code = key & 0x3; switch (size_code) { case 0: case 1: case 2: *data_len = size_code; *key_size = 1; return 1; case 3: *data_len = 4; *key_size = 1; return 1; default: /* Can't ever happen since size_code is & 0x3 */ *data_len = 0; *key_size = 0; break; }; /* malformed report */ return 0; } /* * Get bytes from a HID Report Descriptor. * Only call with a num_bytes of 0, 1, 2, or 4. */ static __u32 get_hid_report_bytes(const __u8 *rpt, size_t len, size_t num_bytes, size_t cur) { /* Return if there aren't enough bytes. */ if (cur + num_bytes >= len) return 0; if (num_bytes == 0) return 0; else if (num_bytes == 1) return rpt[cur + 1]; else if (num_bytes == 2) return (rpt[cur + 2] * 256 + rpt[cur + 1]); else if (num_bytes == 4) return ( rpt[cur + 4] * 0x01000000 + rpt[cur + 3] * 0x00010000 + rpt[cur + 2] * 0x00000100 + rpt[cur + 1] * 0x00000001 ); else return 0; } /* * Iterates until the end of a Collection. * Assumes that *pos is exactly at the beginning of a Collection. * Skips all nested Collection, i.e. iterates until the end of current level Collection. * * The return value is non-0 when an end of current Collection is found, * 0 when error is occured (broken Descriptor, end of a Collection is found before its begin, * or no Collection is found at all). */ static int hid_iterate_over_collection(const __u8 *report_descriptor, __u32 size, unsigned int *pos, int *data_len, int *key_size) { int collection_level = 0; while (*pos < size) { int key = report_descriptor[*pos]; int key_cmd = key & 0xfc; /* Determine data_len and key_size */ if (!get_hid_item_size(report_descriptor, size, *pos, data_len, key_size)) return 0; /* malformed report */ switch (key_cmd) { case 0xa0: /* Collection 6.2.2.4 (Main) */ collection_level++; break; case 0xc0: /* End Collection 6.2.2.4 (Main) */ collection_level--; break; } if (collection_level < 0) { /* Broken descriptor or someone is using this function wrong, * i.e. should be called exactly at the collection start */ return 0; } if (collection_level == 0) { /* Found it! * Also possible when called not at the collection start, but should not happen if used correctly */ return 1; } *pos += *data_len + *key_size; } return 0; /* Did not find the end of a Collection */ } struct hid_usage_iterator { unsigned int pos; int usage_page_found; unsigned short usage_page; }; /* * Retrieves the device's Usage Page and Usage from the report descriptor. * The algorithm returns the current Usage Page/Usage pair whenever a new * Collection is found and a Usage Local Item is currently in scope. * Usage Local Items are consumed by each Main Item (See. 6.2.2.8). * The algorithm should give similar results as Apple's: * https://developer.apple.com/documentation/iokit/kiohiddeviceusagepairskey?language=objc * Physical Collections are also matched (macOS does the same). * * This function can be called repeatedly until it returns non-0 * Usage is found. pos is the starting point (initially 0) and will be updated * to the next search position. * * The return value is 0 when a pair is found. * 1 when finished processing descriptor. * -1 on a malformed report. */ static int get_next_hid_usage(const __u8 *report_descriptor, __u32 size, struct hid_usage_iterator *ctx, unsigned short *usage_page, unsigned short *usage) { int data_len, key_size; int initial = ctx->pos == 0; /* Used to handle case where no top-level application collection is defined */ int usage_found = 0; while (ctx->pos < size) { int key = report_descriptor[ctx->pos]; int key_cmd = key & 0xfc; /* Determine data_len and key_size */ if (!get_hid_item_size(report_descriptor, size, ctx->pos, &data_len, &key_size)) return -1; /* malformed report */ switch (key_cmd) { case 0x4: /* Usage Page 6.2.2.7 (Global) */ ctx->usage_page = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos); ctx->usage_page_found = 1; break; case 0x8: /* Usage 6.2.2.8 (Local) */ if (data_len == 4) { /* Usages 5.5 / Usage Page 6.2.2.7 */ ctx->usage_page = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos + 2); ctx->usage_page_found = 1; *usage = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos); usage_found = 1; } else { *usage = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos); usage_found = 1; } break; case 0xa0: /* Collection 6.2.2.4 (Main) */ if (!hid_iterate_over_collection(report_descriptor, size, &ctx->pos, &data_len, &key_size)) { return -1; } /* A pair is valid - to be reported when Collection is found */ if (usage_found && ctx->usage_page_found) { *usage_page = ctx->usage_page; return 0; } break; } /* Skip over this key and its associated data */ ctx->pos += data_len + key_size; } /* If no top-level application collection is found and usage page/usage pair is found, pair is valid https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections */ if (initial && usage_found && ctx->usage_page_found) { *usage_page = ctx->usage_page; return 0; /* success */ } return 1; /* finished processing */ } /* * Retrieves the hidraw report descriptor from a file. * When using this form, /device/report_descriptor, elevated privileges are not required. */ static int get_hid_report_descriptor(const char *rpt_path, struct hidraw_report_descriptor *rpt_desc) { int rpt_handle; ssize_t res; rpt_handle = open(rpt_path, O_RDONLY | O_CLOEXEC); if (rpt_handle < 0) { register_global_error_format("open failed (%s): %s", rpt_path, strerror(errno)); return -1; } /* * Read in the Report Descriptor * The sysfs file has a maximum size of 4096 (which is the same as HID_MAX_DESCRIPTOR_SIZE) so we should always * be ok when reading the descriptor. * In practice if the HID descriptor is any larger I suspect many other things will break. */ memset(rpt_desc, 0x0, sizeof(*rpt_desc)); res = read(rpt_handle, rpt_desc->value, HID_MAX_DESCRIPTOR_SIZE); if (res < 0) { register_global_error_format("read failed (%s): %s", rpt_path, strerror(errno)); } rpt_desc->size = (__u32) res; close(rpt_handle); return (int) res; } /* return size of the descriptor, or -1 on failure */ static int get_hid_report_descriptor_from_sysfs(const char *sysfs_path, struct hidraw_report_descriptor *rpt_desc) { int res = -1; /* Construct /device/report_descriptor */ size_t rpt_path_len = strlen(sysfs_path) + 25 + 1; char* rpt_path = (char*) calloc(1, rpt_path_len); if (!rpt_path) return -1; snprintf(rpt_path, rpt_path_len, "%s/device/report_descriptor", sysfs_path); res = get_hid_report_descriptor(rpt_path, rpt_desc); free(rpt_path); return res; } /* return non-zero if successfully parsed */ static int parse_hid_vid_pid_from_uevent(const char *uevent, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id) { char tmp[1024]; size_t uevent_len = strlen(uevent); if (uevent_len > sizeof(tmp) - 1) uevent_len = sizeof(tmp) - 1; memcpy(tmp, uevent, uevent_len); tmp[uevent_len] = '\0'; char *saveptr = NULL; char *line; char *key; char *value; line = strtok_r(tmp, "\n", &saveptr); while (line != NULL) { /* line: "KEY=value" */ key = line; value = strchr(line, '='); if (!value) { goto next_line; } *value = '\0'; value++; if (strcmp(key, "HID_ID") == 0) { /** * type vendor product * HID_ID=0003:000005AC:00008242 **/ int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id); if (ret == 3) { return 1; } } next_line: line = strtok_r(NULL, "\n", &saveptr); } register_global_error("Couldn't find/parse HID_ID"); return 0; } /* return non-zero if successfully parsed */ static int parse_hid_vid_pid_from_uevent_path(const char *uevent_path, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id) { int handle; ssize_t res; handle = open(uevent_path, O_RDONLY | O_CLOEXEC); if (handle < 0) { register_global_error_format("open failed (%s): %s", uevent_path, strerror(errno)); return 0; } char buf[1024]; res = read(handle, buf, sizeof(buf) - 1); /* -1 for '\0' at the end */ close(handle); if (res < 0) { register_global_error_format("read failed (%s): %s", uevent_path, strerror(errno)); return 0; } buf[res] = '\0'; return parse_hid_vid_pid_from_uevent(buf, bus_type, vendor_id, product_id); } /* return non-zero if successfully read/parsed */ static int parse_hid_vid_pid_from_sysfs(const char *sysfs_path, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id) { int res = 0; /* Construct /device/uevent */ size_t uevent_path_len = strlen(sysfs_path) + 14 + 1; char* uevent_path = (char*) calloc(1, uevent_path_len); snprintf(uevent_path, uevent_path_len, "%s/device/uevent", sysfs_path); res = parse_hid_vid_pid_from_uevent_path(uevent_path, bus_type, vendor_id, product_id); free(uevent_path); return res; } static int get_hid_report_descriptor_from_hidraw(hid_device *dev, struct hidraw_report_descriptor *rpt_desc) { int desc_size = 0; /* Get Report Descriptor Size */ int res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size); if (res < 0) { register_device_error_format(dev, "ioctl(GRDESCSIZE): %s", strerror(errno)); return res; } /* Get Report Descriptor */ memset(rpt_desc, 0x0, sizeof(*rpt_desc)); rpt_desc->size = desc_size; res = ioctl(dev->device_handle, HIDIOCGRDESC, rpt_desc); if (res < 0) { register_device_error_format(dev, "ioctl(GRDESC): %s", strerror(errno)); } return res; } /* * The caller is responsible for free()ing the (newly-allocated) character * strings pointed to by serial_number_utf8 and product_name_utf8 after use. */ static int parse_uevent_info(const char *uevent, unsigned *bus_type, unsigned short *vendor_id, unsigned short *product_id, char **serial_number_utf8, char **product_name_utf8) { char tmp[1024]; if (!uevent) { return 0; } size_t uevent_len = strlen(uevent); if (uevent_len > sizeof(tmp) - 1) uevent_len = sizeof(tmp) - 1; memcpy(tmp, uevent, uevent_len); tmp[uevent_len] = '\0'; char *saveptr = NULL; char *line; char *key; char *value; int found_id = 0; int found_serial = 0; int found_name = 0; line = strtok_r(tmp, "\n", &saveptr); while (line != NULL) { /* line: "KEY=value" */ key = line; value = strchr(line, '='); if (!value) { goto next_line; } *value = '\0'; value++; if (strcmp(key, "HID_ID") == 0) { /** * type vendor product * HID_ID=0003:000005AC:00008242 **/ int ret = sscanf(value, "%x:%hx:%hx", bus_type, vendor_id, product_id); if (ret == 3) { found_id = 1; } } else if (strcmp(key, "HID_NAME") == 0) { /* The caller has to free the product name */ *product_name_utf8 = strdup(value); found_name = 1; } else if (strcmp(key, "HID_UNIQ") == 0) { /* The caller has to free the serial number */ *serial_number_utf8 = strdup(value); found_serial = 1; } next_line: line = strtok_r(NULL, "\n", &saveptr); } return (found_id && found_name && found_serial); } static struct hid_device_info * create_device_info_for_device(struct udev_device *raw_dev) { struct hid_device_info *root = NULL; struct hid_device_info *cur_dev = NULL; const char *sysfs_path; const char *dev_path; const char *str; struct udev_device *hid_dev; /* The device's HID udev node. */ struct udev_device *usb_dev; /* The device's USB udev node. */ struct udev_device *intf_dev; /* The device's interface (in the USB sense). */ unsigned short dev_vid; unsigned short dev_pid; char *serial_number_utf8 = NULL; char *product_name_utf8 = NULL; unsigned bus_type; int result; struct hidraw_report_descriptor report_desc; sysfs_path = udev_device_get_syspath(raw_dev); dev_path = udev_device_get_devnode(raw_dev); hid_dev = udev_device_get_parent_with_subsystem_devtype( raw_dev, "hid", NULL); if (!hid_dev) { /* Unable to find parent hid device. */ goto end; } result = parse_uevent_info( udev_device_get_sysattr_value(hid_dev, "uevent"), &bus_type, &dev_vid, &dev_pid, &serial_number_utf8, &product_name_utf8); if (!result) { /* parse_uevent_info() failed for at least one field. */ goto end; } /* Filter out unhandled devices right away */ switch (bus_type) { case BUS_BLUETOOTH: case BUS_I2C: case BUS_USB: case BUS_SPI: break; default: goto end; } /* Create the record. */ root = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); if (!root) goto end; cur_dev = root; /* Fill out the record */ cur_dev->next = NULL; cur_dev->path = dev_path? strdup(dev_path): NULL; /* VID/PID */ cur_dev->vendor_id = dev_vid; cur_dev->product_id = dev_pid; /* Serial Number */ cur_dev->serial_number = utf8_to_wchar_t(serial_number_utf8); /* Release Number */ cur_dev->release_number = 0x0; /* Interface Number */ cur_dev->interface_number = -1; switch (bus_type) { case BUS_USB: /* The device pointed to by raw_dev contains information about the hidraw device. In order to get information about the USB device, get the parent device with the subsystem/devtype pair of "usb"/"usb_device". This will be several levels up the tree, but the function will find it. */ usb_dev = udev_device_get_parent_with_subsystem_devtype( raw_dev, "usb", "usb_device"); /* uhid USB devices * Since this is a virtual hid interface, no USB information will * be available. */ if (!usb_dev) { /* Manufacturer and Product strings */ cur_dev->manufacturer_string = wcsdup(L""); cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); break; } cur_dev->manufacturer_string = copy_udev_string(usb_dev, "manufacturer"); cur_dev->product_string = copy_udev_string(usb_dev, "product"); cur_dev->bus_type = HID_API_BUS_USB; str = udev_device_get_sysattr_value(usb_dev, "bcdDevice"); cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0; /* Get a handle to the interface's udev node. */ intf_dev = udev_device_get_parent_with_subsystem_devtype( raw_dev, "usb", "usb_interface"); if (intf_dev) { str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber"); cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1; } break; case BUS_BLUETOOTH: cur_dev->manufacturer_string = wcsdup(L""); cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); cur_dev->bus_type = HID_API_BUS_BLUETOOTH; break; case BUS_I2C: cur_dev->manufacturer_string = wcsdup(L""); cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); cur_dev->bus_type = HID_API_BUS_I2C; break; case BUS_SPI: cur_dev->manufacturer_string = wcsdup(L""); cur_dev->product_string = utf8_to_wchar_t(product_name_utf8); cur_dev->bus_type = HID_API_BUS_SPI; break; default: /* Unknown device type - this should never happen, as we * check for USB and Bluetooth devices above */ break; } /* Usage Page and Usage */ if (sysfs_path) { result = get_hid_report_descriptor_from_sysfs(sysfs_path, &report_desc); } else { result = -1; } if (result >= 0) { unsigned short page = 0, usage = 0; struct hid_usage_iterator usage_iterator; memset(&usage_iterator, 0, sizeof(usage_iterator)); /* * Parse the first usage and usage page * out of the report descriptor. */ if (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) { cur_dev->usage_page = page; cur_dev->usage = usage; } /* * Parse any additional usage and usage pages * out of the report descriptor. */ while (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) { /* Create new record for additional usage pairs */ struct hid_device_info *tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); struct hid_device_info *prev_dev = cur_dev; if (!tmp) break; cur_dev->next = tmp; cur_dev = tmp; /* Update fields */ cur_dev->path = dev_path? strdup(dev_path): NULL; cur_dev->vendor_id = dev_vid; cur_dev->product_id = dev_pid; cur_dev->serial_number = prev_dev->serial_number? wcsdup(prev_dev->serial_number): NULL; cur_dev->release_number = prev_dev->release_number; cur_dev->interface_number = prev_dev->interface_number; cur_dev->manufacturer_string = prev_dev->manufacturer_string? wcsdup(prev_dev->manufacturer_string): NULL; cur_dev->product_string = prev_dev->product_string? wcsdup(prev_dev->product_string): NULL; cur_dev->usage_page = page; cur_dev->usage = usage; cur_dev->bus_type = prev_dev->bus_type; } } end: free(serial_number_utf8); free(product_name_utf8); return root; } static struct hid_device_info * create_device_info_for_hid_device(hid_device *dev) { struct udev *udev; struct udev_device *udev_dev; struct stat s; int ret = -1; struct hid_device_info *root = NULL; register_device_error(dev, NULL); /* Get the dev_t (major/minor numbers) from the file handle. */ ret = fstat(dev->device_handle, &s); if (-1 == ret) { register_device_error(dev, "Failed to stat device handle"); return NULL; } /* Create the udev object */ udev = udev_new(); if (!udev) { errno = ENOMEM; register_device_error(dev, "Couldn't create udev context"); return NULL; } /* Open a udev device from the dev_t. 'c' means character device. */ udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev); if (udev_dev) { root = create_device_info_for_device(udev_dev); } if (!root) { /* TODO: have a better error reporting via create_device_info_for_device */ errno = EIO; register_device_error(dev, "Couldn't create hid_device_info"); } udev_device_unref(udev_dev); udev_unref(udev); return root; } HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) { return &api_version; } HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) { return HID_API_VERSION_STR; } int HID_API_EXPORT hid_init(void) { const char *locale; /* indicate no error */ register_global_error(NULL); /* Set the locale if it's not set. */ locale = setlocale(LC_CTYPE, NULL); if (!locale) setlocale(LC_CTYPE, ""); return 0; } int HID_API_EXPORT hid_exit(void) { /* Free global error message */ register_global_error(NULL); return 0; } struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) { struct udev *udev; struct udev_enumerate *enumerate; struct udev_list_entry *devices, *dev_list_entry; struct hid_device_info *root = NULL; /* return object */ struct hid_device_info *cur_dev = NULL; hid_init(); /* register_global_error: global error is reset by hid_init */ /* Create the udev object */ udev = udev_new(); if (!udev) { register_global_error("Couldn't create udev context"); return NULL; } /* Create a list of the devices in the 'hidraw' subsystem. */ enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, "hidraw"); udev_enumerate_scan_devices(enumerate); devices = udev_enumerate_get_list_entry(enumerate); /* For each item, see if it matches the vid/pid, and if so create a udev_device record for it */ udev_list_entry_foreach(dev_list_entry, devices) { const char *sysfs_path; unsigned short dev_vid = 0; unsigned short dev_pid = 0; unsigned bus_type = 0; struct udev_device *raw_dev; /* The device's hidraw udev node. */ struct hid_device_info * tmp; /* Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it */ sysfs_path = udev_list_entry_get_name(dev_list_entry); if (!sysfs_path) continue; if (vendor_id != 0 || product_id != 0) { if (!parse_hid_vid_pid_from_sysfs(sysfs_path, &bus_type, &dev_vid, &dev_pid)) continue; if (vendor_id != 0 && vendor_id != dev_vid) continue; if (product_id != 0 && product_id != dev_pid) continue; } raw_dev = udev_device_new_from_syspath(udev, sysfs_path); if (!raw_dev) continue; tmp = create_device_info_for_device(raw_dev); if (tmp) { if (cur_dev) { cur_dev->next = tmp; } else { root = tmp; } cur_dev = tmp; /* move the pointer to the tail of returned list */ while (cur_dev->next != NULL) { cur_dev = cur_dev->next; } } udev_device_unref(raw_dev); } /* Free the enumerator and udev objects. */ udev_enumerate_unref(enumerate); udev_unref(udev); if (root == NULL) { if (vendor_id == 0 && product_id == 0) { register_global_error("No HID devices found in the system."); } else { register_global_error("No HID devices with requested VID/PID found in the system."); } } return root; } void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) { struct hid_device_info *d = devs; while (d) { struct hid_device_info *next = d->next; free(d->path); free(d->serial_number); free(d->manufacturer_string); free(d->product_string); free(d); d = next; } } hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { struct hid_device_info *devs, *cur_dev; const char *path_to_open = NULL; hid_device *handle = NULL; /* register_global_error: global error is reset by hid_enumerate/hid_init */ devs = hid_enumerate(vendor_id, product_id); if (devs == NULL) { /* register_global_error: global error is already set by hid_enumerate */ return NULL; } cur_dev = devs; while (cur_dev) { if (cur_dev->vendor_id == vendor_id && cur_dev->product_id == product_id) { if (serial_number) { if (wcscmp(serial_number, cur_dev->serial_number) == 0) { path_to_open = cur_dev->path; break; } } else { path_to_open = cur_dev->path; break; } } cur_dev = cur_dev->next; } if (path_to_open) { /* Open the device */ handle = hid_open_path(path_to_open); } else { register_global_error("Device with requested VID/PID/(SerialNumber) not found"); } hid_free_enumeration(devs); return handle; } hid_device * HID_API_EXPORT hid_open_path(const char *path) { hid_device *dev = NULL; hid_init(); /* register_global_error: global error is reset by hid_init */ dev = new_hid_device(); if (!dev) { errno = ENOMEM; register_global_error("Couldn't allocate memory"); return NULL; } dev->device_handle = open(path, O_RDWR | O_CLOEXEC); if (dev->device_handle >= 0) { int res, desc_size = 0; /* Make sure this is a HIDRAW device - responds to HIDIOCGRDESCSIZE */ res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size); if (res < 0) { register_global_error_format("ioctl(GRDESCSIZE) error for '%s', not a HIDRAW device?: %s", path, strerror(errno)); hid_close(dev); return NULL; } return dev; } else { /* Unable to open a device. */ free(dev); register_global_error_format("Failed to open a device with path '%s': %s", path, strerror(errno)); return NULL; } } int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) { int bytes_written; if (!data || (length == 0)) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } bytes_written = write(dev->device_handle, data, length); register_device_error(dev, (bytes_written == -1)? strerror(errno): NULL); return bytes_written; } int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) { if (!data || (length == 0)) { errno = EINVAL; register_error_str(&dev->last_read_error_str, "Zero buffer/length"); return -1; } /* Set device error to none */ register_error_str(&dev->last_read_error_str, NULL); int bytes_read; if (milliseconds >= 0) { /* Milliseconds is either 0 (non-blocking) or > 0 (contains a valid timeout). In both cases we want to call poll() and wait for data to arrive. Don't rely on non-blocking operation (O_NONBLOCK) since some kernels don't seem to properly report device disconnection through read() when in non-blocking mode. */ int ret; struct pollfd fds; fds.fd = dev->device_handle; fds.events = POLLIN; fds.revents = 0; ret = poll(&fds, 1, milliseconds); if (ret == 0) { /* Timeout */ return ret; } if (ret == -1) { /* Error */ register_error_str(&dev->last_read_error_str, strerror(errno)); return ret; } else { /* Check for errors on the file descriptor. This will indicate a device disconnection. */ if (fds.revents & (POLLERR | POLLHUP | POLLNVAL)) { // We cannot use strerror() here as no -1 was returned from poll(). errno = EIO; register_error_str(&dev->last_read_error_str, "hid_read_timeout: unexpected poll error (device disconnected)"); return -1; } } } bytes_read = read(dev->device_handle, data, length); if (bytes_read < 0) { if (errno == EAGAIN || errno == EINPROGRESS) bytes_read = 0; else register_error_str(&dev->last_read_error_str, strerror(errno)); } return bytes_read; } int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) { return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); } HID_API_EXPORT const wchar_t * HID_API_CALL hid_read_error(hid_device *dev) { if (dev->last_read_error_str == NULL) return L"Success"; return dev->last_read_error_str; } int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) { /* Do all non-blocking in userspace using poll(), since it looks like there's a bug in the kernel in some versions where read() will not return -1 on disconnection of the USB device */ dev->blocking = !nonblock; return 0; /* Success */ } int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) { int res; if (!data || (length == 0)) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data); if (res < 0) register_device_error_format(dev, "ioctl (SFEATURE): %s", strerror(errno)); return res; } int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) { int res; if (!data || (length == 0)) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data); if (res < 0) register_device_error_format(dev, "ioctl (GFEATURE): %s", strerror(errno)); return res; } int HID_API_EXPORT HID_API_CALL hid_send_output_report(hid_device *dev, const unsigned char *data, size_t length) { int res; if (!data || (length == 0)) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); res = ioctl(dev->device_handle, HIDIOCSOUTPUT(length), data); if (res < 0) register_device_error_format(dev, "ioctl (SOUTPUT): %s", strerror(errno)); return res; } int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) { int res; if (!data || (length == 0)) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); res = ioctl(dev->device_handle, HIDIOCGINPUT(length), data); if (res < 0) register_device_error_format(dev, "ioctl (GINPUT): %s", strerror(errno)); return res; } void HID_API_EXPORT hid_close(hid_device *dev) { if (!dev) return; close(dev->device_handle); free(dev->last_error_str); free(dev->last_read_error_str); hid_free_enumeration(dev->device_info); free(dev); } int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } struct hid_device_info *info = hid_get_device_info(dev); if (!info) { // hid_get_device_info will have set an error already return -1; } if (info->manufacturer_string) { wcsncpy(string, info->manufacturer_string, maxlen); string[maxlen - 1] = L'\0'; } else { string[0] = L'\0'; } return 0; } int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } struct hid_device_info *info = hid_get_device_info(dev); if (!info) { // hid_get_device_info will have set an error already return -1; } if (info->product_string) { wcsncpy(string, info->product_string, maxlen); string[maxlen - 1] = L'\0'; } else { string[0] = L'\0'; } return 0; } int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } struct hid_device_info *info = hid_get_device_info(dev); if (!info) { // hid_get_device_info will have set an error already return -1; } if (info->serial_number) { wcsncpy(string, info->serial_number, maxlen); string[maxlen - 1] = L'\0'; } else { string[0] = L'\0'; } return 0; } HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) { if (dev->device_info) { register_device_error(dev, NULL); } else { // Lazy initialize device_info dev->device_info = create_device_info_for_hid_device(dev); } // create_device_info_for_hid_device will set an error if needed return dev->device_info; } int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { (void)string_index; (void)string; (void)maxlen; errno = ENOSYS; register_device_error(dev, "hid_get_indexed_string: not supported by hidraw"); return -1; } int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) { struct hidraw_report_descriptor rpt_desc; if (!buf || !buf_size) { errno = EINVAL; register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); int res = get_hid_report_descriptor_from_hidraw(dev, &rpt_desc); if (res < 0) { /* error already registered */ return res; } if (rpt_desc.size < buf_size) { buf_size = (size_t) rpt_desc.size; } memcpy(buf, rpt_desc.value, buf_size); return (int) buf_size; } /* Passing in NULL means asking for the last global error message. */ HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) { if (dev) { if (dev->last_error_str == NULL) return L"Success"; return dev->last_error_str; } if (last_global_error_str == NULL) return L"Success"; return last_global_error_str; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0693865 hidapi-0.15.0/hidapi/mac/0000755000076500000240000000000015115770112014071 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/mac/hid.c0000644000076500000240000012717715115611013015012 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /* See Apple Technical Note TN2187 for details on IOHidManager. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "hidapi_darwin.h" /* Barrier implementation because Mac OSX doesn't have pthread_barrier. It also doesn't have clock_gettime(). So much for POSIX and SUSv2. This implementation came from Brent Priddy and was posted on StackOverflow. It is used with his permission. */ typedef int pthread_barrierattr_t; typedef struct pthread_barrier { pthread_mutex_t mutex; pthread_cond_t cond; int count; int trip_count; } pthread_barrier_t; static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) { (void) attr; if (count == 0) { errno = EINVAL; return -1; } if (pthread_mutex_init(&barrier->mutex, 0) < 0) { return -1; } if (pthread_cond_init(&barrier->cond, 0) < 0) { pthread_mutex_destroy(&barrier->mutex); return -1; } barrier->trip_count = count; barrier->count = 0; return 0; } static int pthread_barrier_destroy(pthread_barrier_t *barrier) { pthread_cond_destroy(&barrier->cond); pthread_mutex_destroy(&barrier->mutex); return 0; } static int pthread_barrier_wait(pthread_barrier_t *barrier) { pthread_mutex_lock(&barrier->mutex); ++(barrier->count); if (barrier->count >= barrier->trip_count) { barrier->count = 0; pthread_mutex_unlock(&barrier->mutex); pthread_cond_broadcast(&barrier->cond); return 1; } else { do { pthread_cond_wait(&barrier->cond, &(barrier->mutex)); } while (barrier->count != 0); pthread_mutex_unlock(&barrier->mutex); return 0; } } static int return_data(hid_device *dev, unsigned char *data, size_t length); /* Linked List of input reports received from the device. */ struct input_report { uint8_t *data; size_t len; struct input_report *next; }; static struct hid_api_version api_version = { .major = HID_API_VERSION_MAJOR, .minor = HID_API_VERSION_MINOR, .patch = HID_API_VERSION_PATCH }; /* - Run context - */ static IOHIDManagerRef hid_mgr = 0x0; static int is_macos_10_10_or_greater = 0; static IOOptionBits device_open_options = 0; static wchar_t *last_global_error_str = NULL; /* --- */ struct hid_device_ { IOHIDDeviceRef device_handle; IOOptionBits open_options; int blocking; int disconnected; CFStringRef run_loop_mode; CFRunLoopRef run_loop; CFRunLoopSourceRef source; uint8_t *input_report_buf; CFIndex max_input_report_len; struct input_report *input_reports; struct hid_device_info* device_info; pthread_t thread; pthread_mutex_t mutex; /* Protects input_reports */ pthread_cond_t condition; pthread_barrier_t barrier; /* Ensures correct startup sequence */ pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */ int shutdown_thread; wchar_t *last_error_str; wchar_t *last_read_error_str; }; static hid_device *new_hid_device(void) { hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); if (dev == NULL) { return NULL; } dev->device_handle = NULL; dev->open_options = device_open_options; dev->blocking = 1; dev->disconnected = 0; dev->run_loop_mode = NULL; dev->run_loop = NULL; dev->source = NULL; dev->input_report_buf = NULL; dev->input_reports = NULL; dev->device_info = NULL; dev->shutdown_thread = 0; dev->last_error_str = NULL; dev->last_read_error_str = NULL; /* Thread objects */ pthread_mutex_init(&dev->mutex, NULL); pthread_cond_init(&dev->condition, NULL); pthread_barrier_init(&dev->barrier, NULL, 2); pthread_barrier_init(&dev->shutdown_barrier, NULL, 2); return dev; } static void free_hid_device(hid_device *dev) { if (!dev) return; /* Delete any input reports still left over. */ struct input_report *rpt = dev->input_reports; while (rpt) { struct input_report *next = rpt->next; free(rpt->data); free(rpt); rpt = next; } /* Free the string and the report buffer. The check for NULL is necessary here as CFRelease() doesn't handle NULL like free() and others do. */ if (dev->run_loop_mode) CFRelease(dev->run_loop_mode); if (dev->source) CFRelease(dev->source); free(dev->input_report_buf); free(dev->last_error_str); free(dev->last_read_error_str); hid_free_enumeration(dev->device_info); /* Clean up the thread objects */ pthread_barrier_destroy(&dev->shutdown_barrier); pthread_barrier_destroy(&dev->barrier); pthread_cond_destroy(&dev->condition); pthread_mutex_destroy(&dev->mutex); /* Free the structure itself. */ free(dev); } /* The caller must free the returned string with free(). */ static wchar_t *utf8_to_wchar_t(const char *utf8) { wchar_t *ret = NULL; if (utf8) { size_t wlen = mbstowcs(NULL, utf8, 0); if ((size_t) -1 == wlen) { return wcsdup(L""); } ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t)); if (ret == NULL) { /* as much as we can do at this point */ return NULL; } mbstowcs(ret, utf8, wlen+1); ret[wlen] = 0x0000; } return ret; } /* Makes a copy of the given error message (and decoded according to the * currently locale) into the wide string pointer pointed by error_str. * The last stored error string is freed. * Use register_error_str(NULL) to free the error message completely. */ static void register_error_str(wchar_t **error_str, const char *msg) { free(*error_str); *error_str = utf8_to_wchar_t(msg); } /* Similar to register_error_str, but allows passing a format string with va_list args into this function. */ static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args) { char msg[1024]; vsnprintf(msg, sizeof(msg), format, args); register_error_str(error_str, msg); } /* Set the last global error to be reported by hid_error(NULL). * The given error message will be copied (and decoded according to the * currently locale, so do not pass in string constants). * The last stored global error message is freed. * Use register_global_error(NULL) to indicate "no error". */ static void register_global_error(const char *msg) { register_error_str(&last_global_error_str, msg); } /* Similar to register_global_error, but allows passing a format string into this function. */ static void register_global_error_format(const char *format, ...) { va_list args; va_start(args, format); register_error_str_vformat(&last_global_error_str, format, args); va_end(args); } /* Set the last error for a device to be reported by hid_error(dev). * The given error message will be copied (and decoded according to the * currently locale, so do not pass in string constants). * The last stored device error message is freed. * Use register_device_error(dev, NULL) to indicate "no error". */ static void register_device_error(hid_device *dev, const char *msg) { register_error_str(&dev->last_error_str, msg); } /* Similar to register_device_error, but you can pass a format string into this function. */ static void register_device_error_format(hid_device *dev, const char *format, ...) { va_list args; va_start(args, format); register_error_str_vformat(&dev->last_error_str, format, args); va_end(args); } static CFArrayRef get_array_property(IOHIDDeviceRef device, CFStringRef key) { CFTypeRef ref = IOHIDDeviceGetProperty(device, key); if (ref != NULL && CFGetTypeID(ref) == CFArrayGetTypeID()) { return (CFArrayRef)ref; } else { return NULL; } } static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key) { CFTypeRef ref; int32_t value = 0; ref = IOHIDDeviceGetProperty(device, key); if (ref) { if (CFGetTypeID(ref) == CFNumberGetTypeID()) { CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value); return value; } } return 0; } static bool try_get_int_property(IOHIDDeviceRef device, CFStringRef key, int32_t *out_val) { bool result = false; CFTypeRef ref; ref = IOHIDDeviceGetProperty(device, key); if (ref) { if (CFGetTypeID(ref) == CFNumberGetTypeID()) { result = CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, out_val); } } return result; } static bool try_get_ioregistry_int_property(io_service_t service, CFStringRef property, int32_t *out_val) { bool result = false; CFTypeRef ref = IORegistryEntryCreateCFProperty(service, property, kCFAllocatorDefault, 0); if (ref) { if (CFGetTypeID(ref) == CFNumberGetTypeID()) { result = CFNumberGetValue(ref, kCFNumberSInt32Type, out_val); } CFRelease(ref); } return result; } static CFArrayRef get_usage_pairs(IOHIDDeviceRef device) { return get_array_property(device, CFSTR(kIOHIDDeviceUsagePairsKey)); } static unsigned short get_vendor_id(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDVendorIDKey)); } static unsigned short get_product_id(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDProductIDKey)); } static int32_t get_max_report_length(IOHIDDeviceRef device) { return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey)); } static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len) { CFStringRef str; if (!len) return 0; str = (CFStringRef) IOHIDDeviceGetProperty(device, prop); buf[0] = 0; if (str && CFGetTypeID(str) == CFStringGetTypeID()) { CFIndex str_len = CFStringGetLength(str); CFRange range; CFIndex used_buf_len; CFIndex chars_copied; len --; range.location = 0; range.length = ((size_t) str_len > len)? len: (size_t) str_len; chars_copied = CFStringGetBytes(str, range, kCFStringEncodingUTF32LE, (char) '?', FALSE, (UInt8*)buf, len * sizeof(wchar_t), &used_buf_len); if (chars_copied <= 0) buf[0] = 0; else buf[chars_copied] = 0; return 0; } else return -1; } static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len); } static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len); } static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) { return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len); } /* Implementation of wcsdup() for Mac. */ static wchar_t *dup_wcs(const wchar_t *s) { size_t len = wcslen(s); wchar_t *ret = (wchar_t*) malloc((len+1)*sizeof(wchar_t)); wcscpy(ret, s); return ret; } /* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */ static int init_hid_manager(void) { /* Initialize all the HID Manager Objects */ hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (hid_mgr) { IOHIDManagerSetDeviceMatching(hid_mgr, NULL); IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); return 0; } register_global_error("Failed to create IOHIDManager"); return -1; } HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) { return &api_version; } HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) { return HID_API_VERSION_STR; } /* Initialize the IOHIDManager if necessary. This is the public function, and it is safe to call this function repeatedly. Return 0 for success and -1 for failure. */ int HID_API_EXPORT hid_init(void) { register_global_error(NULL); if (!hid_mgr) { is_macos_10_10_or_greater = (kCFCoreFoundationVersionNumber >= 1151.16); /* kCFCoreFoundationVersionNumber10_10 */ hid_darwin_set_open_exclusive(1); /* Backward compatibility */ return init_hid_manager(); } /* Already initialized. */ return 0; } int HID_API_EXPORT hid_exit(void) { if (hid_mgr) { /* Close the HID manager. */ IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone); CFRelease(hid_mgr); hid_mgr = NULL; } /* Free global error message */ register_global_error(NULL); return 0; } static void process_pending_events(void) { SInt32 res; do { res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE); } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut); } static int read_usb_interface_from_hid_service_parent(io_service_t hid_service) { int32_t result = -1; bool success = false; io_registry_entry_t current = IO_OBJECT_NULL; kern_return_t res; int parent_number = 0; res = IORegistryEntryGetParentEntry(hid_service, kIOServicePlane, ¤t); while (KERN_SUCCESS == res /* Only search up to 3 parent entries. * With the default driver - the parent-of-interest supposed to be the first one, * but lets assume some custom drivers or so, with deeper tree. */ && parent_number < 3) { io_registry_entry_t parent = IO_OBJECT_NULL; int32_t interface_number = -1; parent_number++; success = try_get_ioregistry_int_property(current, CFSTR(kUSBInterfaceNumber), &interface_number); if (success) { result = interface_number; break; } res = IORegistryEntryGetParentEntry(current, kIOServicePlane, &parent); if (parent) { IOObjectRelease(current); current = parent; } } if (current) { IOObjectRelease(current); current = IO_OBJECT_NULL; } return result; } static struct hid_device_info *create_device_info_with_usage(IOHIDDeviceRef dev, int32_t usage_page, int32_t usage) { unsigned short dev_vid; unsigned short dev_pid; int BUF_LEN = 256; wchar_t buf[BUF_LEN]; CFTypeRef transport_prop; struct hid_device_info *cur_dev; io_service_t hid_service; kern_return_t res; uint64_t entry_id = 0; if (dev == NULL) { return NULL; } cur_dev = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info)); if (cur_dev == NULL) { return NULL; } dev_vid = get_vendor_id(dev); dev_pid = get_product_id(dev); cur_dev->usage_page = usage_page; cur_dev->usage = usage; /* Fill out the record */ cur_dev->next = NULL; /* Fill in the path (as a unique ID of the service entry) */ cur_dev->path = NULL; hid_service = IOHIDDeviceGetService(dev); if (hid_service != MACH_PORT_NULL) { res = IORegistryEntryGetRegistryEntryID(hid_service, &entry_id); } else { res = KERN_INVALID_ARGUMENT; } if (res == KERN_SUCCESS) { /* max value of entry_id(uint64_t) is 18446744073709551615 which is 20 characters long, so for (max) "path" string 'DevSrvsID:18446744073709551615' we would need 9+1+20+1=31 bytes buffer, but allocate 32 for simple alignment */ const size_t path_len = 32; cur_dev->path = calloc(1, path_len); if (cur_dev->path != NULL) { snprintf(cur_dev->path, path_len, "DevSrvsID:%llu", entry_id); } } if (cur_dev->path == NULL) { /* for whatever reason, trying to keep it a non-NULL string */ cur_dev->path = strdup(""); } /* Serial Number */ get_serial_number(dev, buf, BUF_LEN); cur_dev->serial_number = dup_wcs(buf); /* Manufacturer and Product strings */ get_manufacturer_string(dev, buf, BUF_LEN); cur_dev->manufacturer_string = dup_wcs(buf); get_product_string(dev, buf, BUF_LEN); cur_dev->product_string = dup_wcs(buf); /* VID/PID */ cur_dev->vendor_id = dev_vid; cur_dev->product_id = dev_pid; /* Release Number */ cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey)); /* Interface Number. * We can only retrieve the interface number for USB HID devices. * See below */ cur_dev->interface_number = -1; /* Bus Type */ transport_prop = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDTransportKey)); if (transport_prop != NULL && CFGetTypeID(transport_prop) == CFStringGetTypeID()) { if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) { int32_t interface_number = -1; cur_dev->bus_type = HID_API_BUS_USB; /* A IOHIDDeviceRef used to have this simple property, * until macOS 13.3 - we will try to use it. */ if (try_get_int_property(dev, CFSTR(kUSBInterfaceNumber), &interface_number)) { cur_dev->interface_number = interface_number; } else { /* Otherwise fallback to io_service_t property. * (of one of the parent services). */ cur_dev->interface_number = read_usb_interface_from_hid_service_parent(hid_service); /* If the above doesn't work - * no (known) fallback exists at this point. */ } /* Match "Bluetooth", "BluetoothLowEnergy" and "Bluetooth Low Energy" strings */ } else if (CFStringHasPrefix((CFStringRef)transport_prop, CFSTR(kIOHIDTransportBluetoothValue))) { cur_dev->bus_type = HID_API_BUS_BLUETOOTH; } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportI2CValue), 0) == kCFCompareEqualTo) { cur_dev->bus_type = HID_API_BUS_I2C; } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportSPIValue), 0) == kCFCompareEqualTo) { cur_dev->bus_type = HID_API_BUS_SPI; } } return cur_dev; } static struct hid_device_info *create_device_info(IOHIDDeviceRef device) { const int32_t primary_usage_page = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey)); const int32_t primary_usage = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey)); /* Primary should always be first, to match previous behavior. */ struct hid_device_info *root = create_device_info_with_usage(device, primary_usage_page, primary_usage); struct hid_device_info *cur = root; if (!root) return NULL; CFArrayRef usage_pairs = get_usage_pairs(device); if (usage_pairs != NULL) { struct hid_device_info *next = NULL; for (CFIndex i = 0; i < CFArrayGetCount(usage_pairs); i++) { CFTypeRef dict = CFArrayGetValueAtIndex(usage_pairs, i); if (CFGetTypeID(dict) != CFDictionaryGetTypeID()) { continue; } CFTypeRef usage_page_ref, usage_ref; int32_t usage_page, usage; if (!CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsagePageKey), &usage_page_ref) || !CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsageKey), &usage_ref) || CFGetTypeID(usage_page_ref) != CFNumberGetTypeID() || CFGetTypeID(usage_ref) != CFNumberGetTypeID() || !CFNumberGetValue((CFNumberRef)usage_page_ref, kCFNumberSInt32Type, &usage_page) || !CFNumberGetValue((CFNumberRef)usage_ref, kCFNumberSInt32Type, &usage)) { continue; } if (usage_page == primary_usage_page && usage == primary_usage) continue; /* Already added. */ next = create_device_info_with_usage(device, usage_page, usage); cur->next = next; if (next != NULL) { cur = next; } } } return root; } struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) { struct hid_device_info *root = NULL; /* return object */ struct hid_device_info *cur_dev = NULL; CFIndex num_devices; int i; /* Set up the HID Manager if it hasn't been done */ if (hid_init() < 0) { return NULL; } /* register_global_error: global error is set/reset by hid_init */ /* give the IOHIDManager a chance to update itself */ process_pending_events(); /* Get a list of the Devices */ CFMutableDictionaryRef matching = NULL; if (vendor_id != 0 || product_id != 0) { matching = CFDictionaryCreateMutable(kCFAllocatorDefault, kIOHIDOptionsTypeNone, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (matching && vendor_id != 0) { CFNumberRef v = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &vendor_id); CFDictionarySetValue(matching, CFSTR(kIOHIDVendorIDKey), v); CFRelease(v); } if (matching && product_id != 0) { CFNumberRef p = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &product_id); CFDictionarySetValue(matching, CFSTR(kIOHIDProductIDKey), p); CFRelease(p); } } IOHIDManagerSetDeviceMatching(hid_mgr, matching); if (matching != NULL) { CFRelease(matching); } CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); IOHIDDeviceRef *device_array = NULL; if (device_set != NULL) { /* Convert the list into a C array so we can iterate easily. */ num_devices = CFSetGetCount(device_set); device_array = (IOHIDDeviceRef*) calloc(num_devices, sizeof(IOHIDDeviceRef)); CFSetGetValues(device_set, (const void **) device_array); } else { num_devices = 0; } /* Iterate over each device, making an entry for it. */ for (i = 0; i < num_devices; i++) { IOHIDDeviceRef dev = device_array[i]; if (!dev) { continue; } struct hid_device_info *tmp = create_device_info(dev); if (tmp == NULL) { continue; } if (cur_dev) { cur_dev->next = tmp; } else { root = tmp; } cur_dev = tmp; /* move the pointer to the tail of returned list */ while (cur_dev->next != NULL) { cur_dev = cur_dev->next; } } free(device_array); if (device_set != NULL) CFRelease(device_set); if (root == NULL) { if (vendor_id == 0 && product_id == 0) { register_global_error("No HID devices found in the system."); } else { register_global_error("No HID devices with requested VID/PID found in the system."); } } return root; } void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) { /* This function is identical to the Linux version. Platform independent. */ struct hid_device_info *d = devs; while (d) { struct hid_device_info *next = d->next; free(d->path); free(d->serial_number); free(d->manufacturer_string); free(d->product_string); free(d); d = next; } } hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { /* This function is identical to the Linux version. Platform independent. */ struct hid_device_info *devs, *cur_dev; const char *path_to_open = NULL; hid_device * handle = NULL; /* register_global_error: global error is reset by hid_enumerate/hid_init */ devs = hid_enumerate(vendor_id, product_id); if (devs == NULL) { /* register_global_error: global error is already set by hid_enumerate */ return NULL; } cur_dev = devs; while (cur_dev) { if (cur_dev->vendor_id == vendor_id && cur_dev->product_id == product_id) { if (serial_number) { if (wcscmp(serial_number, cur_dev->serial_number) == 0) { path_to_open = cur_dev->path; break; } } else { path_to_open = cur_dev->path; break; } } cur_dev = cur_dev->next; } if (path_to_open) { handle = hid_open_path(path_to_open); } else { register_global_error("Device with requested VID/PID/(SerialNumber) not found"); } hid_free_enumeration(devs); return handle; } static void hid_device_removal_callback(void *context, IOReturn result, void *sender) { (void) result; (void) sender; /* Stop the Run Loop for this device. */ hid_device *d = (hid_device*) context; d->disconnected = 1; CFRunLoopStop(d->run_loop); } /* The Run Loop calls this function for each input report received. This function puts the data into a linked list to be picked up by hid_read(). */ static void hid_report_callback(void *context, IOReturn result, void *sender, IOHIDReportType report_type, uint32_t report_id, uint8_t *report, CFIndex report_length) { (void) result; (void) sender; (void) report_type; (void) report_id; struct input_report *rpt; hid_device *dev = (hid_device*) context; /* Make a new Input Report object */ rpt = (struct input_report*) calloc(1, sizeof(struct input_report)); rpt->data = (uint8_t*) calloc(1, report_length); memcpy(rpt->data, report, report_length); rpt->len = report_length; rpt->next = NULL; /* Lock this section */ pthread_mutex_lock(&dev->mutex); /* Attach the new report object to the end of the list. */ if (dev->input_reports == NULL) { /* The list is empty. Put it at the root. */ dev->input_reports = rpt; } else { /* Find the end of the list and attach. */ struct input_report *cur = dev->input_reports; int num_queued = 0; while (cur->next != NULL) { cur = cur->next; num_queued++; } cur->next = rpt; /* Pop one off if we've reached 30 in the queue. This way we don't grow forever if the user never reads anything from the device. */ if (num_queued > 30) { return_data(dev, NULL, 0); } } /* Signal a waiting thread that there is data. */ pthread_cond_signal(&dev->condition); /* Unlock */ pthread_mutex_unlock(&dev->mutex); } /* This gets called when the read_thread's run loop gets signaled by hid_close(), and serves to stop the read_thread's run loop. */ static void perform_signal_callback(void *context) { hid_device *dev = (hid_device*) context; CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/ } static void *read_thread(void *param) { hid_device *dev = (hid_device*) param; SInt32 code; /* Move the device's run loop to this thread. */ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode); /* Create the RunLoopSource which is used to signal the event loop to stop when hid_close() is called. */ CFRunLoopSourceContext ctx; memset(&ctx, 0, sizeof(ctx)); ctx.version = 0; ctx.info = dev; ctx.perform = &perform_signal_callback; dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx); CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode); /* Store off the Run Loop so it can be stopped from hid_close() and on device disconnection. */ dev->run_loop = CFRunLoopGetCurrent(); /* Notify the main thread that the read thread is up and running. */ pthread_barrier_wait(&dev->barrier); /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input reports into the hid_report_callback(). */ while (!dev->shutdown_thread && !dev->disconnected) { code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE); /* Return if the device has been disconnected */ if (code == kCFRunLoopRunFinished || code == kCFRunLoopRunStopped) { dev->disconnected = 1; break; } /* Break if The Run Loop returns Finished or Stopped. */ if (code != kCFRunLoopRunTimedOut && code != kCFRunLoopRunHandledSource) { /* There was some kind of error. Setting shutdown seems to make sense, but there may be something else more appropriate */ dev->shutdown_thread = 1; break; } } /* Now that the read thread is stopping, Wake any threads which are waiting on data (in hid_read_timeout()). Do this under a mutex to make sure that a thread which is about to go to sleep waiting on the condition actually will go to sleep before the condition is signaled. */ pthread_mutex_lock(&dev->mutex); pthread_cond_broadcast(&dev->condition); pthread_mutex_unlock(&dev->mutex); /* Wait here until hid_close() is called and makes it past the call to CFRunLoopWakeUp(). This thread still needs to be valid when that function is called on the other thread. */ pthread_barrier_wait(&dev->shutdown_barrier); return NULL; } /* \p path must be one of: - in format 'DevSrvsID:' (as returned by hid_enumerate); - a valid path to an IOHIDDevice in the IOService plane (as returned by IORegistryEntryGetPath, e.g.: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver"); Second format is for compatibility with paths accepted by older versions of HIDAPI. */ static io_registry_entry_t hid_open_service_registry_from_path(const char *path) { if (path == NULL) return MACH_PORT_NULL; /* Get the IORegistry entry for the given path */ if (strncmp("DevSrvsID:", path, 10) == 0) { char *endptr; uint64_t entry_id = strtoull(path + 10, &endptr, 10); if (*endptr == '\0') { return IOServiceGetMatchingService((mach_port_t) 0, IORegistryEntryIDMatching(entry_id)); } } else { /* Fallback to older format of the path */ return IORegistryEntryFromPath((mach_port_t) 0, path); } return MACH_PORT_NULL; } hid_device * HID_API_EXPORT hid_open_path(const char *path) { hid_device *dev = NULL; io_registry_entry_t entry = MACH_PORT_NULL; IOReturn ret = kIOReturnInvalid; char str[32]; /* Set up the HID Manager if it hasn't been done */ if (hid_init() < 0) { return NULL; } /* register_global_error: global error is set/reset by hid_init */ dev = new_hid_device(); if (!dev) { register_global_error("Couldn't allocate memory"); return NULL; } /* Get the IORegistry entry for the given path */ entry = hid_open_service_registry_from_path(path); if (entry == MACH_PORT_NULL) { /* Path wasn't valid (maybe device was removed?) */ register_global_error("hid_open_path: device mach entry not found with the given path"); goto return_error; } /* Create an IOHIDDevice for the entry */ dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry); if (dev->device_handle == NULL) { /* Error creating the HID device */ register_global_error("hid_open_path: failed to create IOHIDDevice from the mach entry"); goto return_error; } /* Open the IOHIDDevice */ ret = IOHIDDeviceOpen(dev->device_handle, dev->open_options); if (ret != kIOReturnSuccess) { register_global_error_format("hid_open_path: failed to open IOHIDDevice from mach entry: (0x%08X) %s", ret, mach_error_string(ret)); goto return_error; } /* Create the buffers for receiving data */ dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle); dev->input_report_buf = (uint8_t*) calloc(dev->max_input_report_len, sizeof(uint8_t)); /* Create the Run Loop Mode for this device. printing the reference seems to work. */ snprintf(str, sizeof(str), "HIDAPI_%p", (void*) dev->device_handle); dev->run_loop_mode = CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII); /* Attach the device to a Run Loop */ IOHIDDeviceRegisterInputReportCallback( dev->device_handle, dev->input_report_buf, dev->max_input_report_len, &hid_report_callback, dev); IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev); /* Start the read thread */ pthread_create(&dev->thread, NULL, read_thread, dev); /* Wait here for the read thread to be initialized. */ pthread_barrier_wait(&dev->barrier); IOObjectRelease(entry); return dev; return_error: if (dev->device_handle != NULL) CFRelease(dev->device_handle); if (entry != MACH_PORT_NULL) IOObjectRelease(entry); free_hid_device(dev); return NULL; } static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length) { const unsigned char *data_to_send = data; CFIndex length_to_send = length; IOReturn res; unsigned char report_id; if (!data || (length == 0)) { register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); report_id = data[0]; if (report_id == 0x0) { /* Not using numbered Reports. Don't send the report number. */ data_to_send = data+1; length_to_send = length-1; } /* Avoid crash if the device has been unplugged. */ if (dev->disconnected) { register_device_error(dev, "Device is disconnected"); return -1; } res = IOHIDDeviceSetReport(dev->device_handle, type, report_id, data_to_send, length_to_send); if (res != kIOReturnSuccess) { register_device_error_format(dev, "IOHIDDeviceSetReport failed: (0x%08X) %s", res, mach_error_string(res)); return -1; } return (int) length; } static int get_report(hid_device *dev, IOHIDReportType type, unsigned char *data, size_t length) { unsigned char *report = data; CFIndex report_length = length; IOReturn res = kIOReturnSuccess; unsigned char report_id; if (!data || (length == 0)) { register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); report_id = data[0]; if (report_id == 0x0) { /* Not using numbered Reports. Don't send the report number. */ report = data+1; report_length = length-1; } /* Avoid crash if the device has been unplugged. */ if (dev->disconnected) { register_device_error(dev, "Device is disconnected"); return -1; } res = IOHIDDeviceGetReport(dev->device_handle, type, report_id, report, &report_length); if (res != kIOReturnSuccess) { register_device_error_format(dev, "IOHIDDeviceGetReport failed: (0x%08X) %s", res, mach_error_string(res)); return -1; } if (report_id == 0x0) { /* 0 report number still present at the beginning */ report_length++; } return (int) report_length; } int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) { return set_report(dev, kIOHIDReportTypeOutput, data, length); } /* Helper function, so that this isn't duplicated in hid_read(). */ static int return_data(hid_device *dev, unsigned char *data, size_t length) { /* Copy the data out of the linked list item (rpt) into the return buffer (data), and delete the liked list item. */ struct input_report *rpt = dev->input_reports; size_t len = (length < rpt->len)? length: rpt->len; if (data != NULL) { memcpy(data, rpt->data, len); } dev->input_reports = rpt->next; free(rpt->data); free(rpt); return (int) len; } static int cond_wait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex) { while (!dev->input_reports) { int res = pthread_cond_wait(cond, mutex); if (res != 0) return res; /* A res of 0 means we may have been signaled or it may be a spurious wakeup. Check to see that there's actually data in the queue before returning, and if not, go back to sleep. See the pthread_cond_timedwait() man page for details. */ if (dev->shutdown_thread || dev->disconnected) { return -1; } } return 0; } static int cond_timedwait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) { while (!dev->input_reports) { int res = pthread_cond_timedwait(cond, mutex, abstime); if (res != 0) return res; /* A res of 0 means we may have been signaled or it may be a spurious wakeup. Check to see that there's actually data in the queue before returning, and if not, go back to sleep. See the pthread_cond_timedwait() man page for details. */ if (dev->shutdown_thread || dev->disconnected) { return -1; } } return 0; } int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) { int bytes_read = -1; if (!data || (length == 0)) { register_error_str(&dev->last_read_error_str, "Zero buffer/length"); return -1; } register_error_str(&dev->last_read_error_str, NULL); /* Lock the access to the report list. */ pthread_mutex_lock(&dev->mutex); /* There's an input report queued up. Return it. */ if (dev->input_reports) { /* Return the first one */ bytes_read = return_data(dev, data, length); goto ret; } /* Return if the device has been disconnected. */ if (dev->disconnected) { bytes_read = -1; register_error_str(&dev->last_read_error_str, "hid_read_timeout: device disconnected"); goto ret; } if (dev->shutdown_thread) { /* This means the device has been closed (or there has been an error. An error code of -1 should be returned. */ bytes_read = -1; register_error_str(&dev->last_read_error_str, "hid_read_timeout: thread shutdown"); goto ret; } /* There is no data. Go to sleep and wait for data. */ if (milliseconds == -1) { /* Blocking */ int res; res = cond_wait(dev, &dev->condition, &dev->mutex); if (res == 0) bytes_read = return_data(dev, data, length); else { /* There was an error, or a device disconnection. */ register_error_str(&dev->last_read_error_str, "hid_read_timeout: error waiting for more data"); bytes_read = -1; } } else if (milliseconds > 0) { /* Non-blocking, but called with timeout. */ int res; struct timespec ts; struct timeval tv; gettimeofday(&tv, NULL); TIMEVAL_TO_TIMESPEC(&tv, &ts); ts.tv_sec += milliseconds / 1000; ts.tv_nsec += (milliseconds % 1000) * 1000000; if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; } res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts); if (res == 0) { bytes_read = return_data(dev, data, length); } else if (res == ETIMEDOUT) { bytes_read = 0; } else { register_error_str(&dev->last_read_error_str, "hid_read_timeout: error waiting for more data"); bytes_read = -1; } } else { /* Purely non-blocking */ bytes_read = 0; } ret: /* Unlock */ pthread_mutex_unlock(&dev->mutex); return bytes_read; } int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) { return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); } HID_API_EXPORT const wchar_t * HID_API_CALL hid_read_error(hid_device *dev) { if (dev->last_read_error_str == NULL) return L"Success"; return dev->last_read_error_str; } int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) { /* All Nonblocking operation is handled by the library. */ dev->blocking = !nonblock; return 0; } int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) { return set_report(dev, kIOHIDReportTypeFeature, data, length); } int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) { return get_report(dev, kIOHIDReportTypeFeature, data, length); } int HID_API_EXPORT hid_send_output_report(hid_device *dev, const unsigned char *data, size_t length) { return set_report(dev, kIOHIDReportTypeOutput, data, length); } int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) { return get_report(dev, kIOHIDReportTypeInput, data, length); } void HID_API_EXPORT hid_close(hid_device *dev) { if (!dev) return; /* Disconnect the report callback before close. See comment below. */ if (is_macos_10_10_or_greater || !dev->disconnected) { IOHIDDeviceRegisterInputReportCallback( dev->device_handle, dev->input_report_buf, dev->max_input_report_len, NULL, dev); IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev); IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode); IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode); } /* Cause read_thread() to stop. */ dev->shutdown_thread = 1; /* Wake up the run thread's event loop so that the thread can exit. */ CFRunLoopSourceSignal(dev->source); CFRunLoopWakeUp(dev->run_loop); /* Notify the read thread that it can shut down now. */ pthread_barrier_wait(&dev->shutdown_barrier); /* Wait for read_thread() to end. */ pthread_join(dev->thread, NULL); /* Close the OS handle to the device, but only if it's not been unplugged. If it's been unplugged, then calling IOHIDDeviceClose() will crash. UPD: The crash part was true in/until some version of macOS. Starting with macOS 10.15, there is an opposite effect in some environments: crash happenes if IOHIDDeviceClose() is not called. Not leaking a resource in all tested environments. */ if (is_macos_10_10_or_greater || !dev->disconnected) { IOHIDDeviceClose(dev->device_handle, dev->open_options); } /* Clear out the queue of received reports. */ pthread_mutex_lock(&dev->mutex); while (dev->input_reports) { return_data(dev, NULL, 0); } pthread_mutex_unlock(&dev->mutex); CFRelease(dev->device_handle); free_hid_device(dev); } int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { register_device_error(dev, "Zero buffer/length"); return -1; } struct hid_device_info *info = hid_get_device_info(dev); if (!info) { // hid_get_device_info will have set an error already return -1; } wcsncpy(string, info->manufacturer_string, maxlen); string[maxlen - 1] = L'\0'; return 0; } int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { register_device_error(dev, "Zero buffer/length"); return -1; } struct hid_device_info *info = hid_get_device_info(dev); if (!info) { // hid_get_device_info will have set an error already return -1; } wcsncpy(string, info->product_string, maxlen); string[maxlen - 1] = L'\0'; return 0; } int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { register_device_error(dev, "Zero buffer/length"); return -1; } struct hid_device_info *info = hid_get_device_info(dev); if (!info) { // hid_get_device_info will have set an error already return -1; } wcsncpy(string, info->serial_number, maxlen); string[maxlen - 1] = L'\0'; return 0; } HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) { if (dev->device_info) { register_device_error(dev, NULL); } else { dev->device_info = create_device_info(dev->device_handle); if (!dev->device_info) { register_device_error(dev, "Failed to create hid_device_info"); } } return dev->device_info; } int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { (void) dev; (void) string_index; (void) string; (void) maxlen; register_device_error(dev, "hid_get_indexed_string: not available on this platform"); return -1; } int HID_API_EXPORT_CALL hid_darwin_get_location_id(hid_device *dev, uint32_t *location_id) { if (!location_id) { register_device_error(dev, "Location ID is NULL"); return -1; } register_device_error(dev, NULL); int res = get_int_property(dev->device_handle, CFSTR(kIOHIDLocationIDKey)); if (res != 0) { *location_id = (uint32_t) res; return 0; } else { register_device_error(dev, "Failed to get IOHIDLocationID property"); return -1; } } void HID_API_EXPORT_CALL hid_darwin_set_open_exclusive(int open_exclusive) { device_open_options = (open_exclusive == 0) ? kIOHIDOptionsTypeNone : kIOHIDOptionsTypeSeizeDevice; } int HID_API_EXPORT_CALL hid_darwin_get_open_exclusive(void) { return (device_open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0; } int HID_API_EXPORT_CALL hid_darwin_is_device_open_exclusive(hid_device *dev) { return (dev->open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0; } int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) { if (!buf || !buf_size) { register_device_error(dev, "Zero buffer/length"); return -1; } register_device_error(dev, NULL); CFTypeRef ref = IOHIDDeviceGetProperty(dev->device_handle, CFSTR(kIOHIDReportDescriptorKey)); if (ref != NULL && CFGetTypeID(ref) == CFDataGetTypeID()) { CFDataRef report_descriptor = (CFDataRef) ref; const UInt8 *descriptor_buf = CFDataGetBytePtr(report_descriptor); const CFIndex descriptor_buf_len = CFDataGetLength(report_descriptor); size_t copy_len = (size_t) descriptor_buf_len; if (descriptor_buf == NULL || descriptor_buf_len < 0) { register_device_error(dev, "Zero descriptor from device"); return -1; } if (buf_size < copy_len) { copy_len = buf_size; } memcpy(buf, descriptor_buf, copy_len); return copy_len; } else { register_device_error(dev, "Failed to get kIOHIDReportDescriptorKey property"); return -1; } } HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) { if (dev) { if (dev->last_error_str == NULL) return L"Success"; return dev->last_error_str; } if (last_global_error_str == NULL) return L"Success"; return last_global_error_str; } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216765.0 hidapi-0.15.0/hidapi/mac/hidapi_darwin.h0000644000076500000240000000607015115610775017057 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /** @file * @defgroup API hidapi API * Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) */ #ifndef HIDAPI_DARWIN_H__ #define HIDAPI_DARWIN_H__ #include #include "hidapi.h" #ifdef __cplusplus extern "C" { #endif /** @brief Get the location ID for a HID device. Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) @ingroup API @param dev A device handle returned from hid_open(). @param location_id The device's location ID on return. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_darwin_get_location_id(hid_device *dev, uint32_t *location_id); /** @brief Changes the behavior of all further calls to @ref hid_open or @ref hid_open_path. By default on Darwin platform all devices opened by HIDAPI with @ref hid_open or @ref hid_open_path are opened in exclusive mode (see kIOHIDOptionsTypeSeizeDevice). Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) @ingroup API @param open_exclusive When set to 0 - all further devices will be opened in non-exclusive mode. Otherwise - all further devices will be opened in exclusive mode. @note During the initialisation by @ref hid_init - this property is set to 1 (TRUE). This is done to preserve full backward compatibility with previous behavior. @note Calling this function before @ref hid_init or after @ref hid_exit has no effect. */ void HID_API_EXPORT_CALL hid_darwin_set_open_exclusive(int open_exclusive); /** @brief Getter for option set by @ref hid_darwin_set_open_exclusive. Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) @ingroup API @return 1 if all further devices will be opened in exclusive mode. @note Value returned by this function before calling to @ref hid_init or after @ref hid_exit is not reliable. */ int HID_API_EXPORT_CALL hid_darwin_get_open_exclusive(void); /** @brief Check how the device was opened. Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) @ingroup API @param dev A device to get property from. @return 1 if the device is opened in exclusive mode, 0 - opened in non-exclusive, -1 - if dev is invalid. */ int HID_API_EXPORT_CALL hid_darwin_is_device_open_exclusive(hid_device *dev); #ifdef __cplusplus } #endif #endif ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0717402 hidapi-0.15.0/hidapi/windows/0000755000076500000240000000000015115770112015023 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/windows/hid.c0000644000076500000240000013226015115611013015731 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. Alan Ott Signal 11 Software libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /* Do not warn about wcsncpy usage. https://docs.microsoft.com/cpp/c-runtime-library/security-features-in-the-crt */ #define _CRT_SECURE_NO_WARNINGS #endif #ifdef __cplusplus extern "C" { #endif #include "hidapi_winapi.h" #include #ifndef _NTDEF_ typedef LONG NTSTATUS; #endif #ifdef __MINGW32__ #include #include #define WC_ERR_INVALID_CHARS 0x00000080 #endif #ifdef __CYGWIN__ #include #include #define _wcsdup wcsdup #endif /*#define HIDAPI_USE_DDK*/ #include "hidapi_cfgmgr32.h" #include "hidapi_hidclass.h" #include "hidapi_hidsdi.h" #include #include #include #ifdef MIN #undef MIN #endif #define MIN(x,y) ((x) < (y)? (x): (y)) /* MAXIMUM_USB_STRING_LENGTH from usbspec.h is 255 */ /* BLUETOOTH_DEVICE_NAME_SIZE from bluetoothapis.h is 256 */ #define MAX_STRING_WCHARS 256 /* For certain USB devices, using a buffer larger or equal to 127 wchars results in successful completion of HID API functions, but a broken string is stored in the output buffer. This behaviour persists even if HID API is bypassed and HID IOCTLs are passed to the HID driver directly. Therefore, for USB devices, the buffer MUST NOT exceed 126 WCHARs. */ #define MAX_STRING_WCHARS_USB 126 static struct hid_api_version api_version = { .major = HID_API_VERSION_MAJOR, .minor = HID_API_VERSION_MINOR, .patch = HID_API_VERSION_PATCH }; #ifndef HIDAPI_USE_DDK /* Since we're not building with the DDK, and the HID header files aren't part of the Windows SDK, we define what we need ourselves. In lookup_functions(), the function pointers defined below are set. */ static HidD_GetHidGuid_ HidD_GetHidGuid; static HidD_GetAttributes_ HidD_GetAttributes; static HidD_GetSerialNumberString_ HidD_GetSerialNumberString; static HidD_GetManufacturerString_ HidD_GetManufacturerString; static HidD_GetProductString_ HidD_GetProductString; static HidD_SetFeature_ HidD_SetFeature; static HidD_GetFeature_ HidD_GetFeature; static HidD_SetOutputReport_ HidD_SetOutputReport; static HidD_GetInputReport_ HidD_GetInputReport; static HidD_GetIndexedString_ HidD_GetIndexedString; static HidD_GetPreparsedData_ HidD_GetPreparsedData; static HidD_FreePreparsedData_ HidD_FreePreparsedData; static HidP_GetCaps_ HidP_GetCaps; static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers; static CM_Locate_DevNodeW_ CM_Locate_DevNodeW = NULL; static CM_Get_Parent_ CM_Get_Parent = NULL; static CM_Get_DevNode_PropertyW_ CM_Get_DevNode_PropertyW = NULL; static CM_Get_Device_Interface_PropertyW_ CM_Get_Device_Interface_PropertyW = NULL; static CM_Get_Device_Interface_List_SizeW_ CM_Get_Device_Interface_List_SizeW = NULL; static CM_Get_Device_Interface_ListW_ CM_Get_Device_Interface_ListW = NULL; static HMODULE hid_lib_handle = NULL; static HMODULE cfgmgr32_lib_handle = NULL; static BOOLEAN hidapi_initialized = FALSE; static void free_library_handles() { if (hid_lib_handle) FreeLibrary(hid_lib_handle); hid_lib_handle = NULL; if (cfgmgr32_lib_handle) FreeLibrary(cfgmgr32_lib_handle); cfgmgr32_lib_handle = NULL; } static int lookup_functions() { hid_lib_handle = LoadLibraryW(L"hid.dll"); if (hid_lib_handle == NULL) { goto err; } cfgmgr32_lib_handle = LoadLibraryW(L"cfgmgr32.dll"); if (cfgmgr32_lib_handle == NULL) { goto err; } #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wcast-function-type" #endif #define RESOLVE(lib_handle, x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) goto err; RESOLVE(hid_lib_handle, HidD_GetHidGuid); RESOLVE(hid_lib_handle, HidD_GetAttributes); RESOLVE(hid_lib_handle, HidD_GetSerialNumberString); RESOLVE(hid_lib_handle, HidD_GetManufacturerString); RESOLVE(hid_lib_handle, HidD_GetProductString); RESOLVE(hid_lib_handle, HidD_SetFeature); RESOLVE(hid_lib_handle, HidD_GetFeature); RESOLVE(hid_lib_handle, HidD_SetOutputReport); RESOLVE(hid_lib_handle, HidD_GetInputReport); RESOLVE(hid_lib_handle, HidD_GetIndexedString); RESOLVE(hid_lib_handle, HidD_GetPreparsedData); RESOLVE(hid_lib_handle, HidD_FreePreparsedData); RESOLVE(hid_lib_handle, HidP_GetCaps); RESOLVE(hid_lib_handle, HidD_SetNumInputBuffers); RESOLVE(cfgmgr32_lib_handle, CM_Locate_DevNodeW); RESOLVE(cfgmgr32_lib_handle, CM_Get_Parent); RESOLVE(cfgmgr32_lib_handle, CM_Get_DevNode_PropertyW); RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_PropertyW); RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_List_SizeW); RESOLVE(cfgmgr32_lib_handle, CM_Get_Device_Interface_ListW); #undef RESOLVE #if defined(__GNUC__) # pragma GCC diagnostic pop #endif return 0; err: free_library_handles(); return -1; } #endif /* HIDAPI_USE_DDK */ struct hid_device_ { HANDLE device_handle; BOOL blocking; USHORT output_report_length; unsigned char *write_buf; size_t input_report_length; USHORT feature_report_length; unsigned char *feature_buf; wchar_t *last_error_str; wchar_t *last_read_error_str; BOOL read_pending; char *read_buf; OVERLAPPED ol; OVERLAPPED write_ol; struct hid_device_info* device_info; DWORD write_timeout_ms; }; static hid_device *new_hid_device() { hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); if (dev == NULL) { return NULL; } dev->device_handle = INVALID_HANDLE_VALUE; dev->blocking = TRUE; dev->output_report_length = 0; dev->write_buf = NULL; dev->input_report_length = 0; dev->feature_report_length = 0; dev->feature_buf = NULL; dev->last_error_str = NULL; dev->last_read_error_str = NULL; dev->read_pending = FALSE; dev->read_buf = NULL; memset(&dev->ol, 0, sizeof(dev->ol)); dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); memset(&dev->write_ol, 0, sizeof(dev->write_ol)); dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); dev->device_info = NULL; dev->write_timeout_ms = 1000; return dev; } static void free_hid_device(hid_device *dev) { CloseHandle(dev->ol.hEvent); CloseHandle(dev->write_ol.hEvent); CloseHandle(dev->device_handle); free(dev->last_error_str); free(dev->last_read_error_str); dev->last_error_str = NULL; dev->last_read_error_str = NULL; free(dev->write_buf); free(dev->feature_buf); free(dev->read_buf); hid_free_enumeration(dev->device_info); free(dev); } static void register_winapi_error_to_buffer(wchar_t **error_buffer, const WCHAR *op) { free(*error_buffer); *error_buffer = NULL; /* Only clear out error messages if NULL is passed into op */ if (!op) { return; } WCHAR system_err_buf[1024]; DWORD error_code = GetLastError(); DWORD system_err_len = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_err_buf, ARRAYSIZE(system_err_buf), NULL); DWORD op_len = (DWORD)wcslen(op); DWORD op_prefix_len = op_len + 15 /*: (0x00000000) */ ; DWORD msg_len = + op_prefix_len + system_err_len ; *error_buffer = (WCHAR *)calloc(msg_len + 1, sizeof (WCHAR)); WCHAR *msg = *error_buffer; if (!msg) return; int printf_written = swprintf(msg, msg_len + 1, L"%.*ls: (0x%08X) %.*ls", (int)op_len, op, error_code, (int)system_err_len, system_err_buf); if (printf_written < 0) { /* Highly unlikely */ msg[0] = L'\0'; return; } /* Get rid of the CR and LF that FormatMessage() sticks at the end of the message. Thanks Microsoft! */ while(msg[msg_len-1] == L'\r' || msg[msg_len-1] == L'\n' || msg[msg_len-1] == L' ') { msg[msg_len-1] = L'\0'; msg_len--; } } #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Warray-bounds" #endif /* A bug in GCC/mingw gives: * error: array subscript 0 is outside array bounds of 'wchar_t *[0]' {aka 'short unsigned int *[]'} [-Werror=array-bounds] * | free(*error_buffer); * Which doesn't make sense in this context. */ static void register_string_error_to_buffer(wchar_t **error_buffer, const WCHAR *string_error) { free(*error_buffer); *error_buffer = NULL; if (string_error) { *error_buffer = _wcsdup(string_error); } } #if defined(__GNUC__) # pragma GCC diagnostic pop #endif static void register_winapi_error(hid_device *dev, const WCHAR *op) { register_winapi_error_to_buffer(&dev->last_error_str, op); } static void register_string_error(hid_device *dev, const WCHAR *string_error) { register_string_error_to_buffer(&dev->last_error_str, string_error); } static wchar_t *last_global_error_str = NULL; static void register_global_winapi_error(const WCHAR *op) { register_winapi_error_to_buffer(&last_global_error_str, op); } static void register_global_error(const WCHAR *string_error) { register_string_error_to_buffer(&last_global_error_str, string_error); } static HANDLE open_device(const wchar_t *path, BOOL open_rw) { HANDLE handle; DWORD desired_access = (open_rw)? (GENERIC_WRITE | GENERIC_READ): 0; DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE; handle = CreateFileW(path, desired_access, share_mode, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/ 0); return handle; } HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void) { return &api_version; } HID_API_EXPORT const char* HID_API_CALL hid_version_str(void) { return HID_API_VERSION_STR; } int HID_API_EXPORT hid_init(void) { register_global_error(NULL); #ifndef HIDAPI_USE_DDK if (!hidapi_initialized) { if (lookup_functions() < 0) { register_global_winapi_error(L"resolve DLL functions"); return -1; } hidapi_initialized = TRUE; } #endif return 0; } int HID_API_EXPORT hid_exit(void) { #ifndef HIDAPI_USE_DDK free_library_handles(); hidapi_initialized = FALSE; #endif register_global_error(NULL); return 0; } static void* hid_internal_get_devnode_property(DEVINST dev_node, const DEVPROPKEY* property_key, DEVPROPTYPE expected_property_type) { ULONG len = 0; CONFIGRET cr; DEVPROPTYPE property_type; PBYTE property_value = NULL; cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, NULL, &len, 0); if (cr != CR_BUFFER_SMALL || property_type != expected_property_type) return NULL; property_value = (PBYTE)calloc(len, sizeof(BYTE)); cr = CM_Get_DevNode_PropertyW(dev_node, property_key, &property_type, property_value, &len, 0); if (cr != CR_SUCCESS) { free(property_value); return NULL; } return property_value; } static void* hid_internal_get_device_interface_property(const wchar_t* interface_path, const DEVPROPKEY* property_key, DEVPROPTYPE expected_property_type) { ULONG len = 0; CONFIGRET cr; DEVPROPTYPE property_type; PBYTE property_value = NULL; cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, NULL, &len, 0); if (cr != CR_BUFFER_SMALL || property_type != expected_property_type) return NULL; property_value = (PBYTE)calloc(len, sizeof(BYTE)); cr = CM_Get_Device_Interface_PropertyW(interface_path, property_key, &property_type, property_value, &len, 0); if (cr != CR_SUCCESS) { free(property_value); return NULL; } return property_value; } static void hid_internal_towupper(wchar_t* string) { for (wchar_t* p = string; *p; ++p) *p = towupper(*p); } static int hid_internal_extract_int_token_value(wchar_t* string, const wchar_t* token) { int token_value; wchar_t* startptr, * endptr; startptr = wcsstr(string, token); if (!startptr) return -1; startptr += wcslen(token); token_value = wcstol(startptr, &endptr, 16); if (endptr == startptr) return -1; return token_value; } static void hid_internal_get_usb_info(struct hid_device_info* dev, DEVINST dev_node) { wchar_t *device_id = NULL, *hardware_ids = NULL; device_id = (wchar_t *)hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); if (!device_id) goto end; /* Normalize to upper case */ hid_internal_towupper(device_id); /* Check for Xbox Common Controller class (XUSB) device. https://docs.microsoft.com/windows/win32/xinput/directinput-and-xusb-devices https://docs.microsoft.com/windows/win32/xinput/xinput-and-directinput */ if (hid_internal_extract_int_token_value(device_id, L"IG_") != -1) { /* Get devnode parent to reach out USB device. */ if (CM_Get_Parent(&dev_node, dev_node, 0) != CR_SUCCESS) goto end; } /* Get the hardware ids from devnode */ hardware_ids = (wchar_t *)hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_HardwareIds, DEVPROP_TYPE_STRING_LIST); if (!hardware_ids) goto end; /* Get additional information from USB device's Hardware ID https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers https://docs.microsoft.com/windows-hardware/drivers/usbcon/enumeration-of-interfaces-not-grouped-in-collections */ for (wchar_t* hardware_id = hardware_ids; *hardware_id; hardware_id += wcslen(hardware_id) + 1) { /* Normalize to upper case */ hid_internal_towupper(hardware_id); if (dev->release_number == 0) { /* USB_DEVICE_DESCRIPTOR.bcdDevice value. */ int release_number = hid_internal_extract_int_token_value(hardware_id, L"REV_"); if (release_number != -1) { dev->release_number = (unsigned short)release_number; } } if (dev->interface_number == -1) { /* USB_INTERFACE_DESCRIPTOR.bInterfaceNumber value. */ int interface_number = hid_internal_extract_int_token_value(hardware_id, L"MI_"); if (interface_number != -1) { dev->interface_number = interface_number; } } } /* Try to get USB device manufacturer string if not provided by HidD_GetManufacturerString. */ if (wcslen(dev->manufacturer_string) == 0) { wchar_t* manufacturer_string = (wchar_t *)hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_Manufacturer, DEVPROP_TYPE_STRING); if (manufacturer_string) { free(dev->manufacturer_string); dev->manufacturer_string = manufacturer_string; } } /* Try to get USB device serial number if not provided by HidD_GetSerialNumberString. */ if (wcslen(dev->serial_number) == 0) { DEVINST usb_dev_node = dev_node; if (dev->interface_number != -1) { /* Get devnode parent to reach out composite parent USB device. https://docs.microsoft.com/windows-hardware/drivers/usbcon/enumeration-of-the-composite-parent-device */ if (CM_Get_Parent(&usb_dev_node, dev_node, 0) != CR_SUCCESS) goto end; } /* Get the device id of the USB device. */ free(device_id); device_id = (wchar_t *)hid_internal_get_devnode_property(usb_dev_node, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); if (!device_id) goto end; /* Extract substring after last '\\' of Instance ID. For USB devices it may contain device's serial number. https://docs.microsoft.com/windows-hardware/drivers/install/instance-ids */ for (wchar_t *ptr = device_id + wcslen(device_id); ptr > device_id; --ptr) { /* Instance ID is unique only within the scope of the bus. For USB devices it means that serial number is not available. Skip. */ if (*ptr == L'&') break; if (*ptr == L'\\') { free(dev->serial_number); dev->serial_number = _wcsdup(ptr + 1); break; } } } /* If we can't get the interface number, it means that there is only one interface. */ if (dev->interface_number == -1) dev->interface_number = 0; end: free(device_id); free(hardware_ids); } /* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices Request this info via dev node properties instead. https://docs.microsoft.com/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html */ static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_node) { if (wcslen(dev->manufacturer_string) == 0) { /* Manufacturer Name String (UUID: 0x2A29) */ wchar_t* manufacturer_string = (wchar_t *)hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_Manufacturer, DEVPROP_TYPE_STRING); if (manufacturer_string) { free(dev->manufacturer_string); dev->manufacturer_string = manufacturer_string; } } if (wcslen(dev->serial_number) == 0) { /* Serial Number String (UUID: 0x2A25) */ wchar_t* serial_number = (wchar_t *)hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_DeviceAddress, DEVPROP_TYPE_STRING); if (serial_number) { free(dev->serial_number); dev->serial_number = serial_number; } } if (wcslen(dev->product_string) == 0) { /* Model Number String (UUID: 0x2A24) */ wchar_t* product_string = (wchar_t *)hid_internal_get_devnode_property(dev_node, (const DEVPROPKEY*)&PKEY_DeviceInterface_Bluetooth_ModelNumber, DEVPROP_TYPE_STRING); if (!product_string) { DEVINST parent_dev_node = 0; /* Fallback: Get devnode grandparent to reach out Bluetooth LE device node */ if (CM_Get_Parent(&parent_dev_node, dev_node, 0) == CR_SUCCESS) { /* Device Name (UUID: 0x2A00) */ product_string = (wchar_t *)hid_internal_get_devnode_property(parent_dev_node, &DEVPKEY_NAME, DEVPROP_TYPE_STRING); } } if (product_string) { free(dev->product_string); dev->product_string = product_string; } } } /* Unfortunately, HID_API_BUS_xxx constants alone aren't enough to distinguish between BLUETOOTH and BLE */ #define HID_API_BUS_FLAG_BLE 0x01 typedef struct hid_internal_detect_bus_type_result_ { DEVINST dev_node; hid_bus_type bus_type; unsigned int bus_flags; } hid_internal_detect_bus_type_result; static hid_internal_detect_bus_type_result hid_internal_detect_bus_type(const wchar_t* interface_path) { wchar_t *device_id = NULL, *compatible_ids = NULL; CONFIGRET cr; DEVINST dev_node; hid_internal_detect_bus_type_result result = { 0 }; /* Get the device id from interface path */ device_id = (wchar_t *)hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); if (!device_id) goto end; /* Open devnode from device id */ cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL); if (cr != CR_SUCCESS) goto end; /* Get devnode parent */ cr = CM_Get_Parent(&dev_node, dev_node, 0); if (cr != CR_SUCCESS) goto end; /* Get the compatible ids from parent devnode */ compatible_ids = (wchar_t *)hid_internal_get_devnode_property(dev_node, &DEVPKEY_Device_CompatibleIds, DEVPROP_TYPE_STRING_LIST); if (!compatible_ids) goto end; /* Now we can parse parent's compatible IDs to find out the device bus type */ for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += wcslen(compatible_id) + 1) { /* Normalize to upper case */ hid_internal_towupper(compatible_id); /* USB devices https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers */ if (wcsstr(compatible_id, L"USB") != NULL) { result.bus_type = HID_API_BUS_USB; break; } /* Bluetooth devices https://docs.microsoft.com/windows-hardware/drivers/bluetooth/installing-a-bluetooth-device */ if (wcsstr(compatible_id, L"BTHENUM") != NULL) { result.bus_type = HID_API_BUS_BLUETOOTH; break; } /* Bluetooth LE devices */ if (wcsstr(compatible_id, L"BTHLEDEVICE") != NULL) { result.bus_type = HID_API_BUS_BLUETOOTH; result.bus_flags |= HID_API_BUS_FLAG_BLE; break; } /* I2C devices https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-support-and-power-management */ if (wcsstr(compatible_id, L"PNP0C50") != NULL) { result.bus_type = HID_API_BUS_I2C; break; } /* SPI devices https://docs.microsoft.com/windows-hardware/drivers/hid/plug-and-play-for-spi */ if (wcsstr(compatible_id, L"PNP0C51") != NULL) { result.bus_type = HID_API_BUS_SPI; break; } } result.dev_node = dev_node; end: free(device_id); free(compatible_ids); return result; } static char *hid_internal_UTF16toUTF8(const wchar_t *src) { char *dst = NULL; int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, NULL, 0, NULL, NULL); if (len) { dst = (char*)calloc(len, sizeof(char)); if (dst == NULL) { return NULL; } WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, src, -1, dst, len, NULL, NULL); } return dst; } static wchar_t *hid_internal_UTF8toUTF16(const char *src) { wchar_t *dst = NULL; int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, NULL, 0); if (len) { dst = (wchar_t*)calloc(len, sizeof(wchar_t)); if (dst == NULL) { return NULL; } MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, src, -1, dst, len); } return dst; } static struct hid_device_info *hid_internal_get_device_info(const wchar_t *path, HANDLE handle) { struct hid_device_info *dev = NULL; /* return object */ HIDD_ATTRIBUTES attrib; PHIDP_PREPARSED_DATA pp_data = NULL; HIDP_CAPS caps; wchar_t string[MAX_STRING_WCHARS + 1]; ULONG len; ULONG size; hid_internal_detect_bus_type_result detect_bus_type_result; /* Create the record. */ dev = (struct hid_device_info*)calloc(1, sizeof(struct hid_device_info)); if (dev == NULL) { return NULL; } /* Fill out the record */ dev->next = NULL; dev->path = hid_internal_UTF16toUTF8(path); dev->interface_number = -1; attrib.Size = sizeof(HIDD_ATTRIBUTES); if (HidD_GetAttributes(handle, &attrib)) { /* VID/PID */ dev->vendor_id = attrib.VendorID; dev->product_id = attrib.ProductID; /* Release Number */ dev->release_number = attrib.VersionNumber; } /* Get the Usage Page and Usage for this device. */ if (HidD_GetPreparsedData(handle, &pp_data)) { if (HidP_GetCaps(pp_data, &caps) == HIDP_STATUS_SUCCESS) { dev->usage_page = caps.UsagePage; dev->usage = caps.Usage; } HidD_FreePreparsedData(pp_data); } /* detect bus type before reading string descriptors */ detect_bus_type_result = hid_internal_detect_bus_type(path); dev->bus_type = detect_bus_type_result.bus_type; len = dev->bus_type == HID_API_BUS_USB ? MAX_STRING_WCHARS_USB : MAX_STRING_WCHARS; string[len] = L'\0'; size = len * sizeof(wchar_t); /* Serial Number */ string[0] = L'\0'; HidD_GetSerialNumberString(handle, string, size); dev->serial_number = _wcsdup(string); /* Manufacturer String */ string[0] = L'\0'; HidD_GetManufacturerString(handle, string, size); dev->manufacturer_string = _wcsdup(string); /* Product String */ string[0] = L'\0'; HidD_GetProductString(handle, string, size); dev->product_string = _wcsdup(string); /* now, the portion that depends on string descriptors */ switch (dev->bus_type) { case HID_API_BUS_USB: hid_internal_get_usb_info(dev, detect_bus_type_result.dev_node); break; case HID_API_BUS_BLUETOOTH: if (detect_bus_type_result.bus_flags & HID_API_BUS_FLAG_BLE) hid_internal_get_ble_info(dev, detect_bus_type_result.dev_node); break; case HID_API_BUS_UNKNOWN: case HID_API_BUS_SPI: case HID_API_BUS_I2C: /* shut down -Wswitch */ break; } return dev; } struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id) { struct hid_device_info *root = NULL; /* return object */ struct hid_device_info *cur_dev = NULL; GUID interface_class_guid; CONFIGRET cr; wchar_t* device_interface_list = NULL; DWORD len; if (hid_init() < 0) { /* register_global_error: global error is reset by hid_init */ return NULL; } /* Retrieve HID Interface Class GUID https://docs.microsoft.com/windows-hardware/drivers/install/guid-devinterface-hid */ HidD_GetHidGuid(&interface_class_guid); /* Get the list of all device interfaces belonging to the HID class. */ /* Retry in case of list was changed between calls to CM_Get_Device_Interface_List_SizeW and CM_Get_Device_Interface_ListW */ do { cr = CM_Get_Device_Interface_List_SizeW(&len, &interface_class_guid, NULL, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); if (cr != CR_SUCCESS) { register_global_error(L"Failed to get size of HID device interface list"); break; } if (device_interface_list != NULL) { free(device_interface_list); } device_interface_list = (wchar_t*)calloc(len, sizeof(wchar_t)); if (device_interface_list == NULL) { register_global_error(L"Failed to allocate memory for HID device interface list"); return NULL; } cr = CM_Get_Device_Interface_ListW(&interface_class_guid, NULL, device_interface_list, len, CM_GET_DEVICE_INTERFACE_LIST_PRESENT); if (cr != CR_SUCCESS && cr != CR_BUFFER_SMALL) { register_global_error(L"Failed to get HID device interface list"); } } while (cr == CR_BUFFER_SMALL); if (cr != CR_SUCCESS) { goto end_of_function; } /* Iterate over each device interface in the HID class, looking for the right one. */ for (wchar_t* device_interface = device_interface_list; *device_interface; device_interface += wcslen(device_interface) + 1) { HANDLE device_handle = INVALID_HANDLE_VALUE; HIDD_ATTRIBUTES attrib; /* Open read-only handle to the device */ device_handle = open_device(device_interface, FALSE); /* Check validity of device_handle. */ if (device_handle == INVALID_HANDLE_VALUE) { /* Unable to open the device. */ continue; } /* Get the Vendor ID and Product ID for this device. */ attrib.Size = sizeof(HIDD_ATTRIBUTES); if (!HidD_GetAttributes(device_handle, &attrib)) { goto cont_close; } /* Check the VID/PID to see if we should add this device to the enumeration list. */ if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) && (product_id == 0x0 || attrib.ProductID == product_id)) { /* VID/PID match. Create the record. */ struct hid_device_info *tmp = hid_internal_get_device_info(device_interface, device_handle); if (tmp == NULL) { goto cont_close; } if (cur_dev) { cur_dev->next = tmp; } else { root = tmp; } cur_dev = tmp; } cont_close: CloseHandle(device_handle); } if (root == NULL) { if (vendor_id == 0 && product_id == 0) { register_global_error(L"No HID devices found in the system."); } else { register_global_error(L"No HID devices with requested VID/PID found in the system."); } } end_of_function: free(device_interface_list); return root; } void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs) { /* TODO: Merge this with the Linux version. This function is platform-independent. */ struct hid_device_info *d = devs; while (d) { struct hid_device_info *next = d->next; free(d->path); free(d->serial_number); free(d->manufacturer_string); free(d->product_string); free(d); d = next; } } HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) { /* TODO: Merge this functions with the Linux version. This function should be platform independent. */ struct hid_device_info *devs, *cur_dev; const char *path_to_open = NULL; hid_device *handle = NULL; /* register_global_error: global error is reset by hid_enumerate/hid_init */ devs = hid_enumerate(vendor_id, product_id); if (!devs) { /* register_global_error: global error is already set by hid_enumerate */ return NULL; } cur_dev = devs; while (cur_dev) { if (cur_dev->vendor_id == vendor_id && cur_dev->product_id == product_id) { if (serial_number) { if (cur_dev->serial_number && wcscmp(serial_number, cur_dev->serial_number) == 0) { path_to_open = cur_dev->path; break; } } else { path_to_open = cur_dev->path; break; } } cur_dev = cur_dev->next; } if (path_to_open) { /* Open the device */ handle = hid_open_path(path_to_open); } else { register_global_error(L"Device with requested VID/PID/(SerialNumber) not found"); } hid_free_enumeration(devs); return handle; } HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path) { hid_device *dev = NULL; wchar_t* interface_path = NULL; HANDLE device_handle = INVALID_HANDLE_VALUE; PHIDP_PREPARSED_DATA pp_data = NULL; HIDP_CAPS caps; if (hid_init() < 0) { /* register_global_error: global error is reset by hid_init */ goto end_of_function; } interface_path = hid_internal_UTF8toUTF16(path); if (!interface_path) { register_global_error(L"Path conversion failure"); goto end_of_function; } /* Open a handle to the device */ device_handle = open_device(interface_path, TRUE); /* Check validity of write_handle. */ if (device_handle == INVALID_HANDLE_VALUE) { /* System devices, such as keyboards and mice, cannot be opened in read-write mode, because the system takes exclusive control over them. This is to prevent keyloggers. However, feature reports can still be sent and received. Retry opening the device, but without read/write access. */ device_handle = open_device(interface_path, FALSE); /* Check the validity of the limited device_handle. */ if (device_handle == INVALID_HANDLE_VALUE) { register_global_winapi_error(L"open_device"); goto end_of_function; } } /* Set the Input Report buffer size to 64 reports. */ if (!HidD_SetNumInputBuffers(device_handle, 64)) { register_global_winapi_error(L"set input buffers"); goto end_of_function; } /* Get the Input Report length for the device. */ if (!HidD_GetPreparsedData(device_handle, &pp_data)) { register_global_winapi_error(L"get preparsed data"); goto end_of_function; } if (HidP_GetCaps(pp_data, &caps) != HIDP_STATUS_SUCCESS) { register_global_error(L"HidP_GetCaps"); goto end_of_function; } dev = new_hid_device(); if (dev == NULL) { register_global_error(L"hid_device allocation error"); goto end_of_function; } dev->device_handle = device_handle; device_handle = INVALID_HANDLE_VALUE; dev->output_report_length = caps.OutputReportByteLength; dev->input_report_length = caps.InputReportByteLength; dev->feature_report_length = caps.FeatureReportByteLength; dev->read_buf = (char*) malloc(dev->input_report_length); dev->device_info = hid_internal_get_device_info(interface_path, dev->device_handle); end_of_function: free(interface_path); if (device_handle != INVALID_HANDLE_VALUE) { CloseHandle(device_handle); } if (pp_data) { HidD_FreePreparsedData(pp_data); } return dev; } void HID_API_EXPORT_CALL hid_winapi_set_write_timeout(hid_device *dev, unsigned long timeout) { dev->write_timeout_ms = timeout; } int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length) { DWORD bytes_written = 0; int function_result = -1; BOOL res; BOOL overlapped = FALSE; unsigned char *buf; if (!data || !length) { register_string_error(dev, L"Zero buffer/length"); return function_result; } register_string_error(dev, NULL); /* Make sure the right number of bytes are passed to WriteFile. Windows expects the number of bytes which are in the _longest_ report (plus one for the report number) bytes even if the data is a report which is shorter than that. Windows gives us this value in caps.OutputReportByteLength. If a user passes in fewer bytes than this, use cached temporary buffer which is the proper size. */ if (length >= dev->output_report_length) { /* The user passed the right number of bytes. Use the buffer as-is. */ buf = (unsigned char *) data; } else { if (dev->write_buf == NULL) { dev->write_buf = (unsigned char *) malloc(dev->output_report_length); if (dev->write_buf == NULL) { register_string_error(dev, L"hid_write/malloc"); goto end_of_function; } } buf = dev->write_buf; memcpy(buf, data, length); memset(buf + length, 0, dev->output_report_length - length); length = dev->output_report_length; } res = WriteFile(dev->device_handle, buf, (DWORD) length, &bytes_written, &dev->write_ol); if (!res) { if (GetLastError() != ERROR_IO_PENDING) { /* WriteFile() failed. Return error. */ register_winapi_error(dev, L"WriteFile"); goto end_of_function; } overlapped = TRUE; } else { /* WriteFile() succeeded synchronously. */ function_result = bytes_written; } if (overlapped) { /* Wait for the transaction to complete. This makes hid_write() synchronous. */ res = WaitForSingleObject(dev->write_ol.hEvent, dev->write_timeout_ms); if (res != WAIT_OBJECT_0) { /* There was a Timeout. */ register_winapi_error(dev, L"hid_write/WaitForSingleObject"); goto end_of_function; } /* Get the result. */ res = GetOverlappedResult(dev->device_handle, &dev->write_ol, &bytes_written, FALSE/*wait*/); if (res) { function_result = bytes_written; } else { /* The Write operation failed. */ register_winapi_error(dev, L"hid_write/GetOverlappedResult"); goto end_of_function; } } end_of_function: return function_result; } int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) { DWORD bytes_read = 0; size_t copy_len = 0; BOOL res = FALSE; BOOL overlapped = FALSE; if (!data || !length) { register_string_error_to_buffer(&dev->last_read_error_str, L"Zero buffer/length"); return -1; } register_string_error_to_buffer(&dev->last_read_error_str, NULL); /* Copy the handle for convenience. */ HANDLE ev = dev->ol.hEvent; if (!dev->read_pending) { /* Start an Overlapped I/O read. */ dev->read_pending = TRUE; memset(dev->read_buf, 0, dev->input_report_length); ResetEvent(ev); res = ReadFile(dev->device_handle, dev->read_buf, (DWORD) dev->input_report_length, &bytes_read, &dev->ol); if (!res) { if (GetLastError() != ERROR_IO_PENDING) { /* ReadFile() has failed. Clean up and return error. */ register_winapi_error_to_buffer(&dev->last_read_error_str, L"ReadFile"); CancelIo(dev->device_handle); dev->read_pending = FALSE; goto end_of_function; } overlapped = TRUE; } } else { overlapped = TRUE; } if (overlapped) { /* See if there is any data yet. */ res = WaitForSingleObject(ev, milliseconds >= 0 ? (DWORD)milliseconds : INFINITE); if (res != WAIT_OBJECT_0) { /* There was no data this time. Return zero bytes available, but leave the Overlapped I/O running. */ return 0; } /* Get the number of bytes read. The actual data has been copied to the data[] array which was passed to ReadFile(). We must not wait here because we've already waited on our event above, and since it's auto-reset, it will have been reset back to unsignalled by now. */ res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, FALSE/*don't wait now - already did on the prev step*/); } /* Set pending back to false, even if GetOverlappedResult() returned error. */ dev->read_pending = FALSE; if (res && bytes_read > 0) { if (dev->read_buf[0] == 0x0) { /* If report numbers aren't being used, but Windows sticks a report number (0x0) on the beginning of the report anyway. To make this work like the other platforms, and to make it work more like the HID spec, we'll skip over this byte. */ bytes_read--; copy_len = length > bytes_read ? bytes_read : length; memcpy(data, dev->read_buf+1, copy_len); } else { /* Copy the whole buffer, report number and all. */ copy_len = length > bytes_read ? bytes_read : length; memcpy(data, dev->read_buf, copy_len); } } if (!res) { register_winapi_error_to_buffer(&dev->last_read_error_str, L"hid_read_timeout/GetOverlappedResult"); } end_of_function: if (!res) { return -1; } return (int) copy_len; } int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length) { return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); } HID_API_EXPORT const wchar_t * HID_API_CALL hid_read_error(hid_device *dev) { if (dev->last_read_error_str == NULL) return L"Success"; return dev->last_read_error_str; } int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock) { dev->blocking = !nonblock; return 0; /* Success */ } int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) { BOOL res = FALSE; unsigned char *buf; size_t length_to_send; if (!data || !length) { register_string_error(dev, L"Zero buffer/length"); return -1; } register_string_error(dev, NULL); /* Windows expects at least caps.FeatureReportByteLength bytes passed to HidD_SetFeature(), even if the report is shorter. Any less sent and the function fails with error ERROR_INVALID_PARAMETER set. Any more and HidD_SetFeature() silently truncates the data sent in the report to caps.FeatureReportByteLength. */ if (length >= dev->feature_report_length) { buf = (unsigned char *) data; length_to_send = length; } else { if (dev->feature_buf == NULL) { dev->feature_buf = (unsigned char *) malloc(dev->feature_report_length); if (dev->feature_buf == NULL) { register_string_error(dev, L"hid_send_feature_report/malloc"); return -1; } } buf = dev->feature_buf; memcpy(buf, data, length); memset(buf + length, 0, dev->feature_report_length - length); length_to_send = dev->feature_report_length; } res = HidD_SetFeature(dev->device_handle, (PVOID)buf, (DWORD) length_to_send); if (!res) { register_winapi_error(dev, L"HidD_SetFeature"); return -1; } return (int) length; } static int hid_get_report(hid_device *dev, DWORD report_type, unsigned char *data, size_t length) { BOOL res; DWORD bytes_returned = 0; OVERLAPPED ol; memset(&ol, 0, sizeof(ol)); if (!data || !length) { register_string_error(dev, L"Zero buffer/length"); return -1; } register_string_error(dev, NULL); res = DeviceIoControl(dev->device_handle, report_type, data, (DWORD) length, data, (DWORD) length, &bytes_returned, &ol); if (!res) { if (GetLastError() != ERROR_IO_PENDING) { /* DeviceIoControl() failed. Return error. */ register_winapi_error(dev, L"Get Input/Feature Report DeviceIoControl"); return -1; } } /* Wait here until the write is done. This makes hid_get_feature_report() synchronous. */ res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/); if (!res) { /* The operation failed. */ register_winapi_error(dev, L"Get Input/Feature Report GetOverLappedResult"); return -1; } /* When numbered reports aren't used, bytes_returned seem to include only what is actually received from the device (not including the first byte with 0, as an indication "no numbered reports"). */ if (data[0] == 0x0) { bytes_returned++; } return bytes_returned; } int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) { /* We could use HidD_GetFeature() instead, but it doesn't give us an actual length, unfortunately */ return hid_get_report(dev, IOCTL_HID_GET_FEATURE, data, length); } int HID_API_EXPORT HID_API_CALL hid_send_output_report(hid_device* dev, const unsigned char* data, size_t length) { BOOL res = FALSE; unsigned char *buf; size_t length_to_send; if (!data || !length) { register_string_error(dev, L"Zero buffer/length"); return -1; } register_string_error(dev, NULL); /* Windows expects at least caps.OutputeportByteLength bytes passed to HidD_SetOutputReport(), even if the report is shorter. Any less sent and the function fails with error ERROR_INVALID_PARAMETER set. Any more and HidD_SetOutputReport() silently truncates the data sent in the report to caps.OutputReportByteLength. */ if (length >= dev->output_report_length) { buf = (unsigned char *) data; length_to_send = length; } else { if (dev->write_buf == NULL) { dev->write_buf = (unsigned char *) malloc(dev->output_report_length); if (dev->write_buf == NULL) { register_string_error(dev, L"hid_send_output_report/malloc"); return -1; } } buf = dev->write_buf; memcpy(buf, data, length); memset(buf + length, 0, dev->output_report_length - length); length_to_send = dev->output_report_length; } res = HidD_SetOutputReport(dev->device_handle, (PVOID)buf, (DWORD) length_to_send); if (!res) { register_string_error(dev, L"HidD_SetOutputReport"); return -1; } return (int) length; } int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) { /* We could use HidD_GetInputReport() instead, but it doesn't give us an actual length, unfortunately */ return hid_get_report(dev, IOCTL_HID_GET_INPUT_REPORT, data, length); } void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev) { if (!dev) return; CancelIo(dev->device_handle); free_hid_device(dev); } int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { register_string_error(dev, L"Zero buffer/length"); return -1; } if (!dev->device_info) { register_string_error(dev, L"NULL device info"); return -1; } wcsncpy(string, dev->device_info->manufacturer_string, maxlen); string[maxlen - 1] = L'\0'; register_string_error(dev, NULL); return 0; } int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { register_string_error(dev, L"Zero buffer/length"); return -1; } if (!dev->device_info) { register_string_error(dev, L"NULL device info"); return -1; } wcsncpy(string, dev->device_info->product_string, maxlen); string[maxlen - 1] = L'\0'; register_string_error(dev, NULL); return 0; } int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) { if (!string || !maxlen) { register_string_error(dev, L"Zero buffer/length"); return -1; } if (!dev->device_info) { register_string_error(dev, L"NULL device info"); return -1; } wcsncpy(string, dev->device_info->serial_number, maxlen); string[maxlen - 1] = L'\0'; register_string_error(dev, NULL); return 0; } HID_API_EXPORT struct hid_device_info * HID_API_CALL hid_get_device_info(hid_device *dev) { if (!dev->device_info) { register_string_error(dev, L"NULL device info"); return NULL; } register_string_error(dev, NULL); return dev->device_info; } int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) { BOOL res; if (dev->device_info && dev->device_info->bus_type == HID_API_BUS_USB && maxlen > MAX_STRING_WCHARS_USB) { string[MAX_STRING_WCHARS_USB] = L'\0'; maxlen = MAX_STRING_WCHARS_USB; } res = HidD_GetIndexedString(dev->device_handle, string_index, string, (ULONG)maxlen * sizeof(wchar_t)); if (!res) { register_winapi_error(dev, L"HidD_GetIndexedString"); return -1; } register_string_error(dev, NULL); return 0; } int HID_API_EXPORT_CALL hid_winapi_get_container_id(hid_device *dev, GUID *container_id) { wchar_t *interface_path = NULL, *device_id = NULL; CONFIGRET cr = CR_FAILURE; DEVINST dev_node; DEVPROPTYPE property_type; ULONG len; if (!container_id) { register_string_error(dev, L"Invalid Container ID"); return -1; } register_string_error(dev, NULL); interface_path = hid_internal_UTF8toUTF16(dev->device_info->path); if (!interface_path) { register_string_error(dev, L"Path conversion failure"); goto end; } /* Get the device id from interface path */ device_id = (wchar_t *)hid_internal_get_device_interface_property(interface_path, &DEVPKEY_Device_InstanceId, DEVPROP_TYPE_STRING); if (!device_id) { register_string_error(dev, L"Failed to get device interface property InstanceId"); goto end; } /* Open devnode from device id */ cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL); if (cr != CR_SUCCESS) { register_string_error(dev, L"Failed to locate device node"); goto end; } /* Get the container id from devnode */ len = sizeof(*container_id); cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_ContainerId, &property_type, (PBYTE)container_id, &len, 0); if (cr == CR_SUCCESS && property_type != DEVPROP_TYPE_GUID) cr = CR_FAILURE; if (cr != CR_SUCCESS) register_string_error(dev, L"Failed to read ContainerId property from device node"); end: free(interface_path); free(device_id); return cr == CR_SUCCESS ? 0 : -1; } int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size) { PHIDP_PREPARSED_DATA pp_data = NULL; if (!HidD_GetPreparsedData(dev->device_handle, &pp_data) || pp_data == NULL) { register_string_error(dev, L"HidD_GetPreparsedData"); return -1; } int res = hid_winapi_descriptor_reconstruct_pp_data(pp_data, buf, buf_size); HidD_FreePreparsedData(pp_data); if (res == 0) { register_string_error(dev, NULL); } else { register_string_error(dev, L"Failed to reconstruct descriptor from PREPARSED_DATA"); } return res; } HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) { if (dev) { if (dev->last_error_str == NULL) return L"Success"; return (wchar_t*)dev->last_error_str; } if (last_global_error_str == NULL) return L"Success"; return last_global_error_str; } #ifndef hidapi_winapi_EXPORTS #include "hidapi_descriptor_reconstruct.c" #endif #ifdef __cplusplus } /* extern "C" */ #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216765.0 hidapi-0.15.0/hidapi/windows/hidapi_cfgmgr32.h0000644000076500000240000000734515115610775020145 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #ifndef HIDAPI_CFGMGR32_H #define HIDAPI_CFGMGR32_H #ifdef HIDAPI_USE_DDK #include #include #include #include #else /* This part of the header mimics cfgmgr32.h, but only what is used by HIDAPI */ #include #include #include typedef DWORD RETURN_TYPE; typedef RETURN_TYPE CONFIGRET; typedef DWORD DEVNODE, DEVINST; typedef DEVNODE* PDEVNODE, * PDEVINST; typedef WCHAR* DEVNODEID_W, * DEVINSTID_W; #define CR_SUCCESS (0x00000000) #define CR_BUFFER_SMALL (0x0000001A) #define CR_FAILURE (0x00000013) #define CM_LOCATE_DEVNODE_NORMAL 0x00000000 #define CM_GET_DEVICE_INTERFACE_LIST_PRESENT (0x00000000) typedef CONFIGRET(__stdcall* CM_Locate_DevNodeW_)(PDEVINST pdnDevInst, DEVINSTID_W pDeviceID, ULONG ulFlags); typedef CONFIGRET(__stdcall* CM_Get_Parent_)(PDEVINST pdnDevInst, DEVINST dnDevInst, ULONG ulFlags); typedef CONFIGRET(__stdcall* CM_Get_DevNode_PropertyW_)(DEVINST dnDevInst, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_PropertyW_)(LPCWSTR pszDeviceInterface, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_List_SizeW_)(PULONG pulLen, LPGUID InterfaceClassGuid, DEVINSTID_W pDeviceID, ULONG ulFlags); typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_ListW_)(LPGUID InterfaceClassGuid, DEVINSTID_W pDeviceID, PZZWSTR Buffer, ULONG BufferLen, ULONG ulFlags); // from devpkey.h DEFINE_DEVPROPKEY(DEVPKEY_NAME, 0xb725f130, 0x47ef, 0x101a, 0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10); // DEVPROP_TYPE_STRING DEFINE_DEVPROPKEY(DEVPKEY_Device_Manufacturer, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 13); // DEVPROP_TYPE_STRING DEFINE_DEVPROPKEY(DEVPKEY_Device_InstanceId, 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 256); // DEVPROP_TYPE_STRING DEFINE_DEVPROPKEY(DEVPKEY_Device_HardwareIds, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3); // DEVPROP_TYPE_STRING_LIST DEFINE_DEVPROPKEY(DEVPKEY_Device_CompatibleIds, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 4); // DEVPROP_TYPE_STRING_LIST DEFINE_DEVPROPKEY(DEVPKEY_Device_ContainerId, 0x8c7ed206, 0x3f8a, 0x4827, 0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c, 2); // DEVPROP_TYPE_GUID // from propkey.h DEFINE_PROPERTYKEY(PKEY_DeviceInterface_Bluetooth_DeviceAddress, 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A, 1); // DEVPROP_TYPE_STRING DEFINE_PROPERTYKEY(PKEY_DeviceInterface_Bluetooth_Manufacturer, 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A, 4); // DEVPROP_TYPE_STRING DEFINE_PROPERTYKEY(PKEY_DeviceInterface_Bluetooth_ModelNumber, 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A, 5); // DEVPROP_TYPE_STRING #endif #endif /* HIDAPI_CFGMGR32_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/windows/hidapi_descriptor_reconstruct.c0000644000076500000240000014721115115611013023316 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #include "hidapi_descriptor_reconstruct.h" /** * @brief References to report descriptor buffer. * */ struct rd_buffer { unsigned char* buf; /* Pointer to the array which stores the reconstructed descriptor */ size_t buf_size; /* Size of the buffer in bytes */ size_t byte_idx; /* Index of the next report byte to write to buf array */ }; /** * @brief Function that appends a byte to encoded report descriptor buffer. * * @param[in] byte Single byte to append. * @param rpt_desc Pointer to report descriptor buffer struct. */ static void rd_append_byte(unsigned char byte, struct rd_buffer* rpt_desc) { if (rpt_desc->byte_idx < rpt_desc->buf_size) { rpt_desc->buf[rpt_desc->byte_idx] = byte; rpt_desc->byte_idx++; } } /** * @brief Writes a short report descriptor item according USB HID spec 1.11 chapter 6.2.2.2. * * @param[in] rd_item Enumeration identifying type (Main, Global, Local) and function (e.g Usage or Report Count) of the item. * @param[in] data Data (Size depends on rd_item 0,1,2 or 4bytes). * @param rpt_desc Pointer to report descriptor buffer struct. * * @return Returns 0 if successful, -1 for error. */ static int rd_write_short_item(rd_items rd_item, LONG64 data, struct rd_buffer* rpt_desc) { if (rd_item & 0x03) { // Invalid input data, last to bits are reserved for data size return -1; } if (rd_item == rd_main_collection_end) { // Item without data (1Byte prefix only) unsigned char oneBytePrefix = (unsigned char) rd_item + 0x00; rd_append_byte(oneBytePrefix, rpt_desc); } else if ((rd_item == rd_global_logical_minimum) || (rd_item == rd_global_logical_maximum) || (rd_item == rd_global_physical_minimum) || (rd_item == rd_global_physical_maximum)) { // Item with signed integer data if ((data >= -128) && (data <= 127)) { // 1Byte prefix + 1Byte data unsigned char oneBytePrefix = (unsigned char) rd_item + 0x01; char localData = (char)data; rd_append_byte(oneBytePrefix, rpt_desc); rd_append_byte(localData & 0xFF, rpt_desc); } else if ((data >= -32768) && (data <= 32767)) { // 1Byte prefix + 2Byte data unsigned char oneBytePrefix = (unsigned char) rd_item + 0x02; INT16 localData = (INT16)data; rd_append_byte(oneBytePrefix, rpt_desc); rd_append_byte(localData & 0xFF, rpt_desc); rd_append_byte(localData >> 8 & 0xFF, rpt_desc); } else if ((data >= -2147483648LL) && (data <= 2147483647)) { // 1Byte prefix + 4Byte data unsigned char oneBytePrefix = (unsigned char) rd_item + 0x03; INT32 localData = (INT32)data; rd_append_byte(oneBytePrefix, rpt_desc); rd_append_byte(localData & 0xFF, rpt_desc); rd_append_byte(localData >> 8 & 0xFF, rpt_desc); rd_append_byte(localData >> 16 & 0xFF, rpt_desc); rd_append_byte(localData >> 24 & 0xFF, rpt_desc); } else { // Data out of 32 bit signed integer range return -1; } } else { // Item with unsigned integer data if ((data >= 0) && (data <= 0xFF)) { // 1Byte prefix + 1Byte data unsigned char oneBytePrefix = (unsigned char) rd_item + 0x01; unsigned char localData = (unsigned char)data; rd_append_byte(oneBytePrefix, rpt_desc); rd_append_byte(localData & 0xFF, rpt_desc); } else if ((data >= 0) && (data <= 0xFFFF)) { // 1Byte prefix + 2Byte data unsigned char oneBytePrefix = (unsigned char) rd_item + 0x02; UINT16 localData = (UINT16)data; rd_append_byte(oneBytePrefix, rpt_desc); rd_append_byte(localData & 0xFF, rpt_desc); rd_append_byte(localData >> 8 & 0xFF, rpt_desc); } else if ((data >= 0) && (data <= 0xFFFFFFFF)) { // 1Byte prefix + 4Byte data unsigned char oneBytePrefix = (unsigned char) rd_item + 0x03; UINT32 localData = (UINT32)data; rd_append_byte(oneBytePrefix, rpt_desc); rd_append_byte(localData & 0xFF, rpt_desc); rd_append_byte(localData >> 8 & 0xFF, rpt_desc); rd_append_byte(localData >> 16 & 0xFF, rpt_desc); rd_append_byte(localData >> 24 & 0xFF, rpt_desc); } else { // Data out of 32 bit unsigned integer range return -1; } } return 0; } static struct rd_main_item_node * rd_append_main_item_node(int first_bit, int last_bit, rd_node_type type_of_node, int caps_index, int collection_index, rd_main_items main_item_type, unsigned char report_id, struct rd_main_item_node **list) { struct rd_main_item_node *new_list_node; // Determine last node in the list while (*list != NULL) { list = &(*list)->next; } new_list_node = (struct rd_main_item_node *)malloc(sizeof(*new_list_node)); // Create new list entry new_list_node->FirstBit = first_bit; new_list_node->LastBit = last_bit; new_list_node->TypeOfNode = type_of_node; new_list_node->CapsIndex = caps_index; new_list_node->CollectionIndex = collection_index; new_list_node->MainItemType = main_item_type; new_list_node->ReportID = report_id; new_list_node->next = NULL; // NULL marks last node in the list *list = new_list_node; return new_list_node; } static struct rd_main_item_node * rd_insert_main_item_node(int first_bit, int last_bit, rd_node_type type_of_node, int caps_index, int collection_index, rd_main_items main_item_type, unsigned char report_id, struct rd_main_item_node **list) { // Insert item after the main item node referenced by list struct rd_main_item_node *next_item = (*list)->next; (*list)->next = NULL; rd_append_main_item_node(first_bit, last_bit, type_of_node, caps_index, collection_index, main_item_type, report_id, list); (*list)->next->next = next_item; return (*list)->next; } static struct rd_main_item_node * rd_search_main_item_list_for_bit_position(int search_bit, rd_main_items main_item_type, unsigned char report_id, struct rd_main_item_node **list) { // Determine first INPUT/OUTPUT/FEATURE main item, where the last bit position is equal or greater than the search bit position while (((*list)->next->MainItemType != rd_collection) && ((*list)->next->MainItemType != rd_collection_end) && !(((*list)->next->LastBit >= search_bit) && ((*list)->next->ReportID == report_id) && ((*list)->next->MainItemType == main_item_type)) ) { list = &(*list)->next; } return *list; } int hid_winapi_descriptor_reconstruct_pp_data(void *preparsed_data, unsigned char *buf, size_t buf_size) { hidp_preparsed_data *pp_data = (hidp_preparsed_data *) preparsed_data; // Check if MagicKey is correct, to ensure that pp_data points to an valid preparse data structure if (memcmp(pp_data->MagicKey, "HidP KDR", 8) != 0) { return -1; } struct rd_buffer rpt_desc = { .buf = buf, .buf_size = buf_size, .byte_idx = 0 }; // Set pointer to the first node of link_collection_nodes phid_pp_link_collection_node link_collection_nodes = (phid_pp_link_collection_node)(((unsigned char*)&pp_data->caps[0]) + pp_data->FirstByteOfLinkCollectionArray); // **************************************************************************************************************************** // Create lookup tables for the bit range of each report per collection (position of first bit and last bit in each collection) // coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] // **************************************************************************************************************************** // Allocate memory and initialize lookup table rd_bit_range ****coll_bit_range; coll_bit_range = (rd_bit_range ****)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_bit_range)); for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { coll_bit_range[collection_node_idx] = (rd_bit_range ***)malloc(256 * sizeof(*coll_bit_range[0])); // 256 possible report IDs (incl. 0x00) for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { coll_bit_range[collection_node_idx][reportid_idx] = (rd_bit_range **)malloc(NUM_OF_HIDP_REPORT_TYPES * sizeof(*coll_bit_range[0][0])); for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { coll_bit_range[collection_node_idx][reportid_idx][rt_idx] = (rd_bit_range *)malloc(sizeof(rd_bit_range)); coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit = -1; coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit = -1; } } } // Fill the lookup table where caps exist for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { for (USHORT caps_idx = pp_data->caps_info[rt_idx].FirstCap; caps_idx < pp_data->caps_info[rt_idx].LastCap; caps_idx++) { int first_bit, last_bit; first_bit = (pp_data->caps[caps_idx].BytePosition - 1) * 8 + pp_data->caps[caps_idx].BitPosition; last_bit = first_bit + pp_data->caps[caps_idx].ReportSize * pp_data->caps[caps_idx].ReportCount - 1; if (coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit == -1 || coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit > first_bit) { coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit = first_bit; } if (coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->LastBit < last_bit) { coll_bit_range[pp_data->caps[caps_idx].LinkCollection][pp_data->caps[caps_idx].ReportID][rt_idx]->LastBit = last_bit; } } } // ************************************************************************* // -Determine hierarchy levels of each collections and store it in: // coll_levels[COLLECTION_INDEX] // -Determine number of direct childs of each collections and store it in: // coll_number_of_direct_childs[COLLECTION_INDEX] // ************************************************************************* int max_coll_level = 0; int *coll_levels = (int *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_levels[0])); int *coll_number_of_direct_childs = (int *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_number_of_direct_childs[0])); for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { coll_levels[collection_node_idx] = -1; coll_number_of_direct_childs[collection_node_idx] = 0; } { int actual_coll_level = 0; USHORT collection_node_idx = 0; while (actual_coll_level >= 0) { coll_levels[collection_node_idx] = actual_coll_level; if ((link_collection_nodes[collection_node_idx].NumberOfChildren > 0) && (coll_levels[link_collection_nodes[collection_node_idx].FirstChild] == -1)) { actual_coll_level++; coll_levels[collection_node_idx] = actual_coll_level; if (max_coll_level < actual_coll_level) { max_coll_level = actual_coll_level; } coll_number_of_direct_childs[collection_node_idx]++; collection_node_idx = link_collection_nodes[collection_node_idx].FirstChild; } else if (link_collection_nodes[collection_node_idx].NextSibling != 0) { coll_number_of_direct_childs[link_collection_nodes[collection_node_idx].Parent]++; collection_node_idx = link_collection_nodes[collection_node_idx].NextSibling; } else { actual_coll_level--; if (actual_coll_level >= 0) { collection_node_idx = link_collection_nodes[collection_node_idx].Parent; } } } } // ********************************************************************************* // Propagate the bit range of each report from the child collections to their parent // and store the merged result for the parent // ********************************************************************************* for (int actual_coll_level = max_coll_level - 1; actual_coll_level >= 0; actual_coll_level--) { for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { if (coll_levels[collection_node_idx] == actual_coll_level) { USHORT child_idx = link_collection_nodes[collection_node_idx].FirstChild; while (child_idx) { for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { // Merge bit range from childs if ((coll_bit_range[child_idx][reportid_idx][rt_idx]->FirstBit != -1) && (coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit > coll_bit_range[child_idx][reportid_idx][rt_idx]->FirstBit)) { coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->FirstBit = coll_bit_range[child_idx][reportid_idx][rt_idx]->FirstBit; } if (coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit < coll_bit_range[child_idx][reportid_idx][rt_idx]->LastBit) { coll_bit_range[collection_node_idx][reportid_idx][rt_idx]->LastBit = coll_bit_range[child_idx][reportid_idx][rt_idx]->LastBit; } child_idx = link_collection_nodes[child_idx].NextSibling; } } } } } } // ************************************************************************************************** // Determine child collection order of the whole hierarchy, based on previously determined bit ranges // and store it this index coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] // ************************************************************************************************** USHORT **coll_child_order = (USHORT **)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_child_order)); { BOOLEAN *coll_parsed_flag = (BOOLEAN *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_parsed_flag[0])); for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { coll_parsed_flag[collection_node_idx] = FALSE; } int actual_coll_level = 0; USHORT collection_node_idx = 0; while (actual_coll_level >= 0) { if ((coll_number_of_direct_childs[collection_node_idx] != 0) && (coll_parsed_flag[link_collection_nodes[collection_node_idx].FirstChild] == FALSE)) { coll_parsed_flag[link_collection_nodes[collection_node_idx].FirstChild] = TRUE; coll_child_order[collection_node_idx] = (USHORT *)malloc((coll_number_of_direct_childs[collection_node_idx]) * sizeof(*coll_child_order[0])); { // Create list of child collection indices // sorted reverse to the order returned to HidP_GetLinkCollectionNodeschild // which seems to match the original order, as long as no bit position needs to be considered USHORT child_idx = link_collection_nodes[collection_node_idx].FirstChild; int child_count = coll_number_of_direct_childs[collection_node_idx] - 1; coll_child_order[collection_node_idx][child_count] = child_idx; while (link_collection_nodes[child_idx].NextSibling) { child_count--; child_idx = link_collection_nodes[child_idx].NextSibling; coll_child_order[collection_node_idx][child_count] = child_idx; } } if (coll_number_of_direct_childs[collection_node_idx] > 1) { // Sort child collections indices by bit positions for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { for (int child_idx = 1; child_idx < coll_number_of_direct_childs[collection_node_idx]; child_idx++) { // since the coll_bit_range array is not sorted, we need to reference the collection index in // our sorted coll_child_order array, and look up the corresponding bit ranges for comparing values to sort int prev_coll_idx = coll_child_order[collection_node_idx][child_idx - 1]; int cur_coll_idx = coll_child_order[collection_node_idx][child_idx]; if ((coll_bit_range[prev_coll_idx][reportid_idx][rt_idx]->FirstBit != -1) && (coll_bit_range[cur_coll_idx][reportid_idx][rt_idx]->FirstBit != -1) && (coll_bit_range[prev_coll_idx][reportid_idx][rt_idx]->FirstBit > coll_bit_range[cur_coll_idx][reportid_idx][rt_idx]->FirstBit)) { // Swap position indices of the two compared child collections USHORT idx_latch = coll_child_order[collection_node_idx][child_idx - 1]; coll_child_order[collection_node_idx][child_idx - 1] = coll_child_order[collection_node_idx][child_idx]; coll_child_order[collection_node_idx][child_idx] = idx_latch; } } } } } actual_coll_level++; collection_node_idx = link_collection_nodes[collection_node_idx].FirstChild; } else if (link_collection_nodes[collection_node_idx].NextSibling != 0) { collection_node_idx = link_collection_nodes[collection_node_idx].NextSibling; } else { actual_coll_level--; if (actual_coll_level >= 0) { collection_node_idx = link_collection_nodes[collection_node_idx].Parent; } } } free(coll_parsed_flag); } // *************************************************************************************** // Create sorted main_item_list containing all the Collection and CollectionEnd main items // *************************************************************************************** struct rd_main_item_node *main_item_list = NULL; // List root // Lookup table to find the Collection items in the list by index struct rd_main_item_node **coll_begin_lookup = (struct rd_main_item_node **)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_begin_lookup)); struct rd_main_item_node **coll_end_lookup = (struct rd_main_item_node **)malloc(pp_data->NumberLinkCollectionNodes * sizeof(*coll_end_lookup)); { int *coll_last_written_child = (int *)malloc(pp_data->NumberLinkCollectionNodes * sizeof(coll_last_written_child[0])); for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { coll_last_written_child[collection_node_idx] = -1; } int actual_coll_level = 0; USHORT collection_node_idx = 0; struct rd_main_item_node *firstDelimiterNode = NULL; struct rd_main_item_node *delimiterCloseNode = NULL; coll_begin_lookup[0] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection, 0, &main_item_list); while (actual_coll_level >= 0) { if ((coll_number_of_direct_childs[collection_node_idx] != 0) && (coll_last_written_child[collection_node_idx] == -1)) { // Collection has child collections, but none is written to the list yet coll_last_written_child[collection_node_idx] = coll_child_order[collection_node_idx][0]; collection_node_idx = coll_child_order[collection_node_idx][0]; // In a HID Report Descriptor, the first usage declared is the most preferred usage for the control. // While the order in the WIN32 capabiliy strutures is the opposite: // Here the preferred usage is the last aliased usage in the sequence. if (link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode == NULL)) { // Alliased Collection (First node in link_collection_nodes -> Last entry in report descriptor output) firstDelimiterNode = main_item_list; coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &main_item_list); coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_close, 0, &main_item_list); delimiterCloseNode = main_item_list; } else { // Normal not aliased collection coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection, 0, &main_item_list); actual_coll_level++; } } else if ((coll_number_of_direct_childs[collection_node_idx] > 1) && (coll_last_written_child[collection_node_idx] != coll_child_order[collection_node_idx][coll_number_of_direct_childs[collection_node_idx] - 1])) { // Collection has child collections, and this is not the first child int nextChild = 1; while (coll_last_written_child[collection_node_idx] != coll_child_order[collection_node_idx][nextChild - 1]) { nextChild++; } coll_last_written_child[collection_node_idx] = coll_child_order[collection_node_idx][nextChild]; collection_node_idx = coll_child_order[collection_node_idx][nextChild]; if (link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode == NULL)) { // Alliased Collection (First node in link_collection_nodes -> Last entry in report descriptor output) firstDelimiterNode = main_item_list; coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &main_item_list); coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_close, 0, &main_item_list); delimiterCloseNode = main_item_list; } else if (link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode != NULL)) { coll_begin_lookup[collection_node_idx] = rd_insert_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &firstDelimiterNode); } else if (!link_collection_nodes[collection_node_idx].IsAlias && (firstDelimiterNode != NULL)) { coll_begin_lookup[collection_node_idx] = rd_insert_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_usage, 0, &firstDelimiterNode); coll_begin_lookup[collection_node_idx] = rd_insert_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_delimiter_open, 0, &firstDelimiterNode); firstDelimiterNode = NULL; main_item_list = delimiterCloseNode; delimiterCloseNode = NULL; // Last entry of alias has .IsAlias == FALSE } if (!link_collection_nodes[collection_node_idx].IsAlias) { coll_begin_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection, 0, &main_item_list); actual_coll_level++; } } else { actual_coll_level--; coll_end_lookup[collection_node_idx] = rd_append_main_item_node(0, 0, rd_item_node_collection, 0, collection_node_idx, rd_collection_end, 0, &main_item_list); collection_node_idx = link_collection_nodes[collection_node_idx].Parent; } } free(coll_last_written_child); } // **************************************************************** // Inserted Input/Output/Feature main items into the main_item_list // in order of reconstructed bit positions // **************************************************************** for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { // Add all value caps to node list struct rd_main_item_node *firstDelimiterNode = NULL; struct rd_main_item_node *delimiterCloseNode = NULL; for (USHORT caps_idx = pp_data->caps_info[rt_idx].FirstCap; caps_idx < pp_data->caps_info[rt_idx].LastCap; caps_idx++) { struct rd_main_item_node *coll_begin = coll_begin_lookup[pp_data->caps[caps_idx].LinkCollection]; int first_bit, last_bit; first_bit = (pp_data->caps[caps_idx].BytePosition - 1) * 8 + pp_data->caps[caps_idx].BitPosition; last_bit = first_bit + pp_data->caps[caps_idx].ReportSize * pp_data->caps[caps_idx].ReportCount - 1; for (int child_idx = 0; child_idx < coll_number_of_direct_childs[pp_data->caps[caps_idx].LinkCollection]; child_idx++) { // Determine in which section before/between/after child collection the item should be inserted if (first_bit < coll_bit_range[coll_child_order[pp_data->caps[caps_idx].LinkCollection][child_idx]][pp_data->caps[caps_idx].ReportID][rt_idx]->FirstBit) { // Note, that the default value for undefined coll_bit_range is -1, which can't be greater than the bit position break; } coll_begin = coll_end_lookup[coll_child_order[pp_data->caps[caps_idx].LinkCollection][child_idx]]; } struct rd_main_item_node *list_node; list_node = rd_search_main_item_list_for_bit_position(first_bit, (rd_main_items) rt_idx, pp_data->caps[caps_idx].ReportID, &coll_begin); // In a HID Report Descriptor, the first usage declared is the most preferred usage for the control. // While the order in the WIN32 capabiliy strutures is the opposite: // Here the preferred usage is the last aliased usage in the sequence. if (pp_data->caps[caps_idx].IsAlias && (firstDelimiterNode == NULL)) { // Alliased Usage (First node in pp_data->caps -> Last entry in report descriptor output) firstDelimiterNode = list_node; rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_usage, pp_data->caps[caps_idx].ReportID, &list_node); rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_close, pp_data->caps[caps_idx].ReportID, &list_node); delimiterCloseNode = list_node; } else if (pp_data->caps[caps_idx].IsAlias && (firstDelimiterNode != NULL)) { rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_usage, pp_data->caps[caps_idx].ReportID, &list_node); } else if (!pp_data->caps[caps_idx].IsAlias && (firstDelimiterNode != NULL)) { // Alliased Collection (Last node in pp_data->caps -> First entry in report descriptor output) rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_usage, pp_data->caps[caps_idx].ReportID, &list_node); rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, rd_delimiter_open, pp_data->caps[caps_idx].ReportID, &list_node); firstDelimiterNode = NULL; list_node = delimiterCloseNode; delimiterCloseNode = NULL; // Last entry of alias has .IsAlias == FALSE } if (!pp_data->caps[caps_idx].IsAlias) { rd_insert_main_item_node(first_bit, last_bit, rd_item_node_cap, caps_idx, pp_data->caps[caps_idx].LinkCollection, (rd_main_items) rt_idx, pp_data->caps[caps_idx].ReportID, &list_node); } } } // *********************************************************** // Add const main items for padding to main_item_list // -To fill all bit gaps // -At each report end for 8bit padding // Note that information about the padding at the report end, // is not stored in the preparsed data, but in practice all // report descriptors seem to have it, as assumed here. // *********************************************************** { int last_bit_position[NUM_OF_HIDP_REPORT_TYPES][256]; struct rd_main_item_node *last_report_item_lookup[NUM_OF_HIDP_REPORT_TYPES][256]; for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { last_bit_position[rt_idx][reportid_idx] = -1; last_report_item_lookup[rt_idx][reportid_idx] = NULL; } } BOOLEAN devicehasReportIDs = FALSE; struct rd_main_item_node *list = main_item_list; // List root; // Windows pp_data are per top-level collection, therefore top level coll end is unique struct rd_main_item_node* node_before_top_level_coll_end = NULL; while (list->next != NULL) { if ((list->MainItemType >= rd_input) && (list->MainItemType <= rd_feature)) { // INPUT, OUTPUT or FEATURE if (list->FirstBit != -1) { if ((last_bit_position[list->MainItemType][list->ReportID] + 1 != list->FirstBit) && (last_report_item_lookup[list->MainItemType][list->ReportID] != NULL) && (last_report_item_lookup[list->MainItemType][list->ReportID]->FirstBit != list->FirstBit) // Happens in case of IsMultipleItemsForArray for multiple dedicated usages for a multi-button array ) { struct rd_main_item_node *list_node = rd_search_main_item_list_for_bit_position(last_bit_position[list->MainItemType][list->ReportID], list->MainItemType, list->ReportID, &last_report_item_lookup[list->MainItemType][list->ReportID]); rd_insert_main_item_node(last_bit_position[list->MainItemType][list->ReportID] + 1, list->FirstBit - 1, rd_item_node_padding, -1, 0, list->MainItemType, list->ReportID, &list_node); } if (list->ReportID != 0) { devicehasReportIDs = TRUE; } last_bit_position[list->MainItemType][list->ReportID] = list->LastBit; last_report_item_lookup[list->MainItemType][list->ReportID] = list; } } if (list->next->MainItemType == rd_collection_end) { // Store the node before the collection end - the last occurence is the end of the top level collection node_before_top_level_coll_end = list; } list = list->next; } // Add 8 bit padding at each report end for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { if (last_bit_position[rt_idx][reportid_idx] != -1) { int padding = 8 - ((last_bit_position[rt_idx][reportid_idx] + 1) % 8); if (padding < 8) { // Insert padding item after item referenced in last_report_item_lookup rd_insert_main_item_node(last_bit_position[rt_idx][reportid_idx] + 1, last_bit_position[rt_idx][reportid_idx] + padding, rd_item_node_padding, -1, 0, (rd_main_items) rt_idx, (unsigned char) reportid_idx, &last_report_item_lookup[rt_idx][reportid_idx]); if (last_report_item_lookup[rt_idx][reportid_idx] == node_before_top_level_coll_end) { // If this padding item is at the end of the top level collection, update node_before_top_level_coll_end node_before_top_level_coll_end = last_report_item_lookup[rt_idx][reportid_idx]->next; } last_bit_position[rt_idx][reportid_idx] += padding; } } } } // Add full byte padding at the end of the report descriptor (only reconstructable, for devices without Report IDs) for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { if (!devicehasReportIDs && pp_data->caps_info[rt_idx].NumberOfCaps > 0 && pp_data->caps_info[rt_idx].ReportByteLength > 0) { // ReportID 0 means this device uses not Report IDs // => Maximum one report per type possible, so we can take the size from the buffer size for the report type const unsigned char reportId = 0; // ReportByteLength is the report length in bytes plus the one byte for the optional ReportID int padding = (pp_data->caps_info[rt_idx].ReportByteLength - 1) * 8 - (last_bit_position[rt_idx][reportId] + 1); if (padding > 0) { // Insert padding item after item referenced in last_report_item_lookup rd_insert_main_item_node(last_bit_position[rt_idx][reportId] + 1, last_bit_position[rt_idx][reportId] + padding, rd_item_node_padding, -1, 0, (rd_main_items)rt_idx, reportId, &node_before_top_level_coll_end); } } } } // *********************************** // Encode the report descriptor output // *********************************** UCHAR last_report_id = 0; USAGE last_usage_page = 0; LONG last_physical_min = 0;// If both, Physical Minimum and Physical Maximum are 0, the logical limits should be taken as physical limits according USB HID spec 1.11 chapter 6.2.2.7 LONG last_physical_max = 0; ULONG last_unit_exponent = 0; // If Unit Exponent is Undefined it should be considered as 0 according USB HID spec 1.11 chapter 6.2.2.7 ULONG last_unit = 0; // If the first nibble is 7, or second nibble of Unit is 0, the unit is None according USB HID spec 1.11 chapter 6.2.2.7 BOOLEAN inhibit_write_of_usage = FALSE; // Needed in case of delimited usage print, before the normal collection or cap int report_count = 0; while (main_item_list != NULL) { int rt_idx = main_item_list->MainItemType; int caps_idx = main_item_list->CapsIndex; if (main_item_list->MainItemType == rd_collection) { if (last_usage_page != link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage) { // Write "Usage Page" at the begin of a collection - except it refers the same table as wrote last rd_write_short_item(rd_global_usage_page, link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage, &rpt_desc); last_usage_page = link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage; } if (inhibit_write_of_usage) { // Inhibit only once after DELIMITER statement inhibit_write_of_usage = FALSE; } else { // Write "Usage" of collection rd_write_short_item(rd_local_usage, link_collection_nodes[main_item_list->CollectionIndex].LinkUsage, &rpt_desc); } // Write begin of "Collection" rd_write_short_item(rd_main_collection, link_collection_nodes[main_item_list->CollectionIndex].CollectionType, &rpt_desc); } else if (main_item_list->MainItemType == rd_collection_end) { // Write "End Collection" rd_write_short_item(rd_main_collection_end, 0, &rpt_desc); } else if (main_item_list->MainItemType == rd_delimiter_open) { if (main_item_list->CollectionIndex != -1) { // Write "Usage Page" inside of a collection delmiter section if (last_usage_page != link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage) { rd_write_short_item(rd_global_usage_page, link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage, &rpt_desc); last_usage_page = link_collection_nodes[main_item_list->CollectionIndex].LinkUsagePage; } } else if (main_item_list->CapsIndex != 0) { // Write "Usage Page" inside of a main item delmiter section if (pp_data->caps[caps_idx].UsagePage != last_usage_page) { rd_write_short_item(rd_global_usage_page, pp_data->caps[caps_idx].UsagePage, &rpt_desc); last_usage_page = pp_data->caps[caps_idx].UsagePage; } } // Write "Delimiter Open" rd_write_short_item(rd_local_delimiter, 1, &rpt_desc); // 1 = open set of aliased usages } else if (main_item_list->MainItemType == rd_delimiter_usage) { if (main_item_list->CollectionIndex != -1) { // Write aliased collection "Usage" rd_write_short_item(rd_local_usage, link_collection_nodes[main_item_list->CollectionIndex].LinkUsage, &rpt_desc); } if (main_item_list->CapsIndex != 0) { // Write aliased main item range from "Usage Minimum" to "Usage Maximum" if (pp_data->caps[caps_idx].IsRange) { rd_write_short_item(rd_local_usage_minimum, pp_data->caps[caps_idx].Range.UsageMin, &rpt_desc); rd_write_short_item(rd_local_usage_maximum, pp_data->caps[caps_idx].Range.UsageMax, &rpt_desc); } else { // Write single aliased main item "Usage" rd_write_short_item(rd_local_usage, pp_data->caps[caps_idx].NotRange.Usage, &rpt_desc); } } } else if (main_item_list->MainItemType == rd_delimiter_close) { // Write "Delimiter Close" rd_write_short_item(rd_local_delimiter, 0, &rpt_desc); // 0 = close set of aliased usages // Inhibit next usage write inhibit_write_of_usage = TRUE; } else if (main_item_list->TypeOfNode == rd_item_node_padding) { // Padding // The preparsed data doesn't contain any information about padding. Therefore all undefined gaps // in the reports are filled with the same style of constant bit or byte padding. if ((main_item_list->LastBit - main_item_list->FirstBit + 1) % 8 == 0) { // Padding in full bytes // Write "Report Size" for padding bytes is 8 rd_write_short_item(rd_global_report_size, 8, &rpt_desc); // Write "Report Count" with number of padding bytes rd_write_short_item(rd_global_report_count, (main_item_list->LastBit - main_item_list->FirstBit + 1) / 8, &rpt_desc); } else { // Padding in bits // Write "Report Size" with number of padding bits rd_write_short_item(rd_global_report_size, (main_item_list->LastBit - main_item_list->FirstBit + 1), &rpt_desc); // Write "Report Count" for padding bits is 1 rd_write_short_item(rd_global_report_count, 1, &rpt_desc); } if (rt_idx == HidP_Input) { // Write "Input" main item - We know it's Constant - We can only guess the other bits, but they don't matter in case of const rd_write_short_item(rd_main_input, 0x03, &rpt_desc); // Const / Abs } else if (rt_idx == HidP_Output) { // Write "Output" main item - We know it's Constant - We can only guess the other bits, but they don't matter in case of const rd_write_short_item(rd_main_output, 0x03, &rpt_desc); // Const / Abs } else if (rt_idx == HidP_Feature) { // Write "Feature" main item - We know it's Constant - We can only guess the other bits, but they don't matter in case of const rd_write_short_item(rd_main_feature, 0x03, &rpt_desc); // Const / Abs } report_count = 0; } else if (pp_data->caps[caps_idx].IsButtonCap) { // Button // (The preparsed data contain different data for 1 bit Button caps, than for parametric Value caps) if (last_report_id != pp_data->caps[caps_idx].ReportID) { // Write "Report ID" if changed rd_write_short_item(rd_global_report_id, pp_data->caps[caps_idx].ReportID, &rpt_desc); last_report_id = pp_data->caps[caps_idx].ReportID; } // Write "Usage Page" when changed if (pp_data->caps[caps_idx].UsagePage != last_usage_page) { rd_write_short_item(rd_global_usage_page, pp_data->caps[caps_idx].UsagePage, &rpt_desc); last_usage_page = pp_data->caps[caps_idx].UsagePage; } // Write only local report items for each cap, if ReportCount > 1 if (pp_data->caps[caps_idx].IsRange) { report_count += (pp_data->caps[caps_idx].Range.DataIndexMax - pp_data->caps[caps_idx].Range.DataIndexMin); } if (inhibit_write_of_usage) { // Inhibit only once after Delimiter - Reset flag inhibit_write_of_usage = FALSE; } else { if (pp_data->caps[caps_idx].IsRange) { // Write range from "Usage Minimum" to "Usage Maximum" rd_write_short_item(rd_local_usage_minimum, pp_data->caps[caps_idx].Range.UsageMin, &rpt_desc); rd_write_short_item(rd_local_usage_maximum, pp_data->caps[caps_idx].Range.UsageMax, &rpt_desc); } else { // Write single "Usage" rd_write_short_item(rd_local_usage, pp_data->caps[caps_idx].NotRange.Usage, &rpt_desc); } } if (pp_data->caps[caps_idx].IsDesignatorRange) { // Write physical descriptor indices range from "Designator Minimum" to "Designator Maximum" rd_write_short_item(rd_local_designator_minimum, pp_data->caps[caps_idx].Range.DesignatorMin, &rpt_desc); rd_write_short_item(rd_local_designator_maximum, pp_data->caps[caps_idx].Range.DesignatorMax, &rpt_desc); } else if (pp_data->caps[caps_idx].NotRange.DesignatorIndex != 0) { // Designator set 0 is a special descriptor set (of the HID Physical Descriptor), // that specifies the number of additional descriptor sets. // Therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. // Write single "Designator Index" rd_write_short_item(rd_local_designator_index, pp_data->caps[caps_idx].NotRange.DesignatorIndex, &rpt_desc); } if (pp_data->caps[caps_idx].IsStringRange) { // Write range of indices of the USB string descriptor, from "String Minimum" to "String Maximum" rd_write_short_item(rd_local_string_minimum, pp_data->caps[caps_idx].Range.StringMin, &rpt_desc); rd_write_short_item(rd_local_string_maximum, pp_data->caps[caps_idx].Range.StringMax, &rpt_desc); } else if (pp_data->caps[caps_idx].NotRange.StringIndex != 0) { // String Index 0 is a special entry of the USB string descriptor, that contains a list of supported languages, // therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. // Write single "String Index" rd_write_short_item(rd_local_string, pp_data->caps[caps_idx].NotRange.StringIndex, &rpt_desc); } if ((main_item_list->next != NULL) && ((int)main_item_list->next->MainItemType == rt_idx) && (main_item_list->next->TypeOfNode == rd_item_node_cap) && (pp_data->caps[main_item_list->next->CapsIndex].IsButtonCap) && (!pp_data->caps[caps_idx].IsRange) && // This node in list is no array (!pp_data->caps[main_item_list->next->CapsIndex].IsRange) && // Next node in list is no array (pp_data->caps[main_item_list->next->CapsIndex].UsagePage == pp_data->caps[caps_idx].UsagePage) && (pp_data->caps[main_item_list->next->CapsIndex].ReportID == pp_data->caps[caps_idx].ReportID) && (pp_data->caps[main_item_list->next->CapsIndex].BitField == pp_data->caps[caps_idx].BitField) ) { if (main_item_list->next->FirstBit != main_item_list->FirstBit) { // In case of IsMultipleItemsForArray for multiple dedicated usages for a multi-button array, the report count should be incremented // Skip global items until any of them changes, than use ReportCount item to write the count of identical report fields report_count++; } } else { if ((pp_data->caps[caps_idx].Button.LogicalMin == 0) && (pp_data->caps[caps_idx].Button.LogicalMax == 0)) { // While a HID report descriptor must always contain LogicalMinimum and LogicalMaximum, // the preparsed data contain both fields set to zero, for the case of simple buttons // Write "Logical Minimum" set to 0 and "Logical Maximum" set to 1 rd_write_short_item(rd_global_logical_minimum, 0, &rpt_desc); rd_write_short_item(rd_global_logical_maximum, 1, &rpt_desc); } else { // Write logical range from "Logical Minimum" to "Logical Maximum" rd_write_short_item(rd_global_logical_minimum, pp_data->caps[caps_idx].Button.LogicalMin, &rpt_desc); rd_write_short_item(rd_global_logical_maximum, pp_data->caps[caps_idx].Button.LogicalMax, &rpt_desc); } // Write "Report Size" rd_write_short_item(rd_global_report_size, pp_data->caps[caps_idx].ReportSize, &rpt_desc); // Write "Report Count" if (!pp_data->caps[caps_idx].IsRange) { // Variable bit field with one bit per button // In case of multiple usages with the same items, only "Usage" is written per cap, and "Report Count" is incremented rd_write_short_item(rd_global_report_count, pp_data->caps[caps_idx].ReportCount + report_count, &rpt_desc); } else { // Button array of "Report Size" x "Report Count rd_write_short_item(rd_global_report_count, pp_data->caps[caps_idx].ReportCount, &rpt_desc); } // Buttons have only 1 bit and therefore no physical limits/units -> Set to undefined state if (last_physical_min != 0) { // Write "Physical Minimum", but only if changed last_physical_min = 0; rd_write_short_item(rd_global_physical_minimum, last_physical_min, &rpt_desc); } if (last_physical_max != 0) { // Write "Physical Maximum", but only if changed last_physical_max = 0; rd_write_short_item(rd_global_physical_maximum, last_physical_max, &rpt_desc); } if (last_unit_exponent != 0) { // Write "Unit Exponent", but only if changed last_unit_exponent = 0; rd_write_short_item(rd_global_unit_exponent, last_unit_exponent, &rpt_desc); } if (last_unit != 0) { // Write "Unit",but only if changed last_unit = 0; rd_write_short_item(rd_global_unit, last_unit, &rpt_desc); } // Write "Input" main item if (rt_idx == HidP_Input) { rd_write_short_item(rd_main_input, pp_data->caps[caps_idx].BitField, &rpt_desc); } // Write "Output" main item else if (rt_idx == HidP_Output) { rd_write_short_item(rd_main_output, pp_data->caps[caps_idx].BitField, &rpt_desc); } // Write "Feature" main item else if (rt_idx == HidP_Feature) { rd_write_short_item(rd_main_feature, pp_data->caps[caps_idx].BitField, &rpt_desc); } report_count = 0; } } else { if (last_report_id != pp_data->caps[caps_idx].ReportID) { // Write "Report ID" if changed rd_write_short_item(rd_global_report_id, pp_data->caps[caps_idx].ReportID, &rpt_desc); last_report_id = pp_data->caps[caps_idx].ReportID; } // Write "Usage Page" if changed if (pp_data->caps[caps_idx].UsagePage != last_usage_page) { rd_write_short_item(rd_global_usage_page, pp_data->caps[caps_idx].UsagePage, &rpt_desc); last_usage_page = pp_data->caps[caps_idx].UsagePage; } if (inhibit_write_of_usage) { // Inhibit only once after Delimiter - Reset flag inhibit_write_of_usage = FALSE; } else { if (pp_data->caps[caps_idx].IsRange) { // Write usage range from "Usage Minimum" to "Usage Maximum" rd_write_short_item(rd_local_usage_minimum, pp_data->caps[caps_idx].Range.UsageMin, &rpt_desc); rd_write_short_item(rd_local_usage_maximum, pp_data->caps[caps_idx].Range.UsageMax, &rpt_desc); } else { // Write single "Usage" rd_write_short_item(rd_local_usage, pp_data->caps[caps_idx].NotRange.Usage, &rpt_desc); } } if (pp_data->caps[caps_idx].IsDesignatorRange) { // Write physical descriptor indices range from "Designator Minimum" to "Designator Maximum" rd_write_short_item(rd_local_designator_minimum, pp_data->caps[caps_idx].Range.DesignatorMin, &rpt_desc); rd_write_short_item(rd_local_designator_maximum, pp_data->caps[caps_idx].Range.DesignatorMax, &rpt_desc); } else if (pp_data->caps[caps_idx].NotRange.DesignatorIndex != 0) { // Designator set 0 is a special descriptor set (of the HID Physical Descriptor), // that specifies the number of additional descriptor sets. // Therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. // Write single "Designator Index" rd_write_short_item(rd_local_designator_index, pp_data->caps[caps_idx].NotRange.DesignatorIndex, &rpt_desc); } if (pp_data->caps[caps_idx].IsStringRange) { // Write range of indices of the USB string descriptor, from "String Minimum" to "String Maximum" rd_write_short_item(rd_local_string_minimum, pp_data->caps[caps_idx].Range.StringMin, &rpt_desc); rd_write_short_item(rd_local_string_maximum, pp_data->caps[caps_idx].Range.StringMax, &rpt_desc); } else if (pp_data->caps[caps_idx].NotRange.StringIndex != 0) { // String Index 0 is a special entry of the USB string descriptor, that contains a list of supported languages, // therefore Designator Index 0 can never be a useful reference for a control and we can inhibit it. // Write single "String Index" rd_write_short_item(rd_local_string, pp_data->caps[caps_idx].NotRange.StringIndex, &rpt_desc); } if ((pp_data->caps[caps_idx].BitField & 0x02) != 0x02) { // In case of an value array overwrite "Report Count" pp_data->caps[caps_idx].ReportCount = pp_data->caps[caps_idx].Range.DataIndexMax - pp_data->caps[caps_idx].Range.DataIndexMin + 1; } // Print only local report items for each cap, if ReportCount > 1 if ((main_item_list->next != NULL) && ((int) main_item_list->next->MainItemType == rt_idx) && (main_item_list->next->TypeOfNode == rd_item_node_cap) && (!pp_data->caps[main_item_list->next->CapsIndex].IsButtonCap) && (!pp_data->caps[caps_idx].IsRange) && // This node in list is no array (!pp_data->caps[main_item_list->next->CapsIndex].IsRange) && // Next node in list is no array (pp_data->caps[main_item_list->next->CapsIndex].UsagePage == pp_data->caps[caps_idx].UsagePage) && (pp_data->caps[main_item_list->next->CapsIndex].NotButton.LogicalMin == pp_data->caps[caps_idx].NotButton.LogicalMin) && (pp_data->caps[main_item_list->next->CapsIndex].NotButton.LogicalMax == pp_data->caps[caps_idx].NotButton.LogicalMax) && (pp_data->caps[main_item_list->next->CapsIndex].NotButton.PhysicalMin == pp_data->caps[caps_idx].NotButton.PhysicalMin) && (pp_data->caps[main_item_list->next->CapsIndex].NotButton.PhysicalMax == pp_data->caps[caps_idx].NotButton.PhysicalMax) && (pp_data->caps[main_item_list->next->CapsIndex].UnitsExp == pp_data->caps[caps_idx].UnitsExp) && (pp_data->caps[main_item_list->next->CapsIndex].Units == pp_data->caps[caps_idx].Units) && (pp_data->caps[main_item_list->next->CapsIndex].ReportSize == pp_data->caps[caps_idx].ReportSize) && (pp_data->caps[main_item_list->next->CapsIndex].ReportID == pp_data->caps[caps_idx].ReportID) && (pp_data->caps[main_item_list->next->CapsIndex].BitField == pp_data->caps[caps_idx].BitField) && (pp_data->caps[main_item_list->next->CapsIndex].ReportCount == 1) && (pp_data->caps[caps_idx].ReportCount == 1) ) { // Skip global items until any of them changes, than use ReportCount item to write the count of identical report fields report_count++; } else { // Value // Write logical range from "Logical Minimum" to "Logical Maximum" rd_write_short_item(rd_global_logical_minimum, pp_data->caps[caps_idx].NotButton.LogicalMin, &rpt_desc); rd_write_short_item(rd_global_logical_maximum, pp_data->caps[caps_idx].NotButton.LogicalMax, &rpt_desc); if ((last_physical_min != pp_data->caps[caps_idx].NotButton.PhysicalMin) || (last_physical_max != pp_data->caps[caps_idx].NotButton.PhysicalMax)) { // Write range from "Physical Minimum" to " Physical Maximum", but only if one of them changed rd_write_short_item(rd_global_physical_minimum, pp_data->caps[caps_idx].NotButton.PhysicalMin, &rpt_desc); last_physical_min = pp_data->caps[caps_idx].NotButton.PhysicalMin; rd_write_short_item(rd_global_physical_maximum, pp_data->caps[caps_idx].NotButton.PhysicalMax, &rpt_desc); last_physical_max = pp_data->caps[caps_idx].NotButton.PhysicalMax; } if (last_unit_exponent != pp_data->caps[caps_idx].UnitsExp) { // Write "Unit Exponent", but only if changed rd_write_short_item(rd_global_unit_exponent, pp_data->caps[caps_idx].UnitsExp, &rpt_desc); last_unit_exponent = pp_data->caps[caps_idx].UnitsExp; } if (last_unit != pp_data->caps[caps_idx].Units) { // Write physical "Unit", but only if changed rd_write_short_item(rd_global_unit, pp_data->caps[caps_idx].Units, &rpt_desc); last_unit = pp_data->caps[caps_idx].Units; } // Write "Report Size" rd_write_short_item(rd_global_report_size, pp_data->caps[caps_idx].ReportSize, &rpt_desc); // Write "Report Count" rd_write_short_item(rd_global_report_count, pp_data->caps[caps_idx].ReportCount + report_count, &rpt_desc); if (rt_idx == HidP_Input) { // Write "Input" main item rd_write_short_item(rd_main_input, pp_data->caps[caps_idx].BitField, &rpt_desc); } else if (rt_idx == HidP_Output) { // Write "Output" main item rd_write_short_item(rd_main_output, pp_data->caps[caps_idx].BitField, &rpt_desc); } else if (rt_idx == HidP_Feature) { // Write "Feature" main item rd_write_short_item(rd_main_feature, pp_data->caps[caps_idx].BitField, &rpt_desc); } report_count = 0; } } // Go to next item in main_item_list and free the memory of the actual item struct rd_main_item_node *main_item_list_prev = main_item_list; main_item_list = main_item_list->next; free(main_item_list_prev); } // Free multidimensionable array: coll_bit_range[COLLECTION_INDEX][REPORT_ID][INPUT/OUTPUT/FEATURE] // Free multidimensionable array: coll_child_order[COLLECTION_INDEX][DIRECT_CHILD_INDEX] for (USHORT collection_node_idx = 0; collection_node_idx < pp_data->NumberLinkCollectionNodes; collection_node_idx++) { for (int reportid_idx = 0; reportid_idx < 256; reportid_idx++) { for (int rt_idx = 0; rt_idx < NUM_OF_HIDP_REPORT_TYPES; rt_idx++) { free(coll_bit_range[collection_node_idx][reportid_idx][rt_idx]); } free(coll_bit_range[collection_node_idx][reportid_idx]); } free(coll_bit_range[collection_node_idx]); if (coll_number_of_direct_childs[collection_node_idx] != 0) free(coll_child_order[collection_node_idx]); } free(coll_bit_range); free(coll_child_order); // Free one dimensional arrays free(coll_begin_lookup); free(coll_end_lookup); free(coll_levels); free(coll_number_of_direct_childs); return (int) rpt_desc.byte_idx; } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/windows/hidapi_descriptor_reconstruct.h0000644000076500000240000001663015115611013023323 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #ifndef HIDAPI_DESCRIPTOR_RECONSTRUCT_H__ #define HIDAPI_DESCRIPTOR_RECONSTRUCT_H__ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) /* Do not warn about wcsncpy usage. https://docs.microsoft.com/cpp/c-runtime-library/security-features-in-the-crt */ #define _CRT_SECURE_NO_WARNINGS #endif #include "hidapi_winapi.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4200) #pragma warning(disable: 4201) #pragma warning(disable: 4214) #endif #include #include "hidapi_hidsdi.h" #include #define NUM_OF_HIDP_REPORT_TYPES 3 typedef enum rd_items_ { rd_main_input = 0x80, /* 1000 00 nn */ rd_main_output = 0x90, /* 1001 00 nn */ rd_main_feature = 0xB0, /* 1011 00 nn */ rd_main_collection = 0xA0, /* 1010 00 nn */ rd_main_collection_end = 0xC0, /* 1100 00 nn */ rd_global_usage_page = 0x04, /* 0000 01 nn */ rd_global_logical_minimum = 0x14, /* 0001 01 nn */ rd_global_logical_maximum = 0x24, /* 0010 01 nn */ rd_global_physical_minimum = 0x34, /* 0011 01 nn */ rd_global_physical_maximum = 0x44, /* 0100 01 nn */ rd_global_unit_exponent = 0x54, /* 0101 01 nn */ rd_global_unit = 0x64, /* 0110 01 nn */ rd_global_report_size = 0x74, /* 0111 01 nn */ rd_global_report_id = 0x84, /* 1000 01 nn */ rd_global_report_count = 0x94, /* 1001 01 nn */ rd_global_push = 0xA4, /* 1010 01 nn */ rd_global_pop = 0xB4, /* 1011 01 nn */ rd_local_usage = 0x08, /* 0000 10 nn */ rd_local_usage_minimum = 0x18, /* 0001 10 nn */ rd_local_usage_maximum = 0x28, /* 0010 10 nn */ rd_local_designator_index = 0x38, /* 0011 10 nn */ rd_local_designator_minimum = 0x48, /* 0100 10 nn */ rd_local_designator_maximum = 0x58, /* 0101 10 nn */ rd_local_string = 0x78, /* 0111 10 nn */ rd_local_string_minimum = 0x88, /* 1000 10 nn */ rd_local_string_maximum = 0x98, /* 1001 10 nn */ rd_local_delimiter = 0xA8 /* 1010 10 nn */ } rd_items; typedef enum rd_main_items_ { rd_input = HidP_Input, rd_output = HidP_Output, rd_feature = HidP_Feature, rd_collection, rd_collection_end, rd_delimiter_open, rd_delimiter_usage, rd_delimiter_close, } rd_main_items; typedef struct rd_bit_range_ { int FirstBit; int LastBit; } rd_bit_range; typedef enum rd_item_node_type_ { rd_item_node_cap, rd_item_node_padding, rd_item_node_collection, } rd_node_type; struct rd_main_item_node { int FirstBit; /* Position of first bit in report (counting from 0) */ int LastBit; /* Position of last bit in report (counting from 0) */ rd_node_type TypeOfNode; /* Information if caps index refers to the array of button caps, value caps, or if the node is just a padding element to fill unused bit positions. The node can also be a collection node without any bits in the report. */ int CapsIndex; /* Index in the array of caps */ int CollectionIndex; /* Index in the array of link collections */ rd_main_items MainItemType; /* Input, Output, Feature, Collection or Collection End */ unsigned char ReportID; struct rd_main_item_node* next; }; typedef struct hid_pp_caps_info_ { USHORT FirstCap; USHORT NumberOfCaps; // Includes empty caps after LastCap USHORT LastCap; USHORT ReportByteLength; } hid_pp_caps_info, *phid_pp_caps_info; typedef struct hid_pp_link_collection_node_ { USAGE LinkUsage; USAGE LinkUsagePage; USHORT Parent; USHORT NumberOfChildren; USHORT NextSibling; USHORT FirstChild; ULONG CollectionType : 8; ULONG IsAlias : 1; ULONG Reserved : 23; // Same as the public API structure HIDP_LINK_COLLECTION_NODE, but without PVOID UserContext at the end } hid_pp_link_collection_node, *phid_pp_link_collection_node; // Note: This is risk-reduction-measure for this specific struct, as it has ULONG bit-field. // Although very unlikely, it might still be possible that the compiler creates a memory layout that is // not binary compatile. // Other structs are not checked at the time of writing. static_assert(sizeof(struct hid_pp_link_collection_node_) == 16, "Size of struct hid_pp_link_collection_node_ not as expected. This might break binary compatibility"); typedef struct hidp_unknown_token_ { UCHAR Token; /* Specifies the one-byte prefix of a global item. */ UCHAR Reserved[3]; ULONG BitField; /* Specifies the data part of the global item. */ } hidp_unknown_token, * phidp_unknown_token; typedef struct hid_pp_cap_ { USAGE UsagePage; UCHAR ReportID; UCHAR BitPosition; USHORT ReportSize; // WIN32 term for this is BitSize USHORT ReportCount; USHORT BytePosition; USHORT BitCount; ULONG BitField; USHORT NextBytePosition; USHORT LinkCollection; USAGE LinkUsagePage; USAGE LinkUsage; // Start of 8 Flags in one byte BOOLEAN IsMultipleItemsForArray:1; BOOLEAN IsPadding:1; BOOLEAN IsButtonCap:1; BOOLEAN IsAbsolute:1; BOOLEAN IsRange:1; BOOLEAN IsAlias:1; // IsAlias is set to TRUE in the first n-1 capability structures added to the capability array. IsAlias set to FALSE in the nth capability structure. BOOLEAN IsStringRange:1; BOOLEAN IsDesignatorRange:1; // End of 8 Flags in one byte BOOLEAN Reserved1[3]; hidp_unknown_token UnknownTokens[4]; // 4 x 8 Byte union { struct { USAGE UsageMin; USAGE UsageMax; USHORT StringMin; USHORT StringMax; USHORT DesignatorMin; USHORT DesignatorMax; USHORT DataIndexMin; USHORT DataIndexMax; } Range; struct { USAGE Usage; USAGE Reserved1; USHORT StringIndex; USHORT Reserved2; USHORT DesignatorIndex; USHORT Reserved3; USHORT DataIndex; USHORT Reserved4; } NotRange; }; union { struct { LONG LogicalMin; LONG LogicalMax; } Button; struct { BOOLEAN HasNull; UCHAR Reserved4[3]; LONG LogicalMin; LONG LogicalMax; LONG PhysicalMin; LONG PhysicalMax; } NotButton; }; ULONG Units; ULONG UnitsExp; } hid_pp_cap, *phid_pp_cap; typedef struct hidp_preparsed_data_ { UCHAR MagicKey[8]; USAGE Usage; USAGE UsagePage; USHORT Reserved[2]; // CAPS structure for Input, Output and Feature hid_pp_caps_info caps_info[3]; USHORT FirstByteOfLinkCollectionArray; USHORT NumberLinkCollectionNodes; #ifndef _MSC_VER // MINGW fails with: Flexible array member in union not supported // Solution: https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html union { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" hid_pp_cap caps[0]; hid_pp_link_collection_node LinkCollectionArray[0]; #pragma GCC diagnostic pop }; #else union { hid_pp_cap caps[]; hid_pp_link_collection_node LinkCollectionArray[]; }; #endif } hidp_preparsed_data; #ifdef _MSC_VER #pragma warning(pop) #endif #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/windows/hidapi_hidclass.h0000644000076500000240000000304015115611013020273 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #ifndef HIDAPI_HIDCLASS_H #define HIDAPI_HIDCLASS_H #ifdef HIDAPI_USE_DDK #include #else /* This part of the header mimics hidclass.h, but only what is used by HIDAPI */ #ifndef FILE_DEVICE_KEYBOARD #define FILE_DEVICE_KEYBOARD 0x0000000b #endif #ifndef METHOD_OUT_DIRECT #define METHOD_OUT_DIRECT 2 #endif #ifndef FILE_ANY_ACCESS #define FILE_ANY_ACCESS 0 #endif #ifndef CTL_CODE #define CTL_CODE( DeviceType, Function, Method, Access ) ( \ ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ ) #endif #define HID_OUT_CTL_CODE(id) CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS) #define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100) #define IOCTL_HID_GET_INPUT_REPORT HID_OUT_CTL_CODE(104) #endif #endif /* HIDAPI_HIDCLASS_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216765.0 hidapi-0.15.0/hidapi/windows/hidapi_hidpi.h0000644000076500000240000000356215115610775017625 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #ifndef HIDAPI_HIDPI_H #define HIDAPI_HIDPI_H #ifdef HIDAPI_USE_DDK #include #else /* This part of the header mimics hidpi.h, but only what is used by HIDAPI */ typedef enum _HIDP_REPORT_TYPE { HidP_Input, HidP_Output, HidP_Feature } HIDP_REPORT_TYPE; typedef struct _HIDP_PREPARSED_DATA * PHIDP_PREPARSED_DATA; typedef struct _HIDP_CAPS { USAGE Usage; USAGE UsagePage; USHORT InputReportByteLength; USHORT OutputReportByteLength; USHORT FeatureReportByteLength; USHORT Reserved[17]; USHORT NumberLinkCollectionNodes; USHORT NumberInputButtonCaps; USHORT NumberInputValueCaps; USHORT NumberInputDataIndices; USHORT NumberOutputButtonCaps; USHORT NumberOutputValueCaps; USHORT NumberOutputDataIndices; USHORT NumberFeatureButtonCaps; USHORT NumberFeatureValueCaps; USHORT NumberFeatureDataIndices; } HIDP_CAPS, *PHIDP_CAPS; #define HIDP_STATUS_SUCCESS 0x00110000 #define HIDP_STATUS_INVALID_PREPARSED_DATA 0xc0110001 typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, PHIDP_CAPS caps); #endif #endif /* HIDAPI_HIDPI_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/windows/hidapi_hidsdi.h0000644000076500000240000000445715115611013017762 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ #ifndef HIDAPI_HIDSDI_H #define HIDAPI_HIDSDI_H #ifdef HIDAPI_USE_DDK #include #else /* This part of the header mimics hidsdi.h, but only what is used by HIDAPI */ typedef USHORT USAGE; #include "hidapi_hidpi.h" typedef struct _HIDD_ATTRIBUTES{ ULONG Size; USHORT VendorID; USHORT ProductID; USHORT VersionNumber; } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; typedef void (__stdcall *HidD_GetHidGuid_)(LPGUID hid_guid); typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib); typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len); typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length); typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length); typedef BOOLEAN (__stdcall* HidD_SetOutputReport_)(HANDLE handle, PVOID data, ULONG length); typedef BOOLEAN (__stdcall *HidD_GetInputReport_)(HANDLE handle, PVOID data, ULONG length); typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len); typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data); typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data); typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers); #endif #endif /* HIDAPI_HIDSDI_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216779.0 hidapi-0.15.0/hidapi/windows/hidapi_winapi.h0000644000076500000240000000655215115611013020003 0ustar00stickstaff/******************************************************* HIDAPI - Multi-Platform library for communication with HID devices. libusb/hidapi Team Copyright 2022, All Rights Reserved. At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the original HIDAPI license as outlined in the LICENSE.txt, LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt files located at the root of the source distribution. These files may also be found in the public source code repository located at: https://github.com/libusb/hidapi . ********************************************************/ /** @file * @defgroup API hidapi API * * Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) */ #ifndef HIDAPI_WINAPI_H__ #define HIDAPI_WINAPI_H__ #include #include #include "hidapi.h" #ifdef __cplusplus extern "C" { #endif /** @brief Get the container ID for a HID device. Since version 0.12.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 12, 0) This function returns the `DEVPKEY_Device_ContainerId` property of the given device. This can be used to correlate different interfaces/ports on the same hardware device. @ingroup API @param dev A device handle returned from hid_open(). @param container_id The device's container ID on return. @returns This function returns 0 on success and -1 on error. */ int HID_API_EXPORT_CALL hid_winapi_get_container_id(hid_device *dev, GUID *container_id); /** * @brief Reconstructs a HID Report Descriptor from a Win32 HIDP_PREPARSED_DATA structure. * This reconstructed report descriptor is logical identical to the real report descriptor, * but not byte wise identical. * * @param[in] hidp_preparsed_data Pointer to the HIDP_PREPARSED_DATA to read, i.e.: the value of PHIDP_PREPARSED_DATA, * as returned by HidD_GetPreparsedData WinAPI function. * @param buf Pointer to the buffer where the report descriptor should be stored. * @param[in] buf_size Size of the buffer. The recommended size for the buffer is @ref HID_API_MAX_REPORT_DESCRIPTOR_SIZE bytes. * * @return Returns size of reconstructed report descriptor if successful, -1 for error. */ int HID_API_EXPORT_CALL hid_winapi_descriptor_reconstruct_pp_data(void *hidp_preparsed_data, unsigned char *buf, size_t buf_size); /** * @brief Sets the timeout for hid_write operation. * * Since version 0.15.0, @ref HID_API_VERSION >= HID_API_MAKE_VERSION(0, 15, 0) * * The default timeout is 1sec for winapi backend. * * In case if 1sec is not enough, on in case of multi-platform development, * the recommended value is 5sec, e.g. to match (unconfigurable) 5sec timeout * set for hidraw (linux kernel) implementation. * * When the timeout is set to 0, hid_write function becomes non-blocking and would exit immediately. * When the timeout is set to INFINITE ((DWORD)-1), the function will not exit, * until the write operation is performed or an error occured. * See dwMilliseconds parameter documentation of WaitForSingleObject function. * * @param timeout New timeout value in milliseconds. */ void HID_API_EXPORT_CALL hid_winapi_set_write_timeout(hid_device *dev, unsigned long timeout); #ifdef __cplusplus } #endif #endif ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1765273674.072004 hidapi-0.15.0/hidapi.egg-info/0000755000076500000240000000000015115770112015023 5ustar00stickstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273674.0 hidapi-0.15.0/hidapi.egg-info/PKG-INFO0000644000076500000240000000717515115770112016132 0ustar00stickstaffMetadata-Version: 2.4 Name: hidapi Version: 0.15.0 Summary: A Cython interface to the hidapi from https://github.com/libusb/hidapi Home-page: https://github.com/trezor/cython-hidapi Author: Pavol Rusnak Author-email: pavol@rusnak.io Maintainer: Pavol Rusnak Maintainer-email: pavol@rusnak.io Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: License :: OSI Approved :: BSD License Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 License-File: LICENSE-bsd.txt License-File: LICENSE-gpl3.txt License-File: LICENSE-orig.txt License-File: LICENSE.txt Dynamic: author Dynamic: author-email Dynamic: classifier Dynamic: description Dynamic: home-page Dynamic: license-file Dynamic: maintainer Dynamic: maintainer-email Dynamic: summary cython-hidapi ============= .. contents:: Description ----------- A Cython interface to `HIDAPI `_ library. This has been tested with: * `TREZOR `_ Hardware Wallet * the PIC18F4550 on the development board from CCS with their example program * the Fine Offset WH3081 Weather Station It works on Linux, Windows and macOS. Software Dependencies --------------------- * `Python `_ * `Cython `_ * hidraw or libusb+libudev on Linux License ------- cython-hidapi may be used by one of three licenses as outlined in LICENSE.txt Install ------- :: $ sudo apt-get install python-dev libusb-1.0-0-dev libudev-dev $ sudo pip install --upgrade setuptools $ sudo pip install hidapi For other download options visit the `PyPi page `_. Build from source ----------------- 1. Download cython-hidapi archive:: $ git clone --recursive https://github.com/trezor/cython-hidapi.git $ cd cython-hidapi 2. Build cython-hidapi extension module:: $ python setup.py build On Linux, the hidraw API is now used by default, and the libusb API is not included. That is, --without-libusb is now the default behavior. To force the use of the libusb API instead, use the --with-libusb option:: $ python setup.py build --with-libusb Or you can also use the environment variable:: $ export HIDAPI_WITH_LIBUSB=1 $ python setup.py build 3. Install cython-hidapi module into your Python distribution:: $ sudo python setup.py install **Alternatively**, you can run pip directly, which will call the necessary build and install commands:: $ pip install -e . 4. Test install:: $ python >>> import hid >>> 5. Try example script:: $ python try.py Udev rules ---------- For correct functionality under Linux, you need to create a rule file similar to `this one `_ in your udev rules directory. Also you might need to call ``udevadm control --reload-rules`` to reload the rules. Documentation ------------- Documentation can be built using Sphinx:: $ cd docs && make html The HTML output will be in ``docs/_build/html``. The documentation is extracted from the code using ``autodoc``. Note that the build output is used. So rebuilt the package before generating documentation. Built documentation is also deployed to: `https://trezor.github.io/cython-hidapi/ `_. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273674.0 hidapi-0.15.0/hidapi.egg-info/SOURCES.txt0000644000076500000240000000141515115770112016710 0ustar00stickstaffLICENSE-bsd.txt LICENSE-gpl3.txt LICENSE-orig.txt LICENSE.txt MANIFEST.in README.rst chid.pxd hid.c hid.pyx hidraw.pyx pyproject.toml setup.py tests.py try.py /Users/stick/work/trezor/cython-hidapi/hidapi/mac/hid.c hidapi.egg-info/PKG-INFO hidapi.egg-info/SOURCES.txt hidapi.egg-info/dependency_links.txt hidapi.egg-info/top_level.txt hidapi/hidapi/hidapi.h hidapi/libusb/hid.c hidapi/libusb/hidapi_libusb.h hidapi/libusb/hidapi_thread_pthread.h hidapi/linux/hid.c hidapi/mac/hid.c hidapi/mac/hidapi_darwin.h hidapi/windows/hid.c hidapi/windows/hidapi_cfgmgr32.h hidapi/windows/hidapi_descriptor_reconstruct.c hidapi/windows/hidapi_descriptor_reconstruct.h hidapi/windows/hidapi_hidclass.h hidapi/windows/hidapi_hidpi.h hidapi/windows/hidapi_hidsdi.h hidapi/windows/hidapi_winapi.h././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273674.0 hidapi-0.15.0/hidapi.egg-info/dependency_links.txt0000644000076500000240000000000115115770112021071 0ustar00stickstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273674.0 hidapi-0.15.0/hidapi.egg-info/top_level.txt0000644000076500000240000000000415115770112017547 0ustar00stickstaffhid ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273139.0 hidapi-0.15.0/hidraw.pyx0000644000076500000240000003211515115767063014130 0ustar00stickstaffimport sys import weakref from chid cimport * from libc.stddef cimport wchar_t, size_t __version__ = "0.15.0" hid_init() cdef extern from "": int wcslen(wchar_t*) cdef extern from "": void free(void* ptr) void* malloc(size_t size) cdef extern from *: object PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) Py_ssize_t PyUnicode_AsWideChar(object unicode, wchar_t *w, Py_ssize_t size) cdef object U(wchar_t *wcs): if wcs == NULL: return '' cdef int n = wcslen(wcs) return PyUnicode_FromWideChar(wcs, n) def enumerate(int vendor_id=0, int product_id=0): """Return a list of discovered HID devices. The fields of dict are: - 'path' - 'vendor_id' - 'product_id' - 'serial_number' - 'release_number' - 'manufacturer_string' - 'product_string' - 'usage_page' - 'usage' - 'interface_number' :param vendor_id: Vendor id to look for, default = 0 :type vendor_id: int, optional :param product_id: Product id to look for, default = 0 :type product_id: int, optional :return: List of device dictionaries :rtype: List[Dict] """ cdef hid_device_info* info with nogil: info = hid_enumerate(vendor_id, product_id) cdef hid_device_info* c = info res = [] while c: res.append({ 'path': c.path, 'vendor_id': c.vendor_id, 'product_id': c.product_id, 'serial_number': U(c.serial_number), 'release_number': c.release_number, 'manufacturer_string': U(c.manufacturer_string), 'product_string': U(c.product_string), 'usage_page': c.usage_page, 'usage': c.usage, 'interface_number': c.interface_number, 'bus_type': c.bus_type, }) c = c.next hid_free_enumeration(info) return res def version_str(): """Return a runtime version string of the hidapi C library. :return: version string of library :rtype: str """ return (hid_version_str()).decode('ascii') cdef class _closer: """Wrap a hid_device *ptr and a provide a way to call hid_close() on it. Used internally for weakref.finalize, which only accepts Python objects. """ cdef hid_device *_ptr @staticmethod cdef wrap(hid_device *ptr): cdef _closer closer = _closer() closer._ptr = ptr return closer def close(self): hid_close(self._ptr) cdef class device: """Device class. A device instance can be used to read from and write to a HID device. """ cdef hid_device *_c_hid cdef object __weakref__ # enable weak-reference support cdef object _close def open(self, int vendor_id=0, int product_id=0, unicode serial_number=None): """Open the connection. :param vendor_id: Vendor id to connect to, default = 0 :type vendor_id: int, optional :param product_id: Product id to connect to, default = 0 :type product_id: int, optional :param serial_number: :type serial_number: unicode, optional :raises IOError: """ cdef wchar_t * cserial_number = NULL cdef int serial_len cdef Py_ssize_t result if self._c_hid != NULL: raise RuntimeError('already open') try: if serial_number is not None: serial_len = len(serial_number) cserial_number = malloc(sizeof(wchar_t) * (serial_len+1)) if cserial_number == NULL: raise MemoryError() result = PyUnicode_AsWideChar(serial_number, cserial_number, serial_len) if result == -1: raise ValueError("invalid serial number string") cserial_number[serial_len] = 0 # Must explicitly null-terminate self._c_hid = hid_open(vendor_id, product_id, cserial_number) finally: if cserial_number != NULL: free(cserial_number) if self._c_hid == NULL: raise IOError('open failed') self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) def open_path(self, bytes path): """Open connection by path. :param path: Path to device :type path: bytes :raises IOError: """ cdef char* cbuff = path if self._c_hid != NULL: raise RuntimeError('already open') self._c_hid = hid_open_path(cbuff) if self._c_hid == NULL: raise IOError('open failed') self._close = weakref.finalize(self, _closer.wrap(self._c_hid).close) def close(self): """Close connection. This should always be called after opening a connection. """ if self._c_hid != NULL: self._close() self._close.detach() self._c_hid = NULL def write(self, buff): """Accept a list of integers (0-255) and send them to the device. :param buff: Data to write (must be convertible to `bytes`) :type buff: Any :return: Write result :rtype: int """ if self._c_hid == NULL: raise ValueError('not open') # convert to bytes if sys.version_info < (3, 0): buff = ''.join(map(chr, buff)) else: buff = bytes(buff) cdef hid_device * c_hid = self._c_hid cdef unsigned char* cbuff = buff # covert to c string cdef size_t c_buff_len = len(buff) cdef int result with nogil: result = hid_write(c_hid, cbuff, c_buff_len) return result def set_nonblocking(self, int v): """Set the nonblocking flag. :param v: Flag value (1 or 0, True or False) :type v: int, bool :return: Flag result :rtype: int """ if self._c_hid == NULL: raise ValueError('not open') return hid_set_nonblocking(self._c_hid, v) def read(self, int max_length, int timeout_ms=0): """Return a list of integers (0-255) from the device up to max_length bytes. :param max_length: Maximum number of bytes to read :type max_length: int :param timeout_ms: Number of milliseconds until timeout (default: no timeout) :type timeout_ms: int, optional :return: Read bytes :rtype: List[int] """ if self._c_hid == NULL: raise ValueError('not open') cdef unsigned char lbuff[16] cdef unsigned char* cbuff cdef size_t c_max_length = max_length cdef int c_timeout_ms = timeout_ms cdef hid_device * c_hid = self._c_hid try: if max_length <= 16: cbuff = lbuff else: cbuff = malloc(max_length) if timeout_ms > 0: with nogil: n = hid_read_timeout(c_hid, cbuff, c_max_length, c_timeout_ms) else: with nogil: n = hid_read(c_hid, cbuff, c_max_length) if n == -1: raise IOError('read error') res = list(cbuff[:n]) finally: if max_length > 16: free(cbuff) return res def get_manufacturer_string(self): """Return manufacturer string (e.g. vendor name). :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef int r = hid_get_manufacturer_string(self._c_hid, buff, 255) if r < 0: raise IOError('get manufacturer string error') return U(buff) def get_product_string(self): """Return product string (e.g. device description). :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef int r = hid_get_product_string(self._c_hid, buff, 255) if r < 0: raise IOError('get product string error') return U(buff) def get_serial_number_string(self): """Return serial number. :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef int r = hid_get_serial_number_string(self._c_hid, buff, 255) if r < 0: raise IOError('get serial number string error') return U(buff) def get_indexed_string(self, index): """Return indexed string. :return: :rtype: str :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef wchar_t buff[255] cdef unsigned char c_index = index cdef int r = hid_get_indexed_string(self._c_hid, c_index, buff, 255) if r < 0: raise IOError('get indexed string error') return U(buff) def send_feature_report(self, buff): """Accept a list of integers (0-255) and send them to the device. :param buff: Data to send (must be convertible into bytes) :type buff: any :return: Send result :rtype: int """ if self._c_hid == NULL: raise ValueError('not open') # convert to bytes if sys.version_info < (3, 0): buff = ''.join(map(chr, buff)) else: buff = bytes(buff) cdef hid_device * c_hid = self._c_hid cdef unsigned char* cbuff = buff # covert to c string cdef size_t c_buff_len = len(buff) cdef int result with nogil: result = hid_send_feature_report(c_hid, cbuff, c_buff_len) return result def get_report_descriptor(self): """Return the HID Report Descriptor for this device. :return: :rtype: List[int] :raises ValueError: If connection is not opened. :raises IOError: If read error """ if self._c_hid == NULL: raise ValueError('not open') cdef unsigned char cbuff[HID_API_MAX_REPORT_DESCRIPTOR_SIZE] cdef hid_device * c_hid = self._c_hid cdef int n with nogil: n = hid_get_report_descriptor(c_hid, cbuff, sizeof(cbuff)) if n < 0: raise IOError('read error') return list(cbuff[:n]) def get_feature_report(self, int report_num, int max_length): """Receive feature report. :param report_num: :type report_num: int :param max_length: :type max_length: int :return: Incoming feature report :rtype: List[int] :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef hid_device * c_hid = self._c_hid cdef unsigned char lbuff[16] cdef unsigned char* cbuff cdef size_t c_max_length = max_length cdef int n try: if max_length <= 16: cbuff = lbuff else: cbuff = malloc(max_length) cbuff[0] = report_num with nogil: n = hid_get_feature_report(c_hid, cbuff, c_max_length) if n < 0: raise IOError('read error') res = list(cbuff[:n]) finally: if max_length > 16: free(cbuff) return res def get_input_report(self, int report_num, int max_length): """Get input report :param report_num: :type report_num: int :param max_length: :type max_length: int :return: :rtype: List[int] :raises ValueError: If connection is not opened. :raises IOError: """ if self._c_hid == NULL: raise ValueError('not open') cdef hid_device * c_hid = self._c_hid cdef unsigned char lbuff[16] cdef unsigned char* cbuff cdef size_t c_max_length = max_length cdef int n try: if max_length <= 16: cbuff = lbuff else: cbuff = malloc(max_length) cbuff[0] = report_num with nogil: n = hid_get_input_report(c_hid, cbuff, c_max_length) if n < 0: raise IOError('read error') res = list(cbuff[:n]) finally: if max_length > 16: free(cbuff) return res def error(self): """Get error from device, or global error if no device is opened. :return: :rtype: str :raises IOError: """ return U(hid_error(self._c_hid)) # Finalize the HIDAPI library *only* once there are no more references to this # module, and it is being garbage collected. weakref.finalize(sys.modules[__name__], hid_exit) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/pyproject.toml0000644000076500000240000000013315115610727015011 0ustar00stickstaff[build-system] requires = ["setuptools", "Cython"] build-backend = "setuptools.build_meta" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1765273674.0723605 hidapi-0.15.0/setup.cfg0000644000076500000240000000004615115770112013714 0ustar00stickstaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765273139.0 hidapi-0.15.0/setup.py0000755000076500000240000002162615115767063013632 0ustar00stickstaff#!/usr/bin/python from Cython.Build import cythonize from setuptools import setup, Extension, Distribution from subprocess import call, PIPE, Popen import os import re import shlex import subprocess import sys min_required_hidapi_version = "0.14" libusb_pkgconfig = "libusb-1.0 >= 1.0.9" hidapi_libusb_pkgconfig = "hidapi-libusb >= " + min_required_hidapi_version hidapi_hidraw_pkgconfig = "hidapi-hidraw >= " + min_required_hidapi_version hidapi_pkgconfig = "hidapi >= " + min_required_hidapi_version tld = os.path.abspath(os.path.dirname(__file__)) embedded_hidapi_topdir = os.path.join(tld, "hidapi") embedded_hidapi_include = os.path.join(embedded_hidapi_topdir, "hidapi") def to_bool(bool_str): if str(bool_str).lower() in ["true", "t", "1", "on", "yes", "y"]: return True return False def get_extension_compiler_type(): """ Returns a compiler to be used by setuptools to build Extensions Taken from https://github.com/pypa/setuptools/issues/2806#issuecomment-961805789 """ d = Distribution() build_ext = Distribution().get_command_obj("build_ext") build_ext.finalize_options() # register an extension to ensure a compiler is created build_ext.extensions = [Extension("ignored", ["ignored.c"])] # disable building fake extensions build_ext.build_extensions = lambda: None # run to populate self.compiler build_ext.run() return build_ext.compiler.compiler_type # this could have been just pkgconfig.configure_extension(), but: https://github.com/matze/pkgconfig/issues/65 # additionally contains a few small improvements def pkgconfig_configure_extension(ext, package): pkg_config_exe = os.environ.get("PKG_CONFIG", None) or "pkg-config" def exists(package): cmd = f"{pkg_config_exe} --exists '{package}'" return call(shlex.split(cmd)) == 0 if not exists(package): raise Exception(f"pkg-config package '{package}' not found") def query_pkg_config(package, *options): cmd = f"{pkg_config_exe} {' '.join(options)} '{package}'" proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE) out, err = proc.communicate() return out.rstrip().decode("utf-8") def query_and_extend(option, target): os_opts = ["--msvc-syntax"] if get_extension_compiler_type() == "msvc" else [] flags = query_pkg_config(package, *os_opts, option) flags = flags.replace('\\"', "") if flags: target.extend(re.split(r"(?=19.0"], ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/tests.py0000644000076500000240000000030315115610727013610 0ustar00stickstaffimport unittest import hid class HIDTests(unittest.TestCase): def test_enumerate(self): self.assertTrue(len(hid.enumerate()) >= 0) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1765216727.0 hidapi-0.15.0/try.py0000644000076500000240000000246415115610727013276 0ustar00stickstafffrom __future__ import print_function import hid import time # enumerate USB devices for d in hid.enumerate(): keys = list(d.keys()) keys.sort() for key in keys: print("%s : %s" % (key, d[key])) print() # try opening a device, then perform write and read h = hid.device() try: print("Opening the device") h.open(0x534C, 0x0001) # TREZOR VendorID/ProductID print("Manufacturer: %s" % h.get_manufacturer_string()) print("Product: %s" % h.get_product_string()) print("Serial No: %s" % h.get_serial_number_string()) print("Report descriptor: %s" % h.get_report_descriptor()) # enable non-blocking mode h.set_nonblocking(1) # write some data to the device print("Write the data") h.write([0, 63, 35, 35] + [0] * 61) # wait time.sleep(0.05) # read back the answer print("Read the data") while True: d = h.read(64) if d: print(d) else: break print("Closing the device") h.close() except IOError as ex: print(ex) print("hid error:") print(h.error()) print("") print("You probably don't have the hard-coded device.") print("Update the h.open() line in this script with the one") print("from the enumeration list output above and try again.") print("Done")