pax_global_header00006660000000000000000000000064137047613770014531gustar00rootroot0000000000000052 comment=6d7d91cc200eda9d68427c30511fa0db139e7028 logiops-0.2.2/000077500000000000000000000000001370476137700132065ustar00rootroot00000000000000logiops-0.2.2/.github/000077500000000000000000000000001370476137700145465ustar00rootroot00000000000000logiops-0.2.2/.github/FUNDING.yml000066400000000000000000000012501370476137700163610ustar00rootroot00000000000000# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: pixlone tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] logiops-0.2.2/.github/workflows/000077500000000000000000000000001370476137700166035ustar00rootroot00000000000000logiops-0.2.2/.github/workflows/release.yml000066400000000000000000000020451370476137700207470ustar00rootroot00000000000000name: release-ci on: push: types: - tags workflow_dispatch: jobs: job: name: ${{ matrix.os }}-release runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest] include: - os: ubuntu-latest triplet: x64-linux installDependencies: 'sudo apt-get update -m && sudo apt-get install libconfig++-dev libevdev-dev libudev-dev' steps: - uses: actions/checkout@v1 with: submodules: true - name: Install dependencies run: '${{ matrix.installDependencies }}' - name: Run CMake+Make uses: lukka/run-cmake@v2 id: runcmake with: cmakeGenerator: 'UnixMakefiles' cmakeListsOrSettingsJson: 'CMakeListsTxtBasic' cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt' cmakeAdditionalArgs: '-DFORCE_BUILD_HIDPP=True' buildWithCMakeArgs: '-- -v' cmakeBuildType: 'Release' buildDirectory: '${{ runner.workspace }}/build/' logiops-0.2.2/.gitignore000066400000000000000000000000471370476137700151770ustar00rootroot00000000000000/build *.swp *~ /compile_commands.json logiops-0.2.2/CMakeLists.txt000066400000000000000000000023541370476137700157520ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.10) set(CMAKE_INSTALL_PREFIX /usr) project(logiops) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -Wall -Wextra") set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(Git) # Set version number if(GIT_FOUND AND EXISTS ${CMAKE_SOURCE_DIR}/.git) execute_process(COMMAND ${GIT_EXECUTABLE} describe OUTPUT_VARIABLE LOGIOPS_VERSION RESULT_VARIABLE LOGIOPS_VERSION_RET ERROR_QUIET) if(NOT LOGIOPS_VERSION_RET EQUAL "0") execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD OUTPUT_VARIABLE LOGIOPS_COMMIT_HASH) set(LOGIOPS_VERSION git-${LOGIOPS_COMMIT_HASH}) endif() string(REGEX REPLACE "\n$" "" LOGIOPS_VERSION ${LOGIOPS_VERSION}) elseif(EXISTS ${CMAKE_SOURCE_DIR}/version.txt) file(READ version.txt LOGIOPS_VERSION) string(REGEX REPLACE "\n$" "" LOGIOPS_VERSION ${LOGIOPS_VERSION}) endif() if(NOT LOGIOPS_VERSION) set(LOGIOPS_VERSION "null") endif() message("LogiOps Version Number: ${LOGIOPS_VERSION}") add_definitions( -DLOGIOPS_VERSION="${LOGIOPS_VERSION}") add_subdirectory(src/logid) logiops-0.2.2/LICENSE000066400000000000000000001045151370476137700142210ustar00rootroot00000000000000 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 . logiops-0.2.2/README.md000066400000000000000000000036771370476137700145020ustar00rootroot00000000000000# logiops This is an unofficial driver for Logitech mice and keyboard. This is currently only compatible with HID++ \>2.0 devices. ## Configuration [Refer to the wiki for details.](https://github.com/PixlOne/logiops/wiki/Configuration) You may also refer to logid.example.cfg for an example. Default location for the configuration file is /etc/logid.cfg. ## Dependencies This project requires a C++14 compiler, cmake, libevdev, libudev, and libconfig. For popular distributions, I've included commands below. **Debian/Ubuntu:** `sudo apt install cmake libevdev-dev libudev-dev libconfig++-dev` **Arch Linux:** `sudo pacman -S cmake libevdev libconfig pkgconf` ## Building To build this project, run: ``` mkdir build cd build cmake .. make ``` To install, run `sudo make install` after building. You can set the daemon to start at boot by running `sudo systemctl start logid`. ## Donate This program is (and will always be) provided free of charge. If you would like to support the development of this project by donating, you can donate to my Ko-Fi below. Buy Me a Coffee at ko-fi.com I'm also looking for contributors to help in my project; feel free to submit a pull request or e-mail me if you would like to contribute. ## Compatible Devices [For a list of tested devices, check TESTED.md](TESTED.md) ## Special Thanks Thanks to the following people for contributing to this repository. - [ClĂ©ment Vuchener & contributors for creating the old HID++ library](https://github.com/cvuchener/hidpp) - [Developers of Solaar for providing information on HID++](https://github.com/pwr-Solaar/Solaar) - [Nestor Lopez Casado for providing Logitech documentation on the HID++ protocol](http://drive.google.com/folderview?id=0BxbRzx7vEV7eWmgwazJ3NUFfQ28) - Everyone listed in the contributors page logiops-0.2.2/TESTED.md000066400000000000000000000010321370476137700145140ustar00rootroot00000000000000# Compatible Devices This is not by any means an exhaustive list. Many more devices are supported but these devices are the ones that are confirmed to be working. To add to this list, submit a pull request adding your device. | Device | Compatible? | |:------------:|:-----------:| | MX Master 3 | Yes | | MX Master 2S | Yes | | MX Master | Yes | | MX Vertical | Yes | | MX Ergo | Yes | | M720 | Yes | | M590 | Yes | | T400 | Yes | logiops-0.2.2/logid.example.cfg000066400000000000000000000036161370476137700164250ustar00rootroot00000000000000devices: ( { name: "MX Master"; smartshift: { on: true; threshold: 30; }; hiresscroll: { hires: true; invert: false; target: false; }; dpi: 1000; buttons: ( { cid: 0xc3; action = { type: "Gestures"; gestures: ( { direction: "Up"; mode: "OnRelease"; action = { type: "Keypress"; keys: ["KEY_UP"]; }; }, { direction: "Down"; mode: "OnRelease"; action = { type: "Keypress"; keys: ["KEY_DOWN"]; }; }, { direction: "Left"; mode: "OnRelease"; action = { type: "CycleDPI"; dpis: [400, 600, 800, 1000, 1200, 1400, 1600]; }; }, { direction: "Right"; mode: "OnRelease"; action = { type = "ToggleSmartshift"; } }, { direction: "None" mode: "NoPress" } ); }; }, { cid: 0xc4; action = { type: "Keypress"; keys: ["KEY_A"]; }; } ); } );logiops-0.2.2/src/000077500000000000000000000000001370476137700137755ustar00rootroot00000000000000logiops-0.2.2/src/logid/000077500000000000000000000000001370476137700150735ustar00rootroot00000000000000logiops-0.2.2/src/logid/CMakeLists.txt000066400000000000000000000071271370476137700176420ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.10) project(logid) set(CMAKE_CXX_STANDARD 14) set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/../CMake") find_package(Threads REQUIRED) find_package(PkgConfig REQUIRED) add_executable(logid logid.cpp util/log.cpp InputDevice.cpp DeviceManager.cpp Device.cpp Receiver.cpp Configuration.cpp features/DPI.cpp features/SmartShift.cpp features/HiresScroll.cpp features/RemapButton.cpp features/DeviceStatus.cpp actions/Action.cpp actions/NullAction.cpp actions/KeypressAction.cpp actions/ToggleHiresScroll.cpp actions/ToggleSmartShift.cpp actions/CycleDPI.cpp actions/ChangeDPI.cpp actions/GestureAction.cpp actions/ChangeHostAction.cpp actions/gesture/Gesture.cpp actions/gesture/ReleaseGesture.cpp actions/gesture/IntervalGesture.cpp actions/gesture/AxisGesture.cpp actions/gesture/NullGesture.cpp backend/Error.cpp backend/raw/DeviceMonitor.cpp backend/raw/RawDevice.cpp backend/dj/Receiver.cpp backend/dj/ReceiverMonitor.cpp backend/dj/Error.cpp backend/hidpp/Device.cpp backend/hidpp/Report.cpp backend/hidpp10/Error.cpp backend/hidpp10/Device.cpp backend/hidpp20/Device.cpp backend/hidpp20/Error.cpp backend/hidpp20/Feature.cpp backend/hidpp20/EssentialFeature.cpp backend/hidpp20/features/Root.cpp backend/hidpp20/features/FeatureSet.cpp backend/hidpp20/features/DeviceName.cpp backend/hidpp20/features/Reset.cpp backend/hidpp20/features/AdjustableDPI.cpp backend/hidpp20/features/SmartShift.cpp backend/hidpp20/features/ReprogControls.cpp backend/hidpp20/features/HiresScroll.cpp backend/hidpp20/features/ChangeHost.cpp backend/hidpp20/features/WirelessDeviceStatus.cpp backend/dj/Report.cpp util/mutex_queue.h util/workqueue.cpp util/worker_thread.cpp util/task.cpp util/thread.cpp util/ExceptionHandler.cpp) set_target_properties(logid PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) pkg_check_modules(PC_EVDEV libevdev REQUIRED) pkg_check_modules(SYSTEMD "systemd") pkg_check_modules(LIBCONFIG libconfig REQUIRED) pkg_check_modules(LIBUDEV libudev REQUIRED) find_path(EVDEV_INCLUDE_DIR libevdev/libevdev.h HINTS ${PC_EVDEV_INCLUDE_DIRS} ${PC_EVDEV_INCLUDEDIR}) find_library(EVDEV_LIBRARY NAMES evdev libevdev) include_directories(${EVDEV_INCLUDE_DIR} ${LIBUDEV_INCLUDE_DIRECTORIES}) target_link_libraries(logid ${CMAKE_THREAD_LIBS_INIT} ${EVDEV_LIBRARY} config++ ${LIBUDEV_LIBRARIES}) install(TARGETS logid DESTINATION bin) if (SYSTEMD_FOUND AND "${SYSTEMD_SERVICES_INSTALL_DIR}" STREQUAL "") execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=systemdsystemunitdir systemd OUTPUT_VARIABLE SYSTEMD_SERVICES_INSTALL_DIR) string(REGEX REPLACE "[ \t\n]+" "" SYSTEMD_SERVICES_INSTALL_DIR "${SYSTEMD_SERVICES_INSTALL_DIR}") configure_file(logid.service.cmake ${CMAKE_BINARY_DIR}/logid.service) message(STATUS "systemd units will be installed at ${SYSTEMD_SERVICES_INSTALL_DIR}") install(FILES ${CMAKE_BINARY_DIR}/logid.service DESTINATION ${SYSTEMD_SERVICES_INSTALL_DIR} COMPONENT cp) elseif(NOT SYSTEMD_FOUND AND SYSTEMD_SERVICES_INSTALL_DIR) message(FATAL_ERROR "systemd is not found w/ pkg-config but SYSTEMD_SERVICES_INSTALL_DIR is defined.") endif() logiops-0.2.2/src/logid/Configuration.cpp000066400000000000000000000133431370476137700204120ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include #include "Configuration.h" #include "util/log.h" using namespace logid; using namespace libconfig; using namespace std::chrono; Configuration::Configuration(const std::string& config_file) { try { _config.readFile(config_file.c_str()); } catch(const FileIOException &e) { logPrintf(ERROR, "I/O Error while reading %s: %s", config_file.c_str(), e.what()); throw e; } catch(const ParseException &e) { logPrintf(ERROR, "Parse error in %s, line %d: %s", e.getFile(), e.getLine(), e.getError()); throw e; } const Setting &root = _config.getRoot(); try { auto& worker_count = root["workers"]; if(worker_count.getType() == Setting::TypeInt) { _worker_threads = worker_count; if(_worker_threads < 0) logPrintf(WARN, "Line %d: workers cannot be negative.", worker_count.getSourceLine()); } else { logPrintf(WARN, "Line %d: workers must be an integer.", worker_count.getSourceLine()); } } catch(const SettingNotFoundException& e) { // Ignore } try { auto& timeout = root["io_timeout"]; if(timeout.isNumber()) { if(timeout.getType() == Setting::TypeFloat) _io_timeout = duration_cast( duration(timeout)); else _io_timeout = milliseconds((int)timeout); } else logPrintf(WARN, "Line %d: io_timeout must be a number.", timeout.getSourceLine()); } catch(const SettingNotFoundException& e) { // Ignore } try { auto& devices = root["devices"]; for(int i = 0; i < devices.getLength(); i++) { const Setting& device = devices[i]; std::string name; try { if(!device.lookupValue("name", name)) { logPrintf(WARN, "Line %d: 'name' must be a string, skipping" " device.", device["name"].getSourceLine()); continue; } } catch(SettingNotFoundException &e) { logPrintf(WARN, "Line %d: Missing name field, skipping device." , device.getSourceLine()); continue; } _device_paths.insert({name, device.getPath()}); } } catch(const SettingNotFoundException &e) { logPrintf(WARN, "No devices listed in config file."); } try { auto& ignore = root.lookup("ignore"); if(ignore.getType() == libconfig::Setting::TypeInt) { _ignore_list.insert((int)ignore); } else if(ignore.isList() || ignore.isArray()) { int ignore_count = ignore.getLength(); for(int i = 0; i < ignore_count; i++) { if(ignore[i].getType() != libconfig::Setting::TypeInt) { logPrintf(WARN, "Line %d: ignore must refer to device PIDs", ignore[i].getSourceLine()); if(ignore.isArray()) break; } else _ignore_list.insert((int)ignore[i]); } } } catch(const SettingNotFoundException& e) { // May be called blacklist try { auto& ignore = root.lookup("blacklist"); if(ignore.getType() == libconfig::Setting::TypeInt) { _ignore_list.insert((int)ignore); } else if(ignore.isList() || ignore.isArray()) { int ignore_count = ignore.getLength(); for(int i = 0; i < ignore_count; i++) { if(ignore[i].getType() != libconfig::Setting::TypeInt) { logPrintf(WARN, "Line %d: blacklist must refer to " "device PIDs", ignore[i].getSourceLine()); if(ignore.isArray()) break; } else _ignore_list.insert((int)ignore[i]); } } } catch(const SettingNotFoundException& e) { // Ignore } } } libconfig::Setting& Configuration::getSetting(const std::string& path) { return _config.lookup(path); } std::string Configuration::getDevice(const std::string& name) { auto it = _device_paths.find(name); if(it == _device_paths.end()) throw DeviceNotFound(name); else return it->second; } bool Configuration::isIgnored(uint16_t pid) const { return _ignore_list.find(pid) != _ignore_list.end(); } Configuration::DeviceNotFound::DeviceNotFound(std::string name) : _name (std::move(name)) { } const char * Configuration::DeviceNotFound::what() const noexcept { return _name.c_str(); } int Configuration::workerCount() const { return _worker_threads; } std::chrono::milliseconds Configuration::ioTimeout() const { return _io_timeout; } logiops-0.2.2/src/logid/Configuration.h000066400000000000000000000036721370476137700200630ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_CONFIGURATION_H #define LOGID_CONFIGURATION_H #include #include #include #include #include #define LOGID_DEFAULT_IO_TIMEOUT std::chrono::seconds(2) #define LOGID_DEFAULT_WORKER_COUNT 4 namespace logid { class Configuration { public: explicit Configuration(const std::string& config_file); Configuration() = default; libconfig::Setting& getSetting(const std::string& path); std::string getDevice(const std::string& name); bool isIgnored(uint16_t pid) const; class DeviceNotFound : public std::exception { public: explicit DeviceNotFound(std::string name); const char* what() const noexcept override; private: std::string _name; }; std::chrono::milliseconds ioTimeout() const; int workerCount() const; private: std::map _device_paths; std::set _ignore_list; std::chrono::milliseconds _io_timeout = LOGID_DEFAULT_IO_TIMEOUT; int _worker_threads = LOGID_DEFAULT_WORKER_COUNT; libconfig::Config _config; }; extern std::shared_ptr global_config; } #endif //LOGID_CONFIGURATION_H logiops-0.2.2/src/logid/Device.cpp000066400000000000000000000072331370476137700170030ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "util/log.h" #include "features/DPI.h" #include "Device.h" #include "features/SmartShift.h" #include "features/RemapButton.h" #include "backend/hidpp20/features/Reset.h" #include "features/HiresScroll.h" #include "features/DeviceStatus.h" using namespace logid; using namespace logid::backend; Device::Device(std::string path, backend::hidpp::DeviceIndex index) : _hidpp20 (path, index), _path (std::move(path)), _index (index), _config (global_config, this) { _init(); } Device::Device(const std::shared_ptr& raw_device, hidpp::DeviceIndex index) : _hidpp20(raw_device, index), _path (raw_device->hidrawPath()), _index (index), _config (global_config, this) { _init(); } void Device::_init() { logPrintf(INFO, "Device found: %s on %s:%d", name().c_str(), hidpp20().devicePath().c_str(), _index); _addFeature("dpi"); _addFeature("smartshift"); _addFeature("hiresscroll"); _addFeature("remapbutton"); _addFeature("devicestatus"); _makeResetMechanism(); reset(); for(auto& feature: _features) { feature.second->configure(); feature.second->listen(); } _hidpp20.listen(); } std::string Device::name() { return _hidpp20.name(); } uint16_t Device::pid() { return _hidpp20.pid(); } void Device::sleep() { logPrintf(INFO, "%s:%d fell asleep.", _path.c_str(), _index); } void Device::wakeup() { logPrintf(INFO, "%s:%d woke up.", _path.c_str(), _index); std::this_thread::sleep_for(std::chrono::milliseconds(100)); reset(); for(auto& feature: _features) feature.second->configure(); } void Device::reset() { if(_reset_mechanism) (*_reset_mechanism)(); else logPrintf(DEBUG, "%s:%d tried to reset, but no reset mechanism was " "available.", _path.c_str(), _index); } DeviceConfig& Device::config() { return _config; } hidpp20::Device& Device::hidpp20() { return _hidpp20; } void Device::_makeResetMechanism() { try { hidpp20::Reset reset(&_hidpp20); _reset_mechanism = std::make_unique>( [dev=&this->_hidpp20]{ hidpp20::Reset reset(dev); reset.reset(reset.getProfile()); }); } catch(hidpp20::UnsupportedFeature& e) { // Reset unsupported, ignore. } } DeviceConfig::DeviceConfig(const std::shared_ptr& config, Device* device) : _device (device), _config (config) { try { _root_setting = config->getDevice(device->name()); } catch(Configuration::DeviceNotFound& e) { logPrintf(INFO, "Device %s not configured, using default config.", device->name().c_str()); } } libconfig::Setting& DeviceConfig::getSetting(const std::string& path) { return _config->getSetting(_root_setting + '/' + path); } logiops-0.2.2/src/logid/Device.h000066400000000000000000000060201370476137700164410ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_DEVICE_H #define LOGID_DEVICE_H #include "backend/hidpp/defs.h" #include "backend/hidpp20/Device.h" #include "features/DeviceFeature.h" #include "Configuration.h" #include "util/log.h" namespace logid { class Device; class DeviceConfig { public: DeviceConfig(const std::shared_ptr& config, Device* device); libconfig::Setting& getSetting(const std::string& path); private: Device* _device; std::string _root_setting; std::shared_ptr _config; }; /* TODO: Implement HID++ 1.0 support * Currently, the logid::Device class has a hardcoded requirement * for an HID++ 2.0 device. */ class Device { public: Device(std::string path, backend::hidpp::DeviceIndex index); Device(const std::shared_ptr& raw_device, backend::hidpp::DeviceIndex index); std::string name(); uint16_t pid(); DeviceConfig& config(); backend::hidpp20::Device& hidpp20(); void wakeup(); void sleep(); void reset(); template std::shared_ptr getFeature(std::string name) { auto it = _features.find(name); if(it == _features.end()) return nullptr; try { return std::dynamic_pointer_cast(it->second); } catch(std::bad_cast& e) { logPrintf(ERROR, "bad_cast while getting device feature %s: %s", name.c_str(), e.what()); return nullptr; } } private: void _init(); /* Adds a feature without calling an error if unsupported */ template void _addFeature(std::string name) { try { _features.emplace(name, std::make_shared(this)); } catch (features::UnsupportedFeature& e) { } } backend::hidpp20::Device _hidpp20; std::string _path; backend::hidpp::DeviceIndex _index; std::map> _features; DeviceConfig _config; void _makeResetMechanism(); std::unique_ptr> _reset_mechanism; }; } #endif //LOGID_DEVICE_H logiops-0.2.2/src/logid/DeviceManager.cpp000066400000000000000000000072631370476137700203010ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include "DeviceManager.h" #include "Receiver.h" #include "util/log.h" #include "backend/hidpp10/Error.h" #include "backend/Error.h" using namespace logid; using namespace logid::backend; void DeviceManager::addDevice(std::string path) { bool defaultExists = true; bool isReceiver = false; // Check if device is ignored before continuing { raw::RawDevice raw_dev(path); if(global_config->isIgnored(raw_dev.productId())) { logPrintf(DEBUG, "%s: Device 0x%04x ignored.", path.c_str(), raw_dev.productId()); return; } } try { hidpp::Device device(path, hidpp::DefaultDevice); isReceiver = device.version() == std::make_tuple(1, 0); } catch(hidpp10::Error &e) { if(e.code() != hidpp10::Error::UnknownDevice) throw; } catch(hidpp::Device::InvalidDevice &e) { // Ignore defaultExists = false; } catch(std::system_error &e) { logPrintf(WARN, "I/O error on %s: %s, skipping device.", path.c_str(), e.what()); return; } catch (TimeoutError &e) { logPrintf(WARN, "Device %s timed out.", path.c_str()); defaultExists = false; } if(isReceiver) { logPrintf(INFO, "Detected receiver at %s", path.c_str()); auto receiver = std::make_shared(path); receiver->run(); _receivers.emplace(path, receiver); } else { /* TODO: Can non-receivers only contain 1 device? * If the device exists, it is guaranteed to be an HID++ 2.0 device */ if(defaultExists) { auto device = std::make_shared(path, hidpp::DefaultDevice); _devices.emplace(path, device); } else { try { auto device = std::make_shared(path, hidpp::CordedDevice); _devices.emplace(path, device); } catch(hidpp10::Error &e) { if(e.code() != hidpp10::Error::UnknownDevice) throw; else logPrintf(WARN, "HID++ 1.0 error while trying to initialize %s:" "%s", path.c_str(), e.what()); } catch(hidpp::Device::InvalidDevice &e) { // Ignore } catch(std::system_error &e) { // This error should have been thrown previously logPrintf(WARN, "I/O error on %s: %s", path.c_str(), e.what()); } } } } void DeviceManager::removeDevice(std::string path) { auto receiver = _receivers.find(path); if(receiver != _receivers.end()) { _receivers.erase(receiver); logPrintf(INFO, "Receiver on %s disconnected", path.c_str()); } else { auto device = _devices.find(path); if(device != _devices.find(path)) { _devices.erase(device); logPrintf(INFO, "Device on %s disconnected", path.c_str()); } } } logiops-0.2.2/src/logid/DeviceManager.h000066400000000000000000000026131370476137700177400ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_DEVICEMANAGER_H #define LOGID_DEVICEMANAGER_H #include #include #include #include "backend/raw/DeviceMonitor.h" #include "backend/hidpp/Device.h" #include "Device.h" #include "Receiver.h" namespace logid { class DeviceManager : public backend::raw::DeviceMonitor { public: DeviceManager() = default; protected: void addDevice(std::string path) override; void removeDevice(std::string path) override; private: std::map> _devices; std::map> _receivers; }; extern std::unique_ptr device_manager; } #endif //LOGID_DEVICEMANAGER_Hlogiops-0.2.2/src/logid/InputDevice.cpp000066400000000000000000000052311370476137700200170ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "InputDevice.h" extern "C" { #include #include } using namespace logid; InputDevice::InvalidEventCode::InvalidEventCode(const std::string& name) : _what ("Invalid event code " + name) { } const char* InputDevice::InvalidEventCode::what() const noexcept { return _what.c_str(); } InputDevice::InputDevice(const char* name) { device = libevdev_new(); libevdev_set_name(device, name); ///TODO: Is it really a good idea to enable all events? libevdev_enable_event_type(device, EV_KEY); for(unsigned int i = 0; i < KEY_CNT; i++) libevdev_enable_event_code(device, EV_KEY, i, nullptr); libevdev_enable_event_type(device, EV_REL); for(unsigned int i = 0; i < REL_CNT; i++) libevdev_enable_event_code(device, EV_REL, i, nullptr); int err = libevdev_uinput_create_from_device(device, LIBEVDEV_UINPUT_OPEN_MANAGED, &ui_device); if(err != 0) throw std::system_error(-err, std::generic_category()); } InputDevice::~InputDevice() { libevdev_uinput_destroy(ui_device); libevdev_free(device); } void InputDevice::moveAxis(uint axis, int movement) { _sendEvent(EV_REL, axis, movement); } void InputDevice::pressKey(uint code) { _sendEvent(EV_KEY, code, 1); } void InputDevice::releaseKey(uint code) { _sendEvent(EV_KEY, code, 0); } uint InputDevice::toKeyCode(const std::string& name) { return _toEventCode(EV_KEY, name); } uint InputDevice::toAxisCode(const std::string& name) { return _toEventCode(EV_REL, name); } uint InputDevice::_toEventCode(uint type, const std::string& name) { int code = libevdev_event_code_from_name(type, name.c_str()); if(code == -1) throw InvalidEventCode(name); return code; } void InputDevice::_sendEvent(uint type, uint code, int value) { libevdev_uinput_write_event(ui_device, type, code, value); libevdev_uinput_write_event(ui_device, EV_SYN, SYN_REPORT, 0); }logiops-0.2.2/src/logid/InputDevice.h000066400000000000000000000033661370476137700174730ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_INPUTDEVICE_H #define LOGID_INPUTDEVICE_H #include extern "C" { #include #include } namespace logid { class InputDevice { public: class InvalidEventCode : public std::exception { public: explicit InvalidEventCode(const std::string& name); const char* what() const noexcept override; private: const std::string _what; }; explicit InputDevice(const char *name); ~InputDevice(); void moveAxis(uint axis, int movement); void pressKey(uint code); void releaseKey(uint code); static uint toKeyCode(const std::string& name); static uint toAxisCode(const std::string& name); private: void _sendEvent(uint type, uint code, int value); static uint _toEventCode(uint type, const std::string& name); libevdev* device; libevdev_uinput* ui_device{}; }; extern std::unique_ptr virtual_input; } #endif //LOGID_INPUTDEVICE_Hlogiops-0.2.2/src/logid/Receiver.cpp000066400000000000000000000056131370476137700173500ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "Receiver.h" #include "util/log.h" #include "backend/hidpp10/Error.h" #include "backend/hidpp20/Error.h" #include "backend/Error.h" using namespace logid; using namespace logid::backend; Receiver::Receiver(const std::string& path) : dj::ReceiverMonitor(path), _path (path) { } void Receiver::addDevice(hidpp::DeviceConnectionEvent event) { std::unique_lock lock(_devices_change); try { // Check if device is ignored before continuing if(global_config->isIgnored(event.pid)) { logPrintf(DEBUG, "%s:%d: Device 0x%04x ignored.", _path.c_str(), event.index, event.pid); return; } auto dev = _devices.find(event.index); if(dev != _devices.end()) { if(event.linkEstablished) dev->second->wakeup(); else dev->second->sleep(); return; } if(!event.linkEstablished) return; hidpp::Device hidpp_device(receiver(), event); auto version = hidpp_device.version(); if(std::get<0>(version) < 2) { logPrintf(INFO, "Unsupported HID++ 1.0 device on %s:%d connected.", _path.c_str(), event.index); return; } std::shared_ptr device = std::make_shared( receiver()->rawDevice(), event.index); _devices.emplace(event.index, device); } catch(hidpp10::Error &e) { logPrintf(ERROR, "Caught HID++ 1.0 error while trying to initialize " "%s:%d: %s", _path.c_str(), event.index, e.what()); } catch(hidpp20::Error &e) { logPrintf(ERROR, "Caught HID++ 2.0 error while trying to initialize " "%s:%d: %s", _path.c_str(), event.index, e.what()); } catch(TimeoutError &e) { if(!event.fromTimeoutCheck) logPrintf(DEBUG, "%s:%d timed out, waiting for input from device to" " initialize.", _path.c_str(), event.index); waitForDevice(event.index); } } void Receiver::removeDevice(hidpp::DeviceIndex index) { std::unique_lock lock(_devices_change); _devices.erase(index); }logiops-0.2.2/src/logid/Receiver.h000066400000000000000000000024421370476137700170120ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_RECEIVER_H #define LOGID_RECEIVER_H #include #include "backend/dj/ReceiverMonitor.h" #include "Device.h" namespace logid { class Receiver : public backend::dj::ReceiverMonitor { public: Receiver(const std::string& path); protected: void addDevice(backend::hidpp::DeviceConnectionEvent event) override; void removeDevice(backend::hidpp::DeviceIndex index) override; private: std::mutex _devices_change; std::map> _devices; std::string _path; }; } #endif //LOGID_RECEIVER_Hlogiops-0.2.2/src/logid/actions/000077500000000000000000000000001370476137700165335ustar00rootroot00000000000000logiops-0.2.2/src/logid/actions/Action.cpp000066400000000000000000000053531370476137700204620ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "Action.h" #include "../util/log.h" #include "KeypressAction.h" #include "ToggleSmartShift.h" #include "ToggleHiresScroll.h" #include "GestureAction.h" #include "NullAction.h" #include "CycleDPI.h" #include "ChangeDPI.h" #include "ChangeHostAction.h" using namespace logid; using namespace logid::actions; std::shared_ptr Action::makeAction(Device *device, libconfig::Setting &setting) { if(!setting.isGroup()) { logPrintf(WARN, "Line %d: Action is not a group, ignoring.", setting.getSourceLine()); throw InvalidAction(); } try { auto& action_type = setting.lookup("type"); if(action_type.getType() != libconfig::Setting::TypeString) { logPrintf(WARN, "Line %d: Action type must be a string", action_type.getSourceLine()); throw InvalidAction(); } std::string type = action_type; std::transform(type.begin(), type.end(), type.begin(), ::tolower); if(type == "keypress") return std::make_shared(device, setting); else if(type == "togglesmartshift") return std::make_shared(device); else if(type == "togglehiresscroll") return std::make_shared(device); else if(type == "gestures") return std::make_shared(device, setting); else if(type == "cycledpi") return std::make_shared(device, setting); else if(type == "changedpi") return std::make_shared(device, setting); else if(type == "none") return std::make_shared(device); else if(type == "changehost") return std::make_shared(device, setting); else throw InvalidAction(type); } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: Action type is missing, ignoring.", setting.getSourceLine()); throw InvalidAction(); } }logiops-0.2.2/src/logid/actions/Action.h000066400000000000000000000040511370476137700201210ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_H #define LOGID_ACTION_H #include #include #include namespace logid { class Device; namespace actions { class InvalidAction : public std::exception { public: InvalidAction() { } explicit InvalidAction(std::string& action) : _action (action) { } const char* what() const noexcept override { return _action.c_str(); } private: std::string _action; }; class Action { public: static std::shared_ptr makeAction(Device* device, libconfig::Setting& setting); virtual void press() = 0; virtual void release() = 0; virtual void move(int16_t x, int16_t y) { // Suppress unused warning (void)x; (void)y; } virtual bool pressed() { return _pressed; } virtual uint8_t reprogFlags() const = 0; class Config { protected: explicit Config(Device* device) : _device (device) { } Device* _device; }; protected: explicit Action(Device* device) : _device (device), _pressed (false) { } Device* _device; std::atomic _pressed; }; }} #endif //LOGID_ACTION_H logiops-0.2.2/src/logid/actions/ChangeDPI.cpp000066400000000000000000000065731370476137700207740ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "ChangeDPI.h" #include "../Device.h" #include "../util/task.h" #include "../util/log.h" #include "../backend/hidpp20/Error.h" #include "../backend/hidpp20/features/ReprogControls.h" using namespace logid::actions; ChangeDPI::ChangeDPI(Device *device, libconfig::Setting &setting) : Action(device), _config(device, setting) { _dpi = _device->getFeature("dpi"); if(!_dpi) logPrintf(WARN, "%s:%d: DPI feature not found, cannot use " "ChangeDPI action.", _device->hidpp20().devicePath().c_str(), _device->hidpp20().deviceIndex()); } void ChangeDPI::press() { _pressed = true; if(_dpi) { task::spawn([this]{ try { uint16_t last_dpi = _dpi->getDPI(_config.sensor()); _dpi->setDPI(last_dpi + _config.interval(), _config.sensor()); } catch (backend::hidpp20::Error& e) { if(e.code() == backend::hidpp20::Error::InvalidArgument) logPrintf(WARN, "%s:%d: Could not get/set DPI for sensor " "%d", _device->hidpp20().devicePath().c_str(), _device->hidpp20().deviceIndex(), _config.sensor()); else throw e; } }); } } void ChangeDPI::release() { _pressed = false; } uint8_t ChangeDPI::reprogFlags() const { return backend::hidpp20::ReprogControls::TemporaryDiverted; } ChangeDPI::Config::Config(Device *device, libconfig::Setting &config) : Action::Config(device), _interval (0), _sensor (0) { if(!config.isGroup()) { logPrintf(WARN, "Line %d: action must be an object, skipping.", config.getSourceLine()); return; } try { auto& inc = config.lookup("inc"); if(inc.getType() != libconfig::Setting::TypeInt) logPrintf(WARN, "Line %d: inc must be an integer", inc.getSourceLine()); _interval = (int)inc; } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: inc is a required field, skipping.", config.getSourceLine()); } try { auto& sensor = config.lookup("sensor"); if(sensor.getType() != libconfig::Setting::TypeInt) logPrintf(WARN, "Line %d: sensor must be an integer", sensor.getSourceLine()); _sensor = (int)sensor; } catch(libconfig::SettingNotFoundException& e) { // Ignore } } uint16_t ChangeDPI::Config::interval() const { return _interval; } uint8_t ChangeDPI::Config::sensor() const { return _sensor; }logiops-0.2.2/src/logid/actions/ChangeDPI.h000066400000000000000000000031341370476137700204270ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_CHANGEDPI_H #define LOGID_ACTION_CHANGEDPI_H #include #include "Action.h" #include "../features/DPI.h" namespace logid { namespace actions { class ChangeDPI : public Action { public: explicit ChangeDPI(Device* device, libconfig::Setting& setting); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; class Config : public Action::Config { public: Config(Device* device, libconfig::Setting& setting); uint16_t interval() const; uint8_t sensor() const; private: uint16_t _interval; uint8_t _sensor; }; protected: Config _config; std::shared_ptr _dpi; }; }} #endif //LOGID_ACTION_CHANGEDPI_Hlogiops-0.2.2/src/logid/actions/ChangeHostAction.cpp000066400000000000000000000075271370476137700224330ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "ChangeHostAction.h" #include "../Device.h" #include "../backend/hidpp20/features/ReprogControls.h" #include "../util/task.h" using namespace logid::actions; using namespace logid::backend; ChangeHostAction::ChangeHostAction(Device *device, libconfig::Setting& config) : Action(device), _config (device, config) { try { _change_host = std::make_shared(&device->hidpp20()); } catch (hidpp20::UnsupportedFeature& e) { logPrintf(WARN, "%s:%d: ChangeHost feature not supported, " "ChangeHostAction will not work.", device->hidpp20() .devicePath().c_str(), device->hidpp20().deviceIndex()); } } void ChangeHostAction::press() { // Do nothing, wait until release } void ChangeHostAction::release() { if(_change_host) { task::spawn([this] { auto host_info = _change_host->getHostInfo(); auto next_host = _config.nextHost(host_info); if(next_host != host_info.currentHost) _change_host->setHost(next_host); }); } } uint8_t ChangeHostAction::reprogFlags() const { return hidpp20::ReprogControls::TemporaryDiverted; } ChangeHostAction::Config::Config(Device *device, libconfig::Setting& config) : Action::Config(device) { try { auto& host = config.lookup("host"); if(host.getType() == libconfig::Setting::TypeInt) { _offset = false; _host = host; _host--; // hosts are one-indexed in config if(_host < 0) { logPrintf(WARN, "Line %d: host must be positive.", host.getSourceLine()); _offset = true; _host = 0; } } else if(host.getType() == libconfig::Setting::TypeString) { _offset = true; std::string hostmode = host; std::transform(hostmode.begin(), hostmode.end(), hostmode.begin(), ::tolower); if(hostmode == "next") _host = 1; else if(hostmode == "prev" || hostmode == "previous") _host = -1; else { logPrintf(WARN, "Line %d: host must equal an integer, 'next'," "or 'prev'.", host.getSourceLine()); _host = 0; } } else { logPrintf(WARN, "Line %d: host must equal an integer, 'next'," "or 'prev'.", host.getSourceLine()); _offset = true; _host = 0; } } catch (libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: host is a required field, skipping.", config.getSourceLine()); _offset = true; _host = 0; } } uint8_t ChangeHostAction::Config::nextHost(hidpp20::ChangeHost::HostInfo info) { if(_offset) { return (info.currentHost + _host) % info.hostCount; } else { if(_host >= info.hostCount || _host < 0) { logPrintf(WARN, "No such host %d, defaulting to current.", _host+1); return info.currentHost; } else return _host; } }logiops-0.2.2/src/logid/actions/ChangeHostAction.h000066400000000000000000000030741370476137700220710ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_CHANGEHOSTACTION_H #define LOGID_ACTION_CHANGEHOSTACTION_H #include #include "Action.h" #include "../backend/hidpp20/features/ChangeHost.h" namespace logid { namespace actions { class ChangeHostAction : public Action { public: ChangeHostAction(Device* device, libconfig::Setting& config); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; class Config : public Action::Config { public: Config(Device* device, libconfig::Setting& setting); uint8_t nextHost(backend::hidpp20::ChangeHost::HostInfo info); private: bool _offset; int _host; }; protected: std::shared_ptr _change_host; Config _config; }; }} #endif //LOGID_ACTION_CHANGEHOSTACTION_H logiops-0.2.2/src/logid/actions/CycleDPI.cpp000066400000000000000000000076641370476137700206500ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "CycleDPI.h" #include "../Device.h" #include "../util/task.h" #include "../util/log.h" #include "../backend/hidpp20/Error.h" #include "../backend/hidpp20/features/ReprogControls.h" using namespace logid::actions; using namespace libconfig; CycleDPI::CycleDPI(Device* device, libconfig::Setting& setting) : Action (device), _config (device, setting) { _dpi = _device->getFeature("dpi"); if(!_dpi) logPrintf(WARN, "%s:%d: DPI feature not found, cannot use " "CycleDPI action.", _device->hidpp20().devicePath().c_str(), _device->hidpp20().deviceIndex()); } void CycleDPI::press() { _pressed = true; if(_dpi && !_config.empty()) { task::spawn([this](){ uint16_t dpi = _config.nextDPI(); try { _dpi->setDPI(dpi, _config.sensor()); } catch (backend::hidpp20::Error& e) { if(e.code() == backend::hidpp20::Error::InvalidArgument) logPrintf(WARN, "%s:%d: Could not set DPI to %d for " "sensor %d", _device->hidpp20().devicePath().c_str(), _device->hidpp20().deviceIndex(), dpi, _config.sensor()); else throw e; } }); } } void CycleDPI::release() { _pressed = false; } uint8_t CycleDPI::reprogFlags() const { return backend::hidpp20::ReprogControls::TemporaryDiverted; } CycleDPI::Config::Config(Device *device, libconfig::Setting &config) : Action::Config(device), _current_index (0), _sensor (0) { if(!config.isGroup()) { logPrintf(WARN, "Line %d: action must be an object, skipping.", config.getSourceLine()); return; } try { auto& sensor = config.lookup("sensor"); if(sensor.getType() != Setting::TypeInt) logPrintf(WARN, "Line %d: sensor must be an integer", sensor.getSourceLine()); _sensor = (int)sensor; } catch(libconfig::SettingNotFoundException& e) { // Ignore } try { auto& dpis = config.lookup("dpis"); if(!dpis.isList() && !dpis.isArray()) { logPrintf(WARN, "Line %d: dpis must be a list or array, skipping.", dpis.getSourceLine()); return; } int dpi_count = dpis.getLength(); for(int i = 0; i < dpi_count; i++) { if(dpis[i].getType() != Setting::TypeInt) { logPrintf(WARN, "Line %d: dpis must be integers, skipping.", dpis[i].getSourceLine()); if(dpis.isList()) continue; else break; } _dpis.push_back((int)(dpis[i])); } } catch (libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: dpis is a required field, skipping.", config.getSourceLine()); } } uint16_t CycleDPI::Config::nextDPI() { uint16_t dpi = _dpis[_current_index++]; if(_current_index >= _dpis.size()) _current_index = 0; return dpi; } bool CycleDPI::Config::empty() const { return _dpis.empty(); } uint8_t CycleDPI::Config::sensor() const { return _sensor; }logiops-0.2.2/src/logid/actions/CycleDPI.h000066400000000000000000000030251370476137700203000ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_CYCLEDPI_H #define LOGID_ACTION_CYCLEDPI_H #include #include "Action.h" #include "../features/DPI.h" namespace logid { namespace actions { class CycleDPI : public Action { public: explicit CycleDPI(Device* device, libconfig::Setting& setting); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; class Config : public Action::Config { public: Config(Device* device, libconfig::Setting& setting); uint16_t nextDPI(); bool empty() const; uint8_t sensor() const; private: std::size_t _current_index; std::vector _dpis; uint8_t _sensor; }; protected: Config _config; std::shared_ptr _dpi; }; }} #endif //LOGID_ACTION_CYCLEDPI_Hlogiops-0.2.2/src/logid/actions/GestureAction.cpp000066400000000000000000000220331370476137700220130ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "GestureAction.h" #include "../Device.h" #include "../backend/hidpp20/features/ReprogControls.h" using namespace logid::actions; using namespace logid; using namespace logid::backend; GestureAction::Direction GestureAction::toDirection(std::string direction) { std::transform(direction.begin(), direction.end(), direction.begin(), ::tolower); if(direction == "up") return Up; else if(direction == "down") return Down; else if(direction == "left") return Left; else if(direction == "right") return Right; else if(direction == "none") return None; else throw std::invalid_argument("direction"); } GestureAction::Direction GestureAction::toDirection(int16_t x, int16_t y) { if(x >= 0 && y >= 0) return x >= y ? Right : Down; else if(x < 0 && y >= 0) return -x <= y ? Down : Left; else if(x <= 0 && y < 0) return x <= y ? Left : Up; else return x <= -y ? Up : Right; } GestureAction::GestureAction(Device* dev, libconfig::Setting& config) : Action (dev), _config (dev, config) { } void GestureAction::press() { _pressed = true; _x = 0, _y = 0; for(auto& gesture : _config.gestures()) gesture.second->press(); } void GestureAction::release() { _pressed = false; bool threshold_met = false; auto d = toDirection(_x, _y); auto primary_gesture = _config.gestures().find(d); if(primary_gesture != _config.gestures().end()) { threshold_met = primary_gesture->second->metThreshold(); primary_gesture->second->release(true); } for(auto& gesture : _config.gestures()) { if(gesture.first == d) continue; if(!threshold_met) { if(gesture.second->metThreshold()) { // If the primary gesture did not meet its threshold, use the // secondary one. threshold_met = true; gesture.second->release(true); break; } } else { gesture.second->release(false); } } if(!threshold_met) { if(_config.noneAction()) { _config.noneAction()->press(); _config.noneAction()->release(); } } } void GestureAction::move(int16_t x, int16_t y) { auto new_x = _x + x, new_y = _y + y; if(abs(x) > 0) { if(_x < 0 && new_x >= 0) { // Left -> Origin/Right auto left = _config.gestures().find(Left); if(left != _config.gestures().end()) left->second->move(_x); if(new_x) { // Ignore to origin auto right = _config.gestures().find(Right); if(right != _config.gestures().end()) right->second->move(new_x); } } else if(_x > 0 && new_x <= 0) { // Right -> Origin/Left auto right = _config.gestures().find(Right); if(right != _config.gestures().end()) right->second->move(-_x); if(new_x) { // Ignore to origin auto left = _config.gestures().find(Left); if(left != _config.gestures().end()) left->second->move(-new_x); } } else if(new_x < 0) { // Origin/Left to Left auto left = _config.gestures().find(Left); if(left != _config.gestures().end()) left->second->move(-x); } else if(new_x > 0) { // Origin/Right to Right auto right = _config.gestures().find(Right); if(right != _config.gestures().end()) right->second->move(x); } } if(abs(y) > 0) { if(_y > 0 && new_y <= 0) { // Up -> Origin/Down auto up = _config.gestures().find(Up); if(up != _config.gestures().end()) up->second->move(_y); if(new_y) { // Ignore to origin auto down = _config.gestures().find(Down); if(down != _config.gestures().end()) down->second->move(new_y); } } else if(_y < 0 && new_y >= 0) { // Down -> Origin/Up auto down = _config.gestures().find(Down); if(down != _config.gestures().end()) down->second->move(-_y); if(new_y) { // Ignore to origin auto up = _config.gestures().find(Up); if(up != _config.gestures().end()) up->second->move(-new_y); } } else if(new_y < 0) { // Origin/Up to Up auto up = _config.gestures().find(Up); if(up != _config.gestures().end()) up->second->move(-y); } else if(new_y > 0) {// Origin/Down to Down auto down = _config.gestures().find(Down); if(down != _config.gestures().end()) down->second->move(y); } } _x = new_x; _y = new_y; } uint8_t GestureAction::reprogFlags() const { return (hidpp20::ReprogControls::TemporaryDiverted | hidpp20::ReprogControls::RawXYDiverted); } GestureAction::Config::Config(Device* device, libconfig::Setting &root) : Action::Config(device) { try { auto& gestures = root.lookup("gestures"); if(!gestures.isList()) { logPrintf(WARN, "Line %d: gestures must be a list, ignoring.", gestures.getSourceLine()); return; } int gesture_count = gestures.getLength(); for(int i = 0; i < gesture_count; i++) { if(!gestures[i].isGroup()) { logPrintf(WARN, "Line %d: gesture must be a group, skipping.", gestures[i].getSourceLine()); continue; } Direction d; try { auto& direction = gestures[i].lookup("direction"); if(direction.getType() != libconfig::Setting::TypeString) { logPrintf(WARN, "Line %d: direction must be a string, " "skipping.", direction.getSourceLine()); continue; } try { d = toDirection(direction); } catch(std::invalid_argument& e) { logPrintf(WARN, "Line %d: Invalid direction %s", direction.getSourceLine(), (const char*)direction); continue; } } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: direction is a required field, " "skipping.", gestures[i].getSourceLine()); continue; } if(_gestures.find(d) != _gestures.end() || (d == None && _none_action)) { logPrintf(WARN, "Line %d: Gesture is already defined for " "this direction, duplicate ignored.", gestures[i].getSourceLine()); continue; } if(d == None) { try { _none_action = Action::makeAction(_device, gestures[i].lookup("action")); } catch (InvalidAction& e) { logPrintf(WARN, "Line %d: %s is not a valid action, " "skipping.", gestures[i].lookup("action") .getSourceLine(), e.what()); } catch (libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: action is a required field, " "skipping.", gestures[i].getSourceLine(), e.what()); } continue; } try { _gestures.emplace(d, Gesture::makeGesture(_device, gestures[i])); } catch(InvalidGesture& e) { logPrintf(WARN, "Line %d: Invalid gesture: %s", gestures[i].getSourceLine(), e.what()); } } } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: gestures is a required field, ignoring.", root.getSourceLine()); } } std::map>& GestureAction::Config::gestures() { return _gestures; } std::shared_ptr GestureAction::Config::noneAction() { return _none_action; }logiops-0.2.2/src/logid/actions/GestureAction.h000066400000000000000000000036301370476137700214620ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_GESTUREACTION_H #define LOGID_ACTION_GESTUREACTION_H #include #include #include "Action.h" #include "gesture/Gesture.h" namespace logid { namespace actions { class GestureAction : public Action { public: enum Direction { None, Up, Down, Left, Right }; static Direction toDirection(std::string direction); static Direction toDirection(int16_t x, int16_t y); GestureAction(Device* dev, libconfig::Setting& config); virtual void press(); virtual void release(); virtual void move(int16_t x, int16_t y); virtual uint8_t reprogFlags() const; class Config : public Action::Config { public: Config(Device* device, libconfig::Setting& root); std::map>& gestures(); std::shared_ptr noneAction(); protected: std::map> _gestures; std::shared_ptr _none_action; }; protected: int16_t _x, _y; Config _config; }; }} #endif //LOGID_ACTION_GESTUREACTION_H logiops-0.2.2/src/logid/actions/KeypressAction.cpp000066400000000000000000000054171370476137700222110ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "KeypressAction.h" #include "../util/log.h" #include "../InputDevice.h" #include "../backend/hidpp20/features/ReprogControls.h" using namespace logid::actions; using namespace logid::backend; KeypressAction::KeypressAction(Device *device, libconfig::Setting& config) : Action(device), _config (device, config) { } void KeypressAction::press() { _pressed = true; for(auto& key : _config.keys()) virtual_input->pressKey(key); } void KeypressAction::release() { _pressed = false; for(auto& key : _config.keys()) virtual_input->releaseKey(key); } uint8_t KeypressAction::reprogFlags() const { return hidpp20::ReprogControls::TemporaryDiverted; } KeypressAction::Config::Config(Device* device, libconfig::Setting& config) : Action::Config(device) { if(!config.isGroup()) { logPrintf(WARN, "Line %d: action must be an object, skipping.", config.getSourceLine()); return; } try { auto &keys = config.lookup("keys"); if(keys.isArray() || keys.isList()) { int key_count = keys.getLength(); for(int i = 0; i < key_count; i++) { auto& key = keys[i]; if(key.isNumber()) { _keys.push_back(key); } else if(key.getType() == libconfig::Setting::TypeString) { try { _keys.push_back(virtual_input->toKeyCode(key)); } catch(InputDevice::InvalidEventCode& e) { logPrintf(WARN, "Line %d: Invalid keycode %s, skipping." , key.getSourceLine(), key.c_str()); } } else { logPrintf(WARN, "Line %d: keycode must be string or int", key.getSourceLine(), key.c_str()); } } } } catch (libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: keys is a required field, skipping.", config.getSourceLine()); } } std::vector& KeypressAction::Config::keys() { return _keys; }logiops-0.2.2/src/logid/actions/KeypressAction.h000066400000000000000000000026161370476137700216540ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_KEYPRESS_H #define LOGID_ACTION_KEYPRESS_H #include #include #include "Action.h" namespace logid { namespace actions { class KeypressAction : public Action { public: KeypressAction(Device* dev, libconfig::Setting& config); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; class Config : public Action::Config { public: explicit Config(Device* device, libconfig::Setting& root); std::vector& keys(); protected: std::vector _keys; }; protected: Config _config; }; }} #endif //LOGID_ACTION_KEYPRESS_H logiops-0.2.2/src/logid/actions/NullAction.cpp000066400000000000000000000021141370476137700213050ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "NullAction.h" #include "../Device.h" #include "../backend/hidpp20/features/ReprogControls.h" using namespace logid::actions; NullAction::NullAction(Device* device) : Action(device) { } void NullAction::press() { _pressed = true; } void NullAction::release() { _pressed = false; } uint8_t NullAction::reprogFlags() const { return backend::hidpp20::ReprogControls::TemporaryDiverted; }logiops-0.2.2/src/logid/actions/NullAction.h000066400000000000000000000020401370476137700207500ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_NULL_H #define LOGID_ACTION_NULL_H #include "Action.h" namespace logid { namespace actions { class NullAction : public Action { public: explicit NullAction(Device* device); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; }; }} #endif //LOGID_ACTION_NULL_H logiops-0.2.2/src/logid/actions/ToggleHiresScroll.cpp000066400000000000000000000033471370476137700226410ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "ToggleHiresScroll.h" #include "../Device.h" #include "../util/task.h" #include "../backend/hidpp20/features/ReprogControls.h" using namespace logid::actions; using namespace logid::backend; ToggleHiresScroll::ToggleHiresScroll(Device *dev) : Action (dev) { _hires_scroll = _device->getFeature("hiresscroll"); if(!_hires_scroll) logPrintf(WARN, "%s:%d: HiresScroll feature not found, cannot use " "ToggleHiresScroll action.", _device->hidpp20().devicePath().c_str(), _device->hidpp20().devicePath().c_str()); } void ToggleHiresScroll::press() { _pressed = true; if(_hires_scroll) { task::spawn([hires=this->_hires_scroll](){ auto mode = hires->getMode(); mode ^= backend::hidpp20::HiresScroll::HiRes; hires->setMode(mode); }); } } void ToggleHiresScroll::release() { _pressed = false; } uint8_t ToggleHiresScroll::reprogFlags() const { return hidpp20::ReprogControls::TemporaryDiverted; }logiops-0.2.2/src/logid/actions/ToggleHiresScroll.h000066400000000000000000000023031370476137700222750ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_TOGGLEHIRESSCROLL_H #define LOGID_ACTION_TOGGLEHIRESSCROLL_H #include "Action.h" #include "../features/HiresScroll.h" namespace logid { namespace actions { class ToggleHiresScroll : public Action { public: explicit ToggleHiresScroll(Device* dev); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; protected: std::shared_ptr _hires_scroll; }; }} #endif //LOGID_ACTION_TOGGLEHIRESSCROLL_H logiops-0.2.2/src/logid/actions/ToggleSmartShift.cpp000066400000000000000000000033541370476137700224720ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "ToggleSmartShift.h" #include "../Device.h" #include "../backend/hidpp20/features/ReprogControls.h" #include "../util/task.h" using namespace logid::actions; using namespace logid::backend; ToggleSmartShift::ToggleSmartShift(Device *dev) : Action (dev) { _smartshift = _device->getFeature("smartshift"); if(!_smartshift) logPrintf(WARN, "%s:%d: SmartShift feature not found, cannot use " "ToggleSmartShift action.", _device->hidpp20().devicePath().c_str(), _device->hidpp20().deviceIndex()); } void ToggleSmartShift::press() { _pressed = true; if(_smartshift) { task::spawn([ss=this->_smartshift](){ auto status = ss->getStatus(); status.setActive = true; status.active = !status.active; ss->setStatus(status); }); } } void ToggleSmartShift::release() { _pressed = false; } uint8_t ToggleSmartShift::reprogFlags() const { return hidpp20::ReprogControls::TemporaryDiverted; }logiops-0.2.2/src/logid/actions/ToggleSmartShift.h000066400000000000000000000023221370476137700221310ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_TOGGLESMARTSHIFT_H #define LOGID_ACTION_TOGGLESMARTSHIFT_H #include #include "Action.h" #include "../features/SmartShift.h" namespace logid { namespace actions { class ToggleSmartShift : public Action { public: explicit ToggleSmartShift(Device* dev); virtual void press(); virtual void release(); virtual uint8_t reprogFlags() const; protected: std::shared_ptr _smartshift; }; }} #endif //LOGID_ACTION_TOGGLESMARTSHIFT_Hlogiops-0.2.2/src/logid/actions/gesture/000077500000000000000000000000001370476137700202115ustar00rootroot00000000000000logiops-0.2.2/src/logid/actions/gesture/AxisGesture.cpp000066400000000000000000000073131370476137700231640ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "AxisGesture.h" #include "../../InputDevice.h" #include "../../util/log.h" using namespace logid::actions; AxisGesture::AxisGesture(Device *device, libconfig::Setting &root) : Gesture (device), _config (device, root) { } void AxisGesture::press() { _axis = 0; _axis_remainder = 0; } void AxisGesture::release(bool primary) { // Do nothing (void)primary; // Suppress unused warning } void AxisGesture::move(int16_t axis) { int16_t new_axis = _axis + axis; if(new_axis > _config.threshold()) { double move = axis; if(_axis < _config.threshold()) move = new_axis - _config.threshold(); bool negative_multiplier = _config.multiplier() < 0; if(negative_multiplier) move *= -_config.multiplier(); else move *= _config.multiplier(); double move_floor = floor(move); _axis_remainder = move - move_floor; if(_axis_remainder >= 1) { double int_remainder = floor(_axis_remainder); move_floor += int_remainder; _axis_remainder -= int_remainder; } if(negative_multiplier) move_floor = -move_floor; virtual_input->moveAxis(_config.axis(), move_floor); } _axis = new_axis; } bool AxisGesture::metThreshold() const { return _axis >= _config.threshold(); } AxisGesture::Config::Config(Device *device, libconfig::Setting &setting) : Gesture::Config(device, setting, false) { try { auto& axis = setting.lookup("axis"); if(axis.isNumber()) { _axis = axis; } else if(axis.getType() == libconfig::Setting::TypeString) { try { _axis = virtual_input->toAxisCode(axis); } catch(InputDevice::InvalidEventCode& e) { logPrintf(WARN, "Line %d: Invalid axis %s, skipping." , axis.getSourceLine(), axis.c_str()); } } else { logPrintf(WARN, "Line %d: axis must be string or int, skipping.", axis.getSourceLine(), axis.c_str()); throw InvalidGesture(); } } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: axis is a required field, skippimg.", setting.getSourceLine()); throw InvalidGesture(); } try { auto& multiplier = setting.lookup("axis_multiplier"); if(multiplier.isNumber()) { if(multiplier.getType() == libconfig::Setting::TypeFloat) _multiplier = multiplier; else _multiplier = (int)multiplier; } else { logPrintf(WARN, "Line %d: axis_multiplier must be a number, " "setting to default (1).", multiplier.getSourceLine()); } } catch(libconfig::SettingNotFoundException& e) { // Ignore } } unsigned int AxisGesture::Config::axis() const { return _axis; } double AxisGesture::Config::multiplier() const { return _multiplier; }logiops-0.2.2/src/logid/actions/gesture/AxisGesture.h000066400000000000000000000032011370476137700226210ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_AXISGESTURE_H #define LOGID_ACTION_AXISGESTURE_H #include "Gesture.h" namespace logid { namespace actions { class AxisGesture : public Gesture { public: AxisGesture(Device* device, libconfig::Setting& root); virtual void press(); virtual void release(bool primary=false); virtual void move(int16_t axis); virtual bool metThreshold() const; class Config : public Gesture::Config { public: Config(Device* device, libconfig::Setting& setting); unsigned int axis() const; double multiplier() const; private: unsigned int _axis; double _multiplier = 1; }; protected: int16_t _axis; double _axis_remainder; Config _config; }; }} #endif //LOGID_ACTION_AXISGESTURE_H logiops-0.2.2/src/logid/actions/gesture/Gesture.cpp000066400000000000000000000100741370476137700223350ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "Gesture.h" #include "../../util/log.h" #include "ReleaseGesture.h" #include "../../backend/hidpp20/features/ReprogControls.h" #include "IntervalGesture.h" #include "AxisGesture.h" #include "NullGesture.h" using namespace logid::actions; Gesture::Gesture(Device *device) : _device (device) { } Gesture::Config::Config(Device* device, libconfig::Setting& root, bool action_required) : _device (device) { if(action_required) { try { _action = Action::makeAction(_device, root.lookup("action")); } catch (libconfig::SettingNotFoundException &e) { throw InvalidGesture("action is missing"); } if(_action->reprogFlags() & backend::hidpp20::ReprogControls::RawXYDiverted) throw InvalidGesture("gesture cannot require RawXY"); } _threshold = LOGID_GESTURE_DEFAULT_THRESHOLD; try { auto& threshold = root.lookup("threshold"); if(threshold.getType() == libconfig::Setting::TypeInt) { _threshold = (int)threshold; if(_threshold <= 0) { _threshold = LOGID_GESTURE_DEFAULT_THRESHOLD; logPrintf(WARN, "Line %d: threshold must be positive, setting " "to default (%d)", threshold.getSourceLine(), _threshold); } } else logPrintf(WARN, "Line %d: threshold must be an integer, setting " "to default (%d).", threshold.getSourceLine()); } catch(libconfig::SettingNotFoundException& e) { // Ignore } } std::shared_ptr Gesture::makeGesture(Device *device, libconfig::Setting &setting) { if(!setting.isGroup()) { logPrintf(WARN, "Line %d: Gesture is not a group, ignoring.", setting.getSourceLine()); throw InvalidGesture(); } try { auto& gesture_mode = setting.lookup("mode"); if(gesture_mode.getType() != libconfig::Setting::TypeString) { logPrintf(WARN, "Line %d: Gesture mode must be a string," "defaulting to OnRelease.", gesture_mode.getSourceLine()); return std::make_shared(device, setting); } std::string type = gesture_mode; std::transform(type.begin(), type.end(), type.begin(), ::tolower); if(type == "onrelease") return std::make_shared(device, setting); else if(type == "oninterval" || type == "onfewpixels") return std::make_shared(device, setting); else if(type == "axis") return std::make_shared(device, setting); else if(type == "nopress") return std::make_shared(device, setting); else { logPrintf(WARN, "Line %d: Unknown gesture mode %s, defaulting to " "OnRelease.", gesture_mode.getSourceLine(), (const char*)gesture_mode); return std::make_shared(device, setting); } } catch(libconfig::SettingNotFoundException& e) { return std::make_shared(device, setting); } } int16_t Gesture::Config::threshold() const { return _threshold; } std::shared_ptr Gesture::Config::action() { return _action; }logiops-0.2.2/src/logid/actions/gesture/Gesture.h000066400000000000000000000037231370476137700220050ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_GESTURE_H #define LOGID_ACTION_GESTURE_H #include "../Action.h" #define LOGID_GESTURE_DEFAULT_THRESHOLD 50 namespace logid { namespace actions { class InvalidGesture : public std::exception { public: explicit InvalidGesture(std::string what="") : _what (what) { } virtual const char* what() { return _what.c_str(); } private: std::string _what; }; class Gesture { public: virtual void press() = 0; virtual void release(bool primary=false) = 0; virtual void move(int16_t axis) = 0; virtual bool metThreshold() const = 0; class Config { public: Config(Device* device, libconfig::Setting& root, bool action_required=true); virtual int16_t threshold() const; virtual std::shared_ptr action(); protected: Device* _device; std::shared_ptr _action; int16_t _threshold; }; static std::shared_ptr makeGesture(Device* device, libconfig::Setting& setting); protected: explicit Gesture(Device* device); Device* _device; }; }} #endif //LOGID_ACTION_GESTURE_H logiops-0.2.2/src/logid/actions/gesture/IntervalGesture.cpp000066400000000000000000000053321370476137700240430ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "IntervalGesture.h" #include "../../util/log.h" using namespace logid::actions; IntervalGesture::IntervalGesture(Device *device, libconfig::Setting &root) : Gesture (device), _config (device, root) { } void IntervalGesture::press() { _axis = 0; _interval_pass_count = 0; } void IntervalGesture::release(bool primary) { // Do nothing (void)primary; // Suppress unused warning } void IntervalGesture::move(int16_t axis) { _axis += axis; if(_axis < _config.threshold()) return; int16_t new_interval_count = (_axis - _config.threshold())/ _config.interval(); if(new_interval_count > _interval_pass_count) { _config.action()->press(); _config.action()->release(); } _interval_pass_count = new_interval_count; } bool IntervalGesture::metThreshold() const { return _axis >= _config.threshold(); } IntervalGesture::Config::Config(Device *device, libconfig::Setting &setting) : Gesture::Config(device, setting) { try { auto& interval = setting.lookup("interval"); if(interval.getType() != libconfig::Setting::TypeInt) { logPrintf(WARN, "Line %d: interval must be an integer, skipping.", interval.getSourceLine()); throw InvalidGesture(); } _interval = (int)interval; } catch(libconfig::SettingNotFoundException& e) { try { // pixels is an alias for interval auto& interval = setting.lookup("pixels"); if(interval.getType() != libconfig::Setting::TypeInt) { logPrintf(WARN, "Line %d: pixels must be an integer, skipping.", interval.getSourceLine()); throw InvalidGesture(); } _interval = (int)interval; } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: interval is a required field, skipping.", setting.getSourceLine()); } } } int16_t IntervalGesture::Config::interval() const { return _interval; }logiops-0.2.2/src/logid/actions/gesture/IntervalGesture.h000066400000000000000000000027461370476137700235160ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_INTERVALGESTURE_H #define LOGID_ACTION_INTERVALGESTURE_H #include "Gesture.h" namespace logid { namespace actions { class IntervalGesture : public Gesture { public: IntervalGesture(Device* device, libconfig::Setting& root); virtual void press(); virtual void release(bool primary=false); virtual void move(int16_t axis); virtual bool metThreshold() const; class Config : public Gesture::Config { public: Config(Device* device, libconfig::Setting& setting); int16_t interval() const; private: int16_t _interval; }; protected: int16_t _axis; int16_t _interval_pass_count; Config _config; }; }} #endif //LOGID_ACTION_INTERVALGESTURE_H logiops-0.2.2/src/logid/actions/gesture/NullGesture.cpp000066400000000000000000000022331370476137700231660ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "NullGesture.h" using namespace logid::actions; NullGesture::NullGesture(Device *device, libconfig::Setting& setting) : Gesture (device), _config (device, setting, false) { } void NullGesture::press() { _axis = 0; } void NullGesture::release(bool primary) { // Do nothing (void)primary; // Suppress unused warning } void NullGesture::move(int16_t axis) { _axis += axis; } bool NullGesture::metThreshold() const { return _axis > _config.threshold(); }logiops-0.2.2/src/logid/actions/gesture/NullGesture.h000066400000000000000000000023141370476137700226330ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_NULLGESTURE_H #define LOGID_ACTION_NULLGESTURE_H #include "Gesture.h" namespace logid { namespace actions { class NullGesture : public Gesture { public: NullGesture(Device* device, libconfig::Setting& setting); virtual void press(); virtual void release(bool primary=false); virtual void move(int16_t axis); virtual bool metThreshold() const; protected: int16_t _axis; Gesture::Config _config; }; }} #endif //LOGID_ACTION_NULLGESTURE_H logiops-0.2.2/src/logid/actions/gesture/ReleaseGesture.cpp000066400000000000000000000023261370476137700236370ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "ReleaseGesture.h" using namespace logid::actions; ReleaseGesture::ReleaseGesture(Device *device, libconfig::Setting &root) : Gesture (device), _config (device, root) { } void ReleaseGesture::press() { _axis = 0; } void ReleaseGesture::release(bool primary) { if(metThreshold() && primary) { _config.action()->press(); _config.action()->release(); } } void ReleaseGesture::move(int16_t axis) { _axis += axis; } bool ReleaseGesture::metThreshold() const { return _axis >= _config.threshold(); }logiops-0.2.2/src/logid/actions/gesture/ReleaseGesture.h000066400000000000000000000023311370476137700233000ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_ACTION_RELEASEGESTURE_H #define LOGID_ACTION_RELEASEGESTURE_H #include "Gesture.h" namespace logid { namespace actions { class ReleaseGesture : public Gesture { public: ReleaseGesture(Device* device, libconfig::Setting& root); virtual void press(); virtual void release(bool primary=false); virtual void move(int16_t axis); virtual bool metThreshold() const; protected: int16_t _axis; Gesture::Config _config; }; }} #endif //LOGID_ACTION_RELEASEGESTURE_H logiops-0.2.2/src/logid/backend/000077500000000000000000000000001370476137700164625ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/Error.cpp000066400000000000000000000014521370476137700202610ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "Error.h" const char *logid::backend::TimeoutError::what() const noexcept { return "Device timed out"; } logiops-0.2.2/src/logid/backend/Error.h000066400000000000000000000017231370476137700177270ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_ERROR_H #define LOGID_BACKEND_ERROR_H #include namespace logid { namespace backend { class TimeoutError: public std::exception { public: TimeoutError() = default; const char* what() const noexcept override; }; }} #endif //LOGID_BACKEND_ERROR_Hlogiops-0.2.2/src/logid/backend/dj/000077500000000000000000000000001370476137700170575ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/dj/Error.cpp000066400000000000000000000020611370476137700206530ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "Error.h" using namespace logid::backend::dj; Error::Error(uint8_t code) : _code (code) { } const char* Error::what() const noexcept { switch(_code) { case Unknown: return "Unknown"; case KeepAliveTimeout: return "Keep-alive timeout"; default: return "Reserved"; } } uint8_t Error::code() const noexcept { return _code; }logiops-0.2.2/src/logid/backend/dj/Error.h000066400000000000000000000023311370476137700203200ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_DJ_ERROR_H #define LOGID_BACKEND_DJ_ERROR_H #include #include namespace logid { namespace backend { namespace dj { class Error : public std::exception { public: enum ErrorCode : uint8_t { Unknown = 0x00, KeepAliveTimeout = 0x01 }; explicit Error(uint8_t code); const char* what() const noexcept override; uint8_t code() const noexcept; private: uint8_t _code; }; }}} #endif //LOGID_BACKEND_DJ_ERROR_Hlogiops-0.2.2/src/logid/backend/dj/Receiver.cpp000066400000000000000000000254001370476137700213300ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "Report.h" #include "Receiver.h" #include "Error.h" #include "../../util/thread.h" using namespace logid::backend::dj; using namespace logid::backend; InvalidReceiver::InvalidReceiver(Reason reason) : _reason (reason) { } const char* InvalidReceiver::what() const noexcept { switch(_reason) { case NoDJReports: return "No DJ reports"; default: return "Invalid receiver"; } } InvalidReceiver::Reason InvalidReceiver::code() const noexcept { return _reason; } Receiver::Receiver(std::string path) : _raw_device (std::make_shared(std::move(path))), _hidpp10_device (_raw_device, hidpp::DefaultDevice) { if(!supportsDjReports(_raw_device->reportDescriptor())) throw InvalidReceiver(InvalidReceiver::NoDJReports); } void Receiver::enumerateDj() { _sendDjRequest(hidpp::DefaultDevice, GetPairedDevices,{}); } Receiver::NotificationFlags Receiver::getHidppNotifications() { auto response = _hidpp10_device.getRegister(EnableHidppNotifications, {}, hidpp::ReportType::Short); NotificationFlags flags{}; flags.deviceBatteryStatus = response[0] & (1 << 4); flags.receiverWirelessNotifications = response[1] & (1 << 0); flags.receiverSoftwarePresent = response[1] & (1 << 3); return flags; } void Receiver::enableHidppNotifications(NotificationFlags flags) { std::vector request(3); if(flags.deviceBatteryStatus) request[0] |= (1 << 4); if(flags.receiverWirelessNotifications) request[1] |= 1; if(flags.receiverSoftwarePresent) request[1] |= (1 << 3); _hidpp10_device.setRegister(EnableHidppNotifications, request, hidpp::ReportType::Short); } void Receiver::enumerateHidpp() { /* This isn't in the documentation but this is how solaar does it * All I know is that when (p0 & 2), devices are enumerated */ _hidpp10_device.setRegister(ConnectionState, {2}, hidpp::ReportType::Short); } ///TODO: Investigate usage uint8_t Receiver::getConnectionState(hidpp::DeviceIndex index) { auto response = _hidpp10_device.getRegister(ConnectionState, {index}, hidpp::ReportType::Short); return response[0]; } void Receiver::startPairing(uint8_t timeout) { ///TODO: Device number == Device index? std::vector request(3); request[0] = 1; request[1] = hidpp::DefaultDevice; request[2] = timeout; _hidpp10_device.setRegister(DevicePairing, request, hidpp::ReportType::Short); } void Receiver::stopPairing() { ///TODO: Device number == Device index? std::vector request(3); request[0] = 2; request[1] = hidpp::DefaultDevice; _hidpp10_device.setRegister(DevicePairing, request, hidpp::ReportType::Short); } void Receiver::disconnect(hidpp::DeviceIndex index) { ///TODO: Device number == Device index? std::vector request(3); request[0] = 3; request[1] = index; _hidpp10_device.setRegister(DevicePairing, request, hidpp::ReportType::Short); } std::map Receiver::getDeviceActivity() { auto response = _hidpp10_device.getRegister(DeviceActivity, {}, hidpp::ReportType::Long); std::map device_activity; for(uint8_t i = hidpp::WirelessDevice1; i <= hidpp::WirelessDevice6; i++) device_activity[static_cast(i)] = response[i]; return device_activity; } struct Receiver::PairingInfo Receiver::getPairingInfo(hidpp::DeviceIndex index) { std::vector request(1); request[0] = index; request[0] += 0x1f; auto response = _hidpp10_device.getRegister(PairingInfo, request, hidpp::ReportType::Long); struct PairingInfo info{}; info.destinationId = response[1]; info.reportInterval = response[2]; info.pid = response[4]; info.pid |= (response[3] << 8); info.deviceType = static_cast(response[7]); return info; } struct Receiver::ExtendedPairingInfo Receiver::getExtendedPairingInfo(hidpp::DeviceIndex index) { std::vector request(1); request[0] = index; request[0] += 0x2f; auto response = _hidpp10_device.getRegister(PairingInfo, request, hidpp::ReportType::Long); ExtendedPairingInfo info{}; info.serialNumber = 0; for(uint8_t i = 0; i < 4; i++) info.serialNumber |= (response[i+1] << 8*i); for(uint8_t i = 0; i < 4; i++) info.reportTypes[i] = response[i + 5]; uint8_t psl = response[8] & 0xf; if(psl > 0xc) info.powerSwitchLocation = PowerSwitchLocation::Reserved; else info.powerSwitchLocation = static_cast(psl); return info; } std::string Receiver::getDeviceName(hidpp::DeviceIndex index) { std::vector request(1); request[0] = index; request[0] += 0x3f; auto response = _hidpp10_device.getRegister(PairingInfo, request, hidpp::ReportType::Long); uint8_t size = response[1]; assert(size <= 14); std::string name(size, ' '); for(std::size_t i = 0; i < size; i++) name[i] = response[i + 2]; return name; } hidpp::DeviceIndex Receiver::deviceDisconnectionEvent(const hidpp::Report& report) { assert(report.subId() == DeviceDisconnection); return report.deviceIndex(); } hidpp::DeviceConnectionEvent Receiver::deviceConnectionEvent(const hidpp::Report &report) { assert(report.subId() == DeviceConnection); hidpp::DeviceConnectionEvent event{}; event.index = report.deviceIndex(); event.unifying = ((report.address() & 0b111) == 0x04); event.deviceType = static_cast( report.paramBegin()[0] & 0x0f); event.softwarePresent = report.paramBegin()[0] & (1<<4); event.encrypted = report.paramBegin()[0] & (1<<5); event.linkEstablished = !(report.paramBegin()[0] & (1<<6)); event.withPayload = report.paramBegin()[0] & (1<<7); event.fromTimeoutCheck = false; event.pid =(report.paramBegin()[2] << 8); event.pid |= report.paramBegin()[1]; return event; } void Receiver::_handleDjEvent(Report& report) { for(auto& handler : _dj_event_handlers) if(handler.second->condition(report)) handler.second->callback(report); } void Receiver::_handleHidppEvent(hidpp::Report &report) { for(auto& handler : _hidpp_event_handlers) if(handler.second->condition(report)) handler.second->callback(report); } void Receiver::addDjEventHandler(const std::string& nickname, const std::shared_ptr& handler) { assert(_dj_event_handlers.find(nickname) == _dj_event_handlers.end()); _dj_event_handlers.emplace(nickname, handler); } void Receiver::removeDjEventHandler(const std::string &nickname) { _dj_event_handlers.erase(nickname); } const std::map>& Receiver::djEventHandlers() { return _dj_event_handlers; } void Receiver::addHidppEventHandler(const std::string& nickname, const std::shared_ptr& handler) { assert(_hidpp_event_handlers.find(nickname) == _hidpp_event_handlers.end()); _hidpp_event_handlers.emplace(nickname, handler); } void Receiver::removeHidppEventHandler(const std::string &nickname) { _hidpp_event_handlers.erase(nickname); } const std::map>& Receiver::hidppEventHandlers() { return _hidpp_event_handlers; } void Receiver::_sendDjRequest(hidpp::DeviceIndex index, uint8_t function, const std::vector&& params) { assert(params.size() <= LongParamLength); Report::Type type = params.size() <= ShortParamLength ? ReportType::Short : ReportType::Long; Report request(type, index, function); std::copy(params.begin(), params.end(), request.paramBegin()); _raw_device->sendReportNoResponse(request.rawData()); } Receiver::ConnectionStatusEvent Receiver::connectionStatusEvent(Report& report) { assert(report.feature() == ConnectionStatus); ConnectionStatusEvent event{}; event.index = report.index(); event.linkLost = report.paramBegin()[0]; return event; } void Receiver::listen() { if(!_raw_device->isListening()) _raw_device->listenAsync(); if(_raw_device->eventHandlers().find("RECV_HIDPP") == _raw_device->eventHandlers().end()) { // Pass all HID++ events on DefaultDevice to handleHidppEvent std::shared_ptr hidpp_handler = std::make_shared(); hidpp_handler->condition = [](std::vector& report)->bool { return (report[hidpp::Offset::Type] == hidpp::Report::Type::Short || report[hidpp::Offset::Type] == hidpp::Report::Type::Long); }; hidpp_handler->callback = [this](std::vector& report) ->void { hidpp::Report _report(report); this->_handleHidppEvent(_report); }; _raw_device->addEventHandler("RECV_HIDPP", hidpp_handler); } if(_raw_device->eventHandlers().find("RECV_DJ") == _raw_device->eventHandlers().end()) { // Pass all DJ events with device index to handleDjEvent std::shared_ptr dj_handler = std::make_shared(); dj_handler->condition = [](std::vector& report)->bool { return (report[Offset::Type] == Report::Type::Short || report[Offset::Type] == Report::Type::Long); }; dj_handler->callback = [this](std::vector& report)->void { Report _report(report); this->_handleDjEvent(_report); }; _raw_device->addEventHandler("RECV_DJ", dj_handler); } } void Receiver::stopListening() { _raw_device->removeEventHandler("RECV_HIDPP"); _raw_device->removeEventHandler("RECV_DJ"); if(_raw_device->eventHandlers().empty()) _raw_device->stopListener(); } std::shared_ptr Receiver::rawDevice() const { return _raw_device; }logiops-0.2.2/src/logid/backend/dj/Receiver.h000066400000000000000000000141121370476137700207730ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_DJ_RECEIVER_H #define LOGID_BACKEND_DJ_RECEIVER_H #include #include "../raw/RawDevice.h" #include "Report.h" #include "../hidpp/Report.h" #include "../hidpp10/Device.h" namespace logid { namespace backend { namespace dj { struct EventHandler { std::function condition; std::function callback; }; class InvalidReceiver : public std::exception { public: enum Reason { NoDJReports }; explicit InvalidReceiver(Reason reason); const char* what() const noexcept override; Reason code() const noexcept; private: Reason _reason; }; class Receiver { public: explicit Receiver(std::string path); enum DjEvents : uint8_t { DeviceDisconnection = 0x40, DeviceConnection = 0x41, ConnectionStatus = 0x42 }; enum DjCommands : uint8_t { SwitchAndKeepAlive = 0x80, GetPairedDevices = 0x81 }; void enumerateDj(); struct ConnectionStatusEvent { hidpp::DeviceIndex index; bool linkLost; }; ConnectionStatusEvent connectionStatusEvent(dj::Report& report); /* The following functions deal with HID++ 1.0 features. * While these are not technically DJ functions, it is redundant * to have a separate hidpp10::Receiver class for these functions. */ enum HidppEvents : uint8_t { // These events are identical to their DJ counterparts // DeviceDisconnection = 0x40, // DeviceConnection = 0x41, LockingChange = 0x4a }; enum HidppRegisters : uint8_t { EnableHidppNotifications = 0x00, ConnectionState = 0x02, DevicePairing = 0xb2, DeviceActivity = 0xb3, PairingInfo = 0xb5 }; struct NotificationFlags { bool deviceBatteryStatus; bool receiverWirelessNotifications; bool receiverSoftwarePresent; }; NotificationFlags getHidppNotifications(); void enableHidppNotifications(NotificationFlags flags); void enumerateHidpp(); uint8_t getConnectionState(hidpp::DeviceIndex index); void startPairing(uint8_t timeout = 0); void stopPairing(); void disconnect(hidpp::DeviceIndex index); std::map getDeviceActivity(); struct PairingInfo { uint8_t destinationId; uint8_t reportInterval; uint16_t pid; DeviceType::DeviceType deviceType; }; enum class PowerSwitchLocation : uint8_t { Reserved = 0x0, Base = 0x1, TopCase = 0x2, TopRightEdge = 0x3, Other = 0x4, TopLeft = 0x5, BottomLeft = 0x6, TopRight = 0x7, BottomRight = 0x8, TopEdge = 0x9, RightEdge = 0xa, LeftEdge = 0xb, BottomEdge = 0xc }; struct ExtendedPairingInfo { uint32_t serialNumber; uint8_t reportTypes[4]; PowerSwitchLocation powerSwitchLocation; }; struct PairingInfo getPairingInfo(hidpp::DeviceIndex index); struct ExtendedPairingInfo getExtendedPairingInfo(hidpp::DeviceIndex index); std::string getDeviceName(hidpp::DeviceIndex index); static hidpp::DeviceIndex deviceDisconnectionEvent( const hidpp::Report& report); static hidpp::DeviceConnectionEvent deviceConnectionEvent( const hidpp::Report& report); void listen(); void stopListening(); void addDjEventHandler(const std::string& nickname, const std::shared_ptr& handler); void removeDjEventHandler(const std::string& nickname); const std::map>& djEventHandlers(); void addHidppEventHandler(const std::string& nickname, const std::shared_ptr& handler); void removeHidppEventHandler(const std::string& nickname); const std::map>& hidppEventHandlers(); std::shared_ptr rawDevice() const; private: void _sendDjRequest(hidpp::DeviceIndex index, uint8_t function, const std::vector&& params); void _handleDjEvent(dj::Report& report); void _handleHidppEvent(hidpp::Report& report); std::map> _dj_event_handlers; std::map> _hidpp_event_handlers; std::shared_ptr _raw_device; hidpp10::Device _hidpp10_device; }; } namespace hidpp { struct DeviceConnectionEvent { hidpp::DeviceIndex index; uint16_t pid; dj::DeviceType::DeviceType deviceType; bool unifying; bool softwarePresent; bool encrypted; bool linkEstablished; bool withPayload; bool fromTimeoutCheck = false; // Fake field }; }}} #endif //LOGID_BACKEND_DJ_RECEIVER_Hlogiops-0.2.2/src/logid/backend/dj/ReceiverMonitor.cpp000066400000000000000000000112251370476137700227000ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "ReceiverMonitor.h" #include "../../util/task.h" #include "../../util/log.h" #include #include using namespace logid::backend::dj; ReceiverMonitor::ReceiverMonitor(std::string path) : _receiver ( std::make_shared(std::move(path))) { assert(_receiver->hidppEventHandlers().find("RECVMON") == _receiver->hidppEventHandlers().end()); assert(_receiver->djEventHandlers().find("RECVMON") == _receiver->djEventHandlers().end()); Receiver::NotificationFlags notification_flags{ true, true, true}; _receiver->enableHidppNotifications(notification_flags); } ReceiverMonitor::~ReceiverMonitor() { this->stop(); } void ReceiverMonitor::run() { _receiver->listen(); if(_receiver->hidppEventHandlers().find("RECVMON") == _receiver->hidppEventHandlers().end()) { std::shared_ptr event_handler = std::make_shared(); event_handler->condition = [](hidpp::Report &report) -> bool { return (report.subId() == Receiver::DeviceConnection || report.subId() == Receiver::DeviceDisconnection); }; event_handler->callback = [this](hidpp::Report &report) -> void { /* Running in a new thread prevents deadlocks since the * receiver may be enumerating. */ task::spawn({[this, report]() { if (report.subId() == Receiver::DeviceConnection) this->addDevice(this->_receiver->deviceConnectionEvent (report)); else if (report.subId() == Receiver::DeviceDisconnection) this->removeDevice(this->_receiver-> deviceDisconnectionEvent(report)); }}, {[report, path=this->_receiver->rawDevice()->hidrawPath()] (std::exception& e) { if(report.subId() == Receiver::DeviceConnection) logPrintf(ERROR, "Failed to add device %d to receiver " "on %s: %s", report.deviceIndex(), path.c_str(), e.what()); else if(report.subId() == Receiver::DeviceDisconnection) logPrintf(ERROR, "Failed to remove device %d from " "receiver on %s: %s", report.deviceIndex() ,path.c_str(), e.what()); }}); }; _receiver->addHidppEventHandler("RECVMON", event_handler); } enumerate(); } void ReceiverMonitor::stop() { _receiver->removeHidppEventHandler("RECVMON"); _receiver->stopListening(); } void ReceiverMonitor::enumerate() { _receiver->enumerateHidpp(); } void ReceiverMonitor::waitForDevice(hidpp::DeviceIndex index) { std::string nickname = "WAIT_DEV_" + std::to_string(index); auto handler = std::make_shared(); handler->condition = [index](std::vector& report)->bool { return report[Offset::DeviceIndex] == index; }; handler->callback = [this, index, nickname](std::vector& report) { (void)report; // Suppress unused warning hidpp::DeviceConnectionEvent event{}; event.withPayload = false; event.linkEstablished = true; event.index = index; event.fromTimeoutCheck = true; task::spawn({[this, event, nickname]() { _receiver->rawDevice()->removeEventHandler(nickname); this->addDevice(event); }}, {[path=_receiver->rawDevice()->hidrawPath(), event] (std::exception& e) { logPrintf(ERROR, "Failed to add device %d to receiver " "on %s: %s", event.index, path.c_str(), e.what()); }}); }; _receiver->rawDevice()->addEventHandler(nickname, handler); } std::shared_ptr ReceiverMonitor::receiver() const { return _receiver; }logiops-0.2.2/src/logid/backend/dj/ReceiverMonitor.h000066400000000000000000000032171370476137700223470ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_DJ_RECEIVERMONITOR_H #define LOGID_BACKEND_DJ_RECEIVERMONITOR_H #include #include #include "Receiver.h" #include "../hidpp/defs.h" namespace logid { namespace backend { namespace dj { // This class will run on the RawDevice thread, class ReceiverMonitor { public: explicit ReceiverMonitor(std::string path); ~ReceiverMonitor(); void enumerate(); void run(); void stop(); protected: virtual void addDevice(hidpp::DeviceConnectionEvent event) = 0; virtual void removeDevice(hidpp::DeviceIndex index) = 0; void waitForDevice(hidpp::DeviceIndex index); // Internal methods for derived class void _pair(uint8_t timeout = 0); void _stopPairing(); void _unpair(); std::shared_ptr receiver() const; private: std::shared_ptr _receiver; }; }}} #endif //LOGID_BACKEND_DJ_RECEIVERMONITOR_Hlogiops-0.2.2/src/logid/backend/dj/Report.cpp000066400000000000000000000104471370476137700210440ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include #include "Report.h" using namespace logid::backend::dj; using namespace logid::backend; static const std::array DJReportDesc = { 0xA1, 0x01, // Collection (Application) 0x85, 0x20, // Report ID (32) 0x95, 0x0E, // Report Count (14) 0x75, 0x08, // Report Size (8) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x41, // Usage (0x41) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x41, // Usage (0x41) 0x91, 0x00, // Output (Data, Array, Absolute) 0x85, 0x21, // Report ID (33) 0x95, 0x1F, // Report Count (31) 0x09, 0x42, // Usage (0x42) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x42, // Usage (0x42) 0x91, 0x00, // Output (Data, Array, Absolute) 0xC0 // End Collection }; static const std::array DJReportDesc2 = { 0xA1, 0x01, // Collection (Application) 0x85, 0x20, // Report ID (32) 0x75, 0x08, // Report Size (8) 0x95, 0x0E, // Report Count (14) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x41, // Usage (0x41) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x41, // Usage (0x41) 0x91, 0x00, // Output (Data, Array, Absolute) 0x85, 0x21, // Report ID (33) 0x95, 0x1F, // Report Count (31) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x42, // Usage (0x42) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x42, // Usage (0x42) 0x91, 0x00, // Output (Data, Array, Absolute) 0xC0 // End Collection }; bool dj::supportsDjReports(std::vector&& rdesc) { auto it = std::search(rdesc.begin(), rdesc.end(), DJReportDesc.begin(), DJReportDesc.end()); if(it == rdesc.end()) it = std::search(rdesc.begin(), rdesc.end(), DJReportDesc2.begin(), DJReportDesc2.end()); return it != rdesc.end(); } Report::Report(std::vector& data) : _data (data) { switch(data[Offset::Type]) { case ReportType::Short: _data.resize(HeaderLength+ShortParamLength); break; case ReportType::Long: _data.resize(HeaderLength+LongParamLength); break; default: assert(false); } } Report::Report(Report::Type type, hidpp::DeviceIndex index, uint8_t feature) { switch(type) { case ReportType::Short: _data.resize(HeaderLength+ShortParamLength); break; case ReportType::Long: _data.resize(HeaderLength+LongParamLength); break; default: assert(false); } _data[Offset::Type] = type; _data[Offset::DeviceIndex] = index; _data[Offset::Feature] = feature; } Report::Type Report::type() const { return static_cast(_data[Offset::Type]); } hidpp::DeviceIndex Report::index() const { return static_cast(_data[Offset::DeviceIndex]); } uint8_t Report::feature() const { return _data[Offset::Feature]; } std::vector::iterator Report::paramBegin() { return _data.begin() + Offset::Parameters; } std::vector Report::rawData() const { return _data; } logiops-0.2.2/src/logid/backend/dj/Report.h000066400000000000000000000032321370476137700205030ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_DJ_REPORT_H #define LOGID_BACKEND_DJ_REPORT_H #include #include "../raw/RawDevice.h" #include "defs.h" #include "../hidpp/defs.h" namespace logid { namespace backend { namespace dj { namespace Offset { static constexpr uint8_t Type = 0; static constexpr uint8_t DeviceIndex = 1; static constexpr uint8_t Feature = 2; static constexpr uint8_t Parameters = 3; } bool supportsDjReports(std::vector&& rdesc); class Report { public: typedef ReportType::ReportType Type; explicit Report(std::vector& data); Report(Type type, hidpp::DeviceIndex index, uint8_t feature); Type type() const; hidpp::DeviceIndex index() const; uint8_t feature() const; std::vector::iterator paramBegin(); std::vector rawData() const; private: std::vector _data; }; }}} #endif //LOGID_BACKEND_DJ_REPORT_H logiops-0.2.2/src/logid/backend/dj/defs.h000066400000000000000000000030211370476137700201450ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_DJ_DEFS_H #define LOGID_BACKEND_DJ_DEFS_H #include namespace logid { namespace backend { namespace dj { namespace ReportType { enum ReportType : uint8_t { Short = 0x20, Long = 0x21 }; } namespace DeviceType { enum DeviceType : uint8_t { Unknown = 0x00, Keyboard = 0x01, Mouse = 0x02, Numpad = 0x03, Presenter = 0x04, /* 0x05-0x07 is reserved */ Trackball = 0x08, Touchpad = 0x09 }; } static constexpr uint8_t ErrorFeature = 0x7f; static constexpr std::size_t HeaderLength = 3; static constexpr std::size_t ShortParamLength = 12; static constexpr std::size_t LongParamLength = 29; }}} #endif //LOGID_BACKEND_DJ_DEFS_Hlogiops-0.2.2/src/logid/backend/hidpp/000077500000000000000000000000001370476137700175665ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/hidpp/Device.cpp000066400000000000000000000150671370476137700215020ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include "../../util/thread.h" #include "Device.h" #include "Report.h" #include "../hidpp20/features/Root.h" #include "../hidpp20/features/DeviceName.h" #include "../hidpp20/Error.h" #include "../hidpp10/Error.h" #include "../dj/Receiver.h" using namespace logid::backend; using namespace logid::backend::hidpp; const char* Device::InvalidDevice::what() const noexcept { switch(_reason) { case NoHIDPPReport: return "Invalid HID++ device"; case InvalidRawDevice: return "Invalid raw device"; case Asleep: return "Device asleep"; default: return "Invalid device"; } } Device::InvalidDevice::Reason Device::InvalidDevice::code() const noexcept { return _reason; } Device::Device(const std::string& path, DeviceIndex index): _raw_device (std::make_shared(path)), _receiver (nullptr), _path (path), _index (index) { _init(); } Device::Device(std::shared_ptr raw_device, DeviceIndex index) : _raw_device (std::move(raw_device)), _receiver (nullptr), _path (_raw_device->hidrawPath()), _index (index) { _init(); } Device::Device(std::shared_ptr receiver, hidpp::DeviceConnectionEvent event) : _raw_device (receiver->rawDevice()), _index (event.index) { // Device will throw an error soon, just do it now if(!event.linkEstablished) throw InvalidDevice(InvalidDevice::Asleep); if(!event.fromTimeoutCheck) _pid = event.pid; else _pid = receiver->getPairingInfo(_index).pid; _init(); } std::string Device::devicePath() const { return _path; } DeviceIndex Device::deviceIndex() const { return _index; } std::tuple Device::version() const { return _version; } void Device::_init() { _listening = false; _supported_reports = getSupportedReports(_raw_device->reportDescriptor()); if(!_supported_reports) throw InvalidDevice(InvalidDevice::NoHIDPPReport); try { hidpp20::EssentialRoot root(this); _version = root.getVersion(); } catch(hidpp10::Error &e) { // Valid HID++ 1.0 devices should send an InvalidSubID error if(e.code() != hidpp10::Error::InvalidSubID) throw; // HID++ 2.0 is not supported, assume HID++ 1.0 _version = std::make_tuple(1, 0); } if(!_receiver) { _pid = _raw_device->productId(); if(std::get<0>(_version) >= 2) { try { hidpp20::EssentialDeviceName deviceName(this); _name = deviceName.getName(); } catch(hidpp20::UnsupportedFeature &e) { _name = _raw_device->name(); } } else { _name = _raw_device->name(); } } else { _name = _receiver->getDeviceName(_index); } } Device::~Device() { if(_listening) _raw_device->removeEventHandler("DEV_" + std::to_string(_index)); } void Device::addEventHandler(const std::string& nickname, const std::shared_ptr& handler) { assert(_event_handlers.find(nickname) == _event_handlers.end()); _event_handlers.emplace(nickname, handler); } void Device::removeEventHandler(const std::string& nickname) { _event_handlers.erase(nickname); } const std::map>& Device::eventHandlers() { return _event_handlers; } void Device::handleEvent(Report& report) { for(auto& handler : _event_handlers) if(handler.second->condition(report)) handler.second->callback(report); } Report Device::sendReport(Report& report) { switch(report.type()) { case Report::Type::Short: if(!(_supported_reports & HIDPP_REPORT_SHORT_SUPPORTED)) report.setType(Report::Type::Long); break; case Report::Type::Long: /* Report can be truncated, but that isn't a good idea. */ assert(_supported_reports & HIDPP_REPORT_LONG_SUPPORTED); } auto raw_response = _raw_device->sendReport(report.rawReport()); Report response(raw_response); Report::Hidpp10Error hidpp10_error{}; if(response.isError10(&hidpp10_error)) throw hidpp10::Error(hidpp10_error.error_code); Report::Hidpp20Error hidpp20_error{}; if(response.isError20(&hidpp20_error)) throw hidpp20::Error(hidpp20_error.error_code); return response; } void Device::sendReportNoResponse(Report &report) { switch(report.type()) { case Report::Type::Short: if(!(_supported_reports & HIDPP_REPORT_SHORT_SUPPORTED)) report.setType(Report::Type::Long); break; case Report::Type::Long: /* Report can be truncated, but that isn't a good idea. */ assert(_supported_reports & HIDPP_REPORT_LONG_SUPPORTED); } _raw_device->sendReportNoResponse(report.rawReport()); } std::string Device::name() const { return _name; } uint16_t Device::pid() const { return _pid; } void Device::listen() { if(!_raw_device->isListening()) _raw_device->listenAsync(); // Pass all HID++ events with device index to this device. auto handler = std::make_shared(); handler->condition = [index=this->_index](std::vector& report) ->bool { return (report[Offset::Type] == Report::Type::Short || report[Offset::Type] == Report::Type::Long) && (report[Offset::DeviceIndex] == index); }; handler->callback = [this](std::vector& report)->void { Report _report(report); this->handleEvent(_report); }; _raw_device->addEventHandler("DEV_" + std::to_string(_index), handler); _listening = true; } void Device::stopListening() { if(_listening) _raw_device->removeEventHandler("DEV_" + std::to_string(_index)); _listening = false; if(!_raw_device->eventHandlers().empty()) _raw_device->stopListener(); }logiops-0.2.2/src/logid/backend/hidpp/Device.h000066400000000000000000000061621370476137700211430ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP_DEVICE_H #define LOGID_BACKEND_HIDPP_DEVICE_H #include #include #include #include #include "../raw/RawDevice.h" #include "Report.h" #include "defs.h" namespace logid { namespace backend { namespace dj { // Need to define here for a constructor class Receiver; } namespace hidpp { struct DeviceConnectionEvent; struct EventHandler { std::function condition; std::function callback; }; class Device { public: class InvalidDevice : std::exception { public: enum Reason { NoHIDPPReport, InvalidRawDevice, Asleep }; InvalidDevice(Reason reason) : _reason (reason) {} virtual const char* what() const noexcept; virtual Reason code() const noexcept; private: Reason _reason; }; explicit Device(const std::string& path, DeviceIndex index); explicit Device(std::shared_ptr raw_device, DeviceIndex index); explicit Device(std::shared_ptr receiver, hidpp::DeviceConnectionEvent event); ~Device(); std::string devicePath() const; DeviceIndex deviceIndex() const; std::tuple version() const; std::string name() const; uint16_t pid() const; void listen(); // Runs asynchronously void stopListening(); void addEventHandler(const std::string& nickname, const std::shared_ptr& handler); void removeEventHandler(const std::string& nickname); const std::map>& eventHandlers(); Report sendReport(Report& report); void sendReportNoResponse(Report& report); void handleEvent(Report& report); private: void _init(); std::shared_ptr _raw_device; std::shared_ptr _receiver; std::string _path; DeviceIndex _index; uint8_t _supported_reports; std::tuple _version; uint16_t _pid; std::string _name; std::atomic _listening; std::map> _event_handlers; }; } } } #endif //LOGID_BACKEND_HIDPP_DEVICE_Hlogiops-0.2.2/src/logid/backend/hidpp/Report.cpp000066400000000000000000000210351370476137700215460ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include #include "Report.h" #include "../hidpp10/Error.h" #include "../hidpp20/Error.h" using namespace logid::backend::hidpp; using namespace logid::backend; /* Report descriptors were sourced from cvuchener/hidpp */ static const std::array ShortReportDesc = { 0xA1, 0x01, // Collection (Application) 0x85, 0x10, // Report ID (16) 0x75, 0x08, // Report Size (8) 0x95, 0x06, // Report Count (6) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x01, // Usage (0001 - Vendor) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x01, // Usage (0001 - Vendor) 0x91, 0x00, // Output (Data, Array, Absolute) 0xC0 // End Collection }; static const std::array LongReportDesc = { 0xA1, 0x01, // Collection (Application) 0x85, 0x11, // Report ID (17) 0x75, 0x08, // Report Size (8) 0x95, 0x13, // Report Count (19) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x02, // Usage (0002 - Vendor) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x02, // Usage (0002 - Vendor) 0x91, 0x00, // Output (Data, Array, Absolute) 0xC0 // End Collection }; /* Alternative versions from the G602 */ static const std::array ShortReportDesc2 = { 0xA1, 0x01, // Collection (Application) 0x85, 0x10, // Report ID (16) 0x95, 0x06, // Report Count (6) 0x75, 0x08, // Report Size (8) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x01, // Usage (0001 - Vendor) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x01, // Usage (0001 - Vendor) 0x91, 0x00, // Output (Data, Array, Absolute) 0xC0 // End Collection }; static const std::array LongReportDesc2 = { 0xA1, 0x01, // Collection (Application) 0x85, 0x11, // Report ID (17) 0x95, 0x13, // Report Count (19) 0x75, 0x08, // Report Size (8) 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x09, 0x02, // Usage (0002 - Vendor) 0x81, 0x00, // Input (Data, Array, Absolute) 0x09, 0x02, // Usage (0002 - Vendor) 0x91, 0x00, // Output (Data, Array, Absolute) 0xC0 // End Collection }; uint8_t hidpp::getSupportedReports(std::vector&& rdesc) { uint8_t ret = 0; auto it = std::search(rdesc.begin(), rdesc.end(), ShortReportDesc.begin(), ShortReportDesc.end()); if(it == rdesc.end()) it = std::search(rdesc.begin(), rdesc.end(), ShortReportDesc2.begin(), ShortReportDesc2.end()); if(it != rdesc.end()) ret |= HIDPP_REPORT_SHORT_SUPPORTED; it = std::search(rdesc.begin(), rdesc.end(), LongReportDesc.begin(), LongReportDesc.end()); if(it == rdesc.end()) it = std::search(rdesc.begin(), rdesc.end(), LongReportDesc2.begin(), LongReportDesc2.end()); if(it != rdesc.end()) ret |= HIDPP_REPORT_LONG_SUPPORTED; return ret; } const char *Report::InvalidReportID::what() const noexcept { return "Invalid report ID"; } const char *Report::InvalidReportLength::what() const noexcept { return "Invalid report length"; } Report::Report(Report::Type type, DeviceIndex device_index, uint8_t sub_id, uint8_t address) { switch(type) { case Type::Short: _data.resize(HeaderLength + ShortParamLength); break; case Type::Long: _data.resize(HeaderLength + LongParamLength); break; default: throw InvalidReportID(); } _data[Offset::Type] = type; _data[Offset::DeviceIndex] = device_index; _data[Offset::SubID] = sub_id; _data[Offset::Address] = address; } Report::Report(Report::Type type, DeviceIndex device_index, uint8_t feature_index, uint8_t function, uint8_t sw_id) { assert(function <= 0x0f); assert(sw_id <= 0x0f); switch(type) { case Type::Short: _data.resize(HeaderLength + ShortParamLength); break; case Type::Long: _data.resize(HeaderLength + LongParamLength); break; default: throw InvalidReportID(); } _data[Offset::Type] = type; _data[Offset::DeviceIndex] = device_index; _data[Offset::Feature] = feature_index; _data[Offset::Function] = (function & 0x0f) << 4 | (sw_id & 0x0f); } Report::Report(const std::vector& data) : _data (data) { _data.resize(HeaderLength + LongParamLength); // Truncating data is entirely valid here. switch(_data[Offset::Type]) { case Type::Short: _data.resize(HeaderLength + ShortParamLength); break; case Type::Long: _data.resize(HeaderLength + LongParamLength); break; default: throw InvalidReportID(); } } Report::Type Report::type() const { return static_cast(_data[Offset::Type]); } void Report::setType(Report::Type type) { switch(type) { case Type::Short: _data.resize(HeaderLength + ShortParamLength); break; case Type::Long: _data.resize(HeaderLength + LongParamLength); break; default: throw InvalidReportID(); } _data[Offset::Type] = type; } hidpp::DeviceIndex Report::deviceIndex() const { return static_cast(_data[Offset::DeviceIndex]); } void Report::setDeviceIndex(hidpp::DeviceIndex index) { _data[Offset::DeviceIndex] = index; } uint8_t Report::feature() const { return _data[Offset::Feature]; } void Report::setFeature(uint8_t feature) { _data[Offset::Parameters] = feature; } uint8_t Report::subId() const { return _data[Offset::SubID]; } void Report::setSubId(uint8_t sub_id) { _data[Offset::SubID] = sub_id; } uint8_t Report::function() const { return (_data[Offset::Function] >> 4) & 0x0f; } void Report::setFunction(uint8_t function) { _data[Offset::Function] &= 0x0f; _data[Offset::Function] |= (function & 0x0f) << 4; } uint8_t Report::swId() const { return _data[Offset::Function] & 0x0f; } void Report::setSwId(uint8_t sub_id) { _data[Offset::Function] &= 0x0f; _data[Offset::Function] |= sub_id & 0x0f; } uint8_t Report::address() const { return _data[Offset::Address]; } void Report::setAddress(uint8_t address) { _data[Offset::Address] = address; } std::vector::iterator Report::paramBegin() { return _data.begin() + Offset::Parameters; } std::vector::iterator Report::paramEnd() { return _data.end(); } std::vector::const_iterator Report::paramBegin() const { return _data.begin() + Offset::Parameters; } std::vector::const_iterator Report::paramEnd() const { return _data.end(); } void Report::setParams(const std::vector& _params) { assert(_params.size() <= _data.size()-HeaderLength); for(std::size_t i = 0; i < _params.size(); i++) _data[Offset::Parameters + i] = _params[i]; } bool Report::isError10(Report::Hidpp10Error *error) { assert(error != nullptr); if(_data[Offset::Type] != Type::Short || _data[Offset::SubID] != hidpp10::ErrorID) return false; error->sub_id = _data[3]; error->address = _data[4]; error->error_code = _data[5]; return true; } bool Report::isError20(Report::Hidpp20Error* error) { assert(error != nullptr); if(_data[Offset::Type] != Type::Long || _data[Offset::Feature] != hidpp20::ErrorID) return false; error->feature_index= _data[3]; error->function = (_data[4] >> 4) & 0x0f; error->software_id = _data[4] & 0x0f; error->error_code = _data[5]; return true; }logiops-0.2.2/src/logid/backend/hidpp/Report.h000066400000000000000000000073361370476137700212230ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP_REPORT_H #define LOGID_BACKEND_HIDPP_REPORT_H #include #include "../raw/RawDevice.h" #include "defs.h" /* Some devices only support a subset of these reports */ #define HIDPP_REPORT_SHORT_SUPPORTED 1U #define HIDPP_REPORT_LONG_SUPPORTED 1U<<1U /* Very long reports exist, however they have not been encountered so far */ namespace logid { namespace backend { namespace hidpp { uint8_t getSupportedReports(std::vector&& rdesc); namespace Offset { static constexpr uint8_t Type = 0; static constexpr uint8_t DeviceIndex = 1; static constexpr uint8_t SubID = 2; static constexpr uint8_t Feature = 2; static constexpr uint8_t Address = 3; static constexpr uint8_t Function = 3; static constexpr uint8_t Parameters = 4; } class Report { public: typedef ReportType::ReportType Type; class InvalidReportID: public std::exception { public: InvalidReportID() = default; const char* what() const noexcept override; }; class InvalidReportLength: public std::exception { public: InvalidReportLength() = default;; const char* what() const noexcept override; }; static constexpr std::size_t MaxDataLength = 20; Report(Report::Type type, DeviceIndex device_index, uint8_t sub_id, uint8_t address); Report(Report::Type type, DeviceIndex device_index, uint8_t feature_index, uint8_t function, uint8_t sw_id); explicit Report(const std::vector& data); Report::Type type() const; void setType(Report::Type type); logid::backend::hidpp::DeviceIndex deviceIndex() const; void setDeviceIndex(hidpp::DeviceIndex index); uint8_t feature() const; void setFeature(uint8_t feature); uint8_t subId() const; void setSubId(uint8_t sub_id); uint8_t function() const; void setFunction(uint8_t function); uint8_t swId() const; void setSwId(uint8_t sw_id); uint8_t address() const; void setAddress(uint8_t address); std::vector::iterator paramBegin(); std::vector::iterator paramEnd(); std::vector::const_iterator paramBegin() const; std::vector::const_iterator paramEnd() const; void setParams(const std::vector& _params); struct Hidpp10Error { uint8_t sub_id, address, error_code; }; bool isError10(Hidpp10Error* error); struct Hidpp20Error { uint8_t feature_index, function, software_id, error_code; }; bool isError20(Hidpp20Error* error); std::vector rawReport () const { return _data; } static constexpr std::size_t HeaderLength = 4; private: std::vector _data; }; }}} #endif //LOGID_BACKEND_HIDPP_REPORT_Hlogiops-0.2.2/src/logid/backend/hidpp/defs.h000066400000000000000000000026421370476137700206640ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP_DEFS_H #define LOGID_BACKEND_HIDPP_DEFS_H #define LOGID_HIDPP_SOFTWARE_ID 0 #include namespace logid { namespace backend { namespace hidpp { namespace ReportType { enum ReportType : uint8_t { Short = 0x10, Long = 0x11 }; } enum DeviceIndex: uint8_t { DefaultDevice = 0xff, CordedDevice = 0, WirelessDevice1 = 1, WirelessDevice2 = 2, WirelessDevice3 = 3, WirelessDevice4 = 4, WirelessDevice5 = 5, WirelessDevice6 = 6, }; static constexpr std::size_t ShortParamLength = 3; static constexpr std::size_t LongParamLength = 16; } } } #endif //LOGID_BACKEND_HIDPP_DEFS_Hlogiops-0.2.2/src/logid/backend/hidpp10/000077500000000000000000000000001370476137700177275ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/hidpp10/Device.cpp000066400000000000000000000046551370476137700216440ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include "Device.h" #include "defs.h" using namespace logid::backend; using namespace logid::backend::hidpp10; Device::Device(const std::string &path, hidpp::DeviceIndex index) : hidpp::Device(path, index) { assert(version() == std::make_tuple(1, 0)); } Device::Device(std::shared_ptr raw_dev, hidpp::DeviceIndex index) : hidpp::Device(std::move(raw_dev), index) { assert(version() == std::make_tuple(1, 0)); } std::vector Device::getRegister(uint8_t address, const std::vector& params, hidpp::Report::Type type) { assert(params.size() <= hidpp::LongParamLength); uint8_t sub_id = type == hidpp::Report::Type::Short ? GetRegisterShort : GetRegisterLong; return accessRegister(sub_id, address, params); } std::vector Device::setRegister(uint8_t address, const std::vector& params, hidpp::Report::Type type) { assert(params.size() <= hidpp::LongParamLength); uint8_t sub_id = type == hidpp::Report::Type::Short ? SetRegisterShort : SetRegisterLong; return accessRegister(sub_id, address, params); } std::vector Device::accessRegister(uint8_t sub_id, uint8_t address, const std::vector ¶ms) { hidpp::Report::Type type = params.size() <= hidpp::ShortParamLength ? hidpp::Report::Type::Short : hidpp::Report::Type::Long; hidpp::Report request(type, deviceIndex(), sub_id, address); std::copy(params.begin(), params.end(), request.paramBegin()); auto response = sendReport(request); return std::vector(response.paramBegin(), response.paramEnd()); } logiops-0.2.2/src/logid/backend/hidpp10/Device.h000066400000000000000000000030201370476137700212720ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP10_DEVICE_H #define LOGID_BACKEND_HIDPP10_DEVICE_H #include "../hidpp/Device.h" namespace logid { namespace backend { namespace hidpp10 { class Device : public hidpp::Device { public: Device(const std::string& path, hidpp::DeviceIndex index); Device(std::shared_ptr raw_dev, hidpp::DeviceIndex index); std::vector getRegister(uint8_t address, const std::vector& params, hidpp::Report::Type type); std::vector setRegister(uint8_t address, const std::vector& params, hidpp::Report::Type type); private: std::vector accessRegister(uint8_t sub_id, uint8_t address, const std::vector& params); }; }}} #endif //LOGID_BACKEND_HIDPP10_DEVICE_Hlogiops-0.2.2/src/logid/backend/hidpp10/Error.cpp000066400000000000000000000033671370476137700215350ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include "Error.h" using namespace logid::backend::hidpp10; Error::Error(uint8_t code): _code(code) { assert(code != Success); } const char* Error::what() const noexcept { switch(_code) { case Success: return "Success"; case InvalidSubID: return "Invalid sub ID"; case InvalidAddress: return "Invalid address"; case InvalidValue: return "Invalid value"; case ConnectFail: return "Connection failure"; case TooManyDevices: return "Too many devices"; case AlreadyExists: return "Already exists"; case Busy: return "Busy"; case UnknownDevice: return "Unknown device"; case ResourceError: return "Resource error"; case RequestUnavailable: return "Request unavailable"; case InvalidParameterValue: return "Invalid parameter value"; case WrongPINCode: return "Wrong PIN code"; default: return "Unknown error code"; } } uint8_t Error::code() const noexcept { return _code; }logiops-0.2.2/src/logid/backend/hidpp10/Error.h000066400000000000000000000031701370476137700211720ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP10_ERROR_H #define LOGID_BACKEND_HIDPP10_ERROR_H #include namespace logid { namespace backend { namespace hidpp10 { static constexpr uint8_t ErrorID = 0x8f; class Error: public std::exception { public: enum ErrorCode: uint8_t { Success = 0x00, InvalidSubID = 0x01, InvalidAddress = 0x02, InvalidValue = 0x03, ConnectFail = 0x04, TooManyDevices = 0x05, AlreadyExists = 0x06, Busy = 0x07, UnknownDevice = 0x08, ResourceError = 0x09, RequestUnavailable = 0x0A, InvalidParameterValue = 0x0B, WrongPINCode = 0x0C }; explicit Error(uint8_t code); const char* what() const noexcept override; uint8_t code() const noexcept; private: uint8_t _code; }; }}} #endif //LOGID_BACKEND_HIDPP10_ERROR_Hlogiops-0.2.2/src/logid/backend/hidpp10/defs.h000066400000000000000000000020101370476137700210120ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP10_DEFS_H #define LOGID_BACKEND_HIDPP10_DEFS_H namespace logid { namespace backend { namespace hidpp10 { enum SubID: uint8_t { SetRegisterShort = 0x80, GetRegisterShort = 0x81, SetRegisterLong = 0x82, GetRegisterLong = 0x83 }; }}} #endif //LOGID_BACKEND_HIDPP10_DEFS_Hlogiops-0.2.2/src/logid/backend/hidpp20/000077500000000000000000000000001370476137700177305ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/hidpp20/Device.cpp000066400000000000000000000047661370476137700216500ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "Device.h" #include "../hidpp/defs.h" using namespace logid::backend::hidpp20; Device::Device(std::string path, hidpp::DeviceIndex index) : hidpp::Device(path, index) { assert(std::get<0>(version()) >= 2); } Device::Device(std::shared_ptr raw_device, hidpp::DeviceIndex index) : hidpp::Device(raw_device, index) { assert(std::get<0>(version()) >= 2); } std::vector Device::callFunction(uint8_t feature_index, uint8_t function, std::vector& params) { hidpp::Report::Type type; assert(params.size() <= hidpp::LongParamLength); if(params.size() <= hidpp::ShortParamLength) type = hidpp::Report::Type::Short; else if(params.size() <= hidpp::LongParamLength) type = hidpp::Report::Type::Long; else throw hidpp::Report::InvalidReportID(); hidpp::Report request(type, deviceIndex(), feature_index, function, LOGID_HIDPP_SOFTWARE_ID); std::copy(params.begin(), params.end(), request.paramBegin()); auto response = this->sendReport(request); return std::vector(response.paramBegin(), response.paramEnd()); } void Device::callFunctionNoResponse(uint8_t feature_index, uint8_t function, std::vector ¶ms) { hidpp::Report::Type type; assert(params.size() <= hidpp::LongParamLength); if(params.size() <= hidpp::ShortParamLength) type = hidpp::Report::Type::Short; else if(params.size() <= hidpp::LongParamLength) type = hidpp::Report::Type::Long; else throw hidpp::Report::InvalidReportID(); hidpp::Report request(type, deviceIndex(), feature_index, function, LOGID_HIDPP_SOFTWARE_ID); std::copy(params.begin(), params.end(), request.paramBegin()); this->sendReportNoResponse(request); }logiops-0.2.2/src/logid/backend/hidpp20/Device.h000066400000000000000000000026141370476137700213030ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_DEVICE_H #define LOGID_BACKEND_HIDPP20_DEVICE_H #include "../hidpp/Device.h" #include namespace logid { namespace backend { namespace hidpp20 { class Device : public hidpp::Device { public: Device(std::string path, hidpp::DeviceIndex index); Device(std::shared_ptr raw_device, hidpp::DeviceIndex index); std::vector callFunction(uint8_t feature_index, uint8_t function, std::vector& params); void callFunctionNoResponse(uint8_t feature_index, uint8_t function, std::vector& params); }; }}} #endif //LOGID_BACKEND_HIDPP20_DEVICE_Hlogiops-0.2.2/src/logid/backend/hidpp20/Error.cpp000066400000000000000000000031521370476137700215260ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "Error.h" using namespace logid::backend::hidpp20; Error::Error(uint8_t code) : _code (code) { assert(_code != NoError); } const char* Error::what() const noexcept { switch(_code) { case NoError: return "No error"; case Unknown: return "Unknown"; case InvalidArgument: return "Invalid argument"; case OutOfRange: return "Out of range"; case HardwareError: return "Hardware error"; case LogitechInternal: return "Logitech internal feature"; case InvalidFeatureIndex: return "Invalid feature index"; case InvalidFunctionID: return "Invalid function ID"; case Busy: return "Busy"; case Unsupported: return "Unsupported"; case UnknownDevice: return "Unknown device"; default: return "Unknown error code"; } } uint8_t Error::code() const noexcept { return _code; }logiops-0.2.2/src/logid/backend/hidpp20/Error.h000066400000000000000000000030331370476137700211710ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_ERROR_H #define LOGID_BACKEND_HIDPP20_ERROR_H #include #include namespace logid { namespace backend { namespace hidpp20 { static constexpr uint8_t ErrorID = 0xFF; class Error: public std::exception { public: enum ErrorCode: uint8_t { NoError = 0, Unknown = 1, InvalidArgument = 2, OutOfRange = 3, HardwareError = 4, LogitechInternal = 5, InvalidFeatureIndex = 6, InvalidFunctionID = 7, Busy = 8, Unsupported = 9, UnknownDevice = 10 }; explicit Error(uint8_t code); const char* what() const noexcept override; uint8_t code() const noexcept; private: uint8_t _code; }; }}} #endif //LOGID_BACKEND_HIDPP20_ERROR_Hlogiops-0.2.2/src/logid/backend/hidpp20/EssentialFeature.cpp000066400000000000000000000044501370476137700237020ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "EssentialFeature.h" #include "feature_defs.h" #include "features/Root.h" #include "Error.h" using namespace logid::backend::hidpp20; std::vector EssentialFeature::callFunction(uint8_t function_id, std::vector& params) { hidpp::Report::Type type; assert(params.size() <= hidpp::LongParamLength); if(params.size() <= hidpp::ShortParamLength) type = hidpp::Report::Type::Short; else if(params.size() <= hidpp::LongParamLength) type = hidpp::Report::Type::Long; else throw hidpp::Report::InvalidReportID(); hidpp::Report request(type, _device->deviceIndex(), _index, function_id, LOGID_HIDPP_SOFTWARE_ID); std::copy(params.begin(), params.end(), request.paramBegin()); auto response = _device->sendReport(request); return std::vector(response.paramBegin(), response.paramEnd()); } EssentialFeature::EssentialFeature(hidpp::Device* dev, uint16_t _id) : _device (dev) { _index = hidpp20::FeatureID::ROOT; if(_id) { std::vector getFunc_req(2); getFunc_req[0] = (_id >> 8) & 0xff; getFunc_req[1] = _id & 0xff; try { auto getFunc_resp = this->callFunction(Root::GetFeature, getFunc_req); _index = getFunc_resp[0]; } catch(Error& e) { if(e.code() == Error::InvalidFeatureIndex) throw UnsupportedFeature(_id); throw e; } // 0 if not found if(!_index) throw UnsupportedFeature(_id); } } logiops-0.2.2/src/logid/backend/hidpp20/EssentialFeature.h000066400000000000000000000026711370476137700233520ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_ESSENTIAL_FEATURE_H #define LOGID_BACKEND_HIDPP20_ESSENTIAL_FEATURE_H // WARNING: UNSAFE /* This class is only meant to provide essential HID++ 2.0 features to the * hidpp::Device class. No version checks are provided here */ #include "Device.h" namespace logid { namespace backend { namespace hidpp20 { class EssentialFeature { public: static const uint16_t ID; virtual uint16_t getID() = 0; protected: EssentialFeature(hidpp::Device* dev, uint16_t _id); std::vector callFunction(uint8_t function_id, std::vector& params); private: hidpp::Device* _device; uint8_t _index; }; }}} #endif //LOGID_BACKEND_HIDPP20_ESSENTIAL_FEATURE_Hlogiops-0.2.2/src/logid/backend/hidpp20/Feature.cpp000066400000000000000000000037771370476137700220450ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "Error.h" #include "Feature.h" #include "feature_defs.h" #include "features/Root.h" using namespace logid::backend::hidpp20; const char* UnsupportedFeature::what() const noexcept { return "Unsupported feature"; } uint16_t UnsupportedFeature::code() const noexcept { return _f_id; } std::vector Feature::callFunction(uint8_t function_id, std::vector& params) { return _device->callFunction(_index, function_id, params); } void Feature::callFunctionNoResponse(uint8_t function_id, std::vector& params) { _device->callFunctionNoResponse(_index, function_id, params); } Feature::Feature(Device* dev, uint16_t _id) : _device (dev) { _index = hidpp20::FeatureID::ROOT; if(_id) { std::vector getFunc_req(2); getFunc_req[0] = (_id >> 8) & 0xff; getFunc_req[1] = _id & 0xff; try { auto getFunc_resp = this->callFunction(Root::GetFeature, getFunc_req); _index = getFunc_resp[0]; } catch(Error& e) { if(e.code() == Error::InvalidFeatureIndex) throw UnsupportedFeature(_id); throw e; } // 0 if not found if(!_index) throw UnsupportedFeature(_id); } } uint8_t Feature::featureIndex() { return _index; }logiops-0.2.2/src/logid/backend/hidpp20/Feature.h000066400000000000000000000032071370476137700214760ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_H #define LOGID_BACKEND_HIDPP20_FEATURE_H #include #include "Device.h" namespace logid { namespace backend { namespace hidpp20 { class UnsupportedFeature : public std::exception { public: explicit UnsupportedFeature(uint16_t ID) : _f_id (ID) {} const char* what() const noexcept override; uint16_t code() const noexcept; private: uint16_t _f_id; }; class Feature { public: static const uint16_t ID; virtual uint16_t getID() = 0; uint8_t featureIndex(); protected: explicit Feature(Device* dev, uint16_t _id); std::vector callFunction(uint8_t function_id, std::vector& params); void callFunctionNoResponse(uint8_t function_id, std::vector& params); private: Device* _device; uint8_t _index; }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_Hlogiops-0.2.2/src/logid/backend/hidpp20/feature_defs.h000066400000000000000000000110051370476137700225320ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATUREDEFS #define LOGID_BACKEND_HIDPP20_FEATUREDEFS #include namespace logid { namespace backend { namespace hidpp20 { struct feature_info { uint16_t feature_id; bool obsolete; bool internal; bool hidden; }; namespace FeatureID { enum FeatureID : uint16_t { ROOT = 0x0000, FEATURE_SET = 0x0001, FEATURE_INFO = 0x0002, FW_VERSION = 0x0003, DEVICE_NAME = 0x0005, DEVICE_GROUPS = 0x0006, DEVICE_FRIENDLY_NAME = 0x0007, RESET = 0x0020, CRYPTO_IDENTIFIER = 0x0021, DFUCONTROL = 0x00c0, DFUCONTROL_V2 = 0x00c1, DFUCONTROL_V3 = 0x00c2, DFU = 0xd000, BATTERY_STATUS = 0x1000, BATTERY_VOLTAGE = 0x1001, CHARGING_CONTROL = 0x1010, LED_CONTROL = 0x1300, GENERIC_TEST = 0x1800, DEVICE_RESET = 0x1802, OOB_STATE = 0x1805, CONFIGURABLE_DEVICE_PROPERTIES = 0x1806, CHANGE_HOST = 0x1814, HOSTS_INFO = 0x1815, BACKLIGHT = 0x1981, BACKLIGHT_V2 = 0x1982, BACKLIGHT_V3 = 0x1983, PRESENTER_CONTROL = 0x1a00, SENSOR_3D = 0x1a01, REPROG_CONTROLS = 0x1b00, REPROG_CONTROLS_V2 = 0x1b01, REPROG_CONTROLS_V2_2 = 0x1b02, REPROG_CONTROLS_V3 = 0x1b03, REPROG_CONTROLS_V4 = 0x1b04, PERSISTENT_REMAPPABLE_ACTION = 0x1bc0, WIRELESS_DEVICE_STATUS = 0x1d4b, ENABLE_HIDDEN_FEATURE = 0x1e00, FIRMWARE_PROPERTIES = 0x1f1f, ADC_MEASUREMENT = 0x1f20, LEFT_RIGHT_SWAP = 0x2001, SWAP_BUTTON = 0x2005, POINTER_AXES_ORIENTATION = 0x2006, VERTICAL_SCROLLING = 0x2100, SMART_SHIFT = 0x2110, HIRES_SCROLLING = 0x2120, HIRES_SCROLLING_V2 = 0x2121, // Referred to as Hi-res wheel in cvuchener/hidpp, seems to be V2? LORES_SCROLLING = 0x2130, MOUSE_POINTER = 0x2200, // Possibly predecessor to 0x2201? ADJUSTABLE_DPI = 0x2201, ANGLE_SNAPPING = 0x2230, SURFACE_TUNING = 0x2240, HYBRID_TRACKING = 0x2400, FN_INVERSION = 0x40a0, FN_INVERSION_V2 = 0x40a2, // Is 0x40a1 skipped? FN_INVERSION_V3 = 0x40a3, ENCRYPTION = 0x4100, LOCK_KEY_STATE = 0x4220, SOLAR_DASHBOARD = 0x4301, KEYBOARD_LAYOUT = 0x4520, KEYBOARD_DISABLE = 0x4521, DISABLE_KEYS = 0x4522, MULTIPLATFORM = 0x4530, // Dual platform only? MULTIPLATFORM_V2 = 0x4531, KEYBOARD_LAYOUT_V2 = 0x4540, CROWN = 0x4600, TOUCHPAD_FW = 0x6010, TOUCHPAD_SW = 0x6011, TOUCHPAD_FW_WIN8 = 0x6012, TOUCHMOUSE_RAW = 0x6100, // TOUCHMOUSE_6120 = 0x6120, (Keeping this commented out until a better name is found) GESTURE = 0x6500, GESTURE_V2 = 0x6501, G_KEY = 0x8010, M_KEY = 0x8020, // MR = 0x8030, (Keeping this commented out until a better name is found) BRIGHTNESS_CONTROL = 0x8040, REPORT_RATE = 0x8060, RGB_EFFECTS = 0x8070, RGB_EFFECTS_V2 = 0x8071, PER_KEY_LIGHTING = 0x8080, PER_KEY_LIGHTING_V2 = 0x8081, MODE_STATUS = 0x8100, MOUSE_BUTTON_SPY = 0x8110, LATENCY_MONITORING = 0x8111, GAMING_ATTACHMENTS = 0x8120, FORCE_FEEDBACK = 0x8123, SIDETONE = 0x8300, EQUALIZER = 0x8310, HEADSET_OUT = 0x8320 }; } }}} #endif //LOGID_BACKEND_HIDPP20_FEATUREDEFSlogiops-0.2.2/src/logid/backend/hidpp20/features/000077500000000000000000000000001370476137700215465ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/hidpp20/features/AdjustableDPI.cpp000066400000000000000000000045271370476137700246750ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "AdjustableDPI.h" using namespace logid::backend::hidpp20; AdjustableDPI::AdjustableDPI(Device* dev) : Feature(dev, ID) { } uint8_t AdjustableDPI::getSensorCount() { std::vector params(0); auto response = callFunction(GetSensorCount, params); return response[0]; } AdjustableDPI::SensorDPIList AdjustableDPI::getSensorDPIList(uint8_t sensor) { SensorDPIList dpi_list{}; std::vector params(1); params[0] = sensor; auto response = callFunction(GetSensorDPIList, params); dpi_list.dpiStep = false; for(std::size_t i = 1; i < response.size(); i+=2) { uint16_t dpi = response[i + 1]; dpi |= (response[i] << 8); if(!dpi) break; if(dpi >= 0xe000) { dpi_list.isRange = true; dpi_list.dpiStep = dpi - 0xe000; } else { dpi_list.dpis.push_back(dpi); } } return dpi_list; } uint16_t AdjustableDPI::getDefaultSensorDPI(uint8_t sensor) { std::vector params(1); params[0] = sensor; auto response = callFunction(GetSensorDPI, params); uint16_t default_dpi = response[4]; default_dpi |= (response[3] << 8); return default_dpi; } uint16_t AdjustableDPI::getSensorDPI(uint8_t sensor) { std::vector params(1); params[0] = sensor; auto response = callFunction(GetSensorDPI, params); uint16_t dpi = response[2]; dpi |= (response[1] << 8); return dpi; } void AdjustableDPI::setSensorDPI(uint8_t sensor, uint16_t dpi) { std::vector params(3); params[0] = sensor; params[1] = (dpi >> 8); params[2] = (dpi & 0xFF); callFunction(SetSensorDPI, params); }logiops-0.2.2/src/logid/backend/hidpp20/features/AdjustableDPI.h000066400000000000000000000033171370476137700243360ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_ADJUSTABLEDPI_H #define LOGID_BACKEND_HIDPP20_FEATURE_ADJUSTABLEDPI_H #include "../feature_defs.h" #include "../Feature.h" namespace logid { namespace backend { namespace hidpp20 { class AdjustableDPI : public Feature { public: static const uint16_t ID = FeatureID::ADJUSTABLE_DPI; virtual uint16_t getID() { return ID; } enum Function { GetSensorCount = 0, GetSensorDPIList = 1, GetSensorDPI = 2, SetSensorDPI = 3 }; AdjustableDPI(Device* dev); uint8_t getSensorCount(); struct SensorDPIList { std::vector dpis; bool isRange; uint16_t dpiStep; }; SensorDPIList getSensorDPIList(uint8_t sensor); uint16_t getDefaultSensorDPI(uint8_t sensor); uint16_t getSensorDPI(uint8_t sensor); void setSensorDPI(uint8_t sensor, uint16_t dpi); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_ADJUSTABLEDPI_H logiops-0.2.2/src/logid/backend/hidpp20/features/ChangeHost.cpp000066400000000000000000000040671370476137700243040ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "ChangeHost.h" #include "../Error.h" using namespace logid::backend::hidpp20; ChangeHost::ChangeHost(Device *dev) : Feature(dev, ID), _host_count (0) { } ChangeHost::HostInfo ChangeHost::getHostInfo() { std::vector params(0); auto response = callFunction(GetHostInfo, params); HostInfo info{}; info.hostCount = response[0]; info.currentHost = response[1]; info.enhancedHostSwitch = response[2] & 1; if(!_host_count) _host_count = info.hostCount; return info; } void ChangeHost::setHost(uint8_t host) { /* Expect connection to be severed here, send without response * * Since there is no response, we have to emulate any kind of * error that may be returned (i.e. InvalidArgument as per the docs) */ if(!_host_count) getHostInfo(); if(host >= _host_count) throw hidpp20::Error(hidpp20::Error::InvalidArgument); std::vector params = {host}; callFunctionNoResponse(SetCurrentHost, params); } std::vector ChangeHost::getCookies() { if(!_host_count) getHostInfo(); std::vector params(0); auto response = callFunction(GetCookies, params); response.resize(_host_count); return response; } void ChangeHost::setCookie(uint8_t host, uint8_t cookie) { std::vector params = {host, cookie}; callFunction(SetCookie, params); }logiops-0.2.2/src/logid/backend/hidpp20/features/ChangeHost.h000066400000000000000000000032121370476137700237400ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_CHANGEHOST_H #define LOGID_BACKEND_HIDPP20_FEATURE_CHANGEHOST_H #include "../feature_defs.h" #include "../Feature.h" namespace logid { namespace backend { namespace hidpp20 { class ChangeHost : public Feature { public: static const uint16_t ID = FeatureID::CHANGE_HOST; virtual uint16_t getID() { return ID; } ChangeHost(Device* dev); enum Function { GetHostInfo = 0, SetCurrentHost = 1, GetCookies = 2, SetCookie = 3 }; struct HostInfo { uint8_t hostCount; uint8_t currentHost; bool enhancedHostSwitch; }; HostInfo getHostInfo(); void setHost(uint8_t host); std::vector getCookies(); void setCookie(uint8_t host, uint8_t cookie); private: uint8_t _host_count; }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_CHANGEHOST_H logiops-0.2.2/src/logid/backend/hidpp20/features/DeviceName.cpp000066400000000000000000000046011370476137700242530ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "DeviceName.h" using namespace logid::backend; using namespace logid::backend::hidpp20; DeviceName::DeviceName(Device* dev) : Feature(dev, ID) { } uint8_t DeviceName::getNameLength() { std::vector params(0); auto response = this->callFunction(Function::GetLength, params); return response[0]; } std::string _getName(uint8_t length, const std::function(std::vector)>& fcall) { uint8_t function_calls = length/hidpp::LongParamLength; if(length % hidpp::LongParamLength) function_calls++; std::vector params(1); std::string name; for(uint8_t i = 0; i < function_calls; i++) { params[0] = i*hidpp::LongParamLength; auto name_section = fcall(params); for(std::size_t j = 0; j < hidpp::LongParamLength; j++) { if(params[0] + j >= length) return name; name += name_section[j]; } } return name; } std::string DeviceName::getName() { return _getName(getNameLength(), [this] (std::vector params)->std::vector { return this->callFunction(Function::GetDeviceName, params); }); } EssentialDeviceName::EssentialDeviceName(hidpp::Device* dev) : EssentialFeature(dev, ID) { } uint8_t EssentialDeviceName::getNameLength() { std::vector params(0); auto response = this->callFunction(DeviceName::Function::GetLength, params); return response[0]; } std::string EssentialDeviceName::getName() { return _getName(getNameLength(), [this] (std::vector params)->std::vector { return this->callFunction(DeviceName::Function::GetDeviceName, params); }); }logiops-0.2.2/src/logid/backend/hidpp20/features/DeviceName.h000066400000000000000000000032471370476137700237250ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_DEVICENAME_H #define LOGID_BACKEND_HIDPP20_FEATURE_DEVICENAME_H #include "../Feature.h" #include "../feature_defs.h" #include "../EssentialFeature.h" namespace logid { namespace backend { namespace hidpp20 { class DeviceName : public Feature { public: static const uint16_t ID = FeatureID::DEVICE_NAME; virtual uint16_t getID() { return ID; } enum Function : uint8_t { GetLength = 0, GetDeviceName = 1 }; explicit DeviceName(Device* device); uint8_t getNameLength(); std::string getName(); }; class EssentialDeviceName : public EssentialFeature { public: static const uint16_t ID = FeatureID::DEVICE_NAME; virtual uint16_t getID() { return ID; } explicit EssentialDeviceName(hidpp::Device* device); uint8_t getNameLength(); std::string getName(); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_DEVICENAME_Hlogiops-0.2.2/src/logid/backend/hidpp20/features/FeatureSet.cpp000066400000000000000000000027561370476137700243330ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "FeatureSet.h" using namespace logid::backend::hidpp20; FeatureSet::FeatureSet(Device *device) : Feature(device, ID) { } uint8_t FeatureSet::getFeatureCount() { std::vector params(0); auto response = callFunction(GetFeatureCount, params); return response[0]; } uint16_t FeatureSet::getFeature(uint8_t feature_index) { std::vector params(1); params[0] = feature_index; auto response = callFunction(GetFeature, params); uint16_t feature_id = (response[0] << 8); feature_id |= response[1]; return feature_id; } std::map FeatureSet::getFeatures() { uint8_t feature_count = getFeatureCount(); std::map features; for(uint8_t i = 0; i < feature_count; i++) features[i] = getFeature(i); return features; }logiops-0.2.2/src/logid/backend/hidpp20/features/FeatureSet.h000066400000000000000000000026271370476137700237750ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_FEATURESET_H #define LOGID_BACKEND_HIDPP20_FEATURE_FEATURESET_H #include "../Feature.h" #include "../feature_defs.h" namespace logid { namespace backend { namespace hidpp20 { class FeatureSet : public Feature { public: static const uint16_t ID = FeatureID::FEATURE_SET; virtual uint16_t getID() { return ID; } enum Function : uint8_t { GetFeatureCount = 0, GetFeature = 1 }; explicit FeatureSet(Device* device); uint8_t getFeatureCount(); uint16_t getFeature(uint8_t feature_index); std::map getFeatures(); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_FEATURESET_H logiops-0.2.2/src/logid/backend/hidpp20/features/HiresScroll.cpp000066400000000000000000000042021370476137700245010ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "HiresScroll.h" using namespace logid::backend::hidpp20; HiresScroll::HiresScroll(Device *device) : Feature(device, ID) { } HiresScroll::Capabilities HiresScroll::getCapabilities() { std::vector params(0); auto response = callFunction(GetCapabilities, params); Capabilities capabilities{}; capabilities.multiplier = response[0]; capabilities.flags = response[1]; return capabilities; } uint8_t HiresScroll::getMode() { std::vector params(0); auto response = callFunction(GetMode, params); return response[0]; } void HiresScroll::setMode(uint8_t mode) { std::vector params(1); params[0] = mode; callFunction(SetMode, params); } bool HiresScroll::getRatchetState() { std::vector params(0); auto response = callFunction(GetRatchetState, params); return params[0]; } HiresScroll::WheelStatus HiresScroll::wheelMovementEvent(const hidpp::Report &report) { assert(report.function() == WheelMovement); WheelStatus status{}; status.hiRes = report.paramBegin()[0] & 1<<4; status.periods = report.paramBegin()[0] & 0x0F; status.deltaV = report.paramBegin()[1] << 8 | report.paramBegin()[2]; return status; } HiresScroll::RatchetState HiresScroll::ratchetSwitchEvent(const hidpp::Report &report) { assert(report.function() == WheelMovement); // Possible bad cast return static_cast(report.paramBegin()[0]); }logiops-0.2.2/src/logid/backend/hidpp20/features/HiresScroll.h000066400000000000000000000045261370476137700241570ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_HIRESSCROLL_H #define LOGID_BACKEND_HIDPP20_FEATURE_HIRESSCROLL_H #include "../Feature.h" #include "../feature_defs.h" namespace logid { namespace backend { namespace hidpp20 { class HiresScroll : public Feature { public: ///TODO: Hires scroll V1? static const uint16_t ID = FeatureID::HIRES_SCROLLING_V2; virtual uint16_t getID() { return ID; } enum Function : uint8_t { GetCapabilities = 0, GetMode = 1, SetMode = 2, GetRatchetState = 3 }; enum Event : uint8_t { WheelMovement = 0, RatchetSwitch = 1, }; enum Capability : uint8_t { Invertable = 1<<3, HasRatchet = 1<<2 }; enum Mode : uint8_t { Inverted = 1<<2, HiRes = 1<<1, Target = 1 }; enum RatchetState : uint8_t { FreeWheel = 0, Ratchet = 1 }; struct Capabilities { uint8_t multiplier; uint8_t flags; }; struct WheelStatus { bool hiRes; uint8_t periods; uint16_t deltaV; }; explicit HiresScroll(Device* device); Capabilities getCapabilities(); uint8_t getMode(); void setMode(uint8_t mode); bool getRatchetState(); static WheelStatus wheelMovementEvent(const hidpp::Report& report); static RatchetState ratchetSwitchEvent(const hidpp::Report& report); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_HIRESSCROLL_H logiops-0.2.2/src/logid/backend/hidpp20/features/ReprogControls.cpp000066400000000000000000000125021370476137700252340ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "../Error.h" #include "ReprogControls.h" using namespace logid::backend::hidpp20; #define DEFINE_REPROG(x, base) \ x::x(Device* dev) : base(dev, ID) \ { \ } \ x::x(Device* dev, uint16_t _id) : base(dev, _id) \ { \ } #define MAKE_REPROG(x, dev) \ try { \ return std::make_shared(dev); \ } catch(UnsupportedFeature &e) {\ } // Define all of the ReprogControls versions DEFINE_REPROG(ReprogControls, Feature) DEFINE_REPROG(ReprogControlsV2, ReprogControls) DEFINE_REPROG(ReprogControlsV2_2, ReprogControlsV2) DEFINE_REPROG(ReprogControlsV3, ReprogControlsV2_2) DEFINE_REPROG(ReprogControlsV4, ReprogControlsV3) std::shared_ptr ReprogControls::autoVersion(Device *dev) { MAKE_REPROG(ReprogControlsV4, dev) MAKE_REPROG(ReprogControlsV3, dev) MAKE_REPROG(ReprogControlsV2_2, dev) MAKE_REPROG(ReprogControlsV2, dev) // If base version cannot be made, throw error return std::make_shared(dev); } uint8_t ReprogControls::getControlCount() { std::vector params(0); auto response = callFunction(GetControlCount, params); return response[0]; } ReprogControls::ControlInfo ReprogControls::getControlInfo(uint8_t index) { std::vector params(1); ControlInfo info{}; params[0] = index; auto response = callFunction(GetControlInfo, params); info.controlID = response[1]; info.controlID |= response[0] << 8; info.taskID = response[3]; info.taskID |= response[2] << 8; info.flags = response[4]; info.position = response[5]; info.group = response[6]; info.groupMask = response[7]; info.additionalFlags = response[8]; return info; } void ReprogControls::initCidMap() { std::unique_lock lock(_cids_populating); if(_cids_initialized) return; uint8_t controls = getControlCount(); for(uint8_t i = 0; i < controls; i++) { auto info = getControlInfo(i); _cids.emplace(info.controlID, info); } _cids_initialized = true; } const std::map& ReprogControls::getControls() const { return _cids; } ReprogControls::ControlInfo ReprogControls::getControlIdInfo(uint16_t cid) { if(!_cids_initialized) initCidMap(); auto it = _cids.find(cid); if(it == _cids.end()) throw Error(Error::InvalidArgument); else return it->second; } ReprogControls::ControlInfo ReprogControls::getControlReporting(uint16_t cid) { // Emulate this function, only Reprog controls v4 supports this auto info = getControlIdInfo(cid); ControlInfo report{}; report.controlID = cid; report.flags = 0; if(info.flags & TemporaryDivertable) report.flags |= TemporaryDiverted; if(info.flags & PersisentlyDivertable) report.flags |= PersistentlyDiverted; if(info.additionalFlags & RawXY) report.flags |= RawXYDiverted; return report; } void ReprogControls::setControlReporting(uint8_t cid, ControlInfo info) { // This function does not exist pre-v4 and cannot be emulated, ignore. (void)cid; (void)info; // Suppress unused warnings } std::set ReprogControls::divertedButtonEvent( const hidpp::Report& report) { assert(report.function() == DivertedButtonEvent); std::set buttons; uint8_t cids = std::distance(report.paramBegin(), report.paramEnd())/2; for(uint8_t i = 0; i < cids; i++) { uint16_t cid = report.paramBegin()[2*i + 1]; cid |= report.paramBegin()[2*i] << 8; if(cid) buttons.insert(cid); else break; } return buttons; } ReprogControls::Move ReprogControls::divertedRawXYEvent(const hidpp::Report &report) { assert(report.function() == DivertedRawXYEvent); Move move{}; move.x = report.paramBegin()[1]; move.x |= report.paramBegin()[0] << 8; move.y = report.paramBegin()[3]; move.y |= report.paramBegin()[2] << 8; return move; } ReprogControls::ControlInfo ReprogControlsV4::getControlReporting(uint16_t cid) { std::vector params(2); ControlInfo info{}; params[0] = (cid >> 8) & 0xff; params[1] = cid & 0xff; auto response = callFunction(GetControlReporting, params); info.controlID = response[1]; info.controlID |= response[0] << 8; info.flags = response[2]; return info; } void ReprogControlsV4::setControlReporting(uint8_t cid, ControlInfo info) { std::vector params(5); params[0] = (cid >> 8) & 0xff; params[1] = cid & 0xff; params[2] = info.flags; params[3] = (info.controlID >> 8) & 0xff; params[4] = info.controlID & 0xff; callFunction(SetControlReporting, params); }logiops-0.2.2/src/logid/backend/hidpp20/features/ReprogControls.h000066400000000000000000000116621370476137700247070ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_REPROGCONTROLS_H #define LOGID_BACKEND_HIDPP20_FEATURE_REPROGCONTROLS_H #include #include "../feature_defs.h" #include "../Feature.h" namespace logid { namespace backend { namespace hidpp20 { class ReprogControls : public Feature { public: enum Function { GetControlCount = 0, GetControlInfo = 1, GetControlReporting = 2, SetControlReporting = 3 }; enum Event { DivertedButtonEvent = 0, DivertedRawXYEvent = 1 }; struct ControlInfo { uint16_t controlID; uint16_t taskID; uint8_t flags; uint8_t position; // F key position, 0 if not an Fx key uint8_t group; uint8_t groupMask; uint8_t additionalFlags; }; enum ControlInfoFlags: uint8_t { MouseButton = 1, //Mouse button FKey = 1<<1, //Fx key Hotkey = 1<<2, FnToggle = 1<<3, ReprogHint = 1<<4, TemporaryDivertable = 1<<5, PersisentlyDivertable = 1<<6, Virtual = 1<<7 }; enum ControlInfoAdditionalFlags: uint8_t { RawXY = 1<<0 }; enum ControlReportingFlags: uint8_t { TemporaryDiverted = 1<<0, ChangeTemporaryDivert = 1<<1, PersistentlyDiverted = 1<<2, ChangePersistentDivert = 1<<3, RawXYDiverted = 1<<4, ChangeRawXYDivert = 1<<5 }; struct Move { int16_t x; int16_t y; }; static const uint16_t ID = FeatureID::REPROG_CONTROLS; virtual uint16_t getID() { return ID; } virtual bool supportsRawXY() { return false; } explicit ReprogControls(Device* dev); virtual uint8_t getControlCount(); virtual ControlInfo getControlInfo(uint8_t cid); virtual ControlInfo getControlIdInfo(uint16_t cid); virtual void initCidMap(); const std::map& getControls() const; // Onlu controlId and flags will be set virtual ControlInfo getControlReporting(uint16_t cid); // Only controlId (for remap) and flags will be read virtual void setControlReporting(uint8_t cid, ControlInfo info); static std::set divertedButtonEvent(const hidpp::Report& report); static Move divertedRawXYEvent(const hidpp::Report& report); static std::shared_ptr autoVersion(Device *dev); protected: ReprogControls(Device* dev, uint16_t _id); std::map _cids; bool _cids_initialized = false; std::mutex _cids_populating; }; class ReprogControlsV2 : public ReprogControls { public: static const uint16_t ID = FeatureID::REPROG_CONTROLS_V2; virtual uint16_t getID() { return ID; } explicit ReprogControlsV2(Device* dev); protected: ReprogControlsV2(Device* dev, uint16_t _id); }; class ReprogControlsV2_2 : public ReprogControlsV2 { public: static const uint16_t ID = FeatureID::REPROG_CONTROLS_V2_2; virtual uint16_t getID() { return ID; } explicit ReprogControlsV2_2(Device* dev); protected: ReprogControlsV2_2(Device* dev, uint16_t _id); }; class ReprogControlsV3 : public ReprogControlsV2_2 { public: static const uint16_t ID = FeatureID::REPROG_CONTROLS_V3; virtual uint16_t getID() { return ID; } explicit ReprogControlsV3(Device* dev); protected: ReprogControlsV3(Device* dev, uint16_t _id); }; class ReprogControlsV4 : public ReprogControlsV3 { public: static const uint16_t ID = FeatureID::REPROG_CONTROLS_V4; virtual uint16_t getID() { return ID; } bool supportsRawXY() override { return true; } ControlInfo getControlReporting(uint16_t cid) override; void setControlReporting(uint8_t cid, ControlInfo info) override; explicit ReprogControlsV4(Device* dev); protected: ReprogControlsV4(Device* dev, uint16_t _id); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_REPROGCONTROLS_H logiops-0.2.2/src/logid/backend/hidpp20/features/Reset.cpp000066400000000000000000000022711370476137700233360ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "Reset.h" using namespace logid::backend::hidpp20; Reset::Reset(Device *device) : Feature(device, ID) { } uint16_t Reset::getProfile() { std::vector params(0); auto results = callFunction(GetProfile, params); uint16_t profile = results[1]; profile |= (results[0] << 8); return profile; } void Reset::reset(uint16_t profile) { std::vector params(2); params[0] = (profile >> 8) & 0xff; params[1] = profile & 0xff; callFunction(ResetToProfile, params); }logiops-0.2.2/src/logid/backend/hidpp20/features/Reset.h000066400000000000000000000024701370476137700230040ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_RESET_H #define LOGID_BACKEND_HIDPP20_FEATURE_RESET_H #include "../Feature.h" #include "../feature_defs.h" namespace logid { namespace backend { namespace hidpp20 { class Reset : public Feature { public: static const uint16_t ID = FeatureID::RESET; virtual uint16_t getID() { return ID; } enum Function : uint8_t { GetProfile = 0, ResetToProfile = 1 }; explicit Reset(Device* device); uint16_t getProfile(); void reset(uint16_t profile = 0); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_RESET_H logiops-0.2.2/src/logid/backend/hidpp20/features/Root.cpp000066400000000000000000000053351370476137700232030ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "Root.h" #include "../Error.h" using namespace logid::backend::hidpp20; Root::Root(Device* dev) : Feature(dev, ID) { } std::vector _genGetFeatureParams(uint16_t feature_id) { std::vector params(2); params[0] = feature_id & 0xff; params[1] = (feature_id >> 8) & 0xff; return params; } feature_info _genGetFeatureInfo(uint16_t feature_id, std::vector response) { feature_info info{}; info.feature_id = response[0]; if(!info.feature_id) throw UnsupportedFeature(feature_id); info.hidden = response[1] & Root::FeatureFlag::Hidden; info.obsolete = response[1] & Root::FeatureFlag::Obsolete; info.internal = response[1] & Root::FeatureFlag::Internal; return info; } feature_info Root::getFeature(uint16_t feature_id) { auto params = _genGetFeatureParams(feature_id); try { auto response = this->callFunction(Root::Function::GetFeature, params); return _genGetFeatureInfo(feature_id, response); } catch(Error& e) { if(e.code() == Error::InvalidFeatureIndex) throw UnsupportedFeature(feature_id); throw e; } } std::tuple Root::getVersion() { std::vector params(0); auto response = this->callFunction(Function::Ping, params); return std::make_tuple(response[0], response[1]); } EssentialRoot::EssentialRoot(hidpp::Device* dev) : EssentialFeature(dev, ID) { } feature_info EssentialRoot::getFeature(uint16_t feature_id) { auto params = _genGetFeatureParams(feature_id); try { auto response = this->callFunction(Root::Function::GetFeature, params); return _genGetFeatureInfo(feature_id, response); } catch(Error& e) { if(e.code() == Error::InvalidFeatureIndex) throw UnsupportedFeature(feature_id); throw e; } } std::tuple EssentialRoot::getVersion() { std::vector params(0); auto response = this->callFunction(Root::Function::Ping, params); return std::make_tuple(response[0], response[1]); }logiops-0.2.2/src/logid/backend/hidpp20/features/Root.h000066400000000000000000000035071370476137700226470ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_ROOT_H #define LOGID_BACKEND_HIDPP20_FEATURE_ROOT_H #include "../Feature.h" #include "../EssentialFeature.h" #include "../feature_defs.h" namespace logid { namespace backend { namespace hidpp20 { class Root : public Feature { public: static const uint16_t ID = FeatureID::ROOT; virtual uint16_t getID() { return ID; } enum Function : uint8_t { GetFeature = 0, Ping = 1 }; explicit Root(Device* device); feature_info getFeature (uint16_t feature_id); std::tuple getVersion(); enum FeatureFlag : uint8_t { Obsolete = 1<<7, Hidden = 1<<6, Internal = 1<<5 }; }; class EssentialRoot : public EssentialFeature { public: static const uint16_t ID = FeatureID::ROOT; virtual uint16_t getID() { return ID; } explicit EssentialRoot(hidpp::Device* device); feature_info getFeature(uint16_t feature_id); std::tuple getVersion(); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_ROOT_Hlogiops-0.2.2/src/logid/backend/hidpp20/features/SmartShift.cpp000066400000000000000000000027221370476137700243410ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "SmartShift.h" using namespace logid::backend::hidpp20; SmartShift::SmartShift(Device* dev) : Feature(dev, ID) { } SmartShift::SmartshiftStatus SmartShift::getStatus() { std::vector params(0); SmartshiftStatus status{}; auto response = callFunction(GetStatus, params); status.active = response[0]-1; status.autoDisengage = response[1]; status.defaultAutoDisengage = response[2]; return status; } void SmartShift::setStatus(SmartshiftStatus status) { std::vector params(3); if(status.setActive) params[0] = status.active + 1; if(status.setAutoDisengage) params[1] = status.autoDisengage; if(status.setDefaultAutoDisengage) params[2] = status.defaultAutoDisengage; callFunction(SetStatus, params); }logiops-0.2.2/src/logid/backend/hidpp20/features/SmartShift.h000066400000000000000000000030531370476137700240040ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_SMARTSHIFT_H #define LOGID_BACKEND_HIDPP20_FEATURE_SMARTSHIFT_H #include "../feature_defs.h" #include "../Feature.h" namespace logid { namespace backend { namespace hidpp20 { class SmartShift : public Feature { public: static const uint16_t ID = FeatureID::SMART_SHIFT; virtual uint16_t getID() { return ID; } enum Function { GetStatus = 0, SetStatus = 1 }; explicit SmartShift(Device* dev); struct SmartshiftStatus { bool active; uint8_t autoDisengage; uint8_t defaultAutoDisengage; bool setActive, setAutoDisengage, setDefaultAutoDisengage; }; SmartshiftStatus getStatus(); void setStatus(SmartshiftStatus status); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_SMARTSHIFT_H logiops-0.2.2/src/logid/backend/hidpp20/features/WirelessDeviceStatus.cpp000066400000000000000000000023051370476137700263730ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "WirelessDeviceStatus.h" using namespace logid::backend::hidpp20; WirelessDeviceStatus::WirelessDeviceStatus(Device* dev) : Feature(dev, ID) { } WirelessDeviceStatus::Status WirelessDeviceStatus::statusBroadcastEvent( const hidpp::Report &report) { assert(report.function() == StatusBroadcast); Status status = {}; auto params = report.paramBegin(); status.reconnection = params[0]; status.reconfNeeded = params[1]; status.powerSwitch = params[2]; return status; }logiops-0.2.2/src/logid/backend/hidpp20/features/WirelessDeviceStatus.h000066400000000000000000000027641370476137700260510ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_HIDPP20_FEATURE_WIRELESSDEVICESTATUS_H #define LOGID_BACKEND_HIDPP20_FEATURE_WIRELESSDEVICESTATUS_H #include "../Feature.h" #include "../feature_defs.h" namespace logid { namespace backend { namespace hidpp20 { class WirelessDeviceStatus : public Feature { public: static constexpr uint16_t ID = FeatureID::WIRELESS_DEVICE_STATUS; virtual uint16_t getID() { return ID; } WirelessDeviceStatus(Device* dev); enum Event : uint8_t { StatusBroadcast = 0 }; struct Status { bool reconnection; bool reconfNeeded; bool powerSwitch; }; static Status statusBroadcastEvent(const hidpp::Report &report); }; }}} #endif //LOGID_BACKEND_HIDPP20_FEATURE_WIRELESSDEVICESTATUS_H logiops-0.2.2/src/logid/backend/raw/000077500000000000000000000000001370476137700172535ustar00rootroot00000000000000logiops-0.2.2/src/logid/backend/raw/DeviceMonitor.cpp000066400000000000000000000136201370476137700225300ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "DeviceMonitor.h" #include "../../util/task.h" #include "../../util/log.h" #include "RawDevice.h" #include "../hidpp/Device.h" #include #include extern "C" { #include #include } using namespace logid::backend::raw; DeviceMonitor::DeviceMonitor() { if(-1 == pipe(_pipe)) throw std::system_error(errno, std::system_category(), "pipe creation failed"); _udev_context = udev_new(); if(!_udev_context) throw std::runtime_error("udev_new failed"); } DeviceMonitor::~DeviceMonitor() { this->stop(); udev_unref(_udev_context); for(int i : _pipe) close(i); } void DeviceMonitor::run() { int ret; std::lock_guard lock(_running); struct udev_monitor* monitor = udev_monitor_new_from_netlink(_udev_context, "udev"); if(!monitor) throw std::runtime_error("udev_monitor_new_from_netlink failed"); ret = udev_monitor_filter_add_match_subsystem_devtype(monitor, "hidraw", nullptr); if (0 != ret) throw std::system_error (-ret, std::system_category(), "udev_monitor_filter_add_match_subsystem_devtype"); ret = udev_monitor_enable_receiving(monitor); if(0 != ret) throw std::system_error(-ret, std::system_category(), "udev_moniotr_enable_receiving"); this->enumerate(); int fd = udev_monitor_get_fd(monitor); _run_monitor = true; while (_run_monitor) { fd_set fds; FD_ZERO(&fds); FD_SET(_pipe[0], &fds); FD_SET(fd, &fds); if (-1 == select (std::max (_pipe[0], fd)+1, &fds, nullptr, nullptr, nullptr)) { if (errno == EINTR) continue; throw std::system_error (errno, std::system_category(), "udev_monitor select"); } if (FD_ISSET(fd, &fds)) { struct udev_device *device = udev_monitor_receive_device(monitor); std::string action = udev_device_get_action(device); std::string devnode = udev_device_get_devnode(device); if (action == "add") task::spawn([this, name=devnode]() { // Wait for device to initialise std::this_thread::sleep_for(std::chrono::milliseconds(100)); auto supported_reports = backend::hidpp::getSupportedReports( RawDevice::getReportDescriptor(name)); if(supported_reports) this->addDevice(name); else logPrintf(DEBUG, "Unsupported device %s ignored", name.c_str()); }, [name=devnode](std::exception& e){ logPrintf(WARN, "Error adding device %s: %s", name.c_str(), e.what()); }); else if (action == "remove") task::spawn([this, name=devnode]() { this->removeDevice(name); }, [name=devnode](std::exception& e){ logPrintf(WARN, "Error removing device %s: %s", name.c_str(), e.what()); }); udev_device_unref (device); } if (FD_ISSET(_pipe[0], &fds)) { char c; if (-1 == read(_pipe[0], &c, sizeof (char))) throw std::system_error (errno, std::system_category(), "read pipe"); break; } } } void DeviceMonitor::stop() { _run_monitor = false; std::lock_guard lock(_running); } void DeviceMonitor::enumerate() { int ret; struct udev_enumerate* udev_enum = udev_enumerate_new(_udev_context); ret = udev_enumerate_add_match_subsystem(udev_enum, "hidraw"); if(0 != ret) throw std::system_error(-ret, std::system_category(), "udev_enumerate_add_match_subsystem"); ret = udev_enumerate_scan_devices(udev_enum); if(0 != ret) throw std::system_error(-ret, std::system_category(), "udev_enumerate_scan_devices"); struct udev_list_entry* udev_enum_entry; udev_list_entry_foreach(udev_enum_entry, udev_enumerate_get_list_entry(udev_enum)) { const char* name = udev_list_entry_get_name(udev_enum_entry); struct udev_device* device = udev_device_new_from_syspath(_udev_context, name); if(!device) throw std::runtime_error("udev_device_new_from_syspath failed"); std::string devnode = udev_device_get_devnode(device); udev_device_unref(device); task::spawn([this, name=devnode]() { auto supported_reports = backend::hidpp::getSupportedReports( RawDevice::getReportDescriptor(name)); if(supported_reports) this->addDevice(name); else logPrintf(DEBUG, "Unsupported device %s ignored", name.c_str()); }, [name=devnode](std::exception& e){ logPrintf(WARN, "Error adding device %s: %s", name.c_str(), e.what()); }); } udev_enumerate_unref(udev_enum); }logiops-0.2.2/src/logid/backend/raw/DeviceMonitor.h000066400000000000000000000025751370476137700222040ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_RAW_DEVICEMONITOR_H #define LOGID_BACKEND_RAW_DEVICEMONITOR_H #include #include #include extern "C" { #include } namespace logid { namespace backend { namespace raw { class DeviceMonitor { public: void enumerate(); void run(); void stop(); protected: DeviceMonitor(); ~DeviceMonitor(); virtual void addDevice(std::string device) = 0; virtual void removeDevice(std::string device) = 0; private: struct udev* _udev_context; int _pipe[2]; std::atomic _run_monitor; std::mutex _running; }; }}} #endif //LOGID_BACKEND_RAW_DEVICEMONITOR_Hlogiops-0.2.2/src/logid/backend/raw/RawDevice.cpp000066400000000000000000000342321370476137700216340ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "RawDevice.h" #include "../Error.h" #include "../hidpp/defs.h" #include "../dj/defs.h" #include "../../util/log.h" #include "../hidpp/Report.h" #include "../../Configuration.h" #include "../../util/thread.h" #include "../../util/task.h" #include "../../util/workqueue.h" #include #include #include #define MAX_DATA_LENGTH 32 extern "C" { #include #include #include #include #include } using namespace logid::backend::raw; using namespace logid::backend; using namespace std::chrono; bool RawDevice::supportedReport(uint8_t id, uint8_t length) { switch(id) { case hidpp::ReportType::Short: return length == (hidpp::ShortParamLength + hidpp::Report::HeaderLength); case hidpp::ReportType::Long: return length == (hidpp::LongParamLength + hidpp::Report::HeaderLength); case dj::ReportType::Short: return length == (dj::ShortParamLength + dj::HeaderLength); case dj::ReportType::Long: return length == (dj::LongParamLength + dj::HeaderLength); default: return false; } } RawDevice::RawDevice(std::string path) : _path (std::move(path)), _continue_listen (false), _continue_respond (false) { int ret; _fd = ::open(_path.c_str(), O_RDWR); if (_fd == -1) throw std::system_error(errno, std::system_category(), "RawDevice open failed"); hidraw_devinfo devinfo{}; if (-1 == ::ioctl(_fd, HIDIOCGRAWINFO, &devinfo)) { int err = errno; ::close(_fd); throw std::system_error(err, std::system_category(), "RawDevice HIDIOCGRAWINFO failed"); } _vid = devinfo.vendor; _pid = devinfo.product; char name_buf[256]; if (-1 == (ret = ::ioctl(_fd, HIDIOCGRAWNAME(sizeof(name_buf)), name_buf) )) { int err = errno; ::close(_fd); throw std::system_error(err, std::system_category(), "RawDevice HIDIOCGRAWNAME failed"); } _name.assign(name_buf, ret - 1); _rdesc = getReportDescriptor(_fd); if (-1 == ::pipe(_pipe)) { int err = errno; close(_fd); throw std::system_error(err, std::system_category(), "RawDevice pipe open failed"); } _continue_listen = false; } RawDevice::~RawDevice() { if(_fd != -1) { ::close(_fd); ::close(_pipe[0]); ::close(_pipe[1]); } } std::string RawDevice::hidrawPath() const { return _path; } std::string RawDevice::name() const { return _name; } uint16_t RawDevice::vendorId() const { return _vid; } uint16_t RawDevice::productId() const { return _pid; } std::vector RawDevice::getReportDescriptor(std::string path) { int fd = ::open(path.c_str(), O_RDWR); if (fd == -1) throw std::system_error(errno, std::system_category(), "open failed"); auto rdesc = getReportDescriptor(fd); ::close(fd); return rdesc; } std::vector RawDevice::getReportDescriptor(int fd) { hidraw_report_descriptor rdesc{}; if (-1 == ::ioctl(fd, HIDIOCGRDESCSIZE, &rdesc.size)) { int err = errno; ::close(fd); throw std::system_error(err, std::system_category(), "RawDevice HIDIOCGRDESCSIZE failed"); } if (-1 == ::ioctl(fd, HIDIOCGRDESC, &rdesc)) { int err = errno; ::close(fd); throw std::system_error(err, std::system_category(), "RawDevice HIDIOCGRDESC failed"); } return std::vector(rdesc.value, rdesc.value + rdesc.size); } std::vector RawDevice::reportDescriptor() const { return _rdesc; } std::vector RawDevice::sendReport(const std::vector& report) { /* If the listener will stop, handle I/O manually. * Otherwise, push to queue and wait for result. */ if(_continue_listen) { std::mutex send_report; std::unique_lock lock(send_report); std::condition_variable cv; bool top_of_queue = false; auto task = std::make_shared()>> ( [this, report, &cv, &top_of_queue] () { top_of_queue = true; cv.notify_all(); return this->_respondToReport(report); }); auto f = task->get_future(); _io_queue.push(task); interruptRead(false); // Alert listener to prioritise cv.wait(lock, [&top_of_queue]{ return top_of_queue; }); auto status = f.wait_for(global_config->ioTimeout()); if(status == std::future_status::timeout) { _continue_respond = false; interruptRead(); return f.get(); // Expecting an error, but it could work } return f.get(); } else { std::vector response; std::exception_ptr _exception; std::shared_ptr t = std::make_shared( [this, report, &response]() { response = _respondToReport(report); }, [&_exception](std::exception& e) { try { throw e; } catch(std::exception& e) { _exception = std::make_exception_ptr(e); } }); global_workqueue->queue(t); t->waitStart(); auto status = t->waitFor(global_config->ioTimeout()); if(_exception) std::rethrow_exception(_exception); if(status == std::future_status::timeout) { _continue_respond = false; interruptRead(); t->wait(); if(_exception) std::rethrow_exception(_exception); throw TimeoutError(); } else return response; } } // DJ commands are not systematically acknowledged, do not expect a result. void RawDevice::sendReportNoResponse(const std::vector& report) { /* If the listener will stop, handle I/O manually. * Otherwise, push to queue and wait for result. */ if(_continue_listen) { auto task = std::make_shared()>> ([this, report]() { this->_sendReport(report); return std::vector(); }); auto f = task->get_future(); _io_queue.push(task); f.get(); } else _sendReport(report); } std::vector RawDevice::_respondToReport (const std::vector& request) { _sendReport(request); _continue_respond = true; auto start_point = std::chrono::steady_clock::now(); while(_continue_respond) { std::vector response; auto current_point = std::chrono::steady_clock::now(); auto timeout = global_config->ioTimeout() - std::chrono::duration_cast (current_point - start_point); if(timeout.count() <= 0) throw TimeoutError(); _readReport(response, MAX_DATA_LENGTH, timeout); if(!_continue_respond) throw TimeoutError(); // All reports have the device index at byte 2 if(response[1] != request[1]) { if(_continue_listen) this->_handleEvent(response); continue; } if(hidpp::ReportType::Short == request[0] || hidpp::ReportType::Long == request[0]) { if(hidpp::ReportType::Short != response[0] && hidpp::ReportType::Long != response[0]) { if(_continue_listen) this->_handleEvent(response); continue; } // Error; leave to device to handle if(response[2] == 0x8f || response[2] == 0xff) return response; bool others_match = true; for(int i = 2; i < 4; i++) if(response[i] != request[i]) others_match = false; if(others_match) return response; } else if(dj::ReportType::Short == request[0] || dj::ReportType::Long == request[0]) { //Error; leave to device ot handle if(0x7f == response[2]) return response; else if(response[2] == request[2]) return response; } if(_continue_listen) this->_handleEvent(response); } return {}; } int RawDevice::_sendReport(const std::vector& report) { std::lock_guard lock(_dev_io); if(logid::global_loglevel <= LogLevel::RAWREPORT) { printf("[RAWREPORT] %s OUT: ", _path.c_str()); for(auto &i : report) printf("%02x ", i); printf("\n"); } assert(supportedReport(report[0], report.size())); int ret = ::write(_fd, report.data(), report.size()); if(ret == -1) { ///TODO: This seems like a hacky solution // Try again before failing ret = ::write(_fd, report.data(), report.size()); if(ret == -1) throw std::system_error(errno, std::system_category(), "_sendReport write failed"); } return ret; } int RawDevice::_readReport(std::vector &report, std::size_t maxDataLength) { return _readReport(report, maxDataLength, global_config->ioTimeout()); } int RawDevice::_readReport(std::vector &report, std::size_t maxDataLength, std::chrono::milliseconds timeout) { std::lock_guard lock(_dev_io); int ret; report.resize(maxDataLength); timeval timeout_tv{}; timeout_tv.tv_sec = duration_cast(global_config->ioTimeout()) .count(); timeout_tv.tv_usec = duration_cast( global_config->ioTimeout()).count() % duration_cast(seconds(1)).count(); auto timeout_ms = duration_cast(timeout).count(); fd_set fds; do { FD_ZERO(&fds); FD_SET(_fd, &fds); FD_SET(_pipe[0], &fds); ret = select(std::max(_fd, _pipe[0]) + 1, &fds, nullptr, nullptr, (timeout_ms > 0 ? nullptr : &timeout_tv)); } while(ret == -1 && errno == EINTR); if(ret == -1) throw std::system_error(errno, std::system_category(), "_readReport select failed"); if(FD_ISSET(_fd, &fds)) { ret = read(_fd, report.data(), report.size()); if(ret == -1) throw std::system_error(errno, std::system_category(), "_readReport read failed"); report.resize(ret); } if(FD_ISSET(_pipe[0], &fds)) { char c; ret = read(_pipe[0], &c, sizeof(char)); if(ret == -1) throw std::system_error(errno, std::system_category(), "_readReport read pipe failed"); } if(0 == ret) throw backend::TimeoutError(); if(logid::global_loglevel <= LogLevel::RAWREPORT) { printf("[RAWREPORT] %s IN: ", _path.c_str()); for(auto &i : report) printf("%02x ", i); printf("\n"); } return ret; } void RawDevice::interruptRead(bool wait_for_halt) { char c = 0; if(-1 == write(_pipe[1], &c, sizeof(char))) throw std::system_error(errno, std::system_category(), "interruptRead write pipe failed"); // Ensure I/O has halted if(wait_for_halt) std::lock_guard lock(_dev_io); } void RawDevice::listen() { std::lock_guard lock(_listening); _continue_listen = true; _listen_condition.notify_all(); while(_continue_listen) { while(!_io_queue.empty()) { auto task = _io_queue.front(); (*task)(); _io_queue.pop(); } std::vector report; _readReport(report, MAX_DATA_LENGTH); this->_handleEvent(report); } // Listener is stopped, handle I/O queue while(!_io_queue.empty()) { auto task = _io_queue.front(); (*task)(); _io_queue.pop(); } _continue_listen = false; } void RawDevice::listenAsync() { std::mutex listen_check; std::unique_lock check_lock(listen_check); thread::spawn({[this]() { listen(); }}); // Block until RawDevice is listening _listen_condition.wait(check_lock, [this](){ return (bool)_continue_listen; }); } void RawDevice::stopListener() { _continue_listen = false; interruptRead(); } void RawDevice::addEventHandler(const std::string& nickname, const std::shared_ptr& handler) { std::unique_lock lock(_event_handler_lock); assert(_event_handlers.find(nickname) == _event_handlers.end()); assert(handler); _event_handlers.emplace(nickname, handler); } void RawDevice::removeEventHandler(const std::string &nickname) { std::unique_lock lock(_event_handler_lock); _event_handlers.erase(nickname); } const std::map>& RawDevice::eventHandlers() { std::unique_lock lock(_event_handler_lock); return _event_handlers; } void RawDevice::_handleEvent(std::vector &report) { std::unique_lock lock(_event_handler_lock); for(auto& handler : _event_handlers) if(handler.second->condition(report)) handler.second->callback(report); } bool RawDevice::isListening() { bool ret = _listening.try_lock(); if(ret) _listening.unlock(); return !ret; } logiops-0.2.2/src/logid/backend/raw/RawDevice.h000066400000000000000000000063041370476137700213000ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_RAWDEVICE_H #define LOGID_BACKEND_RAWDEVICE_H #include #include #include #include #include #include #include #include "defs.h" #include "../../util/mutex_queue.h" namespace logid { namespace backend { namespace raw { class RawDevice { public: static bool supportedReport(uint8_t id, uint8_t length); explicit RawDevice(std::string path); ~RawDevice(); std::string hidrawPath() const; std::string name() const; uint16_t vendorId() const; uint16_t productId() const; static std::vector getReportDescriptor(std::string path); static std::vector getReportDescriptor(int fd); std::vector reportDescriptor() const; std::vector sendReport(const std::vector& report); void sendReportNoResponse(const std::vector& report); void interruptRead(bool wait_for_halt=true); void listen(); void listenAsync(); void stopListener(); bool isListening(); void addEventHandler(const std::string& nickname, const std::shared_ptr& handler); void removeEventHandler(const std::string& nickname); const std::map>& eventHandlers(); private: std::mutex _dev_io, _listening; std::string _path; int _fd; int _pipe[2]; uint16_t _vid; uint16_t _pid; std::string _name; std::vector _rdesc; std::atomic _continue_listen; std::atomic _continue_respond; std::condition_variable _listen_condition; std::map> _event_handlers; std::mutex _event_handler_lock; void _handleEvent(std::vector& report); /* These will only be used internally and processed with a queue */ int _sendReport(const std::vector& report); int _readReport(std::vector& report, std::size_t maxDataLength); int _readReport(std::vector& report, std::size_t maxDataLength, std::chrono::milliseconds timeout); std::vector _respondToReport(const std::vector& request); mutex_queue()>>> _io_queue; }; }}} #endif //LOGID_BACKEND_RAWDEVICE_Hlogiops-0.2.2/src/logid/backend/raw/defs.h000066400000000000000000000020631370476137700203460ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_BACKEND_RAW_DEFS_H #define LOGID_BACKEND_RAW_DEFS_H #include #include #include namespace logid { namespace backend { namespace raw { struct RawEventHandler { std::function& )> condition; std::function& )> callback; }; }}} #endif //LOGID_BACKEND_RAW_DEFS_Hlogiops-0.2.2/src/logid/features/000077500000000000000000000000001370476137700167115ustar00rootroot00000000000000logiops-0.2.2/src/logid/features/DPI.cpp000066400000000000000000000105251370476137700200340ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include "DPI.h" #include "../Device.h" #include "../util/log.h" using namespace logid::features; using namespace logid::backend; uint16_t getClosestDPI(hidpp20::AdjustableDPI::SensorDPIList& dpi_list, uint16_t dpi) { if(dpi_list.isRange) { const uint16_t min = *std::min_element(dpi_list.dpis.begin(), dpi_list.dpis.end()); const uint16_t max = *std::max_element(dpi_list.dpis.begin(), dpi_list.dpis.end()); if(!((dpi-min) % dpi_list.dpiStep) && dpi >= min && dpi <= max) return dpi; else if(dpi > max) return max; else if(dpi < min) return min; else return min + round((double)(dpi-min)/dpi_list.dpiStep)*dpi_list .dpiStep; } else { if(std::find(dpi_list.dpis.begin(), dpi_list.dpis.end(), dpi) != dpi_list.dpis.end()) return dpi; else { auto it = std::min_element(dpi_list.dpis.begin(), dpi_list.dpis .end(), [dpi](uint16_t a, uint16_t b) { return (dpi - a) < (dpi - b); }); if(it == dpi_list.dpis.end()) return 0; else return *it; } } } DPI::DPI(Device* device) : DeviceFeature(device), _config (device) { try { _adjustable_dpi = std::make_shared (&device->hidpp20()); } catch (hidpp20::UnsupportedFeature& e) { throw UnsupportedFeature(); } } void DPI::configure() { const uint8_t sensors = _adjustable_dpi->getSensorCount(); for(uint8_t i = 0; i < _config.getSensorCount(); i++) { hidpp20::AdjustableDPI::SensorDPIList dpi_list; if(_dpi_lists.size() <= i) { dpi_list = _adjustable_dpi->getSensorDPIList(i); _dpi_lists.push_back(dpi_list); } else { dpi_list = _dpi_lists[i]; } if(i < sensors) { auto dpi = _config.getDPI(i); if(dpi) { _adjustable_dpi->setSensorDPI(i, getClosestDPI(dpi_list, dpi)); } } } } void DPI::listen() { } uint16_t DPI::getDPI(uint8_t sensor) { return _adjustable_dpi->getSensorDPI(sensor); } void DPI::setDPI(uint16_t dpi, uint8_t sensor) { hidpp20::AdjustableDPI::SensorDPIList dpi_list; if(_dpi_lists.size() <= sensor) { dpi_list = _adjustable_dpi->getSensorDPIList(sensor); for(std::size_t i = _dpi_lists.size()-1; i <= sensor; i++) { _dpi_lists.push_back(_adjustable_dpi->getSensorDPIList(i)); } } dpi_list = _dpi_lists[sensor]; _adjustable_dpi->setSensorDPI(sensor, getClosestDPI(dpi_list, dpi)); } /* Some devices have multiple sensors, but an older config format * only supports a single DPI. The dpi setting can be an array or * an integer. */ DPI::Config::Config(Device *dev) : DeviceFeature::Config(dev) { try { auto& config_root = dev->config().getSetting("dpi"); if(config_root.isNumber()) { int dpi = config_root; _dpis.push_back(dpi); } else if(config_root.isArray()) { for(int i = 0; i < config_root.getLength(); i++) _dpis.push_back((int)config_root[i]); } else { logPrintf(WARN, "Line %d: dpi is improperly formatted", config_root.getSourceLine()); } } catch(libconfig::SettingNotFoundException& e) { // DPI not configured, use default } } uint8_t DPI::Config::getSensorCount() { return _dpis.size(); } uint16_t DPI::Config::getDPI(uint8_t sensor) { return _dpis[sensor]; } logiops-0.2.2/src/logid/features/DPI.h000066400000000000000000000031341370476137700174770ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_FEATURE_DPI_H #define LOGID_FEATURE_DPI_H #include "../backend/hidpp20/features/AdjustableDPI.h" #include "DeviceFeature.h" namespace logid { namespace features { class DPI : public DeviceFeature { public: explicit DPI(Device* dev); virtual void configure(); virtual void listen(); uint16_t getDPI(uint8_t sensor=0); void setDPI(uint16_t dpi, uint8_t sensor=0); class Config : public DeviceFeature::Config { public: explicit Config(Device* dev); uint16_t getDPI(uint8_t sensor); uint8_t getSensorCount(); protected: std::vector _dpis; }; private: Config _config; std::shared_ptr _adjustable_dpi; std::vector _dpi_lists; }; }} #endif //LOGID_FEATURE_DPI_H logiops-0.2.2/src/logid/features/DeviceFeature.h000066400000000000000000000030231370476137700215730ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_FEATURES_DEVICEFEATURE_H #define LOGID_FEATURES_DEVICEFEATURE_H #include namespace logid { class Device; namespace features { class UnsupportedFeature : public std::exception { public: UnsupportedFeature() = default; virtual const char* what() const noexcept { return "Unsupported feature"; } }; class DeviceFeature { public: explicit DeviceFeature(Device* dev) : _device (dev) { } virtual void configure() = 0; virtual void listen() = 0; class Config { public: explicit Config(Device* dev) : _device (dev) { } protected: Device* _device; }; protected: Device* _device; }; }} #endif //LOGID_FEATURES_DEVICEFEATURE_H logiops-0.2.2/src/logid/features/DeviceStatus.cpp000066400000000000000000000040311370476137700220160ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "DeviceStatus.h" #include "../util/task.h" #define EVENTHANDLER_NAME "devicestatus" using namespace logid::features; using namespace logid::backend; DeviceStatus::DeviceStatus(logid::Device *dev) : DeviceFeature(dev) { try { _wireless_device_status =std::make_shared< hidpp20::WirelessDeviceStatus>(&dev->hidpp20()); } catch(hidpp20::UnsupportedFeature& e) { throw UnsupportedFeature(); } } void DeviceStatus::configure() { // Do nothing } void DeviceStatus::listen() { if(_device->hidpp20().eventHandlers().find(EVENTHANDLER_NAME) == _device->hidpp20().eventHandlers().end()) { auto handler = std::make_shared(); handler->condition = [index=_wireless_device_status->featureIndex()]( const hidpp::Report& report)->bool { return report.feature() == index && report.function() == hidpp20::WirelessDeviceStatus::StatusBroadcast; }; handler->callback = [dev=this->_device]( const hidpp::Report& report)->void { auto event = hidpp20::WirelessDeviceStatus::statusBroadcastEvent( report); if(event.reconfNeeded) task::spawn([dev](){ dev->wakeup(); }); }; _device->hidpp20().addEventHandler(EVENTHANDLER_NAME, handler); } }logiops-0.2.2/src/logid/features/DeviceStatus.h000066400000000000000000000023521370476137700214670ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_FEATURE_DEVICESTATUS_H #define LOGID_FEATURE_DEVICESTATUS_H #include "DeviceFeature.h" #include "../Device.h" #include "../backend/hidpp20/features/WirelessDeviceStatus.h" namespace logid { namespace features { class DeviceStatus : public DeviceFeature { public: explicit DeviceStatus(Device* dev); virtual void configure(); virtual void listen(); private: std::shared_ptr _wireless_device_status; }; }} #endif //LOGID_FEATURE_DEVICESTATUS_H logiops-0.2.2/src/logid/features/HiresScroll.cpp000066400000000000000000000070741370476137700216560ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "HiresScroll.h" #include "../Device.h" using namespace logid::features; using namespace logid::backend; HiresScroll::HiresScroll(Device *dev) : DeviceFeature(dev), _config(dev) { try { _hires_scroll = std::make_shared(&dev->hidpp20()); } catch(hidpp20::UnsupportedFeature& e) { throw UnsupportedFeature(); } } void HiresScroll::configure() { auto mode = _hires_scroll->getMode(); mode &= ~_config.getMask(); mode |= (_config.getMode() & _config.getMask()); _hires_scroll->setMode(mode); } void HiresScroll::listen() { ///TODO: Map hires scroll events } uint8_t HiresScroll::getMode() { return _hires_scroll->getMode(); } void HiresScroll::setMode(uint8_t mode) { _hires_scroll->setMode(mode); } HiresScroll::Config::Config(Device *dev) : DeviceFeature::Config(dev) { try { auto& config_root = dev->config().getSetting("hiresscroll"); if(!config_root.isGroup()) { logPrintf(WARN, "Line %d: hiresscroll must be a group", config_root.getSourceLine()); return; } _mode = 0; _mask = 0; try { auto& hires = config_root.lookup("hires"); if(hires.getType() == libconfig::Setting::TypeBoolean) { _mask |= hidpp20::HiresScroll::Mode::HiRes; if(hires) _mode |= hidpp20::HiresScroll::Mode::HiRes; } else { logPrintf(WARN, "Line %d: hires must be a boolean", hires.getSourceLine()); } } catch(libconfig::SettingNotFoundException& e) { } try { auto& invert = config_root.lookup("invert"); if(invert.getType() == libconfig::Setting::TypeBoolean) { _mask |= hidpp20::HiresScroll::Mode::Inverted; if(invert) _mode |= hidpp20::HiresScroll::Mode::Inverted; } else { logPrintf(WARN, "Line %d: invert must be a boolean, ignoring.", invert.getSourceLine()); } } catch(libconfig::SettingNotFoundException& e) { } try { auto& target = config_root.lookup("target"); if(target.getType() == libconfig::Setting::TypeBoolean) { _mask |= hidpp20::HiresScroll::Mode::Target; if(target) _mode |= hidpp20::HiresScroll::Mode::Target; } else { logPrintf(WARN, "Line %d: target must be a boolean, ignoring.", target.getSourceLine()); } } catch(libconfig::SettingNotFoundException& e) { } } catch(libconfig::SettingNotFoundException& e) { // HiresScroll not configured, use default } } uint8_t HiresScroll::Config::getMode() const { return _mode; } uint8_t HiresScroll::Config::getMask() const { return _mask; }logiops-0.2.2/src/logid/features/HiresScroll.h000066400000000000000000000030201370476137700213060ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_FEATURE_HIRESSCROLL_H #define LOGID_FEATURE_HIRESSCROLL_H #include "../backend/hidpp20/features/HiresScroll.h" #include "DeviceFeature.h" namespace logid { namespace features { class HiresScroll : public DeviceFeature { public: explicit HiresScroll(Device* dev); virtual void configure(); virtual void listen(); uint8_t getMode(); void setMode(uint8_t mode); class Config : public DeviceFeature::Config { public: explicit Config(Device* dev); uint8_t getMode() const; uint8_t getMask() const; protected: uint8_t _mode; uint8_t _mask; }; private: std::shared_ptr _hires_scroll; Config _config; }; }} #endif //LOGID_FEATURE_HIRESSCROLL_H logiops-0.2.2/src/logid/features/RemapButton.cpp000066400000000000000000000164501370476137700216630ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "../Device.h" #include "RemapButton.h" #include "../backend/hidpp20/Error.h" using namespace logid::features; using namespace logid::backend; using namespace logid::actions; #define HIDPP20_REPROG_REBIND (hidpp20::ReprogControls::ChangeTemporaryDivert \ | hidpp20::ReprogControls::ChangeRawXYDivert) #define EVENTHANDLER_NAME "REMAP_BUTTON" RemapButton::RemapButton(Device *dev): DeviceFeature(dev), _config (dev) { try { _reprog_controls = hidpp20::ReprogControls::autoVersion( &dev->hidpp20()); } catch(hidpp20::UnsupportedFeature& e) { throw UnsupportedFeature(); } _reprog_controls->initCidMap(); if(global_loglevel <= DEBUG) { #define FLAG(x) control.second.flags & hidpp20::ReprogControls::x ? \ "YES" : "" #define ADDITIONAL_FLAG(x) control.second.additionalFlags & \ hidpp20::ReprogControls::x ? "YES" : "" // Print CIDs, originally by zv0n logPrintf(DEBUG, "%s:%d remappable buttons:", dev->hidpp20().devicePath().c_str(), dev->hidpp20().deviceIndex()); logPrintf(DEBUG, "CID | reprog? | fn key? | mouse key? | " "gesture support?"); for(const auto & control : _reprog_controls->getControls()) logPrintf(DEBUG, "0x%02x | %-7s | %-7s | %-10s | %s", control.first, FLAG(TemporaryDivertable), FLAG(FKey), FLAG(MouseButton), ADDITIONAL_FLAG(RawXY)); #undef FLAG } } RemapButton::~RemapButton() { _device->hidpp20().removeEventHandler(EVENTHANDLER_NAME); } void RemapButton::configure() { ///TODO: DJ reporting trickery if cannot be remapped for(const auto& i : _config.buttons()) { hidpp20::ReprogControls::ControlInfo info{}; try { info = _reprog_controls->getControlIdInfo(i.first); } catch(hidpp20::Error& e) { if(e.code() == hidpp20::Error::InvalidArgument) { logPrintf(WARN, "%s: CID 0x%02x does not exist.", _device->name().c_str(), i.first); continue; } throw e; } if((i.second->reprogFlags() & hidpp20::ReprogControls::RawXYDiverted) && (!_reprog_controls->supportsRawXY() || !(info.additionalFlags & hidpp20::ReprogControls::RawXY))) logPrintf(WARN, "%s: Cannot divert raw XY movements for CID " "0x%02x", _device->name().c_str(), i.first); hidpp20::ReprogControls::ControlInfo report{}; report.controlID = i.first; report.flags = HIDPP20_REPROG_REBIND; report.flags |= i.second->reprogFlags(); _reprog_controls->setControlReporting(i.first, report); } } void RemapButton::listen() { if(_device->hidpp20().eventHandlers().find(EVENTHANDLER_NAME) == _device->hidpp20().eventHandlers().end()) { auto handler = std::make_shared(); handler->condition = [index=_reprog_controls->featureIndex()] (hidpp::Report& report)->bool { return (report.feature() == index) && ((report.function() == hidpp20::ReprogControls::DivertedButtonEvent) || (report .function() == hidpp20::ReprogControls::DivertedRawXYEvent)); }; handler->callback = [this](hidpp::Report& report)->void { if(report.function() == hidpp20::ReprogControls::DivertedButtonEvent) this->_buttonEvent(_reprog_controls->divertedButtonEvent( report)); else { // RawXY auto divertedXY = _reprog_controls->divertedRawXYEvent(report); for(const auto& button : this->_config.buttons()) if(button.second->pressed()) button.second->move(divertedXY.x, divertedXY.y); } }; _device->hidpp20().addEventHandler(EVENTHANDLER_NAME, handler); } } void RemapButton::_buttonEvent(const std::set& new_state) { // Ensure I/O doesn't occur while updating button state std::lock_guard lock(_button_lock); // Press all added buttons for(const auto& i : new_state) { auto old_i = _pressed_buttons.find(i); if(old_i != _pressed_buttons.end()) { _pressed_buttons.erase(old_i); } else { auto action = _config.buttons().find(i); if(action != _config.buttons().end()) action->second->press(); } } // Release all removed buttons for(auto& i : _pressed_buttons) { auto action = _config.buttons().find(i); if(action != _config.buttons().end()) action->second->release(); } _pressed_buttons = new_state; } RemapButton::Config::Config(Device *dev) : DeviceFeature::Config(dev) { try { auto& config_root = dev->config().getSetting("buttons"); if(!config_root.isList()) { logPrintf(WARN, "Line %d: buttons must be a list.", config_root.getSourceLine()); return; } int button_count = config_root.getLength(); for(int i = 0; i < button_count; i++) _parseButton(config_root[i]); } catch(libconfig::SettingNotFoundException& e) { // buttons not configured, use default } } void RemapButton::Config::_parseButton(libconfig::Setting &setting) { if(!setting.isGroup()) { logPrintf(WARN, "Line %d: button must be an object, ignoring.", setting.getSourceLine()); return; } uint16_t cid; try { auto& cid_setting = setting.lookup("cid"); if(!cid_setting.isNumber()) { logPrintf(WARN, "Line %d: cid must be a number, ignoring.", cid_setting.getSourceLine()); return; } cid = (int)cid_setting; } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: cid is required, ignoring.", setting.getSourceLine()); return; } try { _buttons.emplace(cid, Action::makeAction(_device, setting.lookup("action"))); } catch(libconfig::SettingNotFoundException& e) { logPrintf(WARN, "Line %d: action is required, ignoring.", setting.getSourceLine()); } catch(InvalidAction& e) { logPrintf(WARN, "Line %d: %s is not a valid action, ignoring.", setting["action"].getSourceLine(), e.what()); } } const std::map>& RemapButton::Config::buttons() { return _buttons; }logiops-0.2.2/src/logid/features/RemapButton.h000066400000000000000000000034061370476137700213250ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_FEATURE_REMAPBUTTON_H #define LOGID_FEATURE_REMAPBUTTON_H #include "../backend/hidpp20/features/ReprogControls.h" #include "DeviceFeature.h" #include "../actions/Action.h" namespace logid { namespace features { class RemapButton : public DeviceFeature { public: explicit RemapButton(Device* dev); ~RemapButton(); virtual void configure(); virtual void listen(); class Config : public DeviceFeature::Config { public: explicit Config(Device* dev); const std::map>& buttons(); protected: void _parseButton(libconfig::Setting& setting); std::map> _buttons; }; private: void _buttonEvent(const std::set& new_state); Config _config; std::shared_ptr _reprog_controls; std::set _pressed_buttons; std::mutex _button_lock; }; }} #endif //LOGID_FEATURE_REMAPBUTTON_H logiops-0.2.2/src/logid/features/SmartShift.cpp000066400000000000000000000046221370476137700215050ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "SmartShift.h" #include "../Device.h" #include "../util/log.h" using namespace logid::features; using namespace logid::backend; SmartShift::SmartShift(Device* device) : DeviceFeature(device), _config (device) { try { _smartshift = std::make_shared(&device->hidpp20()); } catch (hidpp20::UnsupportedFeature& e) { throw UnsupportedFeature(); } } void SmartShift::configure() { _smartshift->setStatus(_config.getSettings()); } void SmartShift::listen() { } hidpp20::SmartShift::SmartshiftStatus SmartShift::getStatus() { return _smartshift->getStatus(); } void SmartShift::setStatus(backend::hidpp20::SmartShift::SmartshiftStatus status) { _smartshift->setStatus(status); } SmartShift::Config::Config(Device *dev) : DeviceFeature::Config(dev), _status() { try { auto& config_root = dev->config().getSetting("smartshift"); if(!config_root.isGroup()) { logPrintf(WARN, "Line %d: smartshift must be an object", config_root.getSourceLine()); return; } _status.setActive = config_root.lookupValue("on", _status.active); int tmp; _status.setAutoDisengage = config_root.lookupValue("threshold", tmp); if(_status.setAutoDisengage) _status.autoDisengage = tmp; _status.setDefaultAutoDisengage = config_root.lookupValue ("default_threshold", tmp); if(_status.setDefaultAutoDisengage) _status.defaultAutoDisengage = tmp; } catch(libconfig::SettingNotFoundException& e) { // SmartShift not configured, use default } } hidpp20::SmartShift::SmartshiftStatus SmartShift::Config::getSettings() { return _status; }logiops-0.2.2/src/logid/features/SmartShift.h000066400000000000000000000031511370476137700211460ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_FEATURE_SMARTSHIFT_H #define LOGID_FEATURE_SMARTSHIFT_H #include "../backend/hidpp20/features/SmartShift.h" #include "DeviceFeature.h" namespace logid { namespace features { class SmartShift : public DeviceFeature { public: explicit SmartShift(Device* dev); virtual void configure(); virtual void listen(); backend::hidpp20::SmartShift::SmartshiftStatus getStatus(); void setStatus(backend::hidpp20::SmartShift::SmartshiftStatus status); class Config : public DeviceFeature::Config { public: explicit Config(Device* dev); backend::hidpp20::SmartShift::SmartshiftStatus getSettings(); protected: backend::hidpp20::SmartShift::SmartshiftStatus _status; }; private: Config _config; std::shared_ptr _smartshift; }; }} #endif //LOGID_FEATURE_SMARTSHIFT_H logiops-0.2.2/src/logid/logid.cpp000066400000000000000000000135651370476137700167070ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include #include #include "util/log.h" #include "DeviceManager.h" #include "logid.h" #include "InputDevice.h" #include "util/workqueue.h" #define LOGID_VIRTUAL_INPUT_NAME "LogiOps Virtual Input" #define DEFAULT_CONFIG_FILE "/etc/logid.cfg" #ifndef LOGIOPS_VERSION #define LOGIOPS_VERSION "null" #warning Version is undefined! #endif using namespace logid; struct CmdlineOptions { std::string config_file = DEFAULT_CONFIG_FILE; }; LogLevel logid::global_loglevel = INFO; std::shared_ptr logid::global_config; std::unique_ptr logid::device_manager; std::unique_ptr logid::virtual_input; std::shared_ptr logid::global_workqueue; bool logid::kill_logid = false; std::mutex logid::device_manager_reload; enum class Option { None, Verbose, Config, Help, Version }; /* void logid::reload() { log_printf(INFO, "Reloading logid..."); finder_reloading.lock(); finder->stop(); Configuration* old_config = global_config; global_config = new Configuration(config_file.c_str()); delete(old_config); delete(finder); finder = new DeviceMonitor(); finder_reloading.unlock(); } */ void readCliOptions(const int argc, char** argv, CmdlineOptions& options) { for(int i = 1; i < argc; i++) { Option option = Option::None; if(argv[i][0] == '-') { // This argument is an option switch(argv[i][1]) { case '-': { // Full option name std::string op_str = argv[i]; if (op_str == "--verbose") option = Option::Verbose; if (op_str == "--config") option = Option::Config; if (op_str == "--help") option = Option::Help; if (op_str == "--version") option = Option::Version; break; } case 'v': // Verbosity option = Option::Verbose; break; case 'V': //Version option = Option::Version; break; case 'c': // Config file path option = Option::Config; break; case 'h': // Help option = Option::Help; break; default: logPrintf(WARN, "%s is not a valid option, ignoring.", argv[i]); } switch(option) { case Option::Verbose: { if (++i >= argc) { global_loglevel = DEBUG; // Assume debug verbosity break; } std::string loglevel = argv[i]; try { global_loglevel = toLogLevel(argv[i]); } catch (std::invalid_argument &e) { if (argv[i][0] == '-') { global_loglevel = DEBUG; // Assume debug verbosity i--; // Go back to last argument to continue loop. } else { logPrintf(WARN, e.what()); printf("Valid verbosity levels are: Debug, Info, " "Warn/Warning, or Error.\n"); exit(EXIT_FAILURE); } } break; } case Option::Config: { if (++i >= argc) { logPrintf(ERROR, "Config file is not specified."); exit(EXIT_FAILURE); } options.config_file = argv[i]; break; } case Option::Help: printf(R"(logid version %s Usage: %s [options] Possible options are: -v,--verbose [level] Set log level to debug/info/warn/error (leave blank for debug) -V,--version Print version number -c,--config [file path] Change config file from default at %s -h,--help Print this message. )", LOGIOPS_VERSION, argv[0], DEFAULT_CONFIG_FILE); exit(EXIT_SUCCESS); case Option::Version: printf("%s\n", LOGIOPS_VERSION); exit(EXIT_SUCCESS); case Option::None: break; } } } } int main(int argc, char** argv) { CmdlineOptions options{}; readCliOptions(argc, argv, options); // Read config try { global_config = std::make_shared(options.config_file); } catch (std::exception &e) { global_config = std::make_shared(); } global_workqueue = std::make_shared( global_config->workerCount()); //Create a virtual input device try { virtual_input = std::make_unique(LOGID_VIRTUAL_INPUT_NAME); } catch(std::system_error& e) { logPrintf(ERROR, "Could not create input device: %s", e.what()); return EXIT_FAILURE; } // Scan devices, create listeners, handlers, etc. device_manager = std::make_unique(); while(!kill_logid) { device_manager_reload.lock(); device_manager_reload.unlock(); device_manager->run(); } return EXIT_SUCCESS; } logiops-0.2.2/src/logid/logid.h000066400000000000000000000015751370476137700163520ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_LOGID_H #define LOGID_LOGID_H #include namespace logid { // void reload(); extern bool kill_logid; extern std::mutex device_manager_reload; } #endif //LOGID_LOGID_Hlogiops-0.2.2/src/logid/logid.service.cmake000066400000000000000000000003621370476137700206330ustar00rootroot00000000000000[Unit] Description=Logitech Configuration Daemon StartLimitIntervalSec=0 [Service] Type=simple ExecStart=${CMAKE_INSTALL_PREFIX}/bin/logid User=root ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target logiops-0.2.2/src/logid/util/000077500000000000000000000000001370476137700160505ustar00rootroot00000000000000logiops-0.2.2/src/logid/util/ExceptionHandler.cpp000066400000000000000000000030111370476137700220030ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "log.h" #include "ExceptionHandler.h" #include "../backend/hidpp10/Error.h" #include "../backend/hidpp20/Error.h" using namespace logid; void ExceptionHandler::Default(std::exception& error) { try { throw error; } catch(backend::hidpp10::Error& e) { logPrintf(WARN, "HID++ 1.0 error ignored on detached thread/task: %s", error.what()); } catch(backend::hidpp20::Error& e) { logPrintf(WARN, "HID++ 2.0 error ignored on detached thread/task: %s", error.what()); } catch(std::system_error& e) { logPrintf(WARN, "System error ignored on detached thread/task: %s", error.what()); } catch(std::exception& e) { logPrintf(WARN, "Error ignored on detached thread/task: %s", error.what()); } }logiops-0.2.2/src/logid/util/ExceptionHandler.h000066400000000000000000000016051370476137700214570ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_EXCEPTIONHANDLER_H #define LOGID_EXCEPTIONHANDLER_H #include namespace logid { namespace ExceptionHandler { void Default(std::exception& e); }} #endif //LOGID_EXCEPTIONHANDLER_H logiops-0.2.2/src/logid/util/log.cpp000066400000000000000000000036661370476137700173500ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include #include #include #include #include "log.h" using namespace logid; void logid::logPrintf(LogLevel level, const char* format, ...) { if(global_loglevel > level) return; va_list vargs; va_start(vargs, format); FILE* stream = stdout; if(level == ERROR || level == WARN) stream = stderr; fprintf(stream, "[%s] ", levelPrefix(level)); vfprintf(stream, format, vargs); fprintf(stream, "\n"); } const char* logid::levelPrefix(LogLevel level) { switch(level) { case RAWREPORT: return "RAWREPORT"; case DEBUG: return "DEBUG"; case INFO: return "INFO"; case WARN: return "WARN"; case ERROR: return "ERROR"; default: return "UNKNOWN"; } } LogLevel logid::toLogLevel(std::string s) { std::string original_str = s; std::transform(s.begin(), s.end(), s.begin(), ::tolower); if(s == "rawreport") return RAWREPORT; if(s == "debug") return DEBUG; if(s == "info") return INFO; if(s == "warn" || s == "warning") return WARN; if(s == "error") return ERROR; throw std::invalid_argument(original_str + " is an invalid log level."); }logiops-0.2.2/src/logid/util/log.h000066400000000000000000000020741370476137700170050ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_LOG_H #define LOGID_LOG_H #include namespace logid { enum LogLevel { RAWREPORT, DEBUG, INFO, WARN, ERROR }; extern LogLevel global_loglevel; void logPrintf(LogLevel level, const char *format, ...); const char *levelPrefix(LogLevel level); LogLevel toLogLevel(std::string s); } #endif //LOGID_LOG_H logiops-0.2.2/src/logid/util/mutex_queue.h000066400000000000000000000025541370476137700205750ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef MUTEX_QUEUE_H #define MUTEX_QUEUE_H #include #include template class mutex_queue { public: mutex_queue() = default; bool empty() { std::lock_guard lock(_mutex); return _queue.empty(); } data& front() { std::lock_guard lock(_mutex); return _queue.front(); } void push(const data& _data) { std::lock_guard lock(_mutex); _queue.push(_data); } void pop() { std::lock_guard lock(_mutex); _queue.pop(); } private: std::queue _queue; std::mutex _mutex; }; #endif //MUTEX_QUEUE_Hlogiops-0.2.2/src/logid/util/task.cpp000066400000000000000000000042741370476137700175250ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "task.h" #include "workqueue.h" using namespace logid; task::task(const std::function& function, const std::function& exception_handler) : _function (std::make_shared>(function)), _exception_handler (std::make_shared> (exception_handler)), _status (Waiting), _task_pkg ([this](){ try { (*_function)(); } catch(std::exception& e) { (*_exception_handler)(e); } }), _future (_task_pkg.get_future()) { } void task::run() { _status = Running; _status_cv.notify_all(); _task_pkg(); _status = Completed; _status_cv.notify_all(); } task::Status task::getStatus() { return _status; } void task::wait() { if(_future.valid()) _future.wait(); else { std::mutex wait_start; std::unique_lock lock(wait_start); _status_cv.wait(lock, [this](){ return _status == Completed; }); } } void task::waitStart() { std::mutex wait_start; std::unique_lock lock(wait_start); _status_cv.wait(lock, [this](){ return _status != Waiting; }); } std::future_status task::waitFor(std::chrono::milliseconds ms) { return _future.wait_for(ms); } void task::spawn(const std::function& function, const std::function& exception_handler) { auto t = std::make_shared(function, exception_handler); global_workqueue->queue(t); }logiops-0.2.2/src/logid/util/task.h000066400000000000000000000042341370476137700171660ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_TASK_H #define LOGID_TASK_H #include #include #include #include "ExceptionHandler.h" namespace logid { class task { public: enum Status { Waiting, Running, Completed }; explicit task(const std::function& function, const std::function& exception_handler={[](std::exception& e) {ExceptionHandler::Default(e);}}); Status getStatus(); void run(); // Runs synchronously void wait(); void waitStart(); std::future_status waitFor(std::chrono::milliseconds ms); /* This function spawns a new task into the least used worker queue * and forgets about it. */ static void spawn(const std::function& function, const std::function& exception_handler={[](std::exception& e) {ExceptionHandler::Default(e);}}); private: std::shared_ptr> _function; std::shared_ptr> _exception_handler; std::atomic _status; std::condition_variable _status_cv; std::packaged_task _task_pkg; std::future _future; }; } #endif //LOGID_TASK_H logiops-0.2.2/src/logid/util/thread.cpp000066400000000000000000000035551370476137700200330ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include "thread.h" using namespace logid; thread::thread(const std::function& function, const std::function& exception_handler) : _function (std::make_shared>(function)), _exception_handler (std::make_shared> (exception_handler)) { } thread::~thread() { if(_thread) if(_thread->joinable()) _thread->detach(); } void thread::spawn(const std::function& function, const std::function& exception_handler) { std::thread([function, exception_handler](){ thread t(function, exception_handler); t.runSync(); }).detach(); } void thread::run() { _thread = std::make_shared( [f=this->_function,eh=this->_exception_handler]() { try { (*f)(); } catch (std::exception& e) { (*eh)(e); } }); } void thread::wait() { if(_thread) if(_thread->joinable()) _thread->join(); } void thread::runSync() { try { (*_function)(); } catch(std::exception& e) { (*_exception_handler)(e); } }logiops-0.2.2/src/logid/util/thread.h000066400000000000000000000035021370476137700174700ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_THREAD_H #define LOGID_THREAD_H #include #include #include #include "ExceptionHandler.h" namespace logid { class thread { public: explicit thread(const std::function& function, const std::function& exception_handler={[](std::exception& e) {ExceptionHandler::Default(e);}}); ~thread(); /* This function spawns a new thread and forgets about it, * safe equivalent to std::thread{...}.detach() */ static void spawn(const std::function& function, const std::function& exception_handler={[](std::exception& e) {ExceptionHandler::Default(e);}}); void run(); void wait(); void runSync(); private: std::shared_ptr> _function; std::shared_ptr> _exception_handler; std::shared_ptr _thread = nullptr; }; } #endif //LOGID_THREAD_H logiops-0.2.2/src/logid/util/worker_thread.cpp000066400000000000000000000046551370476137700214260ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "worker_thread.h" #include "log.h" #include "workqueue.h" using namespace logid; worker_thread::worker_thread(workqueue* parent, std::size_t worker_number) : _parent (parent), _worker_number (worker_number), _continue_run (false), _thread (std::make_unique ([this](){ _run(); }, [this](std::exception& e){ _exception_handler(e); })) { _thread->run(); } worker_thread::~worker_thread() { _continue_run = false; _queue_cv.notify_all(); // Block until task is complete std::unique_lock lock(_busy); while(!_queue.empty()) { _parent->queue(_queue.front()); _queue.pop(); } } void worker_thread::queue(std::shared_ptr t) { _queue.push(t); _queue_cv.notify_all(); } bool worker_thread::busy() { bool not_busy = _busy.try_lock(); if(not_busy) _busy.unlock(); return !not_busy; } void worker_thread::_run() { std::unique_lock lock(_run_lock); _continue_run = true; while(_continue_run) { _parent->busyUpdate(); _queue_cv.wait(lock, [this]{ return !_queue.empty() || !_continue_run; }); if(!_continue_run) return; std::unique_lock busy_lock(_busy); while(!_queue.empty()) { _queue.front()->run(); _queue.pop(); } } } void worker_thread::_exception_handler(std::exception &e) { logPrintf(WARN, "Exception caught on worker thread %d, restarting: %s", _worker_number, e.what()); // This action destroys the logid::thread, std::thread should detach safely. _thread = std::make_unique([this](){ _run(); }, [this](std::exception& e) { _exception_handler(e); }); _thread->run(); }logiops-0.2.2/src/logid/util/worker_thread.h000066400000000000000000000027171370476137700210700ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_WORKER_THREAD_H #define LOGID_WORKER_THREAD_H #include "mutex_queue.h" #include "task.h" #include "thread.h" namespace logid { class workqueue; class worker_thread { public: worker_thread(workqueue* parent, std::size_t worker_number); ~worker_thread(); void queue(std::shared_ptr t); bool busy(); private: void _run(); void _exception_handler(std::exception& e); workqueue* _parent; std::size_t _worker_number; std::mutex _run_lock; std::atomic _continue_run; std::condition_variable _queue_cv; std::unique_ptr _thread; std::mutex _busy; mutex_queue> _queue; }; } #endif //LOGID_WORKER_THREAD_H logiops-0.2.2/src/logid/util/workqueue.cpp000066400000000000000000000077151370476137700206150ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #include #include "workqueue.h" #include "log.h" using namespace logid; workqueue::workqueue(std::size_t thread_count) : _manager_thread ( std::make_unique( [this](){ _run(); } , [this](std::exception& e){ _exception_handler(e); } )), _continue_run (false), _worker_count (thread_count) { _workers.reserve(_worker_count); for(std::size_t i = 0; i < _worker_count; i++) _workers.push_back(std::make_unique(this, i)); _manager_thread->run(); } workqueue::~workqueue() { stop(); while(_workers.empty()) _workers.pop_back(); // Queue should have been empty before, but just confirm here. while(!_queue.empty()) { thread::spawn([t=_queue.front()](){ t->run(); }); _queue.pop(); } } void workqueue::queue(std::shared_ptr t) { assert(t != nullptr); _queue.push(t); _queue_cv.notify_all(); } void workqueue::busyUpdate() { _busy_cv.notify_all(); } void workqueue::stop() { _continue_run = false; std::unique_lock lock(_run_lock); } std::size_t workqueue::threadCount() const { return _workers.size(); } void workqueue::_run() { using namespace std::chrono_literals; std::unique_lock lock(_run_lock); _continue_run = true; while(_continue_run) { _queue_cv.wait(lock, [this]{ return !(_queue.empty()); }); while(!_queue.empty()) { if(_workers.empty()) { if(_worker_count) logPrintf(DEBUG, "No workers were found, running task in" " a new thread."); thread::spawn([t=_queue.front()](){ t->run(); }); _queue.pop(); continue; } auto worker = _workers.begin(); for(; worker != _workers.end(); worker++) { if(!(*worker)->busy()) break; } if(worker != _workers.end()) (*worker)->queue(_queue.front()); else { _busy_cv.wait_for(lock, 500ms, [this, &worker]{ for(worker = _workers.begin(); worker != _workers.end(); worker++) { if (!(*worker)->busy()) { return true; } } return false; }); if(worker != _workers.end()) (*worker)->queue(_queue.front()); else{ // Workers busy, launch in new thread logPrintf(DEBUG, "All workers were busy for 500ms, " "running task in new thread."); thread::spawn([t = _queue.front()]() { t->run(); }); } } _queue.pop(); } } } void workqueue::_exception_handler(std::exception &e) { logPrintf(WARN, "Exception caught on workqueue manager thread, " "restarting: %s" , e.what()); // This action destroys the logid::thread, std::thread should detach safely. _manager_thread = std::make_unique([this](){ _run(); }, [this](std::exception& e) { _exception_handler(e); }); _manager_thread->run(); }logiops-0.2.2/src/logid/util/workqueue.h000066400000000000000000000030751370476137700202550ustar00rootroot00000000000000/* * Copyright 2019-2020 PixlOne * * 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 . * */ #ifndef LOGID_WORKQUEUE_H #define LOGID_WORKQUEUE_H #include "worker_thread.h" #include "thread.h" namespace logid { class workqueue { public: explicit workqueue(std::size_t thread_count); ~workqueue(); void queue(std::shared_ptr t); void busyUpdate(); void stop(); std::size_t threadCount() const; private: void _run(); void _exception_handler(std::exception& e); std::unique_ptr _manager_thread; mutex_queue> _queue; std::condition_variable _queue_cv; std::condition_variable _busy_cv; std::mutex _run_lock; std::atomic _continue_run; std::vector> _workers; std::size_t _worker_count; }; extern std::shared_ptr global_workqueue; } #endif //LOGID_WORKQUEUE_H logiops-0.2.2/version.txt000066400000000000000000000000051370476137700154270ustar00rootroot00000000000000v0.2