├── LICENSE ├── examples ├── async │ ├── joystick_example.py │ ├── keyboard_example.py │ └── mouse_example.py ├── simple │ ├── joystick_example.py │ ├── keyboard_example.py │ └── mouse_example.py └── tinypico │ ├── tinypico_dpad.py │ ├── tinypico_touchpad.py │ ├── tinypico_trackball.py │ └── trackball.py ├── hid_services.py ├── package.json └── readme.md /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /examples/async/joystick_example.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | # Implements a BLE HID joystick 19 | import uasyncio as asyncio 20 | from machine import SoftSPI, Pin 21 | from hid_services import Joystick 22 | 23 | class Device: 24 | def __init__(self, name="Joystick"): 25 | # Define state 26 | self.axes = (0, 0) 27 | self.updated = False 28 | self.active = True 29 | 30 | # Define buttons 31 | self.pin_forward = Pin(23, Pin.IN) 32 | self.pin_reverse = Pin(19, Pin.IN) 33 | self.pin_left = Pin(18, Pin.IN) 34 | self.pin_right = Pin(5, Pin.IN) 35 | 36 | # Create our device 37 | self.joystick = Joystick(name) 38 | # Set a callback function to catch changes of device state 39 | self.joystick.set_state_change_callback(self.joystick_state_callback) 40 | 41 | # Function that catches device status events 42 | def joystick_state_callback(self): 43 | if self.joystick.get_state() is Joystick.DEVICE_IDLE: 44 | return 45 | elif self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 46 | return 47 | elif self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 48 | return 49 | else: 50 | return 51 | 52 | def advertise(self): 53 | self.joystick.start_advertising() 54 | 55 | def stop_advertise(self): 56 | self.joystick.stop_advertising() 57 | 58 | async def advertise_for(self, seconds=30): 59 | self.advertise() 60 | 61 | while seconds > 0 and self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 62 | await asyncio.sleep(1) 63 | seconds -= 1 64 | 65 | if self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 66 | self.stop_advertise() 67 | 68 | # Input loop 69 | async def gather_input(self): 70 | while self.active: 71 | prevaxes = self.axes 72 | self.axes = (self.pin_right.value() * 127 - self.pin_left.value() * 127, self.pin_forward.value() * 127 - self.pin_reverse.value() * 127) 73 | self.updated = self.updated or not (prevaxes == self.axes) # If updated is still True, we haven't notified yet 74 | await asyncio.sleep_ms(50) 75 | 76 | # Bluetooth device loop 77 | async def notify(self): 78 | while self.active: 79 | # If connected, set axes and notify 80 | # If idle, start advertising for 30s or until connected 81 | if self.updated: 82 | if self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 83 | self.joystick.set_axes(self.axes[0], self.axes[1]) 84 | self.joystick.notify_hid_report() 85 | elif self.joystick.get_state() is Joystick.DEVICE_IDLE: 86 | await self.advertise_for(30) 87 | self.updated = False 88 | 89 | if self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 90 | await asyncio.sleep_ms(50) 91 | else: 92 | await asyncio.sleep(2) 93 | 94 | async def co_start(self): 95 | # Start our device 96 | if self.joystick.get_state() is Joystick.DEVICE_STOPPED: 97 | self.joystick.start() 98 | self.active = True 99 | await asyncio.gather(self.advertise_for(30), self.gather_input(), self.notify()) 100 | 101 | async def co_stop(self): 102 | self.active = False 103 | self.joystick.stop() 104 | 105 | def start(self): 106 | asyncio.run(self.co_start()) 107 | 108 | def stop(self): 109 | asyncio.run(self.co_stop()) 110 | 111 | # Test routine 112 | async def test(self): 113 | while not self.joystick.is_connected(): 114 | await asyncio.sleep(5) 115 | 116 | await asyncio.sleep(5) 117 | self.joystick.set_battery_level(50) 118 | self.joystick.notify_battery_level() 119 | await asyncio.sleep_ms(500) 120 | 121 | for i in range(30): 122 | self.joystick.set_axes(100,100) 123 | self.joystick.set_buttons(1) 124 | self.joystick.notify_hid_report() 125 | await asyncio.sleep_ms(500) 126 | 127 | self.joystick.set_axes(100,-100) 128 | self.joystick.set_buttons(b3=1) 129 | self.joystick.notify_hid_report() 130 | await asyncio.sleep_ms(500) 131 | 132 | self.joystick.set_axes(-100,-100) 133 | self.joystick.set_buttons() 134 | self.joystick.notify_hid_report() 135 | await asyncio.sleep_ms(500) 136 | 137 | self.joystick.set_axes(-100,100) 138 | self.joystick.set_buttons(b2=1) 139 | self.joystick.notify_hid_report() 140 | await asyncio.sleep_ms(500) 141 | 142 | self.joystick.set_axes(0,0) 143 | self.joystick.set_buttons() 144 | self.joystick.notify_hid_report() 145 | await asyncio.sleep_ms(500) 146 | 147 | self.joystick.set_battery_level(100) 148 | self.joystick.notify_battery_level() 149 | 150 | async def co_start_test(self): 151 | self.joystick.start() 152 | await asyncio.gather(self.advertise_for(30), self.test()) 153 | 154 | # start test 155 | def start_test(self): 156 | asyncio.run(self.co_start_test()) 157 | 158 | if __name__ == "__main__": 159 | d = Device() 160 | d.start() 161 | -------------------------------------------------------------------------------- /examples/async/keyboard_example.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | # Implements a BLE HID keyboard 19 | import uasyncio as asyncio 20 | from machine import SoftSPI, Pin 21 | from hid_services import Keyboard 22 | 23 | class Device: 24 | def __init__(self, name="Keyboard"): 25 | # Define state 26 | self.keys = [] 27 | self.updated = False 28 | self.active = True 29 | 30 | # Define buttons 31 | self.pin_w = Pin(5, Pin.IN) 32 | self.pin_s = Pin(23, Pin.IN) 33 | self.pin_d = Pin(19, Pin.IN) 34 | self.pin_a = Pin(18, Pin.IN) 35 | 36 | # Create our device 37 | self.keyboard = Keyboard(name) 38 | # Set a callback function to catch changes of device state 39 | self.keyboard.set_state_change_callback(self.keyboard_state_callback) 40 | 41 | # Function that catches device status events 42 | def keyboard_state_callback(self): 43 | if self.keyboard.get_state() is Keyboard.DEVICE_IDLE: 44 | return 45 | elif self.keyboard.get_state() is Keyboard.DEVICE_ADVERTISING: 46 | return 47 | elif self.keyboard.get_state() is Keyboard.DEVICE_CONNECTED: 48 | return 49 | else: 50 | return 51 | 52 | def keyboard_event_callback(self, bytes): 53 | print("Keyboard state callback with bytes: ", bytes) 54 | 55 | def advertise(self): 56 | self.keyboard.start_advertising() 57 | 58 | def stop_advertise(self): 59 | self.keyboard.stop_advertising() 60 | 61 | async def advertise_for(self, seconds=30): 62 | self.advertise() 63 | 64 | while seconds > 0 and self.keyboard.get_state() is Keyboard.DEVICE_ADVERTISING: 65 | await asyncio.sleep(1) 66 | seconds -= 1 67 | 68 | if self.keyboard.get_state() is Keyboard.DEVICE_ADVERTISING: 69 | self.stop_advertise() 70 | 71 | # Input loop 72 | async def gather_input(self): 73 | while self.active: 74 | prevkeys = self.keys 75 | self.keys.clear() 76 | 77 | # Read pin values and update variables 78 | if self.pin_w.value(): 79 | self.keys.append(0x1A) # W 80 | else: 81 | self.keys.append(0x00) 82 | 83 | if self.pin_a.value(): 84 | self.keys.append(0x04) # A 85 | else: 86 | self.keys.append(0x00) 87 | 88 | if self.pin_s.value(): 89 | self.keys.append(0x16) # S 90 | else: 91 | self.keys.append(0x00) 92 | 93 | if self.pin_d.value(): 94 | self.keys.append(0x07) # D 95 | else: 96 | self.keys.append(0x00) 97 | 98 | self.updated = self.updated or not (prevkeys == self.keys) # If updated is still True, we haven't notified yet 99 | await asyncio.sleep_ms(50) 100 | 101 | # Bluetooth device loop 102 | async def notify(self): 103 | while self.active: 104 | # If the variables changed do something depending on the device state 105 | if self.updated: 106 | # If connected, set keys and notify 107 | # If idle, start advertising for 30s or until connected 108 | if self.keyboard.get_state() is Keyboard.DEVICE_CONNECTED: 109 | self.keyboard.set_keys(self.keys[0], self.keys[1], self.keys[2], self.keys[3]) 110 | self.keyboard.notify_hid_report() 111 | elif self.keyboard.get_state() is Keyboard.DEVICE_IDLE: 112 | await self.advertise_for(30) 113 | self.updated = False 114 | 115 | if self.keyboard.get_state() is Keyboard.DEVICE_CONNECTED: 116 | await asyncio.sleep_ms(50) 117 | else: 118 | await asyncio.sleep(2) 119 | 120 | async def co_start(self): 121 | # Start our device 122 | if self.keyboard.get_state() is Keyboard.DEVICE_STOPPED: 123 | self.keyboard.start() 124 | self.active = True 125 | await asyncio.gather(self.advertise_for(30), self.gather_input(), self.notify()) 126 | 127 | async def co_stop(self): 128 | self.active = False 129 | self.keyboard.stop() 130 | 131 | def start(self): 132 | asyncio.run(self.co_start()) 133 | 134 | def stop(self): 135 | asyncio.run(self.co_stop()) 136 | 137 | # Used with test 138 | def send_char(self, char): 139 | if char == " ": 140 | mod = 0 141 | code = 0x2C 142 | elif ord("a") <= ord(char) <= ord("z"): 143 | mod = 0 144 | code = 0x04 + ord(char) - ord("a") 145 | elif ord("A") <= ord(char) <= ord("Z"): 146 | mod = 1 147 | code = 0x04 + ord(char) - ord("A") 148 | else: 149 | assert 0 150 | 151 | self.keyboard.set_keys(code) 152 | self.keyboard.set_modifiers(left_shift=mod) 153 | self.keyboard.notify_hid_report() 154 | asyncio.sleep_ms(2) 155 | 156 | self.keyboard.set_keys() 157 | self.keyboard.set_modifiers() 158 | self.keyboard.notify_hid_report() 159 | asyncio.sleep_ms(2) 160 | 161 | # Used with test 162 | def send_string(self, st): 163 | for c in st: 164 | self.send_char(c) 165 | 166 | # Test routine 167 | async def test(self): 168 | while not self.keyboard.is_connected(): 169 | await asyncio.sleep(5) 170 | 171 | await asyncio.sleep(5) 172 | self.keyboard.set_battery_level(50) 173 | self.keyboard.notify_battery_level() 174 | await asyncio.sleep_ms(500) 175 | 176 | # Press Shift+W 177 | self.keyboard.set_keys(0x1A) 178 | self.keyboard.set_modifiers(right_shift=1) 179 | self.keyboard.notify_hid_report() 180 | await asyncio.sleep_ms(2) 181 | 182 | # release 183 | self.keyboard.set_keys() 184 | self.keyboard.set_modifiers() 185 | self.keyboard.notify_hid_report() 186 | await asyncio.sleep_ms(500) 187 | 188 | # Press a 189 | self.keyboard.set_keys(0x04) 190 | self.keyboard.notify_hid_report() 191 | await asyncio.sleep_ms(2) 192 | 193 | # release 194 | self.keyboard.set_keys() 195 | self.keyboard.notify_hid_report() 196 | await asyncio.sleep_ms(500) 197 | 198 | # Press s 199 | self.keyboard.set_keys(0x16) 200 | self.keyboard.notify_hid_report() 201 | await asyncio.sleep_ms(2) 202 | 203 | # release 204 | self.keyboard.set_keys() 205 | self.keyboard.notify_hid_report() 206 | await asyncio.sleep_ms(500) 207 | 208 | # Press d 209 | self.keyboard.set_keys(0x07) 210 | self.keyboard.notify_hid_report() 211 | await asyncio.sleep_ms(2) 212 | 213 | # release 214 | self.keyboard.set_keys() 215 | self.keyboard.notify_hid_report() 216 | await asyncio.sleep_ms(500) 217 | 218 | self.send_string(" Hello World") 219 | await asyncio.sleep_ms(500) 220 | 221 | self.keyboard.set_battery_level(100) 222 | self.keyboard.notify_battery_level() 223 | 224 | async def co_start_test(self): 225 | self.keyboard.start() 226 | await asyncio.gather(self.advertise_for(30), self.test()) 227 | 228 | # start test 229 | def start_test(self): 230 | asyncio.run(self.co_start_test()) 231 | 232 | if __name__ == "__main__": 233 | d = Device() 234 | d.start() 235 | -------------------------------------------------------------------------------- /examples/async/mouse_example.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | # Implements a BLE HID mouse 19 | import uasyncio as asyncio 20 | from machine import SoftSPI, Pin 21 | from hid_services import Mouse 22 | 23 | class Device: 24 | def __init__(self, name="Mouse"): 25 | # Define state 26 | self.axes = (0, 0) 27 | self.updated = False 28 | self.active = True 29 | 30 | # Define buttons 31 | self.pin_forward = Pin(5, Pin.IN) 32 | self.pin_reverse = Pin(23, Pin.IN) 33 | self.pin_right = Pin(19, Pin.IN) 34 | self.pin_left = Pin(18, Pin.IN) 35 | 36 | # Create our device 37 | self.mouse = Mouse(name) 38 | # Set a callback function to catch changes of device state 39 | self.mouse.set_state_change_callback(self.mouse_state_callback) 40 | 41 | # Function that catches device status events 42 | def mouse_state_callback(self): 43 | if self.mouse.get_state() is Mouse.DEVICE_IDLE: 44 | return 45 | elif self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 46 | return 47 | elif self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 48 | return 49 | else: 50 | return 51 | 52 | def advertise(self): 53 | self.mouse.start_advertising() 54 | 55 | def stop_advertise(self): 56 | self.mouse.stop_advertising() 57 | 58 | async def advertise_for(self, seconds=30): 59 | self.advertise() 60 | 61 | while seconds > 0 and self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 62 | await asyncio.sleep(1) 63 | seconds -= 1 64 | 65 | if self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 66 | self.stop_advertise() 67 | 68 | # Input loop 69 | async def gather_input(self): 70 | while self.active: 71 | prevaxes = self.axes 72 | self.axes = (self.pin_right.value() * 127 - self.pin_left.value() * 127, self.pin_forward.value() * 127 - self.pin_reverse.value() * 127) 73 | self.updated = self.updated or not (prevaxes == self.axes) # If updated is still True, we haven't notified yet 74 | await asyncio.sleep_ms(50) 75 | 76 | # Bluetooth device loop 77 | async def notify(self): 78 | while self.active: 79 | # If connected, set axes and notify 80 | # If idle, start advertising for 30s or until connected 81 | if self.updated: 82 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 83 | self.mouse.set_axes(self.axes[0], self.axes[1]) 84 | self.mouse.notify_hid_report() 85 | elif self.mouse.get_state() is Mouse.DEVICE_IDLE: 86 | await self.advertise_for(30) 87 | self.updated = False 88 | 89 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 90 | await asyncio.sleep_ms(50) 91 | else: 92 | await asyncio.sleep(2) 93 | 94 | async def co_start(self): 95 | # Start our device 96 | if self.mouse.get_state() is Mouse.DEVICE_STOPPED: 97 | self.mouse.start() 98 | self.active = True 99 | await asyncio.gather(self.advertise_for(30), self.gather_input(), self.notify()) 100 | 101 | async def co_stop(self): 102 | self.active = False 103 | self.mouse.stop() 104 | 105 | def start(self): 106 | asyncio.run(self.co_start()) 107 | 108 | def stop(self): 109 | asyncio.run(self.co_stop()) 110 | 111 | # Test routine 112 | async def test(self): 113 | while not self.mouse.is_connected(): 114 | await asyncio.sleep(5) 115 | 116 | await asyncio.sleep(5) 117 | self.mouse.set_battery_level(50) 118 | self.mouse.notify_battery_level() 119 | await asyncio.sleep_ms(500) 120 | 121 | for i in range(30): 122 | self.mouse.set_axes(100,100) 123 | self.mouse.set_buttons(1) 124 | self.mouse.notify_hid_report() 125 | await asyncio.sleep_ms(500) 126 | 127 | self.mouse.set_axes(100,-100) 128 | self.mouse.set_buttons() 129 | self.mouse.notify_hid_report() 130 | await asyncio.sleep_ms(500) 131 | 132 | self.mouse.set_axes(-100,-100) 133 | self.mouse.set_buttons(b2=1) 134 | self.mouse.notify_hid_report() 135 | await asyncio.sleep_ms(500) 136 | 137 | self.mouse.set_axes(-100,100) 138 | self.mouse.set_buttons() 139 | self.mouse.notify_hid_report() 140 | await asyncio.sleep_ms(500) 141 | 142 | self.mouse.set_axes(0,0) 143 | self.mouse.set_buttons() 144 | self.mouse.notify_hid_report() 145 | await asyncio.sleep_ms(500) 146 | 147 | self.mouse.set_battery_level(100) 148 | self.mouse.notify_battery_level() 149 | 150 | async def co_start_test(self): 151 | self.mouse.start() 152 | await asyncio.gather(self.advertise_for(30), self.test()) 153 | 154 | # start test 155 | def start_test(self): 156 | asyncio.run(self.co_start_test()) 157 | 158 | if __name__ == "__main__": 159 | d = Device() 160 | d.start() 161 | -------------------------------------------------------------------------------- /examples/simple/joystick_example.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | # Implements a BLE HID joystick 19 | import time 20 | from machine import SoftSPI, Pin 21 | from hid_services import Joystick 22 | 23 | class Device: 24 | def __init__(self): 25 | # Define state 26 | self.x = 0 27 | self.y = 0 28 | 29 | self.prev_x = 0 30 | self.prev_y = 0 31 | 32 | # Define buttons 33 | self.pin_forward = Pin(23, Pin.IN) 34 | self.pin_reverse = Pin(19, Pin.IN) 35 | self.pin_left = Pin(18, Pin.IN) 36 | self.pin_right = Pin(5, Pin.IN) 37 | 38 | # Create our device 39 | self.joystick = Joystick("Joystick") 40 | # Set a callback function to catch changes of device state 41 | self.joystick.set_state_change_callback(self.joystick_state_callback) 42 | # Start our device 43 | self.joystick.start() 44 | 45 | # Function that catches device status events 46 | def joystick_state_callback(self): 47 | if self.joystick.get_state() is Joystick.DEVICE_IDLE: 48 | return 49 | elif self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 50 | return 51 | elif self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 52 | return 53 | else: 54 | return 55 | 56 | def advertise(self): 57 | self.joystick.start_advertising() 58 | 59 | def stop_advertise(self): 60 | self.joystick.stop_advertising() 61 | 62 | # Main loop 63 | def start(self): 64 | while True: 65 | # Read pin values and update variables 66 | self.x = self.pin_right.value() * 127 - self.pin_left.value() * 127 67 | self.y = self.pin_reverse.value() * 127 - self.pin_forward.value() * 127 68 | 69 | # If the variables changed do something depending on the device state 70 | if (self.x != self.prev_x) or (self.y != self.prev_y): 71 | # Update values 72 | self.prev_x = self.x 73 | self.prev_y = self.y 74 | 75 | # If connected set axes and notify 76 | # If idle start advertising for 30s or until connected 77 | if self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 78 | self.joystick.set_axes(self.x, self.y) 79 | self.joystick.notify_hid_report() 80 | elif self.joystick.get_state() is Joystick.DEVICE_IDLE: 81 | self.joystick.start_advertising() 82 | i = 10 83 | while i > 0 and self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 84 | time.sleep(3) 85 | i -= 1 86 | if self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 87 | self.joystick.stop_advertising() 88 | 89 | if self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 90 | time.sleep_ms(20) 91 | else: 92 | time.sleep(2) 93 | 94 | # Only for test 95 | def stop(self): 96 | self.joystick.stop() 97 | 98 | # Test routine 99 | def test(self): 100 | self.joystick.set_battery_level(50) 101 | self.joystick.notify_battery_level() 102 | 103 | for i in range(30): 104 | self.joystick.set_axes(100,100) 105 | self.joystick.set_buttons(1) 106 | self.joystick.notify_hid_report() 107 | time.sleep_ms(500) 108 | 109 | self.joystick.set_axes(100,-100) 110 | self.joystick.set_buttons(b3=1) 111 | self.joystick.notify_hid_report() 112 | time.sleep_ms(500) 113 | 114 | self.joystick.set_axes(-100,-100) 115 | self.joystick.set_buttons() 116 | self.joystick.notify_hid_report() 117 | time.sleep_ms(500) 118 | 119 | self.joystick.set_axes(-100,100) 120 | self.joystick.set_buttons(b2=1) 121 | self.joystick.notify_hid_report() 122 | time.sleep_ms(500) 123 | 124 | self.joystick.set_axes(0,0) 125 | self.joystick.set_buttons() 126 | self.joystick.notify_hid_report() 127 | 128 | self.joystick.set_battery_level(100) 129 | self.joystick.notify_battery_level() 130 | 131 | if __name__ == "__main__": 132 | d = Device() 133 | d.start() 134 | -------------------------------------------------------------------------------- /examples/simple/keyboard_example.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | # Implements a BLE HID keyboard 19 | import time 20 | from machine import SoftSPI, Pin 21 | from hid_services import Keyboard 22 | 23 | class Device: 24 | def __init__(self): 25 | # Define state 26 | self.key0 = 0x00 27 | self.key1 = 0x00 28 | self.key2 = 0x00 29 | self.key3 = 0x00 30 | 31 | # Define buttons 32 | self.pin_forward = Pin(5, Pin.IN) 33 | self.pin_reverse = Pin(23, Pin.IN) 34 | self.pin_right = Pin(19, Pin.IN) 35 | self.pin_left = Pin(18, Pin.IN) 36 | 37 | # Create our device 38 | self.keyboard = Keyboard("Keyboard") 39 | # Set a callback function to catch changes of device state 40 | self.keyboard.set_state_change_callback(self.keyboard_state_callback) 41 | # Start our device 42 | self.keyboard.start() 43 | 44 | # Function that catches device status events 45 | def keyboard_state_callback(self): 46 | if self.keyboard.get_state() is Keyboard.DEVICE_IDLE: 47 | return 48 | elif self.keyboard.get_state() is Keyboard.DEVICE_ADVERTISING: 49 | return 50 | elif self.keyboard.get_state() is Keyboard.DEVICE_CONNECTED: 51 | return 52 | else: 53 | return 54 | 55 | def keyboard_event_callback(self, bytes): 56 | print("Keyboard state callback with bytes: ", bytes) 57 | 58 | def advertise(self): 59 | self.keyboard.start_advertising() 60 | 61 | def stop_advertise(self): 62 | self.keyboard.stop_advertising() 63 | 64 | # Main loop 65 | def start(self): 66 | while True: 67 | # Read pin values and update variables 68 | if self.pin_forward.value(): 69 | self.key0 = 0x1A # W 70 | else: 71 | self.key0 = 0x00 72 | 73 | if self.pin_left.value(): 74 | self.key1 = 0x04 # A 75 | else: 76 | self.key1 = 0x00 77 | 78 | if self.pin_reverse.value(): 79 | self.key2 = 0x16 # S 80 | else: 81 | self.key2 = 0x00 82 | 83 | if self.pin_right.value(): 84 | self.key3 = 0x07 # D 85 | else: 86 | self.key3 = 0x00 87 | 88 | # If the variables changed do something depending on the device state 89 | if (self.key0 != 0x00) or (self.key1 != 0x00) or (self.key2 != 0x00) or (self.key3 != 0x00): 90 | # If connected set keys and notify 91 | # If idle start advertising for 30s or until connected 92 | if self.keyboard.get_state() is Keyboard.DEVICE_CONNECTED: 93 | self.keyboard.set_keys(self.key0, self.key1, self.key2, self.key3) 94 | self.keyboard.notify_hid_report() 95 | elif self.keyboard.get_state() is Keyboard.DEVICE_IDLE: 96 | self.keyboard.start_advertising() 97 | i = 10 98 | while i > 0 and self.keyboard.get_state() is Keyboard.DEVICE_ADVERTISING: 99 | time.sleep(3) 100 | i -= 1 101 | if self.keyboard.get_state() is Keyboard.DEVICE_ADVERTISING: 102 | self.keyboard.stop_advertising() 103 | 104 | if self.keyboard.get_state() is Keyboard.DEVICE_CONNECTED: 105 | time.sleep_ms(20) 106 | else: 107 | time.sleep(2) 108 | 109 | def send_char(self, char): 110 | if char == " ": 111 | mod = 0 112 | code = 0x2C 113 | elif ord("a") <= ord(char) <= ord("z"): 114 | mod = 0 115 | code = 0x04 + ord(char) - ord("a") 116 | elif ord("A") <= ord(char) <= ord("Z"): 117 | mod = 1 118 | code = 0x04 + ord(char) - ord("A") 119 | else: 120 | assert 0 121 | 122 | self.keyboard.set_keys(code) 123 | self.keyboard.set_modifiers(left_shift=mod) 124 | self.keyboard.notify_hid_report() 125 | time.sleep_ms(2) 126 | 127 | self.keyboard.set_keys() 128 | self.keyboard.set_modifiers() 129 | self.keyboard.notify_hid_report() 130 | time.sleep_ms(2) 131 | 132 | 133 | def send_string(self, st): 134 | for c in st: 135 | self.send_char(c) 136 | 137 | # Only for test 138 | def stop(self): 139 | self.keyboard.stop() 140 | 141 | # Test routine 142 | def test(self): 143 | time.sleep(5) 144 | self.keyboard.set_battery_level(50) 145 | self.keyboard.notify_battery_level() 146 | time.sleep_ms(2) 147 | 148 | # Press Shift+W 149 | self.keyboard.set_keys(0x1A) 150 | self.keyboard.set_modifiers(right_shift=1) 151 | self.keyboard.notify_hid_report() 152 | 153 | # release 154 | self.keyboard.set_keys() 155 | self.keyboard.set_modifiers() 156 | self.keyboard.notify_hid_report() 157 | time.sleep_ms(500) 158 | 159 | # Press a 160 | self.keyboard.set_keys(0x04) 161 | self.keyboard.notify_hid_report() 162 | 163 | # release 164 | self.keyboard.set_keys() 165 | self.keyboard.notify_hid_report() 166 | time.sleep_ms(500) 167 | 168 | # Press s 169 | self.keyboard.set_keys(0x16) 170 | self.keyboard.notify_hid_report() 171 | 172 | # release 173 | self.keyboard.set_keys() 174 | self.keyboard.notify_hid_report() 175 | time.sleep_ms(500) 176 | 177 | # Press d 178 | self.keyboard.set_keys(0x07) 179 | self.keyboard.notify_hid_report() 180 | 181 | # release 182 | self.keyboard.set_keys() 183 | self.keyboard.notify_hid_report() 184 | time.sleep_ms(500) 185 | 186 | self.send_string(" Hello World") 187 | 188 | self.keyboard.set_battery_level(100) 189 | self.keyboard.notify_battery_level() 190 | 191 | if __name__ == "__main__": 192 | d = Device() 193 | d.start() 194 | -------------------------------------------------------------------------------- /examples/simple/mouse_example.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | # Implements a BLE HID mouse 19 | import time 20 | from machine import SoftSPI, Pin 21 | from hid_services import Mouse 22 | 23 | class Device: 24 | def __init__(self): 25 | # Define state 26 | self.x = 0 27 | self.y = 0 28 | 29 | self.prev_x = 0 30 | self.prev_y = 0 31 | 32 | # Define buttons 33 | self.pin_forward = Pin(5, Pin.IN) 34 | self.pin_reverse = Pin(23, Pin.IN) 35 | self.pin_right = Pin(19, Pin.IN) 36 | self.pin_left = Pin(18, Pin.IN) 37 | 38 | # Create our device 39 | self.mouse = Mouse("Mouse") 40 | # Set a callback function to catch changes of device state 41 | self.mouse.set_state_change_callback(self.mouse_state_callback) 42 | # Start our device 43 | self.mouse.start() 44 | 45 | # Function that catches device status events 46 | def mouse_state_callback(self): 47 | if self.mouse.get_state() is Mouse.DEVICE_IDLE: 48 | return 49 | elif self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 50 | return 51 | elif self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 52 | return 53 | else: 54 | return 55 | 56 | def advertise(self): 57 | self.mouse.start_advertising() 58 | 59 | def stop_advertise(self): 60 | self.mouse.stop_advertising() 61 | 62 | # Main loop 63 | def start(self): 64 | while True: 65 | # Read pin values and update variables 66 | self.x = self.pin_right.value() * 127 - self.pin_left.value() * 127 67 | self.y = self.pin_forward.value() * 127 - self.pin_reverse.value() * 127 68 | 69 | # If the variables changed do something depending on the device state 70 | if (self.x != self.prev_x) or (self.y != self.prev_y): 71 | # Update values 72 | self.prev_x = self.x 73 | self.prev_y = self.y 74 | 75 | # If connected set axes and notify 76 | # If idle start advertising for 30s or until connected 77 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 78 | self.mouse.set_axes(self.x, self.y) 79 | self.mouse.notify_hid_report() 80 | elif self.mouse.get_state() is Mouse.DEVICE_IDLE: 81 | self.mouse.start_advertising() 82 | i = 10 83 | while i > 0 and self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 84 | time.sleep(3) 85 | i -= 1 86 | if self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 87 | self.mouse.stop_advertising() 88 | 89 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 90 | time.sleep_ms(20) 91 | else: 92 | time.sleep(2) 93 | 94 | # Only for test 95 | def stop(self): 96 | self.mouse.stop() 97 | 98 | # Test routine 99 | def test(self): 100 | self.mouse.set_battery_level(50) 101 | self.mouse.notify_battery_level() 102 | 103 | for i in range(30): 104 | self.mouse.set_axes(100,100) 105 | self.mouse.set_buttons(1) 106 | self.mouse.notify_hid_report() 107 | time.sleep_ms(500) 108 | 109 | self.mouse.set_axes(100,-100) 110 | self.mouse.set_buttons() 111 | self.mouse.notify_hid_report() 112 | time.sleep_ms(500) 113 | 114 | self.mouse.set_axes(-100,-100) 115 | self.mouse.set_buttons(b2=1) 116 | self.mouse.notify_hid_report() 117 | time.sleep_ms(500) 118 | 119 | self.mouse.set_axes(-100,100) 120 | self.mouse.set_buttons() 121 | self.mouse.notify_hid_report() 122 | time.sleep_ms(500) 123 | 124 | self.mouse.set_axes(0,0) 125 | self.mouse.set_buttons() 126 | self.mouse.notify_hid_report() 127 | 128 | self.mouse.set_battery_level(100) 129 | self.mouse.notify_battery_level() 130 | 131 | if __name__ == "__main__": 132 | d = Device() 133 | d.start() 134 | -------------------------------------------------------------------------------- /examples/tinypico/tinypico_dpad.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | # Implements a BLE HID joystick on the TinyPICO 18 | import uasyncio as asyncio 19 | from machine import SoftSPI, Pin 20 | from hid_services import Joystick 21 | import tinypico as TinyPICO 22 | from dotstar import DotStar 23 | 24 | class Device: 25 | def __init__(self, name="TinyPICO D-pad"): 26 | # Create a DotStar instance 27 | spi = SoftSPI(sck=Pin( TinyPICO.DOTSTAR_CLK ), mosi=Pin( TinyPICO.DOTSTAR_DATA ), miso=Pin( TinyPICO.SPI_MISO) ) 28 | self.dotstar = DotStar(spi, 1, brightness = 0.5 ) # Just one DotStar, half brightness 29 | 30 | # Turn on the power to the DotStar 31 | TinyPICO.set_dotstar_power( True ) 32 | self.dotstar[0] = (255, 0, 0, 0.5) 33 | 34 | # Define state 35 | self.axes = (0, 0) 36 | self.updated = False 37 | self.active = True 38 | 39 | # Define buttons 40 | self.pin_forward = Pin(23, Pin.IN) 41 | self.pin_reverse = Pin(19, Pin.IN) 42 | self.pin_left = Pin(18, Pin.IN) 43 | self.pin_right = Pin(5, Pin.IN) 44 | 45 | # Create our device 46 | self.joystick = Joystick(name) 47 | # Set a callback function to catch changes of device state 48 | self.joystick.set_state_change_callback(self.joystick_state_callback) 49 | 50 | # Sets dotstar color 51 | def joystick_state_callback(self): 52 | if self.joystick.get_state() is Joystick.DEVICE_IDLE: 53 | self.dotstar[0] = (255, 140, 0, 0.5) 54 | elif self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 55 | self.dotstar[0] = (255, 255, 0, 0.5) 56 | elif self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 57 | self.dotstar[0] = (0, 255, 0, 0.5) 58 | else: 59 | self.dotstar[0] = (255, 0, 0, 0.5) 60 | 61 | def advertise(self): 62 | self.joystick.start_advertising() 63 | 64 | def stop_advertise(self): 65 | self.joystick.stop_advertising() 66 | 67 | async def advertise_for(self, seconds=30): 68 | self.advertise() 69 | 70 | while seconds > 0 and self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 71 | await asyncio.sleep(1) 72 | seconds -= 1 73 | 74 | if self.joystick.get_state() is Joystick.DEVICE_ADVERTISING: 75 | self.stop_advertise() 76 | 77 | # Input loop 78 | async def gather_input(self): 79 | while self.active: 80 | prevaxes = self.axes 81 | self.axes = (self.pin_right.value() * 127 - self.pin_left.value() * 127, self.pin_forward.value() * 127 - self.pin_reverse.value() * 127) 82 | self.updated = self.updated or not (prevaxes == self.axes) # If updated is still True, we haven't notified yet 83 | await asyncio.sleep_ms(50) 84 | 85 | # Bluetooth device loop 86 | async def notify(self): 87 | while self.active: 88 | # If connected, set axes and notify 89 | # If idle, start advertising for 30s or until connected 90 | if self.updated: 91 | if self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 92 | self.joystick.set_axes(self.axes[0], self.axes[1]) 93 | self.joystick.notify_hid_report() 94 | elif self.joystick.get_state() is Joystick.DEVICE_IDLE: 95 | await self.advertise_for(30) 96 | self.updated = False 97 | 98 | if self.joystick.get_state() is Joystick.DEVICE_CONNECTED: 99 | await asyncio.sleep_ms(50) 100 | else: 101 | await asyncio.sleep(2) 102 | 103 | async def co_start(self): 104 | # Start our device 105 | if self.joystick.get_state() is Joystick.DEVICE_STOPPED: 106 | self.joystick.start() 107 | self.active = True 108 | await asyncio.gather(self.advertise_for(30), self.gather_input(), self.notify()) 109 | 110 | async def co_stop(self): 111 | self.active = False 112 | self.joystick.stop() 113 | 114 | def start(self): 115 | asyncio.run(self.co_start()) 116 | 117 | def stop(self): 118 | asyncio.run(self.co_stop()) 119 | 120 | if __name__ == "__main__": 121 | d = Device() 122 | d.start() 123 | -------------------------------------------------------------------------------- /examples/tinypico/tinypico_touchpad.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | # Implements a BLE HID mouse on the TinyPICO 18 | import uasyncio as asyncio 19 | from machine import SoftSPI, SoftI2C, Pin 20 | import tinypico as TinyPICO 21 | from dotstar import DotStar 22 | from hid_services import Mouse 23 | from trackball import Trackball 24 | from trill import Square 25 | from touch import Touches2D 26 | 27 | class Device: 28 | def __init__(self, name="TinyPICO touchpad", sensitivity=50, press_sensitivity=2000): 29 | self.sensitivity = sensitivity 30 | self.press_sensitivity = press_sensitivity 31 | 32 | self.active = False 33 | 34 | # Create a DotStar instance 35 | spi = SoftSPI(sck=Pin( TinyPICO.DOTSTAR_CLK ), mosi=Pin( TinyPICO.DOTSTAR_DATA ), miso=Pin( TinyPICO.SPI_MISO) ) 36 | self.dotstar = DotStar(spi, 1, brightness = 0.5 ) # Just one DotStar, half brightness 37 | 38 | # Turn on the power to the DotStar 39 | TinyPICO.set_dotstar_power( True ) 40 | self.dotstar[0] = (0, 0, 0, 0.5) 41 | 42 | # Define state 43 | self.mousestate = MouseState() 44 | self.touchstate = TouchState(self.press_sensitivity) 45 | 46 | # I2C input sensors 47 | i2c = SoftI2C(scl=Pin(TinyPICO.I2C_SCL), sda=Pin(TinyPICO.I2C_SDA), freq=400000) 48 | self.touchpad = Square(i2c) 49 | self.trackball = Trackball(i2c) 50 | self.trackball.set_color(0, 0, 0, 0) 51 | 52 | # Create our device 53 | self.mouse = Mouse(name) 54 | # Set a callback function to catch changes of device state 55 | self.mouse.set_state_change_callback(self.mouse_state_callback) 56 | 57 | # Function that catches device status events 58 | def mouse_state_callback(self): 59 | if self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 60 | self.dotstar[0] = (0, 0, 255, 0.5) 61 | self.trackball.set_color(0, 0, 255, 0) 62 | else: 63 | self.set_battery_level() 64 | 65 | def advertise(self): 66 | self.mouse.start_advertising() 67 | 68 | def stop_advertise(self): 69 | self.mouse.stop_advertising() 70 | 71 | async def advertise_for(self, seconds=30): 72 | self.advertise() 73 | 74 | while seconds > 0 and self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 75 | await asyncio.sleep(1) 76 | seconds -= 1 77 | 78 | if self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 79 | self.stop_advertise() 80 | 81 | # Input loop 82 | async def gather_input(self): 83 | while self.active: 84 | # Read and update touchstate using touchpad 85 | touches = Touches2D(self.touchpad.read()) 86 | 87 | wasTouched = self.touchstate.is_touched() 88 | self.touchstate.update_touches(touches) 89 | 90 | if self.touchstate.is_touched() or wasTouched: 91 | (x, y) = self.touchstate.get_touch() 92 | (h, v) = self.touchpad.get_size() 93 | 94 | (sx, sy) = (int(x * self.sensitivity/h), int(y * self.sensitivity/v)) 95 | self.mousestate.set_axes_absolute(sx, sy) 96 | 97 | # Read and update touchstate using trackball 98 | left, right, up, down, switch, switch_state = self.trackball.get_state() 99 | 100 | self.mousestate.set_axes_relative(right - left, down - up) 101 | self.mousestate.set_button(0, switch_state or self.touchstate.get_press()) 102 | 103 | await asyncio.sleep_ms(20) 104 | 105 | # Bluetooth device loop 106 | async def notify(self): 107 | while self.active: 108 | # If connected, set axes and notify 109 | # If idle, start advertising for 30s or until connected 110 | if (not self.mousestate.is_centered()) or self.mousestate.is_updated(): 111 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 112 | axes = self.mousestate.get_axes() 113 | buttons = self.mousestate.get_buttons() 114 | self.mouse.set_axes(axes[0], axes[1]) 115 | self.mouse.set_buttons(b1=buttons[0]) 116 | self.mouse.notify_hid_report() 117 | elif self.mouse.get_state() is Mouse.DEVICE_IDLE: 118 | await self.advertise_for(30) 119 | self.mousestate.notified() 120 | 121 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 122 | await asyncio.sleep_ms(20) 123 | else: 124 | await asyncio.sleep(2) 125 | 126 | async def battery_input(self): 127 | while self.active: 128 | self.set_battery_level() 129 | await asyncio.sleep(60) 130 | 131 | async def co_start(self): 132 | # Start our device 133 | if self.mouse.get_state() is Mouse.DEVICE_STOPPED: 134 | self.mouse.start() 135 | self.active = True 136 | await asyncio.gather(self.battery_input(), self.gather_input(), self.notify(), self.advertise_for(30)) 137 | 138 | async def co_stop(self): 139 | self.active = False 140 | self.mouse.stop() 141 | 142 | def set_battery_level(self): 143 | v = TinyPICO.get_battery_voltage() 144 | 145 | if 3.7 == v or 4.2 <= v or TinyPICO.get_battery_charging(): 146 | self.mouse.set_battery_level(100) 147 | self.dotstar[0] = (0, 255, 0, 0.5) 148 | self.trackball.set_color(0, 255, 0, 0) 149 | elif 4.1 <= v < 4.2: 150 | self.mouse.set_battery_level(90) 151 | self.dotstar[0] = (64, 255, 0, 0.5) 152 | self.trackball.set_color(64, 255, 0, 0) 153 | elif 4.0 <= v < 4.1: 154 | self.mouse.set_battery_level(80) 155 | self.dotstar[0] = (192, 255, 0, 0.5) 156 | self.trackball.set_color(192, 255, 0, 0) 157 | elif 3.9 <= v < 4.0: 158 | self.mouse.set_battery_level(60) 159 | self.trackball.set_color(255, 255, 0, 0) 160 | elif 3.8 <= v < 3.9: 161 | self.mouse.set_battery_level(40) 162 | self.dotstar[0] = (255, 192, 0, 0.5) 163 | self.trackball.set_color(255, 192, 0, 0) 164 | elif 3.7 <= v < 3.8: 165 | self.mouse.set_battery_level(20) 166 | self.dotstar[0] = (255, 64, 0, 0.5) 167 | self.trackball.set_color(255, 64, 0, 0) 168 | else: 169 | self.mouse.set_battery_level(0) 170 | self.dotstar[0] = (255, 0, 0, 0.5) 171 | self.trackball.set_color(255, 0, 0, 0) 172 | 173 | if self.mouse.get_state() is self.mouse.DEVICE_CONNECTED: 174 | self.mouse.notify_battery_level() 175 | 176 | def start(self): 177 | asyncio.run(self.co_start()) 178 | 179 | def stop(self): 180 | asyncio.run(self.co_stop()) 181 | 182 | 183 | class MouseState: 184 | 185 | def __init__(self): 186 | self.axes = [0, 0] 187 | self.buttons = [False] * 6 188 | self.updated = False 189 | 190 | def set_axes_absolute(self, x, y): 191 | self.updated = x != 0 or y != 0 or self.axes[0] != 0 or self.axes[1] != 0 192 | self.set_axes(x, y) 193 | 194 | def set_axes_relative(self, x, y): 195 | self.set_axes(self.axes[0] + x, self.axes[1] + y) 196 | self.updated = self.updated or x != 0 or y != 0 197 | 198 | def set_axes(self, x, y): 199 | self.axes[0] = x if -127 <= x <= 127 else (-127 if x < -127 else 127) 200 | self.axes[1] = y if -127 <= y <= 127 else (-127 if y < -127 else 127) 201 | 202 | def set_button(self, index, press): 203 | self.updated = self.updated or press is not self.buttons[index] 204 | 205 | self.buttons[index] = press 206 | 207 | def get_axes(self): 208 | return self.axes 209 | 210 | def get_buttons(self): 211 | return self.buttons 212 | 213 | def is_centered(self): 214 | return self.axes[0] is 0 and self.axes[1] is 0 215 | 216 | def is_updated(self): 217 | return self.updated 218 | 219 | def notified(self): 220 | self.updated = False 221 | 222 | 223 | class TouchState: 224 | 225 | def __init__(self, press=4000): 226 | self.press=press 227 | self.initial = None 228 | self.current = None 229 | self.pressed = False 230 | 231 | def update_touches(self, touches): 232 | if touches.is_empty(): 233 | self.initial = None 234 | self.current = None 235 | self.pressed = False 236 | else: 237 | if self.initial is None: 238 | self.initial = touches.get_touch(0) 239 | else: 240 | self.current = touches.get_touch(0) 241 | 242 | if self.current is not None: 243 | self.pressed = self.current[2] + self.current[3] > self.press 244 | 245 | def get_touch(self): 246 | if self.initial is None or self.current is None: 247 | touch = (0, 0) 248 | else: 249 | touch = (self.current[0] - self.initial[0], self.initial[1] - self.current[1]) 250 | return touch 251 | 252 | def get_press(self): 253 | return self.pressed 254 | 255 | def is_touched(self): 256 | return self.current is not None 257 | 258 | 259 | if __name__ == "__main__": 260 | d = Device() 261 | d.start() 262 | -------------------------------------------------------------------------------- /examples/tinypico/tinypico_trackball.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | # Implements a BLE HID trackball on the TinyPICO 18 | import uasyncio as asyncio 19 | from machine import SoftSPI, SoftI2C, Pin 20 | from hid_services import Mouse 21 | from trackball import Trackball 22 | import tinypico as TinyPICO 23 | from dotstar import DotStar 24 | 25 | class Device: 26 | def __init__(self, name="TinyPICO trackball"): 27 | # Create a DotStar instance 28 | spi = SoftSPI(sck=Pin( TinyPICO.DOTSTAR_CLK ), mosi=Pin( TinyPICO.DOTSTAR_DATA ), miso=Pin( TinyPICO.SPI_MISO) ) 29 | self.dotstar = DotStar(spi, 1, brightness = 0.5 ) # Just one DotStar, half brightness 30 | 31 | # Turn on the power to the DotStar 32 | TinyPICO.set_dotstar_power( True ) 33 | self.dotstar[0] = (255, 0, 0, 0.5) 34 | 35 | # Define state 36 | self.axes = (0, 0) 37 | self.button = 0 38 | self.updated = False 39 | self.active = True 40 | 41 | # Read I2C input 42 | self.i2c = SoftI2C(scl=Pin(TinyPICO.I2C_SCL), sda=Pin(TinyPICO.I2C_SDA), freq=400000) 43 | self.trackball = Trackball(self.i2c, speed_modifier=1) 44 | self.trackball.set_color(255, 0, 0, 0) 45 | 46 | # Create our device 47 | self.mouse = Mouse(name) 48 | # Set a callback function to catch changes of device state 49 | self.mouse.set_state_change_callback(self.mouse_state_callback) 50 | 51 | # Function that catches device status events 52 | def mouse_state_callback(self): 53 | if self.mouse.get_state() is Mouse.DEVICE_IDLE: 54 | self.dotstar[0] = (255, 140, 0, 0.5) 55 | self.trackball.set_color(255, 140, 0, 0) 56 | elif self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 57 | self.dotstar[0] = (255, 255, 0, 0.5) 58 | self.trackball.set_color(255, 255, 0, 0) 59 | elif self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 60 | self.dotstar[0] = (0, 255, 0, 0.5) 61 | self.trackball.set_color(0, 255, 0, 0) 62 | else: 63 | self.dotstar[0] = (255, 0, 0, 0.5) 64 | self.trackball.set_color(255, 0, 0, 0) 65 | 66 | def advertise(self): 67 | self.mouse.start_advertising() 68 | 69 | def stop_advertise(self): 70 | self.mouse.stop_advertising() 71 | 72 | async def advertise_for(self, seconds=30): 73 | self.advertise() 74 | 75 | while seconds > 0 and self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 76 | await asyncio.sleep(1) 77 | seconds -= 1 78 | 79 | if self.mouse.get_state() is Mouse.DEVICE_ADVERTISING: 80 | self.stop_advertise() 81 | 82 | # Input loop 83 | async def gather_input(self): 84 | while self.active: 85 | left, right, up, down, but1, but1_state = self.trackball.get_state() 86 | 87 | prevaxes = self.axes 88 | prevbutton = self.button 89 | 90 | self.axes = (self.clamp(self.axes[0] + left - right), self.clamp(self.axes[1] + up - down)) 91 | self.button = 1 if but1 > 0 else 0 92 | 93 | self.updated = self.updated or not (prevaxes == self.axes) or not (prevbutton == self.button) # If updated is still True, we haven't notified yet 94 | await asyncio.sleep_ms(20) 95 | 96 | def clamp(self, n, minimum=-127, maximum=127): 97 | return max(min(maximum, n), minimum) 98 | 99 | # Bluetooth device loop 100 | async def notify(self): 101 | while self.active: 102 | # If connected, set axes and notify 103 | # If idle, start advertising for 30s or until connected 104 | if self.updated: 105 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 106 | self.mouse.set_axes(self.axes[0], self.axes[1]) 107 | self.mouse.set_buttons(b1=self.button) 108 | self.mouse.notify_hid_report() 109 | elif self.mouse.get_state() is Mouse.DEVICE_IDLE: 110 | await self.advertise_for(30) 111 | self.updated = False 112 | 113 | if self.mouse.get_state() is Mouse.DEVICE_CONNECTED: 114 | await asyncio.sleep_ms(20) 115 | else: 116 | await asyncio.sleep(2) 117 | 118 | async def co_start(self): 119 | # Start our device 120 | if self.mouse.get_state() is Mouse.DEVICE_STOPPED: 121 | self.mouse.start() 122 | self.active = True 123 | await asyncio.gather(self.advertise_for(30), self.gather_input(), self.notify()) 124 | 125 | async def co_stop(self): 126 | self.active = False 127 | self.mouse.stop() 128 | 129 | def start(self): 130 | asyncio.run(self.co_start()) 131 | 132 | def stop(self): 133 | asyncio.run(self.co_stop()) 134 | 135 | 136 | if __name__ == "__main__": 137 | d = Device() 138 | d.start() 139 | -------------------------------------------------------------------------------- /examples/tinypico/trackball.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | # Implements an I2C pimoroni trackball 18 | import struct 19 | 20 | I2C_ADDRESS = 0x0A 21 | 22 | REG_LED_RED = 0x00 23 | REG_LED_GRN = 0x01 24 | REG_LED_BLU = 0x02 25 | REG_LED_WHT = 0x03 26 | 27 | REG_LEFT = 0x04 28 | REG_RIGHT = 0x05 29 | REG_UP = 0x06 30 | REG_DOWN = 0x07 31 | REG_SWITCH = 0x08 32 | 33 | MSK_SWITCH_STATE = 0b10000000 34 | 35 | class Trackball(object): 36 | def __init__(self, i2c, address=I2C_ADDRESS, speed_modifier=1): 37 | self.address = address 38 | self.speed_modifier = speed_modifier 39 | self.i2c = i2c 40 | 41 | def set_color(self, red=0, green=0, blue=0, white=0): 42 | self.i2c.writeto_mem(self.address, REG_LED_RED, struct.pack("4B", red, green, blue, white)) 43 | 44 | def get_color(self): 45 | red, green, blue, white = struct.unpack("4B", self.i2c.readfrom_mem(self.address, REG_LED_RED, 4)) 46 | return red, green, blue, white 47 | 48 | def get_state(self): 49 | left, right, up, down, switch = struct.unpack("5B", self.i2c.readfrom_mem(self.address, REG_LEFT, 5)) 50 | left, right, up, down = left * self.speed_modifier, right * self.speed_modifier, up * self.speed_modifier, down * self.speed_modifier 51 | switch, switch_state = switch & ~MSK_SWITCH_STATE, (switch & MSK_SWITCH_STATE) > 0 52 | return left, right, up, down, switch, switch_state 53 | -------------------------------------------------------------------------------- /hid_services.py: -------------------------------------------------------------------------------- 1 | # MicroPython Human Interface Device library 2 | # Copyright (C) 2021 H. Groefsema 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | 18 | from micropython import const 19 | import struct 20 | import bluetooth 21 | import json 22 | import binascii 23 | from bluetooth import UUID 24 | 25 | F_READ = bluetooth.FLAG_READ 26 | F_WRITE = bluetooth.FLAG_WRITE 27 | F_READ_WRITE = bluetooth.FLAG_READ | bluetooth.FLAG_WRITE 28 | F_READ_NOTIFY = bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY 29 | F_READ_WRITE_NORESPONSE = bluetooth.FLAG_READ | bluetooth.FLAG_WRITE | bluetooth.FLAG_WRITE_NO_RESPONSE 30 | 31 | DSC_F_READ = 0x02 32 | DSC_F_WRITE = 0x03 33 | 34 | # Advertising payloads are repeated packets of the following form: 35 | # 1 byte data length (N + 1) 36 | # 1 byte type (see constants below) 37 | # N bytes type-specific data 38 | _ADV_TYPE_FLAGS = const(0x01) 39 | _ADV_TYPE_NAME = const(0x09) 40 | _ADV_TYPE_UUID16_COMPLETE = const(0x3) 41 | _ADV_TYPE_UUID32_COMPLETE = const(0x5) 42 | _ADV_TYPE_UUID128_COMPLETE = const(0x7) 43 | _ADV_TYPE_UUID16_MORE = const(0x2) 44 | _ADV_TYPE_UUID32_MORE = const(0x4) 45 | _ADV_TYPE_UUID128_MORE = const(0x6) 46 | _ADV_TYPE_APPEARANCE = const(0x19) 47 | 48 | # IRQ peripheral role event codes 49 | _IRQ_CENTRAL_CONNECT = const(1) 50 | _IRQ_CENTRAL_DISCONNECT = const(2) 51 | _IRQ_GATTS_WRITE = const(3) 52 | _IRQ_GATTS_READ_REQUEST = const(4) 53 | _IRQ_SCAN_RESULT = const(5) 54 | _IRQ_SCAN_DONE = const(6) 55 | _IRQ_PERIPHERAL_CONNECT = const(7) 56 | _IRQ_PERIPHERAL_DISCONNECT = const(8) 57 | _IRQ_GATTC_SERVICE_RESULT = const(9) 58 | _IRQ_GATTC_SERVICE_DONE = const(10) 59 | _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) 60 | _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) 61 | _IRQ_GATTC_DESCRIPTOR_RESULT = const(13) 62 | _IRQ_GATTC_DESCRIPTOR_DONE = const(14) 63 | _IRQ_GATTC_READ_RESULT = const(15) 64 | _IRQ_GATTC_READ_DONE = const(16) 65 | _IRQ_GATTC_WRITE_DONE = const(17) 66 | _IRQ_GATTC_NOTIFY = const(18) 67 | _IRQ_GATTC_INDICATE = const(19) 68 | _IRQ_GATTS_INDICATE_DONE = const(20) 69 | _IRQ_MTU_EXCHANGED = const(21) 70 | _IRQ_L2CAP_ACCEPT = const(22) 71 | _IRQ_L2CAP_CONNECT = const(23) 72 | _IRQ_L2CAP_DISCONNECT = const(24) 73 | _IRQ_L2CAP_RECV = const(25) 74 | _IRQ_L2CAP_SEND_READY = const(26) 75 | _IRQ_CONNECTION_UPDATE = const(27) 76 | _IRQ_ENCRYPTION_UPDATE = const(28) 77 | _IRQ_GET_SECRET = const(29) 78 | _IRQ_SET_SECRET = const(30) 79 | _IRQ_PASSKEY_ACTION = const(31) 80 | 81 | _IO_CAPABILITY_DISPLAY_ONLY = const(0) 82 | _IO_CAPABILITY_DISPLAY_YESNO = const(1) 83 | _IO_CAPABILITY_KEYBOARD_ONLY = const(2) 84 | _IO_CAPABILITY_NO_INPUT_OUTPUT = const(3) 85 | _IO_CAPABILITY_KEYBOARD_DISPLAY = const(4) 86 | 87 | _PASSKEY_ACTION_INPUT = const(2) 88 | _PASSKEY_ACTION_DISP = const(3) 89 | _PASSKEY_ACTION_NUMCMP = const(4) 90 | 91 | _GATTS_NO_ERROR = const(0x00) 92 | _GATTS_ERROR_INVALID_HANDLE = const(0x01) 93 | _GATTS_ERROR_READ_NOT_PERMITTED = const(0x02) 94 | _GATTS_ERROR_WRITE_NOT_PERMITTED = const(0x03) 95 | _GATTS_ERROR_INSUFFICIENT_AUTHENTICATION = const(0x05) 96 | _GATTS_ERROR_REQ_NOT_SUPPORTED = const(0x06) 97 | _GATTS_ERROR_INSUFFICIENT_AUTHORIZATION = const(0x08) 98 | _GATTS_ERROR_ATTR_NOT_FOUND = const(0x0a) 99 | _GATTS_ERROR_INSUFFICIENT_ENCRYPTION = const(0x0f) 100 | _GATTS_ERROR_WRITE_REQ_REJECTED = const(0xFC) 101 | 102 | class Advertiser: 103 | 104 | # Generate a payload to be passed to gap_advertise(adv_data=...). 105 | def advertising_payload(self, limited_disc=False, br_edr=False, name=None, services=None, appearance=0): 106 | payload = bytearray() 107 | 108 | def _append(adv_type, value): 109 | nonlocal payload 110 | payload += struct.pack("BB", len(value) + 1, adv_type) + value 111 | 112 | _append( 113 | _ADV_TYPE_FLAGS, 114 | struct.pack("B", (0x01 if limited_disc else 0x02) + (0x18 if br_edr else 0x04)), 115 | ) 116 | 117 | if name: 118 | _append(_ADV_TYPE_NAME, name) 119 | 120 | if services: 121 | for uuid in services: 122 | b = bytes(uuid) 123 | if len(b) == 2: 124 | _append(_ADV_TYPE_UUID16_COMPLETE, b) 125 | elif len(b) == 4: 126 | _append(_ADV_TYPE_UUID32_COMPLETE, b) 127 | elif len(b) == 16: 128 | _append(_ADV_TYPE_UUID128_COMPLETE, b) 129 | 130 | # See org.bluetooth.characteristic.gap.appearance.xml 131 | if appearance: 132 | _append(_ADV_TYPE_APPEARANCE, struct.pack(" _IO_CAPABILITY_NO_INPUT_OUTPUT and not self.authenticated: # If we can authenticate but the client hasn't authenticated, return insufficient authentication. 312 | return _GATTS_ERROR_INSUFFICIENT_AUTHENTICATION 313 | elif self.le_secure and (not self.encrypted or self.key_size < 16): # If we wish for a secure connection but it is unencrypted or not strong enough, return insufficient encryption. 314 | return _GATTS_ERROR_INSUFFICIENT_ENCRYPTION 315 | else: # Otherwise, return no error. 316 | return _GATTS_NO_ERROR 317 | elif event == _IRQ_GATTS_INDICATE_DONE: # A sent indication was done. (We don't use indications currently. If needed, define a callback function and override this function.) 318 | conn_handle, value_handle, status = data 319 | print("Indicate done:", data) 320 | elif event == _IRQ_MTU_EXCHANGED: # MTU was exchanged, set it. 321 | conn_handle, mtu = data 322 | self._ble.config(mtu=mtu) 323 | print("MTU exchanged:", mtu) 324 | elif event == _IRQ_CONNECTION_UPDATE: # Connection parameters were updated. 325 | self.conn_handle, conn_interval, conn_latency, supervision_timeout, status = data # The new parameters. 326 | print("Connection update. Interval=", conn_interval, "latency=", conn_latency, "timeout=", supervision_timeout, "status=", status) 327 | return None # Return an empty packet. 328 | elif event == _IRQ_ENCRYPTION_UPDATE: # Encryption was updated. 329 | conn_handle, self.encrypted, self.authenticated, self.bonded, self.key_size = data # Update the values. 330 | print("Encryption update:", conn_handle, self.encrypted, self.authenticated, self.bonded, self.key_size) 331 | elif event == _IRQ_PASSKEY_ACTION: # Passkey actions: accept connection or show/enter passkey. 332 | conn_handle, action, passkey = data 333 | print("Passkey action:", conn_handle, action, passkey) 334 | if action == _PASSKEY_ACTION_NUMCMP: # Do we accept this connection? 335 | accept = False 336 | if self.passkey_callback is not None: # Is callback function set? 337 | accept = self.passkey_callback() # Call callback for input. 338 | self._ble.gap_passkey(conn_handle, action, accept) 339 | elif action == _PASSKEY_ACTION_DISP: # Show our passkey. 340 | print("Displaying passkey") 341 | self._ble.gap_passkey(conn_handle, action, self.passkey) 342 | elif action == _PASSKEY_ACTION_INPUT: # Enter passkey. 343 | print("Prompting for passkey") 344 | pk = None 345 | if self.passkey_callback is not None: # Is callback function set? 346 | pk = self.passkey_callback() # Call callback for input. 347 | self._ble.gap_passkey(conn_handle, action, pk) 348 | else: 349 | print("Unknown passkey action") 350 | elif event == _IRQ_SET_SECRET: # Set secret for bonding. 351 | sec_type, key, value = data 352 | key = (sec_type, bytes(key)) 353 | value = bytes(value) if value else None 354 | if value is None: # If value is empty, and 355 | if key in self.secrets: # If key is known then 356 | del self.secrets[key] # Forget key 357 | self.save_secrets() 358 | print("Removing secret:", key) 359 | return True 360 | else: 361 | print("Secret not found:", key) 362 | return False 363 | else: 364 | self.secrets[key] = value # Remember key/value 365 | self.save_secrets() 366 | print("Saving secret:", key, value) 367 | return True 368 | elif event == _IRQ_GET_SECRET: # Get secret for bonding 369 | sec_type, index, key = data 370 | _key = (sec_type, bytes(key) if key else None) 371 | value = None 372 | if key is None: 373 | i = 0 374 | for (t, _k), _val in self.secrets.items(): 375 | if t == sec_type: 376 | if i == index: 377 | value = _val 378 | i += 1 379 | else: 380 | value = self.secrets.get(_key, None) 381 | print("Returning secret:", bytes(value) if value else None, "for", "key" if key else "index", _key if key else index, "with type", sec_type) 382 | return value 383 | else: 384 | print("Unhandled IRQ event:", event) 385 | 386 | # Start the service. 387 | # Must be overwritten by subclass, and called in 388 | # the overwritten function by using super(Subclass, self).start(). 389 | def start(self): 390 | if self.device_state is HumanInterfaceDevice.DEVICE_STOPPED: 391 | self._ble.irq(self.ble_irq) # Set interrupt request callback function. 392 | self._ble.active(1) # Turn on BLE radio. 393 | 394 | # Configure BLE interface 395 | self._ble.config(gap_name=self.device_name) # Set GAP device name. 396 | self._ble.config(mtu=23) # Configure MTU. 397 | self._ble.config(bond=self.bond) # Allow bonding. 398 | self._ble.config(le_secure=self.le_secure) # Require secure pairing. 399 | self._ble.config(mitm=self.le_secure) # Require man in the middle protection. 400 | self._ble.config(io=self.io_capability) # Set our input/output capabilities. Determines whether and how passkeys are used. 401 | 402 | self.set_state(HumanInterfaceDevice.DEVICE_IDLE) # Update the device state. 403 | 404 | (addr_type, addr) = self._ble.config('mac') # Get our address type and mac address. 405 | 406 | print("BLE on with", "random" if addr_type else "public", "mac address", addr) 407 | 408 | # After registering the DIS and BAS services, write their characteristic values. 409 | # Must be overwritten by subclass, and called in 410 | # the overwritten function by using 411 | # super(Subclass, self).save_service_characteristics(handles). 412 | def save_service_characteristics(self, handles): 413 | print("Writing service characteristics") 414 | 415 | (h_mod, h_ser, h_fwr, h_hwr, h_swr, h_man, h_pnp) = handles[0] # Get handles to DIS service characteristics. These correspond directly to its definition in self.DIS. Position 0 because of the order of self.services. 416 | (self.h_bat, h_bfmt,) = handles[1] # Get handles to BAS service characteristics. These correspond directly to its definition in self.BAS. Position 1 because of the order of self.services. 417 | (h_sid, h_vid, h_pid, h_ver, h_rec, h_vs) = handles[2] # Get handles to DID service characteristics. These correspond directly to its definition in self.DID. Position 2 because of the order of self.services. 418 | 419 | # Simplify packing strings into byte arrays. 420 | def string_pack(in_str, nr_bytes): 421 | return struct.pack(str(nr_bytes)+"s", in_str.encode('UTF-8')) 422 | 423 | print("Saving device information service characteristics") 424 | self.characteristics[h_mod] = ("Model number", string_pack(self.model_number, 24)) 425 | self.characteristics[h_ser] = ("Serial number", string_pack(self.serial_number, 16)) 426 | self.characteristics[h_fwr] = ("Firmware revision", string_pack(self.firmware_revision, 8)) 427 | self.characteristics[h_hwr] = ("Hardware revision", string_pack(self.hardware_revision, 16)) 428 | self.characteristics[h_swr] = ("Software revision", string_pack(self.software_revision, 8)) 429 | self.characteristics[h_man] = ("Manufacturer name", string_pack(self.manufacture_name, 36)) 430 | self.characteristics[h_pnp] = ("PnP information", struct.pack(">BHHH", self.pnp_manufacturer_source, self.pnp_manufacturer_uuid, self.pnp_product_id, self.pnp_product_version)) 431 | 432 | print("Saving battery service characteristics") 433 | self.characteristics[self.h_bat] = ("Battery level", struct.pack("H", self.pnp_manufacturer_uuid)) 439 | self.characteristics[h_pid] = ("Product ID", struct.pack(">H", self.pnp_product_id)) 440 | self.characteristics[h_ver] = ("Version", struct.pack(">H", self.pnp_product_version)) 441 | self.characteristics[h_rec] = ("Primary record", b'0x01') 442 | self.characteristics[h_vs] = ("Vendor source", struct.pack(">H", self.pnp_manufacturer_source)) 443 | 444 | # Stop the service. 445 | def stop(self): 446 | if self.device_state is not HumanInterfaceDevice.DEVICE_STOPPED: 447 | if self.device_state is HumanInterfaceDevice.DEVICE_ADVERTISING: 448 | self.adv.stop_advertising() 449 | 450 | if self.conn_handle is not None: 451 | self._ble.gap_disconnect(self.conn_handle) 452 | self.conn_handle = None 453 | 454 | self._ble.active(0) 455 | 456 | self.set_state(HumanInterfaceDevice.DEVICE_STOPPED) 457 | print("Server stopped") 458 | 459 | # Write service characteristics 460 | def write_service_characteristics(self): 461 | print("Writing service characteristics") 462 | 463 | for handle, (name, value) in self.characteristics.items(): 464 | self._ble.gatts_write(handle, value) 465 | 466 | # Load bonding keys from json file. 467 | def load_secrets(self): 468 | try: 469 | with open("keys.json", "r") as file: 470 | entries = json.load(file) 471 | for sec_type, key, value in entries: 472 | self.secrets[sec_type, binascii.a2b_base64(key)] = binascii.a2b_base64(value) 473 | except: 474 | print("No secrets available") 475 | 476 | # Save bonding keys to json file. 477 | def save_secrets(self): 478 | try: 479 | with open("keys.json", "w") as file: 480 | json_secrets = [ 481 | (sec_type, binascii.b2a_base64(key, newline=False), binascii.b2a_base64(value, newline=False)) 482 | for (sec_type, key), value in self.secrets.items() 483 | ] 484 | json.dump(json_secrets, file) 485 | except: 486 | print("Failed to save secrets") 487 | 488 | # Returns whether the device is not stopped. 489 | def is_running(self): 490 | return self.device_state is not HumanInterfaceDevice.DEVICE_STOPPED 491 | 492 | # Returns whether the device is connected with a client. 493 | def is_connected(self): 494 | return self.device_state is HumanInterfaceDevice.DEVICE_CONNECTED 495 | 496 | # Returns whether the device services are being advertised. 497 | def is_advertising(self): 498 | return self.device_state is HumanInterfaceDevice.DEVICE_ADVERTISING 499 | 500 | # Set a new state and notify the user's callback function. 501 | def set_state(self, state): 502 | self.device_state = state 503 | if self.state_change_callback is not None: 504 | self.state_change_callback() 505 | 506 | # Returns the state of the device, i.e. 507 | # - DEVICE_STOPPED, 508 | # - DEVICE_IDLE, 509 | # - DEVICE_ADVERTISING, or 510 | # - DEVICE_CONNECTED. 511 | def get_state(self): 512 | return self.device_state 513 | 514 | # Set a callback function to get notifications of state changes, i.e. 515 | # - DEVICE_STOPPED, 516 | # - DEVICE_IDLE, 517 | # - DEVICE_ADVERTISING, or 518 | # - DEVICE_CONNECTED. 519 | def set_state_change_callback(self, callback): 520 | self.state_change_callback = callback 521 | 522 | # Begin advertising the device services. 523 | def start_advertising(self): 524 | if self.device_state is not HumanInterfaceDevice.DEVICE_STOPPED and self.device_state is not HumanInterfaceDevice.DEVICE_ADVERTISING: 525 | self.adv.start_advertising() 526 | self.set_state(HumanInterfaceDevice.DEVICE_ADVERTISING) 527 | 528 | # Stop advertising the device services. 529 | def stop_advertising(self): 530 | if self.device_state is not HumanInterfaceDevice.DEVICE_STOPPED: 531 | self.adv.stop_advertising() 532 | if self.device_state is not HumanInterfaceDevice.DEVICE_CONNECTED: 533 | self.set_state(HumanInterfaceDevice.DEVICE_IDLE) 534 | 535 | # Returns the device name. 536 | def get_device_name(self): 537 | return self.device_name 538 | 539 | # Returns the service id's. 540 | def get_services_uuids(self): 541 | return self.service_uuids 542 | 543 | # Returns the device appearance. 544 | def get_appearance(self): 545 | return self.device_appearance 546 | 547 | # Returns the battery level (percentage). 548 | def get_battery_level(self): 549 | return self.battery_level 550 | 551 | # Sets the value for the battery level (percentage). 552 | def set_battery_level(self, level): 553 | if level > 100: 554 | self.battery_level = 100 555 | elif level < 0: 556 | self.battery_level = 0 557 | else: 558 | self.battery_level = level 559 | 560 | # Set device information. 561 | # Must be called before calling Start(). 562 | # Variables must be Strings. 563 | def set_device_information(self, manufacture_name="Homebrew", model_number="1", serial_number="1"): 564 | self.manufacture_name = manufacture_name 565 | self.model_number = model_number 566 | self.serial_number = serial_number 567 | 568 | # Set device revision. 569 | # Must be called before calling Start(). 570 | # Variables must be Strings. 571 | def set_device_revision(self, firmware_revision="1", hardware_revision="1", software_revision="1"): 572 | self.firmware_revision = firmware_revision 573 | self.hardware_revision = hardware_revision 574 | self.software_revision = software_revision 575 | 576 | # Set device pnp information. 577 | # Must be called before calling Start(). 578 | # Must use the following format: 579 | # pnp_manufacturer_source: 0x01 for manufacturers uuid from the Bluetooth uuid list OR 0x02 from the USBs id list. 580 | # pnp_manufacturer_uuid: 0xFEB2 for Microsoft, 0xFE61 for Logitech, 0xFD65 for Razer with source 0x01. 581 | # pnp_product_id: One byte, user defined. 582 | # pnp_product_version: Two bytes, user defined, format as 0xJJMN which corresponds to version JJ.M.N. 583 | def set_device_pnp_information(self, pnp_manufacturer_source=0x01, pnp_manufacturer_uuid=0xFE61, pnp_product_id=0x01, pnp_product_version=0x0123): 584 | self.pnp_manufacturer_source = pnp_manufacturer_source 585 | self.pnp_manufacturer_uuid = pnp_manufacturer_uuid 586 | self.pnp_product_id = pnp_product_id 587 | self.pnp_product_version = pnp_product_version 588 | 589 | # Set whether to use Bluetooth bonding. 590 | def set_bonding(self, bond=True): 591 | self.bond = bond 592 | 593 | # Set whether to use LE secure pairing. 594 | def set_le_secure(self, le_secure=True): 595 | self.le_secure = le_secure 596 | 597 | # Set input/output capability of this device. 598 | # Determines the pairing procedure, e.g., accept connection/passkey entry/just works. 599 | # Must be called before calling Start(). 600 | # Must use the following values: 601 | # _IO_CAPABILITY_DISPLAY_ONLY, 602 | # _IO_CAPABILITY_DISPLAY_YESNO, 603 | # _IO_CAPABILITY_KEYBOARD_ONLY, 604 | # _IO_CAPABILITY_NO_INPUT_OUTPUT, or 605 | # _IO_CAPABILITY_KEYBOARD_DISPLAY. 606 | def set_io_capability(self, io_capability): 607 | self.io_capability = io_capability 608 | 609 | # Set callback function for pairing events. 610 | # Depending on the I/O capability used, the callback function should return either a 611 | # - boolean to accept or deny a connection, or a 612 | # - passkey that was displayed by the main. 613 | def set_passkey_callback(self, passkey_callback): 614 | self.passkey_callback = passkey_callback 615 | 616 | # Set the passkey used during pairing when entering a passkey at the main. 617 | def set_passkey(self, passkey): 618 | self.passkey = passkey 619 | 620 | # Notifies the client by writing to the battery level handle. 621 | def notify_battery_level(self): 622 | if self.is_connected(): 623 | print("Notify battery level: ", self.battery_level) 624 | value = struct.pack(" 127: 735 | x = 127 736 | elif x < -127: 737 | x = -127 738 | 739 | if y > 127: 740 | y = 127 741 | elif y < -127: 742 | y = -127 743 | 744 | self.x = x 745 | self.y = y 746 | 747 | # Set the joystick button values. 748 | def set_buttons(self, b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0, b8=0): 749 | self.button1 = b1 750 | self.button2 = b2 751 | self.button3 = b3 752 | self.button4 = b4 753 | self.button5 = b5 754 | self.button6 = b6 755 | self.button7 = b7 756 | self.button8 = b8 757 | 758 | # Class that represents the Mouse service. 759 | class Mouse(HumanInterfaceDevice): 760 | def __init__(self, name="Bluetooth Mouse"): 761 | super(Mouse, self).__init__(name) # Set up the general HID services in super. 762 | self.device_appearance = 962 # Device appearance ID, 962 = mouse. 763 | 764 | self.HIDS = ( # Service description: describes the service and how we communicate. 765 | UUID(0x1812), # 0x1812 = Human Interface Device. 766 | ( 767 | (UUID(0x2A4A), F_READ), # 0x2A4A = HID information, to be read by client. 768 | (UUID(0x2A4B), F_READ), # 0x2A4B = HID report map, to be read by client. 769 | (UUID(0x2A4C), F_READ_WRITE_NORESPONSE), # 0x2A4C = HID control point, to be written by client. 770 | (UUID(0x2A4D), F_READ_NOTIFY, ( # 0x2A4D = HID report, to be read by client after notification. 771 | (UUID(0x2908), DSC_F_READ), # 0x2908 = HID reference, to be read by client. 772 | )), 773 | (UUID(0x2A4E), F_READ_WRITE_NORESPONSE), # 0x2A4E = HID protocol mode, to be written & read by client. 774 | ), 775 | ) 776 | 777 | # fmt: off 778 | self.HID_INPUT_REPORT = [ # Report Description: describes what we communicate. 779 | 0x05, 0x01, # USAGE_PAGE (Generic Desktop) 780 | 0x09, 0x02, # USAGE (Mouse) 781 | 0xa1, 0x01, # COLLECTION (Application) 782 | 0x85, 0x01, # REPORT_ID (1) 783 | 0x09, 0x01, # USAGE (Pointer) 784 | 0xa1, 0x00, # COLLECTION (Physical) 785 | 0x05, 0x09, # Usage Page (Buttons) 786 | 0x19, 0x01, # Usage Minimum (1) 787 | 0x29, 0x03, # Usage Maximum (3) 788 | 0x15, 0x00, # Logical Minimum (0) 789 | 0x25, 0x01, # Logical Maximum (1) 790 | 0x95, 0x03, # Report Count (3) 791 | 0x75, 0x01, # Report Size (1) 792 | 0x81, 0x02, # Input(Data, Variable, Absolute); 3 button bits 793 | 0x95, 0x01, # Report Count(1) 794 | 0x75, 0x05, # Report Size(5) 795 | 0x81, 0x03, # Input(Constant); 5 bit padding 796 | 0x05, 0x01, # Usage Page (Generic Desktop) 797 | 0x09, 0x30, # Usage (X) 798 | 0x09, 0x31, # Usage (Y) 799 | 0x09, 0x38, # Usage (Wheel) 800 | 0x15, 0x81, # Logical Minimum (-127) 801 | 0x25, 0x7F, # Logical Maximum (127) 802 | 0x75, 0x08, # Report Size (8) 803 | 0x95, 0x03, # Report Count (3) 804 | 0x81, 0x06, # Input(Data, Variable, Relative); 3 position bytes (X,Y,Wheel) 805 | 0xc0, # END_COLLECTION 806 | 0xc0 # END_COLLECTION 807 | ] 808 | # fmt: on 809 | 810 | # Define the initial mouse state. 811 | self.x = 0 812 | self.y = 0 813 | self.w = 0 814 | 815 | self.button1 = 0 816 | self.button2 = 0 817 | self.button3 = 0 818 | 819 | self.services.append(self.HIDS) # Append to list of service descriptions. 820 | 821 | # Overwrite super to register HID specific service. 822 | def start(self): 823 | super(Mouse, self).start() # Call super to register DIS and BAS services. 824 | 825 | print("Registering services") 826 | handles = self._ble.gatts_register_services(self.services) # Register services and get read/write handles for all services. 827 | self.save_service_characteristics(handles) # Save the values for the characteristics. 828 | self.write_service_characteristics() # Write the values for the characteristics. 829 | self.adv = Advertiser(self._ble, [UUID(0x1812)], self.device_appearance, self.device_name) # Create an Advertiser. Only advertise the top level service, i.e., the HIDS. 830 | 831 | print("Server started") 832 | 833 | # Overwrite super to save HID specific characteristics. 834 | def save_service_characteristics(self, handles): 835 | super(Mouse, self).save_service_characteristics(handles) # Call super to write DIS and BAS characteristics. 836 | 837 | (h_info, h_hid, h_ctrl, self.h_rep, h_d1, h_proto) = handles[3] # Get the handles for the HIDS characteristics. These correspond directly to self.HIDS. Position 3 because of the order of self.services. 838 | 839 | b = self.button1 + self.button2 * 2 + self.button3 * 4 840 | state = struct.pack("Bbbb", b, self.x, self.y, self.w) # Pack the initial mouse state as described by the input report. 841 | 842 | print("Saving HID service characteristics") 843 | self.characteristics[h_info] = ("HID information", b"\x01\x01\x00\x00") # HID info: ver=1.1, country=0, flags=000000cw with c=normally connectable w=wake up signal 844 | self.characteristics[h_hid] = ("HID input report map", bytes(self.HID_INPUT_REPORT)) # HID input report map. 845 | self.characteristics[h_ctrl] = ("HID control point", b"\x00") # HID control point. 846 | self.characteristics[self.h_rep] = ("HID report", state) # HID report. 847 | self.characteristics[h_d1] = ("HID reference", struct.pack(" 127: 862 | x = 127 863 | elif x < -127: 864 | x = -127 865 | 866 | if y > 127: 867 | y = 127 868 | elif y < -127: 869 | y = -127 870 | 871 | self.x = x 872 | self.y = y 873 | 874 | # Set the mouse scroll wheel value. 875 | def set_wheel(self, w=0): 876 | if w > 127: 877 | w = 127 878 | elif w < -127: 879 | w = -127 880 | 881 | self.w = w 882 | 883 | # Set the mouse button values. 884 | def set_buttons(self, b1=0, b2=0, b3=0): 885 | self.button1 = b1 886 | self.button2 = b2 887 | self.button3 = b3 888 | 889 | # Class that represents the Keyboard service. 890 | class Keyboard(HumanInterfaceDevice): 891 | def __init__(self, name="Bluetooth Keyboard"): 892 | super(Keyboard, self).__init__(name) # Set up the general HID services in super. 893 | self.device_appearance = 961 # Device appearance ID, 961 = keyboard. 894 | 895 | self.HIDS = ( # Service description: describes the service and how we communicate. 896 | UUID(0x1812), # Human Interface Device. 897 | ( 898 | (UUID(0x2A4A), F_READ), # 0x2A4A = HID information, to be read by client. 899 | (UUID(0x2A4B), F_READ), # 0x2A4B = HID report map, to be read by client. 900 | (UUID(0x2A4C), F_READ_WRITE_NORESPONSE), # 0x2A4C = HID control point, to be written by client. 901 | (UUID(0x2A4D), F_READ_NOTIFY, ( # 0x2A4D = HID report, to be read by client after notification. 902 | (UUID(0x2908), DSC_F_READ), # 0x2908 = HID reference, to be read by client. 903 | )), 904 | (UUID(0x2A4D), F_READ_WRITE, ( # 0x2A4D = HID report 905 | (UUID(0x2908), DSC_F_READ), # 0x2908 = HID reference, to be read by client. 906 | )), 907 | (UUID(0x2A4E), F_READ_WRITE_NORESPONSE), # 0x2A4E = HID protocol mode, to be written & read by client. 908 | ), 909 | ) 910 | 911 | # fmt: off 912 | self.HID_INPUT_REPORT = [ # Report Description: describes what we communicate. 913 | 0x05, 0x01, # USAGE_PAGE (Generic Desktop) 914 | 0x09, 0x06, # USAGE (Keyboard) 915 | 0xa1, 0x01, # COLLECTION (Application) 916 | 0x85, 0x01, # REPORT_ID (1) 917 | 0x75, 0x01, # Report Size (1) 918 | 0x95, 0x08, # Report Count (8) 919 | 0x05, 0x07, # Usage Page (Key Codes) 920 | 0x19, 0xE0, # Usage Minimum (224) 921 | 0x29, 0xE7, # Usage Maximum (231) 922 | 0x15, 0x00, # Logical Minimum (0) 923 | 0x25, 0x01, # Logical Maximum (1) 924 | 0x81, 0x02, # Input (Data, Variable, Absolute); Modifier byte 925 | 0x95, 0x01, # Report Count (1) 926 | 0x75, 0x08, # Report Size (8) 927 | 0x81, 0x01, # Input (Constant); Reserved byte 928 | 0x95, 0x05, # Report Count (5) 929 | 0x75, 0x01, # Report Size (1) 930 | 0x05, 0x08, # Usage Page (LEDs) 931 | 0x19, 0x01, # Usage Minimum (1) 932 | 0x29, 0x05, # Usage Maximum (5) 933 | 0x91, 0x02, # Output (Data, Variable, Absolute); LED report 934 | 0x95, 0x01, # Report Count (1) 935 | 0x75, 0x03, # Report Size (3) 936 | 0x91, 0x01, # Output (Constant); LED report padding 937 | 0x95, 0x06, # Report Count (6) 938 | 0x75, 0x08, # Report Size (8) 939 | 0x15, 0x00, # Logical Minimum (0) 940 | 0x25, 0x65, # Logical Maximum (101) 941 | 0x05, 0x07, # Usage Page (Key Codes) 942 | 0x19, 0x00, # Usage Minimum (0) 943 | 0x29, 0x65, # Usage Maximum (101) 944 | 0x81, 0x00, # Input (Data, Array); Key array (6 bytes) 945 | 0xc0 # END_COLLECTION 946 | ] 947 | # fmt: on 948 | 949 | # Define the initial keyboard state. 950 | self.modifiers = 0 # 8 bits signifying Right GUI(Win/Command), Right ALT/Option, Right Shift, Right Control, Left GUI, Left ALT, Left Shift, Left Control. 951 | self.keypresses = [0x00] * 6 # 6 keys to hold. 952 | 953 | self.kb_callback = None # Callback function for keyboard messages from client. 954 | 955 | self.services.append(self.HIDS) # Append to list of service descriptions. 956 | 957 | # Interrupt request callback function 958 | # Overwrite super to catch keyboard report write events by the central. 959 | def ble_irq(self, event, data): 960 | if event == _IRQ_GATTS_WRITE: # If a client has written to a characteristic or descriptor. 961 | conn_handle, attr_handle = data # Get the handle to the characteristic that was written. 962 | if attr_handle == self.h_repout: 963 | print("Keyboard changed by Central") 964 | report = self._ble.gatts_read(attr_handle) # Read the report. 965 | bytes = struct.unpack("B", report) # Unpack the report. 966 | if self.kb_callback is not None: # Call the callback function. 967 | self.kb_callback(bytes) 968 | return _GATTS_NO_ERROR 969 | 970 | return super(Keyboard, self).ble_irq(event, data) # Let super handle the event. 971 | 972 | # Overwrite super to register HID specific service. 973 | def start(self): 974 | super(Keyboard, self).start() # Call super to register DIS and BAS services. 975 | 976 | print("Registering services") 977 | handles = self._ble.gatts_register_services(self.services) # Register services and get read/write handles for all services. 978 | self.save_service_characteristics(handles) # Save the values for the characteristics. 979 | self.write_service_characteristics() # Write the values for the characteristics. 980 | self.adv = Advertiser(self._ble, [UUID(0x1812)], self.device_appearance, self.device_name) # Create an Advertiser. Only advertise the top level service, i.e., the HIDS. 981 | print("Server started") 982 | 983 | # Overwrite super to save HID specific characteristics. 984 | def save_service_characteristics(self, handles): 985 | super(Keyboard, self).save_service_characteristics(handles) # Call super to write DIS and BAS characteristics. 986 | 987 | (h_info, h_hid, h_ctrl, self.h_rep, h_d1, self.h_repout, h_d2, h_proto) = handles[3] # Get the handles for the HIDS characteristics. These correspond directly to self.HIDS. Position 3 because of the order of self.services. 988 | 989 | state = struct.pack("8B", self.modifiers, 0, self.keypresses[0], self.keypresses[1], self.keypresses[2], self.keypresses[3], self.keypresses[4], self.keypresses[5]) 990 | 991 | print("Saving HID service characteristics") 992 | self.characteristics[h_info] = ("HID information", b"\x01\x01\x00\x00") # HID info: ver=1.1, country=0, flags=000000cw with c=normally connectable w=wake up signal 993 | self.characteristics[h_hid] = ("HID input report map", bytes(self.HID_INPUT_REPORT)) # HID input report map. 994 | self.characteristics[h_ctrl] = ("HID control point", b"\x00") # HID control point. 995 | self.characteristics[self.h_rep] = ("HID input report", state) # HID report. 996 | self.characteristics[h_d1] = ("HID input reference", struct.pack(" 2 | 3 | 4 | 5 | [![Contributors][contributors-shield]][contributors-url] 6 | [![Forks][forks-shield]][forks-url] 7 | [![Stargazers][stars-shield]][stars-url] 8 | [![Issues][issues-shield]][issues-url] 9 | [![GPL License][license-shield]][license-url] 10 | [![Website][website-shield]][website-url] 11 | 12 | 13 | 14 |
15 |
16 |

