├── .gitignore ├── CHANGELOG ├── COPYING ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── conf.py ├── example.rst ├── index.rst ├── installation.rst ├── pifacedigital.rst ├── reference.rst └── simplewebcontrol.rst ├── examples ├── blink.py ├── presslights.py ├── simplewebcontrol.py └── whackamole.py ├── pifacedigitalio ├── __init__.py ├── core.py └── version.py ├── requirements.txt ├── setup.py └── tests.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.deb 2 | _build 3 | *.log 4 | MANIFEST 5 | deb_dist 6 | 7 | # databases 8 | *.db 9 | 10 | *.py[cod] 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Packages 16 | *.egg 17 | *.egg-info 18 | dist 19 | build 20 | eggs 21 | parts 22 | bin 23 | var 24 | sdist 25 | develop-eggs 26 | .installed.cfg 27 | lib 28 | lib64 29 | __pycache__ 30 | 31 | # Installer logs 32 | pip-log.txt 33 | 34 | # Unit test / coverage reports 35 | .coverage 36 | .tox 37 | nosetests.xml 38 | 39 | # Translations 40 | *.mo 41 | 42 | # Mr Developer 43 | .mr.developer.cfg 44 | .project 45 | .pydevproject 46 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | v3.1.0 5 | ------ 6 | - Added daemon flag for InputEventListener. 7 | 8 | v3.0.5 9 | ------ 10 | - Added PiFace Digital Emulator installation instructions to the docs. 11 | 12 | v3.0.4 13 | ------ 14 | - Added deinit_board method to PiFace Digital. 15 | - Fixed bug where digital_read and digital_write would not close SPI file 16 | descriptor. 17 | 18 | v3.0.3 19 | ------ 20 | - Added documentation for simplewebcontrol.py. 21 | 22 | v3.0.2 23 | ------ 24 | - Added bus and chip_select to deinit. 25 | 26 | v3.0.1 27 | ------ 28 | - Fixed deinit bug (fixes GitHub pifacecommon issue #6). 29 | 30 | v3.0.0 31 | ------ 32 | - Updated for compatibility with pifacecommon v4.0.0 (which uses the MCP23S17 33 | class). 34 | - All occurrences of `board_num` have been replaced with `hardware_addr` which 35 | is more appropriate. 36 | - PiFace Digital is initialised when you instantiate the object. **You do not 37 | need to call pifacedigitalio.init() any more unless you're using digital_read 38 | or digital_write.** 39 | - PiFaceDigital inherits registers from MCP23S17 so you can access all the 40 | registers on the chip. For example GPPUP: 41 | 42 | >>> pfd = PiFaceDigital() 43 | >>> pfd.gppub.value = 0xff 44 | >>> pfd.gppub.bits[4].value = 1 45 | 46 | - InputEventListener now requires that you provide a chip object, not 47 | a hardware_addr (board_num). This defaults to PiFaceDigital(hardware_addr=0). 48 | - Interrupt events contain a chip object representing the calling chip instead 49 | of the hardware_addr (board_num). You can still access the 50 | hardware_addr (board_num) like so: 51 | 52 | >>> def my_callback(event): 53 | ... print(event.chip.hardware_addr) 54 | 55 | - Removed LED, Relay and Switch classes. They added arbitrary restrictions and 56 | were not very useful. `pifacecommon.mcp23s17.MCP23S17RegisterBit` is more 57 | appropriate. 58 | - Updated examples to reflect new changes. 59 | - See the docs (particularly the examples) for more information. 60 | 61 | v2.1.0 62 | ------ 63 | - Added IODIR_FALLING_EDGE and IODIR_RISING_EDGE (pifacecommon v3.1.1). 64 | - Added `bus` and `chip_select` optional arguments to init. 65 | 66 | v2.0.3 67 | ------ 68 | - Interrupts now work for multiple boards. 69 | 70 | v2.0.2 71 | ------ 72 | - Using package structure for version number file and consistency with 73 | other PiFace modules. 74 | - Updated docs with new install instructions. 75 | 76 | v2.0.1 77 | ------ 78 | - Added version number to source. 79 | 80 | v2.0.0 81 | ------ 82 | - Using new interrupt API (check the docs). 83 | 84 | v1.2.1 85 | ------ 86 | - Supports Python 2. 87 | - Started using semantic versioning http://semver.org/. 88 | 89 | v1.2 90 | ------ 91 | - Started using a change log! 92 | - Removed install.sh, everything is now handled by setup.py. 93 | - Updated docs. 94 | - Added some examples. -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include CHANGELOG 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pifacedigitalio 2 | =============== 3 | The PiFace Digital Input/Output module ([PyPI](https://pypi.python.org/pypi/pifacedigitalio/)). 4 | 5 | Use this module to use PiFace Digital and PiFace Digital 2 hardware in Python3 6 | 7 | Install 8 | ======= 9 | 10 | Make sure you are using the lastest version of Raspbian: 11 | 12 | $ sudo apt-get update 13 | $ sudo apt-get upgrade 14 | 15 | Enable SPI (e.g. use raspi-config) 16 | 17 | $ sudo raspi-config 18 | 19 | select `Interface Options` > `SPI` > `Yes` and then select `Finish` 20 | 21 | If you need to install pip3 22 | 23 | $ sudo apt install python3-pip 24 | 25 | Install `pifacedigitalio` with the following command: 26 | 27 | Python 3: 28 | $ sudo pip3 install pifacecommon 29 | $ sudo pip3 install pifacedigitalio 30 | 31 | * Notice 1: Installation from Raspbian repository with apt is not longer the preferred way, take a look into [https://github.com/piface/pifacecommon/issues/27#issuecomment-451400154](issue 27) 32 | * Notice 2: Python 2 support is "end-of-life" since Jan 2020, refer to https://www.python.org/doc/sunset-python-2/ 33 | 34 | Examples 35 | ======== 36 | 37 | To run an example program clone this repo 38 | 39 | $ git clone https://github.com/piface/pifacedigitalio.git 40 | 41 | Test by running the `blink.py` program: 42 | 43 | $ python3 pifacedigitalio/examples/blink.py 44 | 45 | Documentation 46 | ============= 47 | 48 | [http://pifacedigitalio.readthedocs.org/](http://pifacedigitalio.readthedocs.org/) 49 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PiFaceDigitalIO.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PiFaceDigitalIO.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PiFaceDigitalIO" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PiFaceDigitalIO" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # PiFace Digital I/O documentation build configuration file, created by 5 | # sphinx-quickstart on Thu Jun 20 15:23:09 2013. 6 | # 7 | # This file is execfile()d with the current directory set to its containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys, os 16 | 17 | # If extensions (or modules to document with autodoc) are in another directory, 18 | # add these directories to sys.path here. If the directory is relative to the 19 | # documentation root, use os.path.abspath to make it absolute, like shown here. 20 | sys.path.insert(0, os.path.abspath('..')) 21 | try: 22 | import pifacecommon 23 | except ImportError: 24 | sys.path.insert(0, os.path.abspath('../../pifacecommon/')) 25 | 26 | # -- General configuration ----------------------------------------------------- 27 | 28 | # If your documentation needs a minimal Sphinx version, state it here. 29 | #needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be extensions 32 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 33 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath'] 34 | 35 | # Add any paths that contain templates here, relative to this directory. 36 | templates_path = ['_templates'] 37 | 38 | # The suffix of source filenames. 39 | source_suffix = '.rst' 40 | 41 | # The encoding of source files. 42 | #source_encoding = 'utf-8-sig' 43 | 44 | # The master toctree document. 45 | master_doc = 'index' 46 | 47 | # General information about the project. 48 | project = 'PiFace Digital I/O' 49 | copyright = '2013, Thomas Preston' 50 | 51 | # The version info for the project you're documenting, acts as replacement for 52 | # |version| and |release|, also used in various other places throughout the 53 | # built documents. 54 | # 55 | # The short X.Y version. 56 | import pifacedigitalio.version 57 | version = pifacedigitalio.version.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = pifacedigitalio.version.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | 96 | # -- Options for HTML output --------------------------------------------------- 97 | 98 | # on_rtd is whether we are on readthedocs.org 99 | # import os 100 | # on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 101 | 102 | # if not on_rtd: # only import and set the theme if we're building docs locally 103 | # import sphinx_rtd_theme 104 | # html_theme = 'sphinx_rtd_theme' 105 | # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 106 | 107 | # otherwise, readthedocs.org uses their theme by default, so no need to 108 | # specify it 109 | 110 | # The theme to use for HTML and HTML Help pages. See the documentation for 111 | # a list of builtin themes. 112 | # html_theme = 'default' 113 | 114 | # Theme options are theme-specific and customize the look and feel of a theme 115 | # further. For a list of options available for each theme, see the 116 | # documentation. 117 | #html_theme_options = {} 118 | 119 | # Add any paths that contain custom themes here, relative to this directory. 120 | #html_theme_path = [] 121 | 122 | # The name for this set of Sphinx documents. If None, it defaults to 123 | # " v documentation". 124 | #html_title = None 125 | 126 | # A shorter title for the navigation bar. Default is the same as html_title. 127 | #html_short_title = None 128 | 129 | # The name of an image file (relative to this directory) to place at the top 130 | # of the sidebar. 131 | #html_logo = None 132 | 133 | # The name of an image file (within the static path) to use as favicon of the 134 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 135 | # pixels large. 136 | #html_favicon = None 137 | 138 | # Add any paths that contain custom static files (such as style sheets) here, 139 | # relative to this directory. They are copied after the builtin static files, 140 | # so a file named "default.css" will overwrite the builtin "default.css". 141 | html_static_path = ['_static'] 142 | 143 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 144 | # using the given strftime format. 145 | #html_last_updated_fmt = '%b %d, %Y' 146 | 147 | # If true, SmartyPants will be used to convert quotes and dashes to 148 | # typographically correct entities. 149 | #html_use_smartypants = True 150 | 151 | # Custom sidebar templates, maps document names to template names. 152 | #html_sidebars = {} 153 | 154 | # Additional templates that should be rendered to pages, maps page names to 155 | # template names. 156 | #html_additional_pages = {} 157 | 158 | # If false, no module index is generated. 159 | #html_domain_indices = True 160 | 161 | # If false, no index is generated. 162 | #html_use_index = True 163 | 164 | # If true, the index is split into individual pages for each letter. 165 | #html_split_index = False 166 | 167 | # If true, links to the reST sources are added to the pages. 168 | #html_show_sourcelink = True 169 | 170 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 171 | #html_show_sphinx = True 172 | 173 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 174 | #html_show_copyright = True 175 | 176 | # If true, an OpenSearch description file will be output, and all pages will 177 | # contain a tag referring to it. The value of this option must be the 178 | # base URL from which the finished HTML is served. 179 | #html_use_opensearch = '' 180 | 181 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 182 | #html_file_suffix = None 183 | 184 | # Output file base name for HTML help builder. 185 | htmlhelp_basename = 'PiFaceDigitalIOdoc' 186 | 187 | 188 | # -- Options for LaTeX output -------------------------------------------------- 189 | 190 | latex_elements = { 191 | # The paper size ('letterpaper' or 'a4paper'). 192 | #'papersize': 'letterpaper', 193 | 194 | # The font size ('10pt', '11pt' or '12pt'). 195 | #'pointsize': '10pt', 196 | 197 | # Additional stuff for the LaTeX preamble. 198 | #'preamble': '', 199 | } 200 | 201 | # Grouping the document tree into LaTeX files. List of tuples 202 | # (source start file, target name, title, author, documentclass [howto/manual]). 203 | latex_documents = [ 204 | ('index', 'PiFaceDigitalIO.tex', 'PiFace Digital I/O Documentation', 205 | 'Thomas Preston', 'manual'), 206 | ] 207 | 208 | # The name of an image file (relative to this directory) to place at the top of 209 | # the title page. 210 | #latex_logo = None 211 | 212 | # For "manual" documents, if this is true, then toplevel headings are parts, 213 | # not chapters. 214 | #latex_use_parts = False 215 | 216 | # If true, show page references after internal links. 217 | #latex_show_pagerefs = False 218 | 219 | # If true, show URL addresses after external links. 220 | #latex_show_urls = False 221 | 222 | # Documents to append as an appendix to all manuals. 223 | #latex_appendices = [] 224 | 225 | # If false, no module index is generated. 226 | #latex_domain_indices = True 227 | 228 | 229 | # -- Options for manual page output -------------------------------------------- 230 | 231 | # One entry per manual page. List of tuples 232 | # (source start file, name, description, authors, manual section). 233 | man_pages = [ 234 | ('index', 'pifacedigitalio', 'PiFace Digital I/O Documentation', 235 | ['Thomas Preston'], 1) 236 | ] 237 | 238 | # If true, show URL addresses after external links. 239 | #man_show_urls = False 240 | 241 | 242 | # -- Options for Texinfo output ------------------------------------------------ 243 | 244 | # Grouping the document tree into Texinfo files. List of tuples 245 | # (source start file, target name, title, author, 246 | # dir menu entry, description, category) 247 | texinfo_documents = [ 248 | ('index', 'PiFaceDigitalIO', 'PiFace Digital I/O Documentation', 249 | 'Thomas Preston', 'PiFaceDigitalIO', 'One line description of project.', 250 | 'Miscellaneous'), 251 | ] 252 | 253 | # Documents to append as an appendix to all manuals. 254 | #texinfo_appendices = [] 255 | 256 | # If false, no module index is generated. 257 | #texinfo_domain_indices = True 258 | 259 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 260 | #texinfo_show_urls = 'footnote' 261 | 262 | 263 | # Example configuration for intersphinx: refer to the Python standard library. 264 | intersphinx_mapping = {'http://docs.python.org/': None} 265 | 266 | todo_include_todos = True 267 | -------------------------------------------------------------------------------- /docs/example.rst: -------------------------------------------------------------------------------- 1 | ######## 2 | Examples 3 | ######## 4 | 5 | Basic usage 6 | =========== 7 | 8 | :: 9 | 10 | >>> import pifacedigitalio 11 | 12 | >>> pfd = pifacedigitalio.PiFaceDigital() # creates a PiFace Digtal object 13 | 14 | >>> pfd.leds[1].turn_on() # turn on/set high the second LED 15 | >>> pfd.leds[1].set_high() # turn on/set high the second LED 16 | >>> pfd.leds[2].toggle() # toggle third LED 17 | >>> pfd.switches[3].value # check the logical status of switch3 18 | 0 19 | >>> pfd.relays[0].value = 1 # turn on/set high the first relay 20 | 21 | >>> pfd.output_pins[6].value = 1 22 | >>> pfd.output_pins[6].turn_off() 23 | 24 | >>> pfd.input_pins[6].value 25 | 0 26 | 27 | >>> pfd.output_port.all_off() 28 | >>> pfd.output_port.value = 0xAA 29 | >>> pfd.output_port.toggle() 30 | 31 | >>> bin(pfd.input_port.value) # fourth switch pressed (logical input port) 32 | '0b1000' 33 | 34 | >>> bin(pfd.gpiob.value) # fourth switch pressed (physical input port) 35 | '0b11110111' 36 | 37 | >>> pfd.deinit_board() # disables interrupts and closes the file 38 | 39 | .. note: Inputs are active low on GPIO Port B. This is hidden in software 40 | unless you inspect the GPIOB register. 41 | 42 | Here are some functions you might want to use if objects aren't your thing:: 43 | 44 | >>> import pifacedigitalio as p 45 | >>> p.init() 46 | >>> p.digital_write(0, 1) # writes pin0 high 47 | >>> p.digital_write(5, 1, 2) # writes pin5 on board2 high 48 | >>> p.digital_read(4) # reads pin4 (on board0) 49 | 0 50 | >>> p.digital_read(2, 3) # reads pin2 (on board3) 51 | 1 52 | >>> p.deinit() 53 | 54 | .. note: These are just wrappers around the PiFaceDigital object. 55 | 56 | Interrupts 57 | ========== 58 | 59 | Instead of polling for input we can use the :class:`InputEventListener` to 60 | register actions that we wish to be called on certain input events. 61 | 62 | >>> import pifacedigitalio 63 | >>> def toggle_led0(event): 64 | ... event.chip.leds[0].toggle() 65 | ... 66 | >>> pifacedigital = pifacedigitalio.PiFaceDigital() 67 | >>> listener = pifacedigitalio.InputEventListener(chip=pifacedigital) 68 | >>> listener.register(0, pifacedigitalio.IODIR_FALLING_EDGE, toggle_led0) 69 | >>> listener.activate() 70 | 71 | When input 0 is pressed, led0 will be toggled. To stop the listener, call it's 72 | ``deactivate`` method: 73 | 74 | >>> listener.deactivate() 75 | 76 | The :class:`Event` object has some interesting attributes. You can access them 77 | like so:: 78 | 79 | >>> import pifacedigitalio 80 | >>> pifacedigital = pifacedigitalio.PiFaceDigital() 81 | >>> listener = pifacedigitalio.InputEventListener(chip=pifacedigital) 82 | >>> listener.register(0, pifacedigitalio.IODIR_RISING_EDGE, print) 83 | >>> listener.activate() 84 | 85 | This would print out the event information whenever you un-press switch 0:: 86 | 87 | interrupt_flag: 0b1 88 | interrupt_capture: 0b11111111 89 | pin_num: 0 90 | direction: 1 91 | chip: 92 | timestamp: 1380893579.447889 93 | 94 | 95 | Exit from interrupt 96 | ------------------- 97 | In some cases you may want to deactivate the listener and exit your program 98 | on an interrupt (press switch to exit, for example). Since each method 99 | registered to an interrupt is run in a new thread and you can only 100 | deactivate a listener from within the same thread that activated it, you 101 | cannot deactivate a listener from a method registered to an interrupt. That is, 102 | you cannot do the following because the ``deactivate_listener_and_exit()`` 103 | method is started in a different thread:: 104 | 105 | import sys 106 | import pifacedigitalio 107 | 108 | 109 | listener = None 110 | 111 | 112 | def deactivate_listener_and_exit(event): 113 | global listener 114 | listener.deactivate() 115 | sys.exit() 116 | 117 | 118 | pifacedigital = pifacedigitalio.PiFaceDigital() 119 | listener = pifacedigitalio.InputEventListener(chip=pifacedigital) 120 | listener.register(0, 121 | pifacedigitalio.IODIR_FALLING_EDGE, 122 | deactivate_listener_and_exit) 123 | listener.activate() 124 | 125 | One solution is to use a `Barrier `_ synchronisation object. Each thread calls ``wait()`` on the barrier and 126 | then blocks. After the final thread calls ``wait()`` all threads are unblocked. 127 | Here is an example program which successfully exits on an interrupt:: 128 | 129 | 130 | import sys 131 | import threading 132 | import pifacedigitalio 133 | 134 | 135 | exit_barrier = threading.Barrier(2) 136 | 137 | 138 | def deactivate_listener_and_exit(event): 139 | global exit_barrier 140 | exit_barrier.wait() 141 | 142 | 143 | pifacedigital = pifacedigitalio.PiFaceDigital() 144 | listener = pifacedigitalio.InputEventListener(chip=pifacedigital) 145 | listener.register(0, 146 | pifacedigitalio.IODIR_FALLING_EDGE, 147 | deactivate_listener_and_exit) 148 | listener.activate() 149 | exit_barrier.wait() # program will wait here until exit_barrier releases 150 | listener.deactivate() 151 | sys.exit() 152 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. PiFace Digital I/O documentation master file, created by 2 | sphinx-quickstart on Thu Jun 20 15:23:09 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to PiFace Digital I/O's documentation! 7 | ============================================== 8 | 9 | The pifacedigitalio Python module provides functions and classes for 10 | interacting with PiFace Digital. 11 | 12 | Links: 13 | - `Blog `_ 14 | - `GitHub `_ 15 | - `PyPI `_ 16 | 17 | Contents: 18 | 19 | .. toctree:: 20 | :maxdepth: 2 21 | 22 | pifacedigital 23 | installation 24 | example 25 | simplewebcontrol 26 | reference 27 | 28 | 29 | Indices and tables 30 | ================== 31 | 32 | * :ref:`genindex` 33 | * :ref:`modindex` 34 | * :ref:`search` 35 | 36 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ############ 2 | Installation 3 | ############ 4 | 5 | Make sure you are using the lastest version of Raspbian:: 6 | 7 | $ sudo apt-get update 8 | $ sudo apt-get upgrade 9 | 10 | Install ``pifacedigitalio`` with the following command: 11 | 12 | Python 3: 13 | $ sudo pip3 install pifacedigitalio 14 | 15 | Notice 1: Installation from Raspbian repository with apt is not longer the preferred way, take a look into `pifacecommon issue #27 `_ 16 | 17 | Notice 2: Python 2 support is "end-of-life" since Jan 2020, refer to https://www.python.org/doc/sunset-python-2/ 18 | 19 | Test by running the ``blink.py`` program:: 20 | 21 | $ python3 /usr/share/doc/python3-pifacedigitalio/examples/blink.py 22 | 23 | Emulator 24 | ======== 25 | Install ``python3-pifacedigital-emulator`` with the following command:: 26 | 27 | $ sudo apt-get install python3-pifacedigital-emulator 28 | 29 | Start the emulator with:: 30 | 31 | $ pifacedigital-emulator 32 | 33 | .. note:: You must be in an X11 session (``startx``). 34 | -------------------------------------------------------------------------------- /docs/pifacedigital.rst: -------------------------------------------------------------------------------- 1 | ############## 2 | PiFace Digital 3 | ############## 4 | PiFace Digital has eight inputs, eight outputs, eight LED's, two relays and 5 | four switches. 6 | 7 | Outputs 8 | ======= 9 | The eight output pins are located at the top of the board (near the LEDs). The 10 | outputs are open collectors, they can be thought of as switches connecting to 11 | ground. This offers greater flexibility so that PiFace Digital can control devices 12 | that operate using different voltages. The ninth pin provides 5V for connecting 13 | circuits to. 14 | 15 | LEDs 16 | ---- 17 | The LED's are connected in parallel to each of the outputs. This means that 18 | when you set output pin 4 high, LED 4 illuminates. 19 | 20 | >>> import pifacedigitalio 21 | >>> pifacedigital = pifacedigitalio.PiFaceDigital() 22 | >>> pifacedigital.output_pins[4].turn_on() # this command does the same thing... 23 | >>> pifacedigital.leds[4].turn_on() # ...as this command 24 | 25 | Relays 26 | ------ 27 | The two Relays are connected in parallel to output pins 0 and 1 respectively. 28 | When you set output pin 0 high, LED 0 illuminates and Relay 0 activates. 29 | 30 | >>> import pifacedigitalio 31 | >>> pifacedigital = pifacedigitalio.PiFaceDigital() 32 | >>> pifacedigital.output_pins[0].turn_on() # this command does the same thing... 33 | >>> pifacedigital.leds[0].turn_on() # ...as this command... 34 | >>> pifacedigital.relays[0].turn_on() # ...and this command... 35 | 36 | When activated, the relay bridges the top and middle pins. When deactivated the 37 | bottom two are connected. 38 | 39 | Relay activated:: 40 | 41 | [Top Pin ] 42 | [Common ] 43 | Bottom Pin 44 | 45 | Relay Deactivated:: 46 | 47 | Top Pin 48 | [Common ] 49 | [Bottom Pin] 50 | 51 | Inputs 52 | ====== 53 | The eight input pins detect a connection to ground (provided as the ninth pin). 54 | The four switches are connected in parallel to the first four input pins. The 55 | inputs are *pulled up* to 5V. This can be turned off so that the inputs float. 56 | 57 | >>> import pifacedigitalio 58 | >>> pifacedigital = pifacedigitalio.PiFaceDigital() 59 | >>> 60 | >>> # without anything pressed 61 | >>> pifacedigital.input_port.value 62 | 0 63 | >>> pifacedigital.input_pins[0].value 64 | 0 65 | >>> pifacedigital.switches[0].value 66 | 0 67 | >>> 68 | >>> # pressing the third switch 69 | >>> pifacedigital.input_port.value 70 | 8 71 | >>> bin(pifacedigital.input_port.value) 72 | 0b100 73 | >>> pifacedigital.input_pins[2].value # this command is the same as... 74 | 1 75 | >>> pifacedigital.switches[2].value # ...this command 76 | 1 77 | -------------------------------------------------------------------------------- /docs/reference.rst: -------------------------------------------------------------------------------- 1 | ######### 2 | Reference 3 | ######### 4 | .. note:: Functions and classes in pifacedigitalio.core have been imported 5 | into the main namespace. :func:`pifacedigitalio.digital_write` is 6 | the same as :func:`pifacedigitalio.core.digital_write`. 7 | 8 | .. automodule:: pifacedigitalio.core 9 | :members: 10 | -------------------------------------------------------------------------------- /docs/simplewebcontrol.rst: -------------------------------------------------------------------------------- 1 | Simple Web Control 2 | ================== 3 | 4 | You can control PiFace Digital from a web browser (or any network enabled 5 | device) using the `simplewebcontrol.py` tool. 6 | 7 | You can start the tool by running the following command on your Raspberry Pi:: 8 | 9 | $ python3 /usr/share/doc/python3-pifacedigitalio/examples/simplewebcontrol.py 10 | 11 | This will start a simple web server on port 8000 which you can access using 12 | a web browser. 13 | 14 | Type the following into the address bar of a browser on any machine in the 15 | local network:: 16 | 17 | http://192.168.1.3:8000 18 | 19 | .. note:: Relace ``192.168.1.3`` with the IP address of your Raspberry Pi. 20 | 21 | It will return a `JSON object `_ describing the current 22 | state of PiFace Digital:: 23 | 24 | {'input_port': 0, 'output_port': 0} 25 | 26 | 27 | Controlling Output 28 | ------------------ 29 | You can set the output port using the URL:: 30 | 31 | http://192.168.1.61:8000/?output_port=0xaa 32 | 33 | 34 | Changing Port 35 | ------------- 36 | You can specify which port you would like ``simplewebcontrol.py`` to use by 37 | passing the port number as the first argument:: 38 | 39 | $ python3 /usr/share/doc/python3-pifacedigitalio/examples/simplewebcontrol.py 12345 40 | -------------------------------------------------------------------------------- /examples/blink.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import pifacedigitalio 3 | 4 | 5 | DELAY = 1.0 # seconds 6 | 7 | 8 | if __name__ == "__main__": 9 | pifacedigital = pifacedigitalio.PiFaceDigital() 10 | while True: 11 | pifacedigital.leds[7].toggle() 12 | sleep(DELAY) 13 | -------------------------------------------------------------------------------- /examples/presslights.py: -------------------------------------------------------------------------------- 1 | import pifacedigitalio 2 | 3 | 4 | def switch_pressed(event): 5 | event.chip.output_pins[event.pin_num].turn_on() 6 | 7 | 8 | def switch_unpressed(event): 9 | event.chip.output_pins[event.pin_num].turn_off() 10 | 11 | 12 | if __name__ == "__main__": 13 | pifacedigital = pifacedigitalio.PiFaceDigital() 14 | 15 | listener = pifacedigitalio.InputEventListener(chip=pifacedigital) 16 | for i in range(4): 17 | listener.register(i, pifacedigitalio.IODIR_ON, switch_pressed) 18 | listener.register(i, pifacedigitalio.IODIR_OFF, switch_unpressed) 19 | listener.activate() 20 | -------------------------------------------------------------------------------- /examples/simplewebcontrol.py: -------------------------------------------------------------------------------- 1 | """ 2 | simplewebcontrol.py 3 | Controls PiFace Digital through a web browser. Returns the status of the 4 | input port and the output port in a JSON string. Set the output with GET 5 | variables. 6 | 7 | Copyright (C) 2013 Thomas Preston 8 | 9 | This program is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | This program is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with this program. If not, see . 21 | """ 22 | import sys 23 | import subprocess 24 | import http.server 25 | import urllib.parse 26 | import pifacedigitalio 27 | 28 | 29 | JSON_FORMAT = "{{'input_port': {input}, 'output_port': {output}}}" 30 | DEFAULT_PORT = 8000 31 | OUTPUT_PORT_GET_STRING = "output_port" 32 | GET_IP_CMD = "hostname -I" 33 | 34 | 35 | class PiFaceWebHandler(http.server.BaseHTTPRequestHandler): 36 | """Handles PiFace web control requests""" 37 | def do_GET(self): 38 | output_value = self.pifacedigital.output_port.value 39 | input_value = self.pifacedigital.input_port.value 40 | 41 | # parse the query string 42 | qs = urllib.parse.urlparse(self.path).query 43 | query_components = urllib.parse.parse_qs(qs) 44 | 45 | # set the output 46 | if OUTPUT_PORT_GET_STRING in query_components: 47 | new_output_value = query_components["output_port"][0] 48 | output_value = self.set_output_port(new_output_value, output_value) 49 | 50 | # create the JSON content 51 | content = bytes(JSON_FORMAT.format( 52 | input=input_value, 53 | output=output_value, 54 | ), 'UTF-8') 55 | 56 | # reply with JSON 57 | self.send_response(200) 58 | self.send_header("Content-type", "application/json") 59 | self.send_header("Content-length", str(len(content))) 60 | self.end_headers() 61 | self.wfile.write(content) 62 | 63 | # Uncomment this function if you want to access this PiFace server 64 | # from a web app (Web app is loaded from another server, not from this PiFace server). 65 | # Normally this is not allowed. Uncomment this to allow this scenario. 66 | #def end_headers (self): 67 | # self.send_header('Access-Control-Allow-Origin', '*') 68 | # http.server.BaseHTTPRequestHandler.end_headers(self) 69 | 70 | def set_output_port(self, new_value, old_value=0): 71 | """Sets the output port value to new_value, defaults to old_value.""" 72 | print("Setting output port to {}.".format(new_value)) 73 | port_value = old_value 74 | try: 75 | port_value = int(new_value) # dec 76 | except ValueError: 77 | port_value = int(new_value, 16) # hex 78 | finally: 79 | self.pifacedigital.output_port.value = port_value 80 | return port_value 81 | 82 | 83 | def get_my_ip(): 84 | """Returns this computers IP address as a string.""" 85 | ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1] 86 | return ip.strip() 87 | 88 | 89 | if __name__ == "__main__": 90 | # get the port 91 | if len(sys.argv) > 1: 92 | port = int(sys.argv[1]) 93 | else: 94 | port = DEFAULT_PORT 95 | 96 | # set up PiFace Digital 97 | PiFaceWebHandler.pifacedigital = pifacedigitalio.PiFaceDigital() 98 | 99 | print("Starting simple PiFace web control at:\n\n" 100 | "\thttp://{addr}:{port}\n\n" 101 | "Change the output_port with:\n\n" 102 | "\thttp://{addr}:{port}?output_port=0xAA\n" 103 | .format(addr=get_my_ip(), port=port)) 104 | 105 | # run the server 106 | server_address = ('', port) 107 | try: 108 | httpd = http.server.HTTPServer(server_address, PiFaceWebHandler) 109 | httpd.serve_forever() 110 | except KeyboardInterrupt: 111 | print('^C received, shutting down server') 112 | httpd.socket.close() 113 | -------------------------------------------------------------------------------- /examples/whackamole.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from time import sleep 3 | from random import randint, random 4 | import pifacedigitalio 5 | 6 | 7 | NUM_MOLES = 4 # max 4 8 | 9 | 10 | class Mole(object): 11 | def __init__(self, number, pifacedigital): 12 | led_start_index = number * 2 13 | self.leds = ( 14 | pifacedigital.leds[::-1][led_start_index], 15 | pifacedigital.leds[::-1][led_start_index+1] 16 | ) 17 | self.hiding = True 18 | 19 | @property 20 | def hiding(self): 21 | return self._is_hiding 22 | 23 | @hiding.setter 24 | def hiding(self, should_hide): 25 | if should_hide: 26 | self.hide() 27 | else: 28 | self.show() 29 | 30 | def hide(self): 31 | for led in self.leds: 32 | led.turn_off() 33 | self._is_hiding = True 34 | 35 | def show(self): 36 | for led in self.leds: 37 | led.turn_on() 38 | self._is_hiding = False 39 | 40 | def hit(self): 41 | """Attempt to hit a mole, return success.""" 42 | if self.hiding: 43 | return False 44 | else: 45 | self.hide() 46 | return True 47 | 48 | 49 | class WhackAMoleGame(object): 50 | def __init__(self): 51 | self.should_stop = False 52 | self.pifacedigital = pifacedigitalio.PiFaceDigital() 53 | self.moles = [Mole(i, self.pifacedigital) for i in range(NUM_MOLES)] 54 | self._current_points = 0 55 | self.max_points = 0 56 | self.inputlistener = \ 57 | pifacedigitalio.InputEventListener(chip=self.pifacedigital) 58 | for i in range(4): 59 | self.inputlistener.register( 60 | i, pifacedigitalio.IODIR_FALLING_EDGE, self.hit_mole) 61 | self.inputlistener.activate() 62 | 63 | def start(self): 64 | while not self.should_stop: 65 | # randomly moves moles up and down 66 | for mole in self.moles: 67 | should_hide = (randint(0, 1) == 1) 68 | mole.hiding = should_hide 69 | 70 | #sleep(random() * 3) 71 | sleep(1) 72 | self.inputlistener.deactivate() 73 | self.flash_leds() 74 | 75 | @property 76 | def points(self): 77 | return self._current_points 78 | 79 | @points.setter 80 | def points(self, new_value): 81 | if self.max_points > 1 and new_value <= 1: 82 | self.should_stop = True # end the game 83 | return 84 | 85 | self.max_points = max(self.max_points, new_value) 86 | self._current_points = new_value 87 | 88 | def hit_mole(self, event): 89 | # print("You pressed", event.pin_num) 90 | if game.moles[event.pin_num].hit(): 91 | game.points += 1 92 | print("You hit a mole!") 93 | else: 94 | game.points -= 1 95 | print("You missed!") 96 | 97 | def flash_leds(self): 98 | self.pifacedigital.output_port.all_on() 99 | for i in range(10): 100 | self.pifacedigital.output_port.toggle() 101 | sleep(0.1) 102 | self.pifacedigital.output_port.all_off() 103 | 104 | 105 | if __name__ == "__main__": 106 | game = WhackAMoleGame() 107 | game.start() 108 | print("You scored {}!".format(game.max_points)) 109 | -------------------------------------------------------------------------------- /pifacedigitalio/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Provides common I/O methods for interfacing with PiFace Products 3 | Copyright (C) 2013 Thomas Preston 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | """ 18 | from pifacecommon.interrupts import ( 19 | IODIR_FALLING_EDGE, 20 | IODIR_RISING_EDGE, 21 | IODIR_ON, 22 | IODIR_OFF, 23 | IODIR_BOTH, 24 | ) 25 | from .core import * -------------------------------------------------------------------------------- /pifacedigitalio/core.py: -------------------------------------------------------------------------------- 1 | import pifacecommon.mcp23s17 2 | import pifacecommon.interrupts 3 | 4 | # /dev/spidev. 5 | DEFAULT_SPI_BUS = 0 6 | DEFAULT_SPI_CHIP_SELECT = 0 7 | 8 | MAX_BOARDS = 4 9 | # list of PiFace Digitals for digital_read/digital_write 10 | _pifacedigitals = [None] * MAX_BOARDS 11 | 12 | 13 | class NoPiFaceDigitalDetectedError(Exception): 14 | pass 15 | 16 | 17 | class NoPiFaceDigitalError(Exception): 18 | pass 19 | 20 | 21 | class PiFaceDigital(pifacecommon.mcp23s17.MCP23S17, 22 | pifacecommon.interrupts.GPIOInterruptDevice): 23 | """A PiFace Digital board. 24 | 25 | :attribute: input_pins -- list containing 26 | :class:`pifacecommon.mcp23s17.MCP23S17RegisterBitNeg`. 27 | :attribute: input_port -- See 28 | :class:`pifacecommon.mcp23s17.MCP23S17RegisterNeg`. 29 | :attribute: output_pins -- list containing 30 | :class:`pifacecommon.mcp23s17.MCP23S17RegisterBit`. 31 | :attribute: output_port -- See 32 | :class:`pifacecommon.mcp23s17.MCP23S17Register`. 33 | :attribute: leds -- 34 | list containing :class:`pifacecommon.mcp23s17.MCP23S17RegisterBit`. 35 | :attribute: relays -- 36 | list containing :class:`pifacecommon.mcp23s17.MCP23S17RegisterBit`. 37 | :attribute: switches -- 38 | list containing :class:`pifacecommon.mcp23s17.MCP23S17RegisterBit`. 39 | 40 | Example: 41 | 42 | >>> pfd = pifacedigitalio.PiFaceDigital() 43 | >>> pfd.input_port.value 44 | 0 45 | >>> pfd.output_port.value = 0xAA 46 | >>> pfd.leds[5].turn_on() 47 | """ 48 | def __init__(self, 49 | hardware_addr=0, 50 | bus=DEFAULT_SPI_BUS, 51 | chip_select=DEFAULT_SPI_CHIP_SELECT, 52 | init_board=True): 53 | super(PiFaceDigital, self).__init__(hardware_addr, bus, chip_select) 54 | 55 | self.input_pins = [pifacecommon.mcp23s17.MCP23S17RegisterBitNeg( 56 | i, pifacecommon.mcp23s17.GPIOB, self) 57 | for i in range(8)] 58 | 59 | self.input_port = pifacecommon.mcp23s17.MCP23S17RegisterNeg( 60 | pifacecommon.mcp23s17.GPIOB, self) 61 | 62 | self.output_pins = [pifacecommon.mcp23s17.MCP23S17RegisterBit( 63 | i, pifacecommon.mcp23s17.GPIOA, self) 64 | for i in range(8)] 65 | 66 | self.output_port = pifacecommon.mcp23s17.MCP23S17Register( 67 | pifacecommon.mcp23s17.GPIOA, self) 68 | 69 | self.leds = [pifacecommon.mcp23s17.MCP23S17RegisterBit( 70 | i, pifacecommon.mcp23s17.GPIOA, self) 71 | for i in range(8)] 72 | 73 | self.relays = [pifacecommon.mcp23s17.MCP23S17RegisterBit( 74 | i, pifacecommon.mcp23s17.GPIOA, self) 75 | for i in range(2)] 76 | 77 | self.switches = [pifacecommon.mcp23s17.MCP23S17RegisterBitNeg( 78 | i, pifacecommon.mcp23s17.GPIOB, self) 79 | for i in range(4)] 80 | 81 | if init_board: 82 | self.init_board() 83 | 84 | def enable_interrupts(self): 85 | self.gpintenb.value = 0xFF # enable interrupts 86 | self.gpio_interrupts_enable() 87 | 88 | def disable_interrupts(self): 89 | self.gpintenb.value = 0x00 90 | self.gpio_interrupts_disable() 91 | 92 | def init_board(self): 93 | ioconfig = ( 94 | pifacecommon.mcp23s17.BANK_OFF | 95 | pifacecommon.mcp23s17.INT_MIRROR_OFF | 96 | pifacecommon.mcp23s17.SEQOP_OFF | 97 | pifacecommon.mcp23s17.DISSLW_OFF | 98 | pifacecommon.mcp23s17.HAEN_ON | 99 | pifacecommon.mcp23s17.ODR_OFF | 100 | pifacecommon.mcp23s17.INTPOL_LOW 101 | ) 102 | self.iocon.value = ioconfig 103 | if self.iocon.value != ioconfig: 104 | raise NoPiFaceDigitalDetectedError( 105 | "No PiFace Digital board detected (hardware_addr={h}, " 106 | "bus={b}, chip_select={c}).".format( 107 | h=self.hardware_addr, b=self.bus, c=self.chip_select)) 108 | else: 109 | # finish configuring the board 110 | self.gpioa.value = 0 111 | self.iodira.value = 0 # GPIOA as outputs 112 | self.iodirb.value = 0xFF # GPIOB as inputs 113 | self.gppub.value = 0xFF # input pullups on 114 | self.enable_interrupts() 115 | 116 | def deinit_board(self): 117 | if self.gpintenb.value != 0x00: # probably should be a function 118 | self.disable_interrupts() 119 | self.close_fd() 120 | 121 | 122 | class InputEventListener(pifacecommon.interrupts.PortEventListener): 123 | """Listens for events on the input port and calls the mapped callback 124 | functions. 125 | 126 | >>> def print_flag(event): 127 | ... print(event.interrupt_flag) 128 | ... 129 | >>> listener = pifacedigitalio.InputEventListener() 130 | >>> listener.register(0, pifacedigitalio.IODIR_ON, print_flag) 131 | >>> listener.activate() 132 | """ 133 | def __init__(self, chip=None, daemon=False): 134 | if chip is None: 135 | chip = PiFaceDigital() 136 | # requires version bump to v4.0.0 becasue method signature has changed 137 | # super(InputEventListener, self).__init__(pifacecommon.mcp23s17.GPIOB, 138 | # chip, 139 | # daemon=daemon) 140 | # work around for now -- doesn't depend on new version of pifacecommon 141 | super(InputEventListener, self).__init__(pifacecommon.mcp23s17.GPIOB, 142 | chip) 143 | self.detector.daemon = daemon 144 | self.dispatcher.daemon = daemon 145 | 146 | 147 | def init(init_board=True, 148 | bus=DEFAULT_SPI_BUS, 149 | chip_select=DEFAULT_SPI_CHIP_SELECT): 150 | """Initialises all PiFace Digital boards. Only required when using 151 | :func:`digital_read` and :func:`digital_write`. 152 | 153 | :param init_board: Initialise each board (default: True) 154 | :type init_board: boolean 155 | :param bus: SPI bus /dev/spidev. (default: {bus}) 156 | :type bus: int 157 | :param chip_select: SPI chip select /dev/spidev. 158 | (default: {chip}) 159 | :type chip_select: int 160 | :raises: :class:`NoPiFaceDigitalDetectedError` 161 | """.format(bus=DEFAULT_SPI_BUS, chip=DEFAULT_SPI_CHIP_SELECT) 162 | failed_boards = list() 163 | for hardware_addr in range(MAX_BOARDS): 164 | try: 165 | global _pifacedigitals 166 | _pifacedigitals[hardware_addr] = PiFaceDigital(hardware_addr, 167 | bus, 168 | chip_select, 169 | init_board) 170 | except NoPiFaceDigitalDetectedError as e: 171 | failed_boards.append(e) 172 | if len(failed_boards) >= MAX_BOARDS: 173 | raise failed_boards[0] 174 | 175 | 176 | def deinit(bus=DEFAULT_SPI_BUS, 177 | chip_select=DEFAULT_SPI_CHIP_SELECT): 178 | """Stops interrupts on all boards. Only required when using 179 | :func:`digital_read` and :func:`digital_write`. 180 | 181 | :param bus: SPI bus /dev/spidev. (default: {bus}) 182 | :type bus: int 183 | :param chip_select: SPI chip select /dev/spidev. 184 | (default: {chip}) 185 | :type chip_select: int 186 | """ 187 | global _pifacedigitals 188 | for pfd in _pifacedigitals: 189 | try: 190 | pfd.deinit_board() 191 | except AttributeError: 192 | pass 193 | 194 | 195 | # wrapper functions for backwards compatibility 196 | def digital_read(pin_num, hardware_addr=0): 197 | """Returns the value of the input pin specified. 198 | 199 | .. note:: This function is for familiarality with users of other types of 200 | IO board. Consider accessing the ``input_pins`` attribute of a 201 | PiFaceDigital object: 202 | 203 | >>> pfd = PiFaceDigital(hardware_addr) 204 | >>> pfd.input_pins[pin_num].value 205 | 0 206 | 207 | :param pin_num: The pin number to read. 208 | :type pin_num: int 209 | :param hardware_addr: The board to read from (default: 0) 210 | :type hardware_addr: int 211 | :returns: int -- value of the pin 212 | """ 213 | return _get_pifacedigital(hardware_addr).input_pins[pin_num].value 214 | 215 | 216 | def digital_write(pin_num, value, hardware_addr=0): 217 | """Writes the value to the input pin specified. 218 | 219 | .. note:: This function is for familiarality with users of other types of 220 | IO board. Consider accessing the ``output_pins`` attribute of a 221 | PiFaceDigital object: 222 | 223 | >>> pfd = PiFaceDigital(hardware_addr) 224 | >>> pfd.output_pins[pin_num].value = 1 225 | 226 | :param pin_num: The pin number to write to. 227 | :type pin_num: int 228 | :param value: The value to write. 229 | :type value: int 230 | :param hardware_addr: The board to read from (default: 0) 231 | :type hardware_addr: int 232 | """ 233 | _get_pifacedigital(hardware_addr).output_pins[pin_num].value = value 234 | 235 | 236 | def digital_read_pullup(pin_num, hardware_addr=0): 237 | """Returns the value of the input pullup specified. 238 | 239 | .. note:: This function is for familiarality with users of other types of 240 | IO board. Consider accessing the ``gppub`` attribute of a 241 | PiFaceDigital object: 242 | 243 | >>> pfd = PiFaceDigital(hardware_addr) 244 | >>> hex(pfd.gppub.value) 245 | 0xff 246 | >>> pfd.gppub.bits[pin_num].value 247 | 1 248 | 249 | :param pin_num: The pin number to read. 250 | :type pin_num: int 251 | :param hardware_addr: The board to read from (default: 0) 252 | :type hardware_addr: int 253 | :returns: int -- value of the pin 254 | """ 255 | return _get_pifacedigital(hardware_addr).gppub.bits[pin_num].value 256 | 257 | 258 | def digital_write_pullup(pin_num, value, hardware_addr=0): 259 | """Writes the value to the input pullup specified. 260 | 261 | .. note:: This function is for familiarality with users of other types of 262 | IO board. Consider accessing the ``gppub`` attribute of a 263 | PiFaceDigital object: 264 | 265 | >>> pfd = PiFaceDigital(hardware_addr) 266 | >>> hex(pfd.gppub.value) 267 | 0xff 268 | >>> pfd.gppub.bits[pin_num].value = 1 269 | 270 | :param pin_num: The pin number to write to. 271 | :type pin_num: int 272 | :param value: The value to write. 273 | :type value: int 274 | :param hardware_addr: The board to read from (default: 0) 275 | :type hardware_addr: int 276 | """ 277 | _get_pifacedigital(hardware_addr).gppub.bits[pin_num].value = value 278 | 279 | 280 | def _get_pifacedigital(hardware_addr): 281 | global _pifacedigitals 282 | if _pifacedigitals[hardware_addr] is None: 283 | raise NoPiFaceDigitalError("There is no PiFace Digital with " 284 | "hardware_addr {}".format(hardware_addr)) 285 | else: 286 | return _pifacedigitals[hardware_addr] 287 | -------------------------------------------------------------------------------- /pifacedigitalio/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '3.1.0' 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pifacecommon==4.0.0 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from distutils.core import setup 3 | 4 | 5 | # PY3 = sys.version_info.major >= 3 # major is not available in python2.6 6 | PY3 = sys.version_info[0] >= 3 7 | PIFACECOMMON_MIN_VERSION = '3.0.0' 8 | VERSION_FILE = "pifacedigitalio/version.py" 9 | 10 | 11 | def get_version(): 12 | if PY3: 13 | version_vars = {} 14 | with open(VERSION_FILE) as f: 15 | code = compile(f.read(), VERSION_FILE, 'exec') 16 | exec(code, None, version_vars) 17 | return version_vars['__version__'] 18 | else: 19 | execfile(VERSION_FILE) 20 | return __version__ 21 | 22 | 23 | setup( 24 | name='pifacedigitalio', 25 | version=get_version(), 26 | description='The PiFace Digital I/O module.', 27 | author='Thomas Preston', 28 | author_email='thomas.preston@openlx.org.uk', 29 | url='http://piface.github.io/pifacedigitalio/', 30 | packages=['pifacedigitalio'], 31 | long_description=open('README.md').read() + open('CHANGELOG').read(), 32 | classifiers=[ 33 | "License :: OSI Approved :: GNU Affero General Public License v3 or " 34 | "later (AGPLv3+)", 35 | "Programming Language :: Python :: 3", 36 | "Programming Language :: Python :: 2", 37 | "Development Status :: 5 - Production/Stable", 38 | "Intended Audience :: Developers", 39 | "Topic :: Software Development :: Libraries :: Python Modules", 40 | ], 41 | keywords='piface digital raspberrypi openlx', 42 | license='GPLv3+', 43 | requires=['pifacecommon (>='+PIFACECOMMON_MIN_VERSION+')'] 44 | ) 45 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from __future__ import print_function 3 | import sys 4 | import unittest 5 | import threading 6 | import pifacecommon 7 | import pifacedigitalio 8 | import argparse 9 | 10 | 11 | PY3 = sys.version_info.major >= 3 12 | if not PY3: 13 | input = raw_input 14 | 15 | from time import sleep 16 | 17 | class Barrier(object): 18 | def __init__(self, n, timeout=None): 19 | self.count = 0 20 | self.n = n 21 | self.timeout = timeout 22 | 23 | def wait(self): 24 | self.count += 1 25 | while self.count < self.n: 26 | sleep(0.0001) 27 | 28 | threading.Barrier = Barrier 29 | 30 | 31 | OUTPUT_RANGE = LED_RANGE = INPUT_RANGE = 8 32 | SWITCH_RANGE = 4 33 | RELAY_RANGE = 2 34 | 35 | 36 | class TestRangedItem(object): 37 | def test_normal_init(self): 38 | for i in self.item_range: 39 | item_instance = self.item_type(i) 40 | self.assertTrue(type(item_instance) is self.item_type) 41 | 42 | def test_boundary_init(self): 43 | boundaries = (min(self.item_range) - 1, max(self.item_range) + 1) 44 | for i in boundaries: 45 | self.assertRaises( 46 | pifacecommon.core.RangeError, 47 | self.item_type, 48 | i 49 | ) 50 | 51 | 52 | class TestLED(TestRangedItem, unittest.TestCase): 53 | def setUp(self): 54 | self.item_type = pifacedigitalio.LED 55 | self.item_range = range(LED_RANGE) 56 | 57 | 58 | class TestSwitch(TestRangedItem, unittest.TestCase): 59 | def setUp(self): 60 | self.item_type = pifacedigitalio.Switch 61 | self.item_range = range(SWITCH_RANGE) 62 | 63 | 64 | class TestRelay(TestRangedItem, unittest.TestCase): 65 | def setUp(self): 66 | self.item_type = pifacedigitalio.Relay 67 | self.item_range = range(RELAY_RANGE) 68 | 69 | 70 | class TestDigitalRead(unittest.TestCase): 71 | def setUp(self): 72 | self.old_read_bit = pifacecommon.core.read_bit 73 | pifacedigitalio.init() 74 | # function is supposed to return 1, testing with 0 75 | pifacecommon.core.read_bit = lambda pin, port, board: 0 76 | 77 | def test_flip_bit(self): 78 | # digital_read should flip 0 to 1 79 | self.assertEqual(pifacedigitalio.digital_read(0, 0), 1) 80 | 81 | def tearDown(self): 82 | pifacedigitalio.deinit() 83 | pifacecommon.core.read_bit = self.old_read_bit 84 | 85 | 86 | class TestPiFaceDigitalOutput(unittest.TestCase): 87 | def setUp(self): 88 | pifacedigitalio.init() 89 | 90 | def test_leds(self): 91 | global pifacedigitals 92 | for pfd in pifacedigitals: 93 | for i in range(LED_RANGE): 94 | pfd.leds[i].turn_on() 95 | self.assertEqual(pfd.output_pins[i].value, 1) 96 | pfd.leds[i].toggle() 97 | self.assertEqual(pfd.output_pins[i].value, 0) 98 | pfd.leds[i].toggle() 99 | self.assertEqual(pfd.output_pins[i].value, 1) 100 | pfd.leds[i].turn_off() 101 | self.assertEqual(pfd.output_pins[i].value, 0) 102 | 103 | def test_relays(self): 104 | global pifacedigitals 105 | for pfd in pifacedigitals: 106 | for i in range(RELAY_RANGE): 107 | pfd.relays[i].turn_on() 108 | self.assertEqual(pfd.relays[i].value, 1) 109 | pfd.relays[i].toggle() 110 | self.assertEqual(pfd.relays[i].value, 0) 111 | pfd.relays[i].toggle() 112 | self.assertEqual(pfd.relays[i].value, 1) 113 | pfd.relays[i].turn_off() 114 | self.assertEqual(pfd.relays[i].value, 0) 115 | 116 | def test_output_pins(self): 117 | global pifacedigitals 118 | for pfd in pifacedigitals: 119 | for i in range(OUTPUT_RANGE): 120 | pfd.output_pins[i].turn_on() 121 | self.assertEqual(pfd.output_pins[i].value, 1) 122 | pfd.output_pins[i].toggle() 123 | self.assertEqual(pfd.output_pins[i].value, 0) 124 | pfd.output_pins[i].toggle() 125 | self.assertEqual(pfd.output_pins[i].value, 1) 126 | pfd.output_pins[i].turn_off() 127 | self.assertEqual(pfd.output_pins[i].value, 0) 128 | 129 | def test_output_port(self): 130 | global pifacedigitals 131 | for pfd in pifacedigitals: 132 | test_value = 0xAA 133 | pfd.output_port.all_on() 134 | self.assertEqual(pfd.output_port.value, 0xFF) 135 | pfd.output_port.value = test_value 136 | self.assertEqual(pfd.output_port.value, test_value) 137 | pfd.output_port.toggle() 138 | self.assertEqual(pfd.output_port.value, 0xff ^ test_value) 139 | pfd.output_port.toggle() 140 | self.assertEqual(pfd.output_port.value, test_value) 141 | pfd.output_port.all_off() 142 | self.assertEqual(pfd.output_port.value, 0) 143 | 144 | def tearDown(self): 145 | pifacedigitalio.deinit() 146 | 147 | 148 | class TestPiFaceDigitalInput(unittest.TestCase): 149 | """General use tests (not really in the spirit of unittesting).""" 150 | def setUp(self): 151 | pifacedigitalio.init() 152 | 153 | def test_switches(self): 154 | global pifacedigitals 155 | for pfd in pifacedigitals: 156 | for a, b in ((0, 2), (1, 3)): 157 | input( 158 | "Hold switch {a} and {b} on board {board} and then " 159 | "press enter.".format(a=a, b=b, board=pfd.hardware_addr)) 160 | self.assertEqual(pfd.switches[a].value, 1) 161 | self.assertEqual(pfd.switches[a].value, 1) 162 | 163 | # while we're here, test the input pins 164 | self.assertEqual(pfd.input_pins[a].value, 1) 165 | self.assertEqual(pfd.input_pins[a].value, 1) 166 | 167 | # and the input port 168 | bit_pattern = (1 << a) ^ (1 << b) 169 | self.assertEqual(pfd.input_port.value, bit_pattern) 170 | 171 | # def test_input_pins(self): 172 | # if TEST_INPUT_PORT: 173 | # for i in range(INPUT_RANGE): 174 | # input("Connect input {i}, then press enter.".format(i=i)) 175 | # self.assertEqual(self.pfd.switches[i].value, 1) 176 | 177 | # def test_input_port(self): 178 | # if TEST_INPUT_PORT: 179 | # input("Connect pins 0, 2, 4 and 6, then press enter.") 180 | # self.assertEqual(self.pfd.input_port.value, 0xAA) 181 | # input("Connect pins 1, 3, 5 and 7, then press enter.") 182 | # self.assertEqual(self.pfd.input_port.value, 0x55) 183 | 184 | def tearDown(self): 185 | pifacedigitalio.deinit() 186 | 187 | 188 | class TestInterrupts(unittest.TestCase): 189 | def setUp(self): 190 | pifacedigitalio.init() 191 | self.direction = pifacedigitalio.IODIR_ON 192 | self.barriers = dict() 193 | self.board_switch_pressed = list() 194 | self.listeners = list() 195 | 196 | global pifacedigitals 197 | for p in pifacedigitals: 198 | self.barriers[p.hardware_addr] = threading.Barrier(2, timeout=10) 199 | listener = pifacedigitalio.InputEventListener(p.hardware_addr) 200 | listener.register(0, self.direction, self.interrupts_test_helper) 201 | self.listeners.append(listener) 202 | 203 | def test_interrupt(self): 204 | for listener in self.listeners: 205 | listener.activate() 206 | print("Press switch 0 on every board.") 207 | barriers = self.barriers.items() if PY3 else self.barriers.iteritems() 208 | for hardware_addr, barrier in barriers: 209 | barrier.wait() 210 | global pifacedigitals 211 | for p in pifacedigitals: 212 | self.assertTrue(p.hardware_addr in self.board_switch_pressed) 213 | 214 | def interrupts_test_helper(self, event): 215 | self.assertEqual(event.interrupt_flag, 0x1) 216 | self.assertEqual(event.interrupt_capture, 0xfe) 217 | self.assertEqual(event.pin_num, 0) 218 | self.assertEqual(event.direction, self.direction) 219 | self.board_switch_pressed.append(event.hardware_addr) 220 | print("Switch 0 on board {} pressed.".format(event.hardware_addr)) 221 | self.barriers[event.hardware_addr].wait() 222 | 223 | def tearDown(self): 224 | for listener in self.listeners: 225 | listener.deactivate() 226 | pifacedigitalio.deinit() 227 | 228 | 229 | def remove_arg(shortarg, longarg): 230 | try: 231 | sys.argv.remove(longarg) 232 | except ValueError: 233 | sys.argv.remove(shortarg) 234 | 235 | 236 | if __name__ == "__main__": 237 | parser = argparse.ArgumentParser() 238 | parser.add_argument( 239 | "-b0", "--board0", help="test PiFace Digital board 0 (default)", 240 | action="store_true") 241 | for i in range(1, 4): 242 | parser.add_argument( 243 | "-b{}".format(i), 244 | "--board{}".format(i), 245 | help="test PiFace Digital board {}".format(i), 246 | action="store_true") 247 | args = parser.parse_args() 248 | 249 | global pifacedigitals 250 | pifacedigitals = list() 251 | 252 | if args.board0 or not (args.board1 or args.board2 or args.board3): 253 | pifacedigitals.append(pifacedigitalio.PiFaceDigital(0)) 254 | if args.board0: 255 | remove_arg("-b0", "--board0") 256 | 257 | if args.board1: 258 | pifacedigitals.append(pifacedigitalio.PiFaceDigital(1)) 259 | remove_arg("-b1", "--board1") 260 | 261 | if args.board2: 262 | pifacedigitals.append(pifacedigitalio.PiFaceDigital(2)) 263 | remove_arg("-b2", "--board2") 264 | 265 | if args.board3: 266 | pifacedigitals.append(pifacedigitalio.PiFaceDigital(3)) 267 | remove_arg("-b3", "--board3") 268 | 269 | boards_string = ", ".join([str(pfd.hardware_addr) for pfd in pifacedigitals]) 270 | print("Testing boards:", boards_string) 271 | 272 | unittest.main() 273 | --------------------------------------------------------------------------------