MicroPython Human Interface Device library

17 | 18 |

19 | A library that offers implementations of Human Interface Devices (HID) over Bluetooth Low Energy (BLE) GATT for MicroPython. 20 |

21 |
22 | 23 | 24 | 25 | 26 |
27 | Table of Contents 28 |
    29 |
  1. About The Project
  2. 30 |
  3. Requirements
  4. 31 |
  5. Getting Started
  6. 32 |
  7. Usage
  8. 33 |
  9. Contributing
  10. 34 |
  11. License
  12. 35 |
  13. Contact
  14. 36 |
  15. Acknowledgments
  16. 37 |
38 |
39 | 40 | 41 | 42 | 43 | ## About The Project 44 | This library offers implementations of Human Interface Devices (HID) over Bluetooth Low Energy (BLE) GATT for MicroPython. 45 | The library has been tested using an ESP32 development board ([TinyPICO](https://tinypico.com)) as the peripheral and Windows 10 as the central. 46 | Examples and basic implementations of HID devices are available for 47 | 48 | - Keyboard, 49 | - Mouse, and 50 | - Joystick. 51 | 52 | This library is NOT intended to offer functionality for every possible HID device configuration. 53 | Instead, the library is designed to offer basic well-documented classes that you can extend to fit your HID device needs. 54 | For example, the Mouse class offers a three button mouse with vertical scroll wheel. 55 | If you plan on developing a gaming mouse with eight buttons and both vertical and horizontal wheels, you will need to extend the Mouse class and overwrite the required functions to include a new HID report descriptor. 56 | 57 |

(back to top)

58 | 59 | 60 | 61 | ## Requirements 62 | 63 | The following is required to use this library: 64 | - ESP32 chip with 65 | - Bluetooth 66 | - 512 kB SRAM or more 67 | - Micropython v1.18 or higher 68 | 69 |

(back to top)

70 | 71 | 72 | 73 | ## Getting Started 74 | 75 | To get a local copy simply clone this repository. 76 | 77 | ```sh 78 | git clone https://github.com/heerkog/MicroPythonBLEHID.git 79 | ``` 80 | 81 | The repository is structured as followed: 82 | 83 | * `examples/` directory containing some examples. 84 | * `async/` directory containing asynchronous examples. 85 | * `joystick_example.py` 86 | * `keyboard_example.py` 87 | * `mouse_example.py` 88 | * `simple/` directory containing simple examples. 89 | * `joystick_example.py` 90 | * `keyboard_example.py` 91 | * `mouse_example.py` 92 | * `tinypico/` directory containing TinyPICO specific examples. These are mostly personal projects. 93 | * `hid_services.py` the library. 94 | * `LICENSE` the license. 95 | * `readme.md` 96 | 97 |

(back to top)

98 | 99 | 100 | 101 | 102 | ## Usage 103 | 104 | The library offers functionality for creating HID services, advertising them, and setting and notifying the central of HID events. 105 | The library does not offer functionality to, for example, send a string of characters to the central using the keyboard service (eventhough this is included in the keyboard example). 106 | The reason for this is that such functionality is entirely dependent on the intended use of the services and should be kept outside of this library. 107 | 108 | The library consists of five classes with the following functions: 109 | 110 | * `HumanInterfaceDevice` (superclass for the HID service classes, implements the Device Information and Battery services, and sets up BLE and advertisement) 111 | * `__init__(device_name)` (Initialize the superclass) 112 | * `ble_irq(event, data)` (Internal callback function that catches BLE interrupt requests) 113 | * `start()` (Starts Device Information and Battery services) 114 | * `stop()` (Stops Device Information and Battery services) 115 | * `write_service_characteristics(handles)` (Writes Device Information and Battery service characteristics) 116 | * `load_secrets()` (Loads stored secrets for Bluetooth bonding) 117 | * `save_secrets()` (Saves secrets for Bluetooth bonding) 118 | * `start_advertising()` (Starts Bluetooth advertisement) 119 | * `stop_advertising()` (Stops Bluetooth advertisement) 120 | * `is_running()` (Returns `True` if services are running, otherwise `False`) 121 | * `is_connected()` (Returns `True` if a central is connected, otherwise `False`) 122 | * `is_advertising()` (Returns `True` if advertising, otherwise `False`) 123 | * `set_state(state)` (Sets one of the `HumanInterfaceDevice` constants `DEVICE_STOPPED`, `DEVICE_IDLE`, `DEVICE_ADVERTISING`, or `DEVICE_CONNECTED`. Doesn't change the actual function. Used internally) 124 | * `get_state()` (Returns one of the `HumanInterfaceDevice` constants `DEVICE_STOPPED`, `DEVICE_IDLE`, `DEVICE_ADVERTISING`, or `DEVICE_CONNECTED`) 125 | * `set_state_change_callback(callback)` (Sets a callback function that is called when the `HumanInterfaceDevice` state changes between constants `DEVICE_STOPPED`, `DEVICE_IDLE`, `DEVICE_ADVERTISING`, or `DEVICE_CONNECTED`)) 126 | * `get_device_name()` (Returns the device name) 127 | * `get_services_uuids()` (Returns the service UUIDs) 128 | * `get_appearance()` (Returns the device appearance id) 129 | * `get_battery_level()` (Returns the battery level) 130 | * `set_device_information(manufacture_name, model_number, serial_number)` (Sets the basic Device Information characteristics. Must be called before calling `start()`) 131 | * `set_device_revision(firmware_revision, hardware_revision, software_revision)` (Sets the Device Information revision characteristics. Must be called before calling `start()`) 132 | * `set_device_pnp_information(pnp_manufacturer_source, pnp_manufacturer_uuid, pnp_product_id, pnp_product_version)` (Sets the Device Information PnP characteristics. Must be called before calling `start()`) 133 | * `set_bonding(bond)` (Set whether to use Bluetooth bonding) 134 | * `set_le_secure(le_secure)` (Set whether to use LE secure pairing) 135 | * `set_io_capability(io_capability)` (Set input/output capability of this device Determines the pairing procedure, e.g., accept connection/passkey entry/just works. Must be called before calling `start()`) 136 | * `set_passkey_callback(passkey_callback)` (Set callback function for pairing events. Callback function should return boolean to accept connection or passkey depending on I/O capability used) 137 | * `set_passkey(passkey)` (Set the passkey to use for pairing) 138 | * `set_battery_level(level)` (Sets the battery level internally) 139 | * `notify_battery_level()` (Notifies the central of the current battery level. Call after setting battery level) 140 | * `notify_hid_report()` (Function for subclasses to override) 141 | 142 | * `Joystick` (subclass of `HumanInterfaceDevice`, implements joystick service) 143 | * `__init__(name)` (Initialize the joystick) 144 | * `start()` (Starts the HID service using joystick characteristics. Calls `HumanInterfaceDevice.start()`) 145 | * `write_service_characteristics(handles)` (Writes the joystick HID service characteristics. Calls `HumanInterfaceDevice.write_service_characteristics(handles)`) 146 | * `notify_hid_report()` (Notifies the central of the internal HID joystick status) 147 | * `set_axes(x, y)` (Sets the joystick axes internally) 148 | * `set_buttons(b1, b2, b3, b4, b5, b6, b7, b8)` (Sets the joystick buttons internally) 149 | 150 | * `Mouse` (subclass of `HumanInterfaceDevice`, implements mouse service) 151 | * `__init__(name)` (Initialize the mouse) 152 | * `start()` (Starts the HID service using mouse characteristics. Calls `HumanInterfaceDevice.start()`) 153 | * `write_service_characteristics(handles)` (Writes the mouse HID service characteristics. Calls `HumanInterfaceDevice.write_service_characteristics(handles)`) 154 | * `notify_hid_report()` (Notifies the central of the internal HID mouse status) 155 | * `set_axes(x, y)` (Sets the mouse axes movement internally) 156 | * `set_wheel(w)` (Sets the mouse wheel movement internally) 157 | * `set_buttons(b1, b2, b3)` (Sets the mouse buttons internally) 158 | 159 | * `Keyboard` (subclass of `HumanInterfaceDevice`, implements keyboard service) 160 | * `__init__(name)` (Initialize the keyboard) 161 | * `start()` (Starts the HID service using keyboard characteristics. Calls `HumanInterfaceDevice.start()`) 162 | * `write_service_characteristics(handles)` (Writes the keyboard HID service characteristics. Calls `HumanInterfaceDevice.write_service_characteristics(handles)`) 163 | * `notify_hid_report()` (Notifies the central of the internal HID keyboard status) 164 | * `set_modifiers(right_gui, right_alt, right_shift, right_control, left_gui, left_alt, left_shift, left_control)` (Sets the keyboard modifier keys internally) 165 | * `set_keys(k0, k1, k2, k3, k4, k5)` (Sets a list of key codes to press internally. Call without keys to release.) 166 | * `ble_irq(event, data)` (Internal callback function that catches BLE keyboard interrupt requests) 167 | * `set_kb_callback(kb_callback)` (Sets a callback function that is called on a keyboard event) 168 | 169 | * `Advertiser` (from the [MicroPython Bluetooth examples](https://github.com/micropython/micropython), used internally by `HumanInterfaceDevice` class) 170 | * `__init__(ble, services, appearance, name)` 171 | * `advertising_payload(limited_disc, br_edr, name, services, appearance)` 172 | * `decode_field(payload, adv_type)` 173 | * `decode_name(payload)` 174 | * `decode_services(payload)` 175 | * `start_advertising()` (Used internally) 176 | * `stop_advertising()` (Used internally) 177 | 178 | 179 |

(back to top)

180 | 181 | 182 | 183 | ## Contributing 184 | 185 | Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. 186 | 187 | If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". 188 | Don't forget to give the project a star! Thanks again! 189 | 190 | 1. Fork the Project 191 | 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 192 | 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 193 | 4. Push to the Branch (`git push origin feature/AmazingFeature`) 194 | 5. Open a Pull Request 195 | 196 |

(back to top)

197 | 198 | 199 | 200 | 201 | ## License 202 | 203 | Distributed under the GNU General Public License. See `LICENSE` for more information. 204 | 205 |

(back to top)

206 | 207 | 208 | 209 | 210 | ## Contact 211 | 212 | Heerko Groefsema - [@HeerkoG](https://twitter.com/heerkog) - [hgroefsema.nl](https://hgroefsema.nl) 213 | 214 | Project Link: [https://github.com/heerkog/MicroPythonBLEHID](https://github.com/heerkog/MicroPythonBLEHID) 215 | 216 |

(back to top)

217 | 218 | 219 | 220 | 221 | ## Acknowledgments 222 | The following resources were of interest during development: 223 | 224 | * Bluetooth HID 225 | * [Bluetooth Low Energy Specifications](https://www.bluetooth.com/specifications/specs/) 226 | * [Bluetooth assigned numbers list](https://www.bluetooth.com/specifications/assigned-numbers/) 227 | * [Bluetooth device class list](http://domoticx.com/bluetooth-class-of-device-lijst-cod/) 228 | * USB HID 229 | * [USB HID specification](https://www.usb.org/document-library/device-class-definition-hid-111) 230 | * [USB report descriptor tool](https://www.usb.org/document-library/hid-descriptor-tool) 231 | * [USB HID report descriptor tutorial](https://eleccelerator.com/tutorial-about-usb-hid-report-descriptors/) 232 | * Micropython 233 | * [Bluetooth examples](https://github.com/micropython/micropython/tree/master/examples/bluetooth) 234 | * [BLE HID examples](https://github.com/micropython/micropython/pull/6559) 235 | 236 |

(back to top)

237 | 238 | 239 | 240 | 241 | 242 | [contributors-shield]: https://img.shields.io/github/contributors/heerkog/MicroPythonBLEHID.svg?style=for-the-badge 243 | [contributors-url]: https://github.com/heerkog/MicroPythonBLEHID/graphs/contributors 244 | [forks-shield]: https://img.shields.io/github/forks/heerkog/MicroPythonBLEHID.svg?style=for-the-badge 245 | [forks-url]: https://github.com/heerkog/MicroPythonBLEHID/network/members 246 | [stars-shield]: https://img.shields.io/github/stars/heerkog/MicroPythonBLEHID.svg?style=for-the-badge 247 | [stars-url]: https://github.com/heerkog/MicroPythonBLEHID/stargazers 248 | [issues-shield]: https://img.shields.io/github/issues/heerkog/MicroPythonBLEHID.svg?style=for-the-badge 249 | [issues-url]: https://github.com/heerkog/MicroPythonBLEHID/issues 250 | [license-shield]: https://img.shields.io/github/license/heerkog/MicroPythonBLEHID.svg?style=for-the-badge 251 | [license-url]: https://github.com/heerkog/MicroPythonBLEHID/blob/master/LICENSE.txt 252 | 253 | [website-shield]: https://img.shields.io/badge/Website-H-black.svg?style=for-the-badge&colorB=2A638C 254 | [website-url]: https://hgroefsema.nl 255 | --------------------------------------------------------------------------------