├── .gitignore ├── CHANGELOG ├── COPYING ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── conf.py ├── example.rst ├── index.rst ├── installation.rst └── reference.rst ├── pifacecommon ├── __init__.py ├── asm_generic_ioctl.py ├── core.py ├── interrupts.py ├── linux_spi_spidev.py ├── mcp23s17.py ├── spi.py └── version.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | 3 | dpkg-files 4 | makedebpkg.sh 5 | *.deb 6 | _build 7 | *.log 8 | MANIFEST 9 | deb_dist 10 | 11 | # databases 12 | *.db 13 | 14 | *.py[cod] 15 | 16 | # C extensions 17 | *.so 18 | 19 | # Packages 20 | *.egg 21 | *.egg-info 22 | dist 23 | build 24 | eggs 25 | parts 26 | bin 27 | var 28 | sdist 29 | develop-eggs 30 | .installed.cfg 31 | lib 32 | lib64 33 | __pycache__ 34 | 35 | # Installer logs 36 | pip-log.txt 37 | 38 | # Unit test / coverage reports 39 | .coverage 40 | .tox 41 | nosetests.xml 42 | 43 | # Translations 44 | *.mo 45 | 46 | # Mr Developer 47 | .mr.developer.cfg 48 | .project 49 | .pydevproject 50 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | v4.2.2 5 | ------ 6 | - Set explicit SPI frequency to allow board to work in newer kernels which has too high default frequency (PR#23) 7 | 8 | v4.2.0 9 | ------ 10 | - Added daemon flag for PortEventListener. 11 | 12 | v4.1.2 13 | ------ 14 | - Fixed bug with new Device Tree (Pi2) by changing GPIO_INTERRUPT_DEVICE 15 | from `/sys/devices/virtual/gpio/` to `/sys/class/gpio/` and changing udev 16 | rule. 17 | 18 | 19 | v4.1.1 20 | ------ 21 | - Support varying listeners. 22 | 23 | 24 | v4.1.0 25 | ------ 26 | - Added deregister to interrupts. 27 | 28 | 29 | v4.0.1 30 | ------ 31 | - Fixed SPI file descriptor bug when closing. 32 | - Fixed issue #14. 33 | 34 | 35 | v4.0.0 36 | ------ 37 | - Ignored "Interrupted system call" error in `watch_port_events`. 38 | - Rewrite main functions into chip specific (MCP23S17) class. 39 | - GPIOInterruptDevice class replacing core GPIO enable/disable functions. 40 | - SPIDevice class replacing spisend function. Can now add in spi_callback 41 | function which is called before each SPI write. 42 | - Updated installation instructions. 43 | 44 | 45 | v3.1.1 46 | ------ 47 | - Added IODIR_FALLING_EDGE and IODIR_RISING_EDGE to replace IODIR_ON and 48 | IODIR_OFF respectively. IODIR_ON and IODIR_OFF can still be used in the same 49 | way as before. Falling/Rising Edge are for physical level 1/0, On/Off are for 50 | logical (programmer) level 1/0. 51 | 52 | Physical Level (pifacecommon.read_bit): 53 | IODIR_FALLING_EDGE: 1 -> 0 54 | IODIR_RISING_EDGE: 0 -> 1 55 | Logical Level (pifacedigitalio.PiFaceDigital().input_pins[0].value): 56 | IODIR_ON: 0 -> 1 57 | IODIR_OFF: 1 -> 0 58 | 59 | Remember that PiFace Digital Inputs are active low: 60 | >>> pifacecommon.read_bit(0, INPUT_PORT) 61 | >>> 1 # physical 62 | >>> pifacedigitalio.PiFaceDigital().input_pins[0].value 63 | >>> 0 # logical 64 | 65 | - Fixed Debian package bug where setup script would not be executed. 66 | 67 | v3.1.0 68 | ------ 69 | - Added debouncing with adjustable `settle time`. 70 | 71 | v3.0.0 72 | ------ 73 | - Added timeout class (fixing Issue #2) in interrupts. 74 | - Added support for interrupts on multiple boards. 75 | - Interrupts must be enabled/disabled manually. Automatic handling of this 76 | broke interrupts from multiple boards. 77 | 78 | v2.0.2 79 | ------ 80 | - Moved version number to pifacecommon/version.py so that it can be read from 81 | setup.py and bin/uninstall.py. 82 | - Updated SPI help link to point to the new docs. 83 | - Moved installation scripts into single file for Debian packaging. 84 | 85 | v2.0.1 86 | ------ 87 | - Added version number in source. 88 | - Added uninstall script. 89 | 90 | v2.0.0 91 | ------ 92 | - Improved interrupts (different API, check the docs). 93 | - Reduced scope of global variables from package to individual modules. 94 | (Hiding namespaces from the end user is an attempt to simplify the interface 95 | for children. However this package is not intended for that audience 96 | and so messing with the namespaces only confuses things.) 97 | 98 | v1.2.1 99 | ------ 100 | - Supports Python 2. 101 | - Started using semantic versioning http://semver.org/. 102 | 103 | v1.2 104 | ---- 105 | - Started using a change log! 106 | - Removed errors submodule, custom exceptions now go in their respective 107 | modules. This might change back in a future release. 108 | - Fixed DigitalInput value bugs 109 | - Fixed SPI transfer bug.. Function spisend now takes bytes as an argument 110 | instead of a list. This makes more sense, since it returns bytes. 111 | - Removed install.sh, everything is now handled by setup.py. 112 | - Updated docs. 113 | -------------------------------------------------------------------------------- /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 | pifacecommon 2 | ============ 3 | 4 | Common functions for interacting with PiFace products. 5 | 6 | 7 | Documentation 8 | ============= 9 | 10 | [http://pifacecommon.readthedocs.org/](http://pifacecommon.readthedocs.org/) 11 | 12 | You can also find the documentation installed at: 13 | 14 | /usr/share/doc/python3-pifacecommon/ 15 | 16 | Install 17 | ======= 18 | 19 | Make sure you are using the lastest version of Raspbian: 20 | 21 | $ sudo apt-get update 22 | $ sudo apt-get upgrade 23 | 24 | Install `pifacecommon` with the following command: 25 | 26 | Python 3: 27 | $ sudo pip3 install pifacecommon 28 | 29 | 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) 30 | 31 | Notice 2: Python 2 support is "end-of-life" since Jan 2020, refer to https://www.python.org/doc/sunset-python-2/ 32 | 33 | 34 | You will also need to set up automatic loading of the SPI kernel module which 35 | can be done with the lastest version of `raspi-config`. Run: 36 | 37 | $ sudo raspi-config 38 | 39 | Then navigate to `Advanced Options`, `SPI` and select `yes`. 40 | -------------------------------------------------------------------------------- /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/PiFaceCommon.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PiFaceCommon.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/PiFaceCommon" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PiFaceCommon" 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 Common documentation build configuration file, created by 5 | # sphinx-quickstart on Wed Jun 19 13:52:03 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 | 22 | # -- General configuration ----------------------------------------------------- 23 | 24 | # If your documentation needs a minimal Sphinx version, state it here. 25 | #needs_sphinx = '1.0' 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be extensions 28 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 29 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath'] 30 | 31 | # Add any paths that contain templates here, relative to this directory. 32 | templates_path = ['_templates'] 33 | 34 | # The suffix of source filenames. 35 | source_suffix = '.rst' 36 | 37 | # The encoding of source files. 38 | #source_encoding = 'utf-8-sig' 39 | 40 | # The master toctree document. 41 | master_doc = 'index' 42 | 43 | # General information about the project. 44 | project = 'PiFace Common' 45 | copyright = '2013, Thomas Preston' 46 | 47 | # The version info for the project you're documenting, acts as replacement for 48 | # |version| and |release|, also used in various other places throughout the 49 | # built documents. 50 | # 51 | # The short X.Y version. 52 | import pifacecommon.version 53 | #version = '2.0.2' 54 | version = pifacecommon.version.__version__ 55 | # The full version, including alpha/beta/rc tags. 56 | #release = '2.0.2' 57 | release = pifacecommon.version.__version__ 58 | 59 | # The language for content autogenerated by Sphinx. Refer to documentation 60 | # for a list of supported languages. 61 | #language = None 62 | 63 | # There are two options for replacing |today|: either, you set today to some 64 | # non-false value, then it is used: 65 | #today = '' 66 | # Else, today_fmt is used as the format for a strftime call. 67 | #today_fmt = '%B %d, %Y' 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | exclude_patterns = ['_build'] 72 | 73 | # The reST default role (used for this markup: `text`) to use for all documents. 74 | #default_role = None 75 | 76 | # If true, '()' will be appended to :func: etc. cross-reference text. 77 | #add_function_parentheses = True 78 | 79 | # If true, the current module name will be prepended to all description 80 | # unit titles (such as .. function::). 81 | #add_module_names = True 82 | 83 | # If true, sectionauthor and moduleauthor directives will be shown in the 84 | # output. They are ignored by default. 85 | #show_authors = False 86 | 87 | # The name of the Pygments (syntax highlighting) style to use. 88 | pygments_style = 'sphinx' 89 | 90 | # A list of ignored prefixes for module index sorting. 91 | #modindex_common_prefix = [] 92 | 93 | 94 | # -- Options for HTML output --------------------------------------------------- 95 | 96 | # The theme to use for HTML and HTML Help pages. See the documentation for 97 | # a list of builtin themes. 98 | html_theme = 'default' 99 | 100 | # Theme options are theme-specific and customize the look and feel of a theme 101 | # further. For a list of options available for each theme, see the 102 | # documentation. 103 | #html_theme_options = {} 104 | 105 | # Add any paths that contain custom themes here, relative to this directory. 106 | #html_theme_path = [] 107 | 108 | # The name for this set of Sphinx documents. If None, it defaults to 109 | # " v documentation". 110 | #html_title = None 111 | 112 | # A shorter title for the navigation bar. Default is the same as html_title. 113 | #html_short_title = None 114 | 115 | # The name of an image file (relative to this directory) to place at the top 116 | # of the sidebar. 117 | #html_logo = None 118 | 119 | # The name of an image file (within the static path) to use as favicon of the 120 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 121 | # pixels large. 122 | #html_favicon = None 123 | 124 | # Add any paths that contain custom static files (such as style sheets) here, 125 | # relative to this directory. They are copied after the builtin static files, 126 | # so a file named "default.css" will overwrite the builtin "default.css". 127 | html_static_path = ['_static'] 128 | 129 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 130 | # using the given strftime format. 131 | #html_last_updated_fmt = '%b %d, %Y' 132 | 133 | # If true, SmartyPants will be used to convert quotes and dashes to 134 | # typographically correct entities. 135 | #html_use_smartypants = True 136 | 137 | # Custom sidebar templates, maps document names to template names. 138 | #html_sidebars = {} 139 | 140 | # Additional templates that should be rendered to pages, maps page names to 141 | # template names. 142 | #html_additional_pages = {} 143 | 144 | # If false, no module index is generated. 145 | #html_domain_indices = True 146 | 147 | # If false, no index is generated. 148 | #html_use_index = True 149 | 150 | # If true, the index is split into individual pages for each letter. 151 | #html_split_index = False 152 | 153 | # If true, links to the reST sources are added to the pages. 154 | #html_show_sourcelink = True 155 | 156 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 157 | #html_show_sphinx = True 158 | 159 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 160 | #html_show_copyright = True 161 | 162 | # If true, an OpenSearch description file will be output, and all pages will 163 | # contain a tag referring to it. The value of this option must be the 164 | # base URL from which the finished HTML is served. 165 | #html_use_opensearch = '' 166 | 167 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 168 | #html_file_suffix = None 169 | 170 | # Output file base name for HTML help builder. 171 | htmlhelp_basename = 'PiFaceCommondoc' 172 | 173 | 174 | # -- Options for LaTeX output -------------------------------------------------- 175 | 176 | latex_elements = { 177 | # The paper size ('letterpaper' or 'a4paper'). 178 | #'papersize': 'letterpaper', 179 | 180 | # The font size ('10pt', '11pt' or '12pt'). 181 | #'pointsize': '10pt', 182 | 183 | # Additional stuff for the LaTeX preamble. 184 | #'preamble': '', 185 | } 186 | 187 | # Grouping the document tree into LaTeX files. List of tuples 188 | # (source start file, target name, title, author, documentclass [howto/manual]). 189 | latex_documents = [ 190 | ('index', 'PiFaceCommon.tex', 'PiFace Common Documentation', 191 | 'Thomas Preston', 'manual'), 192 | ] 193 | 194 | # The name of an image file (relative to this directory) to place at the top of 195 | # the title page. 196 | #latex_logo = None 197 | 198 | # For "manual" documents, if this is true, then toplevel headings are parts, 199 | # not chapters. 200 | #latex_use_parts = False 201 | 202 | # If true, show page references after internal links. 203 | #latex_show_pagerefs = False 204 | 205 | # If true, show URL addresses after external links. 206 | #latex_show_urls = False 207 | 208 | # Documents to append as an appendix to all manuals. 209 | #latex_appendices = [] 210 | 211 | # If false, no module index is generated. 212 | #latex_domain_indices = True 213 | 214 | 215 | # -- Options for manual page output -------------------------------------------- 216 | 217 | # One entry per manual page. List of tuples 218 | # (source start file, name, description, authors, manual section). 219 | man_pages = [ 220 | ('index', 'pifacecommon', 'PiFace Common Documentation', 221 | ['Thomas Preston'], 1) 222 | ] 223 | 224 | # If true, show URL addresses after external links. 225 | #man_show_urls = False 226 | 227 | 228 | # -- Options for Texinfo output ------------------------------------------------ 229 | 230 | # Grouping the document tree into Texinfo files. List of tuples 231 | # (source start file, target name, title, author, 232 | # dir menu entry, description, category) 233 | texinfo_documents = [ 234 | ('index', 'PiFaceCommon', 'PiFace Common Documentation', 235 | 'Thomas Preston', 'PiFaceCommon', 'One line description of project.', 236 | 'Miscellaneous'), 237 | ] 238 | 239 | # Documents to append as an appendix to all manuals. 240 | #texinfo_appendices = [] 241 | 242 | # If false, no module index is generated. 243 | #texinfo_domain_indices = True 244 | 245 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 246 | #texinfo_show_urls = 'footnote' 247 | 248 | 249 | # Example configuration for intersphinx: refer to the Python standard library. 250 | intersphinx_mapping = {'http://docs.python.org/': None} 251 | -------------------------------------------------------------------------------- /docs/example.rst: -------------------------------------------------------------------------------- 1 | ####### 2 | Example 3 | ####### 4 | Here are some examples of how to use pifacecommon. 5 | 6 | MCP23S17 7 | ======== 8 | 9 | :: 10 | 11 | >>> import pifacecommon.mcp23s17 12 | >>> mcp = pifacecommon.mcp23s17.MCP23S17() 13 | >>> mcp.gpioa.value = 0xAA 14 | >>> mcp.gpioa.value 15 | 170 16 | >>> mcp.gpioa.bits[3].value 17 | 1 18 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. PiFace Common documentation master file, created by 2 | sphinx-quickstart on Wed Jun 19 13:52:03 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 Common's documentation! 7 | ========================================= 8 | 9 | The pifacecommon Python module is required for all PiFace extensions. It 10 | provides functions and classes for generic interfacing with the boards over 11 | SPI. 12 | 13 | Links: 14 | - `Blog `_ 15 | - `GitHub `_ 16 | - `PyPI `_ 17 | 18 | Contents: 19 | 20 | .. toctree:: 21 | :maxdepth: 2 22 | 23 | installation 24 | example 25 | reference 26 | 27 | 28 | Indices and tables 29 | ================== 30 | 31 | * :ref:`genindex` 32 | * :ref:`modindex` 33 | * :ref:`search` 34 | 35 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ############ 2 | Installation 3 | ############ 4 | 5 | Install 6 | ======= 7 | apt-get 8 | ------- 9 | Make sure you are using the lastest version of Raspbian:: 10 | 11 | $ sudo apt-get update 12 | $ sudo apt-get upgrade 13 | 14 | Install ``pifacecommon`` with the following command: 15 | 16 | Python 3: 17 | $ sudo pip3 install pifacecommon 18 | 19 | Notice 1: Installation from Raspbian repository with apt is not longer the preferred way, take a look into `pifacecommon issue #27 `_ 20 | 21 | Notice 2: Python 2 support is "end-of-life" since Jan 2020, refer to https://www.python.org/doc/sunset-python-2/ 22 | 23 | You will also need to set up automatic loading of the SPI kernel module which 24 | can be done with the lastest version of ``raspi-config``. Run:: 25 | 26 | $ sudo raspi-config 27 | 28 | Then navigate to ``Advanced Options``, ``SPI`` and select ``yes``. 29 | 30 | You may need to reboot. 31 | 32 | 33 | Manually 34 | -------- 35 | This is a more detailed description of the installation. You will have 36 | to reboot after setting up SPI and GPIO permissions. 37 | 38 | Building and installing 39 | ^^^^^^^^^^^^^^^^^^^^^^^ 40 | 41 | Download and install with:: 42 | 43 | $ git clone https://github.com/piface/pifacecommon.git 44 | $ cd pifacecommon/ 45 | $ sudo python3 setup.py install 46 | 47 | .. note:: Subtitute ``python3`` for ``python`` if you want to install for 48 | Python 2. 49 | 50 | 51 | Enable the SPI module 52 | ^^^^^^^^^^^^^^^^^^^^^ 53 | PiFace boards communicate with the Raspberry Pi through the SPI interface. 54 | The SPI interface driver is included in the latest Raspbian distributions 55 | but is not enabled by default. You can load the SPI driver manually by running:: 56 | 57 | $ sudo modprobe spi-bcm2708 58 | 59 | You can permanently enable it one of two ways, depending on which kernel 60 | version you're on. 61 | 62 | - Kernel Version < 3.18 (The old way): Comment out ``blacklist spi-bcm2708`` line in ``/etc/modprobe.d/raspi-blacklist.conf``. 63 | 64 | - Kernel Version >= 3.18 (Device Tree): add ``dtparam=spi=on`` to ``/boot/config/txt`` 65 | 66 | The /dev/spidev* devices should now appear but they require special privileges 67 | for the user *pi* to access them. You can set these up by adding the following 68 | `udev rule `_ to 69 | ``/etc/udev/rules.d/50-spi.rules``:: 70 | 71 | KERNEL=="spidev*", GROUP="spi", MODE="0660" 72 | 73 | Then create the spi group and add the user pi:: 74 | 75 | $ groupadd spi 76 | $ gpasswd -a pi spi 77 | 78 | .. note:: To enable other users to access SPI devices (PiFace, for example) 79 | you can add them to the ``spi`` group with ``gpasswd -a otheruser spi``. 80 | 81 | 82 | Enable GPIO access 83 | ^^^^^^^^^^^^^^^^^^ 84 | Interrupts work by monitoring the GPIO pins. You'll need to give the user *pi* 85 | access to these by adding the following udev rule (all on one line) to 86 | ``/etc/udev/rules.d/51-gpio.rules``:: 87 | 88 | SUBSYSTEM=="gpio*", PROGRAM="/bin/sh -c 'chown -R root:gpio /sys/class/gpio && chmod -R 770 /sys/class/gpio'" 89 | 90 | Then create the gpio group and add the user pi:: 91 | 92 | $ groupadd gpio 93 | $ gpasswd -a pi gpio 94 | 95 | Uninstall 96 | ========= 97 | 98 | :: 99 | 100 | $ sudo apt-get remove python{,3}-pifacecommon 101 | -------------------------------------------------------------------------------- /docs/reference.rst: -------------------------------------------------------------------------------- 1 | ######### 2 | Reference 3 | ######### 4 | 5 | **** 6 | Core 7 | **** 8 | .. automodule:: pifacecommon.core 9 | :members: 10 | 11 | ********** 12 | SPI 13 | ********** 14 | .. automodule:: pifacecommon.spi 15 | :members: 16 | 17 | ********** 18 | Interrupts 19 | ********** 20 | .. automodule:: pifacecommon.interrupts 21 | :members: 22 | 23 | ********** 24 | MCP23S17 25 | ********** 26 | Consult the datasheet for more information. 27 | 28 | .. automodule:: pifacecommon.mcp23s17 29 | :members: 30 | -------------------------------------------------------------------------------- /pifacecommon/__init__.py: -------------------------------------------------------------------------------- 1 | """Provides common I/O methods for interfacing with PiFace Products 2 | Copyright (C) 2013 Thomas Preston 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | """ 17 | -------------------------------------------------------------------------------- /pifacecommon/asm_generic_ioctl.py: -------------------------------------------------------------------------------- 1 | # Converted from 2 | 3 | # ioctl command encoding: 32 bits total, command in lower 16 bits, 4 | # size of the parameter structure in the lower 14 bits of the 5 | # upper 16 bits. 6 | # 7 | # Encoding the size of the parameter structure in the ioctl request 8 | # is useful for catching programs compiled with old versions 9 | # and to avoid overwriting user space outside the user buffer area. 10 | # The highest 2 bits are reserved for indicating the ``access mode''. 11 | # 12 | # NOTE: This limits the max parameter size to 16kB -1 ! 13 | 14 | # The following is for compatibility across the various Linux 15 | # platforms. The generic ioctl numbering scheme doesn't really enforce 16 | # a type field. De facto, however, the top 8 bits of the lower 16 17 | # bits are indeed used as a type field, so we might just as well make 18 | # this explicit here. Please be sure to use the decoding macros 19 | # below from now on. 20 | 21 | import ctypes 22 | 23 | _IOC_NRBITS = 8 24 | _IOC_TYPEBITS = 8 25 | 26 | _IOC_SIZEBITS = 14 27 | _IOC_DIRBITS = 2 28 | 29 | _IOC_NRMASK = (1 << _IOC_NRBITS) - 1 30 | _IOC_TYPEMASK = (1 << _IOC_TYPEBITS) - 1 31 | _IOC_SIZEMASK = (1 << _IOC_SIZEBITS) - 1 32 | _IOC_DIRMASK = (1 << _IOC_DIRBITS) - 1 33 | 34 | _IOC_NRSHIFT = 0 35 | _IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS 36 | _IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS 37 | _IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS 38 | 39 | # Direction bits 40 | 41 | _IOC_NONE = 0 42 | _IOC_WRITE = 1 43 | _IOC_READ = 2 44 | 45 | def _IOC(dir, type, nr, size): 46 | return (dir << _IOC_DIRSHIFT) | \ 47 | (type << _IOC_TYPESHIFT) | \ 48 | (nr << _IOC_NRSHIFT) | \ 49 | (size << _IOC_SIZESHIFT) 50 | 51 | def _IOC_TYPECHECK(t): 52 | return ctypes.sizeof(t) 53 | 54 | 55 | # used to create ioctl numbers 56 | 57 | def _IO(type, nr): 58 | return _IOC(_IOC_NONE, type, nr, 0) 59 | 60 | def _IOR(type, nr, size): 61 | return _IOC(_IOC_READ, type, nr, _IOC_TYPECHECK(size)) 62 | 63 | def _IOW(type, nr, size): 64 | return _IOC(_IOC_WRITE, type, nr, _IOC_TYPECHECK(size)) 65 | 66 | def _IOWR(type,nr,size): 67 | return _IOC(_IOC_READ|_IOC_WRITE, type, nr, _IOC_TYPECHECK(size)) 68 | 69 | def _IOR_BAD(type,nr,size): 70 | return _IOC(_IOC_READ, type, nr, sizeof(size)) 71 | 72 | def _IOW_BAD(type,nr,size): 73 | return _IOC(_IOC_WRITE,type,nr, sizeof(size)) 74 | 75 | def _IOWR_BAD(type,nr,size): 76 | return _IOC(_IOC_READ|_IOC_WRITE, type, nr, sizeof(size)) 77 | 78 | 79 | # ...and for the drivers/sound files... 80 | 81 | IOC_IN = _IOC_WRITE << _IOC_DIRSHIFT 82 | IOC_OUT = _IOC_READ << _IOC_DIRSHIFT 83 | IOC_INOUT = (_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT 84 | IOCSIZE_MASK = _IOC_SIZEMASK << _IOC_SIZESHIFT 85 | IOCSIZE_SHIFT = _IOC_SIZESHIFT 86 | 87 | -------------------------------------------------------------------------------- /pifacecommon/core.py: -------------------------------------------------------------------------------- 1 | def get_bit_mask(bit_num): 2 | """Returns as bit mask with bit_num set. 3 | 4 | :param bit_num: The bit number. 5 | :type bit_num: int 6 | :returns: int -- the bit mask 7 | :raises: RangeError 8 | 9 | >>> bin(pifacecommon.core.get_bit_mask(0)) 10 | 1 11 | >>> pifacecommon.core.get_bit_mask(1) 12 | 2 13 | >>> bin(pifacecommon.core.get_bit_mask(3)) 14 | '0b1000' 15 | """ 16 | return 1 << (bit_num) 17 | 18 | 19 | def get_bit_num(bit_pattern): 20 | """Returns the lowest bit num from a given bit pattern. Returns None if no 21 | bits set. 22 | 23 | :param bit_pattern: The bit pattern. 24 | :type bit_pattern: int 25 | :returns: int -- the bit number 26 | :returns: None -- no bits set 27 | 28 | >>> pifacecommon.core.get_bit_num(0) 29 | None 30 | >>> pifacecommon.core.get_bit_num(0b1) 31 | 0 32 | >>> pifacecommon.core.get_bit_num(0b11000) 33 | 3 34 | """ 35 | if bit_pattern == 0: 36 | return None 37 | 38 | bit_num = 0 # assume bit 0 39 | while (bit_pattern & 1) == 0: 40 | bit_pattern = bit_pattern >> 1 41 | bit_num += 1 42 | if bit_num > 7: 43 | bit_num = 0 44 | break 45 | 46 | return bit_num 47 | 48 | 49 | def sleep_microseconds(microseconds): 50 | """Sleeps for the given number of microseconds. 51 | 52 | :param microseconds: Number of microseconds to sleep for. 53 | :type microseconds: int 54 | """ 55 | # divide microseconds by 1 million for seconds 56 | seconds = microseconds / float(1000000) 57 | time.sleep(seconds) 58 | -------------------------------------------------------------------------------- /pifacecommon/interrupts.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import multiprocessing 3 | import select 4 | import time 5 | import errno 6 | from .core import get_bit_num 7 | import pifacecommon.mcp23s17 8 | 9 | 10 | # interrupts 11 | IODIR_FALLING_EDGE = IODIR_ON = 0 12 | IODIR_RISING_EDGE = IODIR_OFF = 1 13 | IODIR_BOTH = None 14 | # IN_EVENT_DIR_OFF = INPUT_DIRECTION_OFF = 1 15 | # IN_EVENT_DIR_BOTH = INPUT_DIRECTION_BOTH = None 16 | 17 | GPIO_INTERRUPT_PIN = 25 18 | GPIO_INTERRUPT_DEVICE = "/sys/class/gpio/gpio%d" % GPIO_INTERRUPT_PIN 19 | GPIO_INTERRUPT_DEVICE_EDGE = '%s/edge' % GPIO_INTERRUPT_DEVICE 20 | GPIO_INTERRUPT_DEVICE_VALUE = '%s/value' % GPIO_INTERRUPT_DEVICE 21 | GPIO_EXPORT_FILE = "/sys/class/gpio/export" 22 | GPIO_UNEXPORT_FILE = "/sys/class/gpio/unexport" 23 | 24 | # max seconds to wait for file I/O (when enabling interrupts) 25 | FILE_IO_TIMEOUT = 1 26 | 27 | READY_FOR_EVENTS = "ready for events" 28 | 29 | # deboucing 30 | DEFAULT_SETTLE_TIME = 0.020 # 20ms 31 | 32 | 33 | class Timeout(Exception): 34 | pass 35 | 36 | 37 | class InterruptEvent(object): 38 | """An interrupt event containting the interrupt flag and capture register 39 | values, the chip object from which the interrupt occured and a timestamp. 40 | """ 41 | def __init__( 42 | self, interrupt_flag, interrupt_capture, chip, timestamp): 43 | self.interrupt_flag = interrupt_flag 44 | self.interrupt_capture = interrupt_capture 45 | self.chip = chip 46 | self.timestamp = timestamp 47 | 48 | def __str__(self): 49 | s = "interrupt_flag: {flag}\n" \ 50 | "interrupt_capture: {capture}\n" \ 51 | "pin_num: {pin_num}\n" \ 52 | "direction: {direction}\n" \ 53 | "chip: {chip}\n" \ 54 | "timestamp: {timestamp}" 55 | return s.format(flag=bin(self.interrupt_flag), 56 | capture=bin(self.interrupt_capture), 57 | pin_num=self.pin_num, 58 | direction=self.direction, 59 | chip=self.chip, 60 | timestamp=self.timestamp) 61 | 62 | @property 63 | def pin_num(self): 64 | return get_bit_num(self.interrupt_flag) 65 | 66 | @property 67 | def direction(self): 68 | return (self.interrupt_flag & self.interrupt_capture) >> self.pin_num 69 | 70 | 71 | class FunctionMap(object): 72 | """Maps something to a callback function. 73 | (This is an abstract class, you must implement a SomethingFunctionMap). 74 | """ 75 | def __init__(self, callback, settle_time=None): 76 | self.callback = callback 77 | self.settle_time = settle_time 78 | 79 | 80 | class PinFunctionMap(FunctionMap): 81 | """Maps an IO pin and a direction to callback function.""" 82 | def __init__(self, pin_num, direction, callback, settle_time): 83 | self.pin_num = pin_num 84 | self.direction = direction 85 | super(PinFunctionMap, self).__init__(callback, settle_time) 86 | 87 | def __str__(self): 88 | s = "Pin num: {pin_num}\n" \ 89 | "Direction:{direction}\n" 90 | return s.format(pin_num=self.pin_num, 91 | direction=self.direction) 92 | 93 | 94 | class EventQueue(object): 95 | """Stores events in a queue.""" 96 | def __init__(self, pin_function_maps): 97 | super(EventQueue, self).__init__() 98 | self.last_event_time = [0]*8 # last event time on each pin 99 | self.pin_function_maps = pin_function_maps 100 | self.queue = multiprocessing.Queue() 101 | 102 | def add_event(self, event): 103 | """Adds events to the queue. Will ignore events that occur before the 104 | settle time for that pin/direction. Such events are assumed to be 105 | bouncing. 106 | """ 107 | # print("Trying to add event:") 108 | # print(event) 109 | # find out the pin settle time 110 | for pin_function_map in self.pin_function_maps: 111 | if _event_matches_pin_function_map(event, pin_function_map): 112 | # if pin_function_map.pin_num == event.pin_num and ( 113 | # pin_function_map.direction == event.direction or 114 | # pin_function_map.direction == IODIR_BOTH): 115 | pin_settle_time = pin_function_map.settle_time 116 | # print("EventQueue: Found event in map.") 117 | break 118 | else: 119 | # Couldn't find event in map, don't bother adding it to the queue 120 | # print("EventQueue: Couldn't find event in map:") 121 | # for pin_function_map in self.pin_function_maps: 122 | # print(pin_function_map) 123 | return 124 | 125 | threshold_time = self.last_event_time[event.pin_num] + pin_settle_time 126 | if event.timestamp > threshold_time: 127 | self.put(event) 128 | self.last_event_time[event.pin_num] = event.timestamp 129 | 130 | def put(self, thing): 131 | self.queue.put(thing) 132 | 133 | def get(self): 134 | return self.queue.get() 135 | 136 | 137 | class PortEventListener(object): 138 | """Listens for port events and calls the registered functions. 139 | 140 | >>> def print_flag(event): 141 | ... print(event.interrupt_flag) 142 | ... 143 | >>> port = pifacecommon.mcp23s17.GPIOA 144 | >>> listener = pifacecommon.interrupts.PortEventListener(port) 145 | >>> listener.register(0, pifacecommon.interrupts.IODIR_ON, print_flag) 146 | >>> listener.activate() 147 | """ 148 | 149 | TERMINATE_SIGNAL = "astalavista" 150 | 151 | def __init__(self, port, chip, return_after_kbdint=True, daemon=False): 152 | self.port = port 153 | self.chip = chip 154 | self.pin_function_maps = list() 155 | self.event_queue = EventQueue(self.pin_function_maps) 156 | self.detector = multiprocessing.Process( 157 | target=watch_port_events, 158 | args=( 159 | self.port, 160 | self.chip, 161 | self.pin_function_maps, 162 | self.event_queue, 163 | return_after_kbdint)) 164 | self.detector.daemon = daemon 165 | self.dispatcher = threading.Thread( 166 | target=handle_events, 167 | args=( 168 | self.pin_function_maps, 169 | self.event_queue, 170 | _event_matches_pin_function_map, 171 | PortEventListener.TERMINATE_SIGNAL)) 172 | self.dispatcher.daemon = daemon 173 | 174 | def register(self, pin_num, direction, callback, 175 | settle_time=DEFAULT_SETTLE_TIME): 176 | """Registers a pin number and direction to a callback function. 177 | 178 | :param pin_num: The pin pin number. 179 | :type pin_num: int 180 | :param direction: The event direction 181 | (use: IODIR_ON/IODIR_OFF/IODIR_BOTH) 182 | :type direction: int 183 | :param callback: The function to run when event is detected. 184 | :type callback: function 185 | :param settle_time: Time within which subsequent events are ignored. 186 | :type settle_time: int 187 | """ 188 | self.pin_function_maps.append( 189 | PinFunctionMap(pin_num, direction, callback, settle_time)) 190 | 191 | def deregister(self, pin_num=None, direction=None): 192 | """De-registers callback functions 193 | 194 | :param pin_num: The pin number. If None then all functions are de-registered 195 | :type pin_num: int 196 | :param direction: The event direction. If None then all functions for the 197 | given pin are de-registered 198 | :type direction:int 199 | """ 200 | to_delete = [] 201 | for i, function_map in enumerate(self.pin_function_maps): 202 | if ( pin_num == None 203 | or ( function_map.pin_num == pin_num 204 | and ( direction == None 205 | or function_map.direction == direction ) ) ): 206 | to_delete.append(i) 207 | for i in reversed(to_delete): 208 | del self.pin_function_maps[i] 209 | 210 | def activate(self): 211 | """When activated the :class:`PortEventListener` will run callbacks 212 | associated with pins/directions. 213 | """ 214 | self.detector.start() 215 | self.dispatcher.start() 216 | 217 | def deactivate(self): 218 | """When deactivated the :class:`PortEventListener` will not run 219 | anything. 220 | """ 221 | self.event_queue.put(self.TERMINATE_SIGNAL) 222 | self.dispatcher.join() 223 | self.detector.terminate() 224 | self.detector.join() 225 | 226 | 227 | class GPIOInterruptDevice(object): 228 | """A device that interrupts using the GPIO pins.""" 229 | def gpio_interrupts_enable(self): 230 | """Enables GPIO interrupts.""" 231 | try: 232 | bring_gpio_interrupt_into_userspace() 233 | set_gpio_interrupt_edge() 234 | except Timeout as e: 235 | raise InterruptEnableException( 236 | "There was an error bringing gpio%d into userspace. %s" % 237 | (GPIO_INTERRUPT_PIN, e.message) 238 | ) 239 | 240 | def gpio_interrupts_disable(self): 241 | """Disables gpio interrupts.""" 242 | set_gpio_interrupt_edge('none') 243 | deactivate_gpio_interrupt() 244 | 245 | 246 | def _event_matches_pin_function_map(event, pin_function_map): 247 | # print("pin num", event.pin_num, pin_function_map.pin_num) 248 | # print("direction", event.direction, pin_function_map.direction) 249 | pin_match = event.pin_num == pin_function_map.pin_num 250 | direction_match = pin_function_map.direction is None 251 | direction_match |= event.direction == pin_function_map.direction 252 | return pin_match and direction_match 253 | 254 | 255 | def watch_port_events(port, chip, pin_function_maps, event_queue, 256 | return_after_kbdint=False): 257 | """Waits for a port event. When a port event occurs it is placed onto the 258 | event queue. 259 | 260 | :param port: The port we are waiting for interrupts on (GPIOA/GPIOB). 261 | :type port: int 262 | :param chip: The chip we are waiting for interrupts on. 263 | :type chip: :class:`pifacecommon.mcp23s17.MCP23S17` 264 | :param pin_function_maps: A list of classes that have inheritted from 265 | :class:`FunctionMap`\ s describing what to do with events. 266 | :type pin_function_maps: list 267 | :param event_queue: A queue to put events on. 268 | :type event_queue: :py:class:`multiprocessing.Queue` 269 | """ 270 | # set up epoll 271 | gpio25 = open(GPIO_INTERRUPT_DEVICE_VALUE, 'r') # change to use 'with'? 272 | epoll = select.epoll() 273 | epoll.register(gpio25, select.EPOLLIN | select.EPOLLET) 274 | 275 | while True: 276 | # wait here until input 277 | try: 278 | events = epoll.poll() 279 | except KeyboardInterrupt as e: 280 | if return_after_kbdint: 281 | return 282 | else: 283 | raise e 284 | except IOError as e: 285 | # ignore "Interrupted system call" error. 286 | # I don't really like this solution. Ignoring problems is bad! 287 | if e.errno != errno.EINTR: 288 | raise 289 | 290 | # find out where the interrupt came from and put it on the event queue 291 | if port == pifacecommon.mcp23s17.GPIOA: 292 | interrupt_flag = chip.intfa.value 293 | else: 294 | interrupt_flag = chip.intfb.value 295 | 296 | if interrupt_flag == 0: 297 | continue # The interrupt has not been flagged on this board 298 | else: 299 | if port == pifacecommon.mcp23s17.GPIOA: 300 | interrupt_capture = chip.intcapa.value 301 | else: 302 | interrupt_capture = chip.intcapb.value 303 | event_queue.add_event(InterruptEvent( 304 | interrupt_flag, interrupt_capture, chip, time.time())) 305 | 306 | epoll.close() 307 | 308 | 309 | def handle_events( 310 | function_maps, event_queue, event_matches_function_map, 311 | terminate_signal): 312 | """Waits for events on the event queue and calls the registered functions. 313 | 314 | :param function_maps: A list of classes that have inheritted from 315 | :class:`FunctionMap`\ s describing what to do with events. 316 | :type function_maps: list 317 | :param event_queue: A queue to put events on. 318 | :type event_queue: :py:class:`multiprocessing.Queue` 319 | :param event_matches_function_map: A function that determines if the given 320 | event and :class:`FunctionMap` match. 321 | :type event_matches_function_map: function 322 | :param terminate_signal: The signal that, when placed on the event queue, 323 | causes this function to exit. 324 | """ 325 | while True: 326 | # print("HANDLE: Waiting for events!") 327 | event = event_queue.get() 328 | # print("HANDLE: It's an event!") 329 | if event == terminate_signal: 330 | return 331 | # if matching get the callback function, else function is None 332 | functions = map( 333 | lambda fm: fm.callback 334 | if event_matches_function_map(event, fm) else None, 335 | function_maps) 336 | # reduce to just the callback functions (remove None) 337 | # TODO: I think this can just be filter(None, functions) 338 | functions = filter(lambda f: f is not None, functions) 339 | 340 | for function in functions: 341 | function(event) 342 | 343 | 344 | # def clear_interrupts(port): 345 | # """Clears the interrupt flags by 'read'ing the capture register 346 | # on all boards. 347 | # """ 348 | # intcap = INTCAPA if port == GPIOA else INTCAPB 349 | # for i in range(MAX_BOARDS): 350 | # read(intcap, i) 351 | 352 | 353 | # def enable_interrupts(port, pin_map=0xff, hardware_addrs=range(MAX_BOARDS)): 354 | # """Enables interrupts on the port specified. A pin map can be given to 355 | # only enable interrupts on some pins. A list of board numbers can also be 356 | # given to only enable the interrupts on some boards. 357 | 358 | # :param port: The port to enable interrupts on 359 | # (pifacecommon.core.GPIOA, pifacecommon.core.GPIOB) 360 | # :type port: int 361 | # :param pin_map: The pins to enable interrupts on 362 | # :type pin_map: int 363 | # :param hardware_addrs: The boards to enable interrupts on. 364 | # :type hardware_addrs: list 365 | # """ 366 | # # enable interrupts 367 | # int_enable_port = GPINTENA if port == GPIOA else GPINTENB 368 | # for board_index in hardware_addrs: 369 | # write(pin_map, int_enable_port, board_index) 370 | 371 | # try: 372 | # bring_gpio_interrupt_into_userspace() 373 | # set_gpio_interrupt_edge() 374 | # except Timeout as e: 375 | # raise InterruptEnableException( 376 | # "There was an error bringing gpio%d into userspace. %s" % 377 | # (GPIO_INTERRUPT_PIN, e.message) 378 | # ) 379 | 380 | 381 | def bring_gpio_interrupt_into_userspace(): # activate gpio interrupt 382 | """Bring the interrupt pin on the GPIO into Linux userspace.""" 383 | try: 384 | # is it already there? 385 | with open(GPIO_INTERRUPT_DEVICE_VALUE): 386 | return 387 | except IOError: 388 | # no, bring it into userspace 389 | with open(GPIO_EXPORT_FILE, 'w') as export_file: 390 | export_file.write(str(GPIO_INTERRUPT_PIN)) 391 | 392 | wait_until_file_exists(GPIO_INTERRUPT_DEVICE_VALUE) 393 | 394 | 395 | def deactivate_gpio_interrupt(): 396 | """Remove the GPIO interrupt pin from Linux userspace.""" 397 | with open(GPIO_UNEXPORT_FILE, 'w') as unexport_file: 398 | unexport_file.write(str(GPIO_INTERRUPT_PIN)) 399 | 400 | 401 | def set_gpio_interrupt_edge(edge='falling'): 402 | """Set the interrupt edge on the userspace GPIO pin. 403 | 404 | :param edge: The interrupt edge ('none', 'falling', 'rising'). 405 | :type edge: string 406 | """ 407 | # we're only interested in the falling edge (1 -> 0) 408 | start_time = time.time() 409 | time_limit = start_time + FILE_IO_TIMEOUT 410 | while time.time() < time_limit: 411 | try: 412 | with open(GPIO_INTERRUPT_DEVICE_EDGE, 'w') as gpio_edge: 413 | gpio_edge.write(edge) 414 | return 415 | except IOError: 416 | pass 417 | 418 | 419 | def wait_until_file_exists(filename): 420 | """Wait until a file exists. 421 | 422 | :param filename: The name of the file to wait for. 423 | :type filename: string 424 | """ 425 | start_time = time.time() 426 | time_limit = start_time + FILE_IO_TIMEOUT 427 | while time.time() < time_limit: 428 | try: 429 | with open(filename): 430 | return 431 | except IOError: 432 | pass 433 | 434 | raise Timeout("Waiting too long for %s." % filename) 435 | 436 | 437 | # def disable_interrupts(port): 438 | # """Disables interrupts for all pins on the port specified. 439 | 440 | # :param port: The port to enable interrupts on 441 | # (pifacecommon.core.GPIOA, pifacecommon.core.GPIOB) 442 | # :type port: int 443 | # """ 444 | # # neither edgez 445 | # with open(GPIO_INTERRUPT_DEVICE_EDGE, 'w') as gpio25edge: 446 | # gpio25edge.write('none') 447 | 448 | # # remove the pin from userspace 449 | # with open(GPIO_UNEXPORT_FILE, 'w') as unexport_file: 450 | # unexport_file.write(str(GPIO_INTERRUPT_PIN)) 451 | 452 | # # disable the interrupt 453 | # int_enable_port = GPINTENA if port == GPIOA else GPINTENB 454 | # for board_index in range(MAX_BOARDS): 455 | # write(0, int_enable_port, board_index) 456 | -------------------------------------------------------------------------------- /pifacecommon/linux_spi_spidev.py: -------------------------------------------------------------------------------- 1 | # Converted from 2 | import ctypes 3 | from .asm_generic_ioctl import _IOR, _IOW, _IOC_SIZEBITS 4 | 5 | SPI_CPHA = 0x01 6 | SPI_CPOL = 0x02 7 | 8 | SPI_MODE_0 = 0 9 | SPI_MODE_1 = SPI_CPHA 10 | SPI_MODE_2 = SPI_CPOL 11 | SPI_MODE_3 = SPI_CPOL | SPI_CPHA 12 | 13 | SPI_CS_HIGH = 0x04 14 | SPI_LSB_FIRST = 0x08 15 | SPI_3WIRE = 0x10 16 | SPI_LOOP = 0x20 17 | SPI_NO_CS = 0x40 18 | SPI_READY = 0x80 19 | 20 | 21 | # IOCTL commands */ 22 | 23 | SPI_IOC_MAGIC = 107 # ord('k') 24 | 25 | 26 | # struct spi_ioc_transfer - describes a single SPI transfer 27 | # 28 | # tx_buf: Holds pointer to userspace buffer with transmit data, or null. 29 | # If no data is provided, zeroes are shifted out. 30 | # rx_buf: Holds pointer to userspace buffer for receive data, or null. 31 | # len: Length of tx and rx buffers, in bytes. 32 | # speed_hz: Temporary override of the device's bitrate. 33 | # bits_per_word: Temporary override of the device's wordsize. 34 | # delay_usecs: If nonzero, how long to delay after the last bit transfer 35 | # before optionally deselecting the device before the next transfer. 36 | # cs_change: True to deselect device before starting the next transfer. 37 | # 38 | # This structure is mapped directly to the kernel spi_transfer structure; 39 | # the fields have the same meanings, except of course that the pointers 40 | # are in a different address space (and may be of different sizes in some 41 | # cases, such as 32-bit i386 userspace over a 64-bit x86_64 kernel). 42 | # Zero-initialize the structure, including currently unused fields, to 43 | # accomodate potential future updates. 44 | # 45 | # SPI_IOC_MESSAGE gives userspace the equivalent of kernel spi_sync(). 46 | # Pass it an array of related transfers, they'll execute together. 47 | # Each transfer may be half duplex (either direction) or full duplex. 48 | # 49 | # struct spi_ioc_transfer mesg[4]; 50 | # ... 51 | # status = ioctl(fd, SPI_IOC_MESSAGE(4), mesg); 52 | # 53 | # So for example one transfer might send a nine bit command (right aligned 54 | # in a 16-bit word), the next could read a block of 8-bit data before 55 | # terminating that command by temporarily deselecting the chip; the next 56 | # could send a different nine bit command (re-selecting the chip), and the 57 | # last transfer might write some register values. 58 | 59 | class spi_ioc_transfer(ctypes.Structure): 60 | """ struct spi_ioc_transfer""" 61 | 62 | _fields_ = [ 63 | ("tx_buf", ctypes.c_uint64), 64 | ("rx_buf", ctypes.c_uint64), 65 | ("len", ctypes.c_uint32), 66 | ("speed_hz", ctypes.c_uint32), 67 | ("delay_usecs", ctypes.c_uint16), 68 | ("bits_per_word", ctypes.c_uint8), 69 | ("cs_change", ctypes.c_uint8), 70 | ("tx_nbits", ctypes.c_uint8), 71 | ("rx_nbits", ctypes.c_uint8), 72 | ("pad", ctypes.c_uint16)] 73 | 74 | __slots__ = [name for name, type in _fields_] 75 | 76 | 77 | # not all platforms use or _IOC_TYPECHECK() ... 78 | def SPI_MSGSIZE(N): 79 | if ((N)*(ctypes.sizeof(spi_ioc_transfer))) < (1 << _IOC_SIZEBITS): 80 | return (N)*(ctypes.sizeof(spi_ioc_transfer)) 81 | else: 82 | return 0 83 | 84 | 85 | def SPI_IOC_MESSAGE(N): 86 | return _IOW(SPI_IOC_MAGIC, 0, ctypes.c_char*SPI_MSGSIZE(N)) 87 | 88 | 89 | # Read / Write of SPI mode (SPI_MODE_0..SPI_MODE_3) 90 | SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, ctypes.c_uint8) 91 | SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, ctypes.c_uint8) 92 | 93 | # Read / Write SPI bit justification 94 | SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, ctypes.c_uint8) 95 | SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, ctypes.c_uint8) 96 | 97 | # Read / Write SPI device word length (1..N) 98 | SPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, ctypes.c_uint8) 99 | SPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_IOC_MAGIC, 3, ctypes.c_uint8) 100 | 101 | # Read / Write SPI device default max speed hz 102 | SPI_IOC_RD_MAX_SPEED_HZ = _IOR(SPI_IOC_MAGIC, 4, ctypes.c_uint32) 103 | SPI_IOC_WR_MAX_SPEED_HZ = _IOW(SPI_IOC_MAGIC, 4, ctypes.c_uint32) 104 | -------------------------------------------------------------------------------- /pifacecommon/mcp23s17.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from .core import ( 4 | get_bit_mask, 5 | get_bit_num, 6 | ) 7 | from .spi import SPIDevice 8 | import pifacecommon.interrupts 9 | 10 | 11 | # Python 2 support 12 | PY3 = sys.version_info[0] >= 3 13 | 14 | WRITE_CMD = 0 15 | READ_CMD = 1 16 | 17 | # Register addresses 18 | IODIRA = 0x0 # I/O direction A 19 | IODIRB = 0x1 # I/O direction B 20 | IPOLA = 0x2 # I/O polarity A 21 | IPOLB = 0x3 # I/O polarity B 22 | GPINTENA = 0x4 # interupt enable A 23 | GPINTENB = 0x5 # interupt enable B 24 | DEFVALA = 0x6 # register default value A (interupts) 25 | DEFVALB = 0x7 # register default value B (interupts) 26 | INTCONA = 0x8 # interupt control A 27 | INTCONB = 0x9 # interupt control B 28 | IOCON = 0xA # I/O config (also 0xB) 29 | GPPUA = 0xC # port A pullups 30 | GPPUB = 0xD # port B pullups 31 | INTFA = 0xE # interupt flag A (where the interupt came from) 32 | INTFB = 0xF # interupt flag B 33 | INTCAPA = 0x10 # interupt capture A (value at interupt is saved here) 34 | INTCAPB = 0x11 # interupt capture B 35 | GPIOA = 0x12 # port A 36 | GPIOB = 0x13 # port B 37 | OLATA = 0x14 # output latch A 38 | OLATB = 0x15 # output latch B 39 | 40 | # I/O config 41 | BANK_OFF = 0x00 # addressing mode 42 | BANK_ON = 0x80 43 | INT_MIRROR_ON = 0x40 # interupt mirror (INTa|INTb) 44 | INT_MIRROR_OFF = 0x00 45 | SEQOP_OFF = 0x20 # incrementing address pointer 46 | SEQOP_ON = 0x00 47 | DISSLW_ON = 0x10 # slew rate 48 | DISSLW_OFF = 0x00 49 | HAEN_ON = 0x08 # hardware addressing 50 | HAEN_OFF = 0x00 51 | ODR_ON = 0x04 # open drain for interupts 52 | ODR_OFF = 0x00 53 | INTPOL_HIGH = 0x02 # interupt polarity 54 | INTPOL_LOW = 0x00 55 | 56 | LOWER_NIBBLE, UPPER_NIBBLE = range(2) 57 | 58 | 59 | class MCP23S17(SPIDevice): 60 | """Microchip's MCP23S17: A 16-Bit I/O Expander with Serial Interface. 61 | 62 | :attribute: iodira/iodirb -- Controls the direction of the data I/O. 63 | :attribute: ipola/ipolb --This register allows the user to configure 64 | the polarity on the corresponding GPIO port 65 | bits. 66 | :attribute: gpintena/gpintenb -- The GPINTEN register controls the 67 | interrupt-onchange feature for each 68 | pin. 69 | :attribute: defvala/defvalb --The default comparison value is 70 | configured in the DEFVAL register. 71 | :attribute: intcona/intconb --The INTCON register controls how the 72 | associated pin value is compared for 73 | the interrupt-on-change feature. 74 | :attribute: iocon --The IOCON register contains several bits for 75 | configuring the device. 76 | :attribute: gppua/gppub --The GPPU register controls the pull-up 77 | resistors for the port pins. 78 | :attribute: intfa/intfb --The INTF register reflects the interrupt 79 | condition on the port pins of any pin that 80 | is enabled for interrupts via the GPINTEN 81 | register. 82 | :attribute: intcapa/intcapb -- The INTCAP register captures the GPIO 83 | port value at the time the interrupt 84 | occurred. 85 | :attribute: gpioa/gpiob -- The GPIO register reflects the value on 86 | the port. 87 | :attribute: olata/olatb -- The OLAT register provides access to the 88 | output latches. 89 | """ 90 | def __init__(self, hardware_addr=0, bus=0, chip_select=0, speed_hz=100000): 91 | super(MCP23S17, self).__init__(bus, chip_select, speed_hz=speed_hz) 92 | self.hardware_addr = hardware_addr 93 | 94 | self.iodira = MCP23S17Register(IODIRA, self) 95 | self.iodirb = MCP23S17Register(IODIRB, self) 96 | self.ipola = MCP23S17Register(IPOLA, self) 97 | self.ipolb = MCP23S17Register(IPOLB, self) 98 | self.gpintena = MCP23S17Register(GPINTENA, self) 99 | self.gpintenb = MCP23S17Register(GPINTENB, self) 100 | self.defvala = MCP23S17Register(DEFVALA, self) 101 | self.defvalb = MCP23S17Register(DEFVALB, self) 102 | self.intcona = MCP23S17Register(INTCONA, self) 103 | self.intconb = MCP23S17Register(INTCONB, self) 104 | self.iocon = MCP23S17Register(IOCON, self) 105 | self.gppua = MCP23S17Register(GPPUA, self) 106 | self.gppub = MCP23S17Register(GPPUB, self) 107 | self.intfa = MCP23S17Register(INTFA, self) 108 | self.intfb = MCP23S17Register(INTFB, self) 109 | self.intcapa = MCP23S17Register(INTCAPA, self) 110 | self.intcapb = MCP23S17Register(INTCAPB, self) 111 | self.gpioa = MCP23S17Register(GPIOA, self) 112 | self.gpiob = MCP23S17Register(GPIOB, self) 113 | self.olata = MCP23S17Register(OLATA, self) 114 | self.olatb = MCP23S17Register(OLATB, self) 115 | 116 | def _get_spi_control_byte(self, read_write_cmd): 117 | """Returns an SPI control byte. 118 | 119 | The MCP23S17 is a slave SPI device. The slave address contains 120 | four fixed bits and three user-defined hardware address bits 121 | (if enabled via IOCON.HAEN) (pins A2, A1 and A0) with the 122 | read/write bit filling out the control byte:: 123 | 124 | +--------------------+ 125 | |0|1|0|0|A2|A1|A0|R/W| 126 | +--------------------+ 127 | 7 6 5 4 3 2 1 0 128 | 129 | :param read_write_cmd: Read or write command. 130 | :type read_write_cmd: int 131 | """ 132 | # board_addr_pattern = (self.hardware_addr & 0b111) << 1 133 | board_addr_pattern = (self.hardware_addr << 1) & 0xE 134 | rw_cmd_pattern = read_write_cmd & 1 # make sure it's just 1 bit long 135 | return 0x40 | board_addr_pattern | rw_cmd_pattern 136 | 137 | def read(self, address): 138 | """Returns the value of the address specified. 139 | 140 | :param address: The address to read from. 141 | :type address: int 142 | """ 143 | return self._pyver_read(address) 144 | 145 | def _py3read(self, address): 146 | ctrl_byte = self._get_spi_control_byte(READ_CMD) 147 | op, addr, data = self.spisend(bytes((ctrl_byte, address, 0))) 148 | return data 149 | 150 | def _py2read(self, address): 151 | ctrl_byte = self._get_spi_control_byte(READ_CMD) 152 | op, addr, data = self.spisend(chr(ctrl_byte)+chr(address)+chr(0)) 153 | return ord(data) 154 | 155 | def write(self, data, address): 156 | """Writes data to the address specified. 157 | 158 | :param data: The data to write. 159 | :type data: int 160 | :param address: The address to write to. 161 | :type address: int 162 | """ 163 | self._pyver_write(data, address) 164 | 165 | def _py3write(self, data, address): 166 | ctrl_byte = self._get_spi_control_byte(WRITE_CMD) 167 | self.spisend(bytes((ctrl_byte, address, data))) 168 | 169 | def _py2write(self, data, address): 170 | ctrl_byte = self._get_spi_control_byte(WRITE_CMD) 171 | self.spisend(chr(ctrl_byte)+chr(address)+chr(data)) 172 | 173 | # Python 2 support 174 | _pyver_read = _py3read if PY3 else _py2read 175 | _pyver_write = _py3write if PY3 else _py2write 176 | 177 | def read_bit(self, bit_num, address): 178 | """Returns the bit specified from the address. 179 | 180 | :param bit_num: The bit number to read from. 181 | :type bit_num: int 182 | :param address: The address to read from. 183 | :type address: int 184 | :returns: int -- the bit value from the address 185 | """ 186 | value = self.read(address) 187 | bit_mask = get_bit_mask(bit_num) 188 | return 1 if value & bit_mask else 0 189 | 190 | def write_bit(self, value, bit_num, address): 191 | """Writes the value given to the bit in the address specified. 192 | 193 | :param value: The value to write. 194 | :type value: int 195 | :param bit_num: The bit number to write to. 196 | :type bit_num: int 197 | :param address: The address to write to. 198 | :type address: int 199 | """ 200 | bit_mask = get_bit_mask(bit_num) 201 | old_byte = self.read(address) 202 | # generate the new byte 203 | if value: 204 | new_byte = old_byte | bit_mask 205 | else: 206 | new_byte = old_byte & ~bit_mask 207 | self.write(new_byte, address) 208 | 209 | def clear_interrupts(self, port): 210 | """Clears the interrupt flags by 'read'ing the capture register.""" 211 | self.read(INTCAPA if port == GPIOA else INTCAPB) 212 | 213 | 214 | class MCP23S17RegisterBase(object): 215 | """Base class for objects on an 8-bit register inside an MCP23S17.""" 216 | def __init__(self, address, chip): 217 | self.address = address 218 | self.chip = chip 219 | 220 | 221 | class MCP23S17Register(MCP23S17RegisterBase): 222 | """An 8-bit register inside an MCP23S17.""" 223 | def __init__(self, address, chip): 224 | super(MCP23S17Register, self).__init__(address, chip) 225 | self.lower_nibble = MCP23S17RegisterNibble(LOWER_NIBBLE, self.address, 226 | self.chip) 227 | self.upper_nibble = MCP23S17RegisterNibble(UPPER_NIBBLE, self.address, 228 | self.chip) 229 | self.bits = [MCP23S17RegisterBit(i, self.address, self.chip) 230 | for i in range(8)] 231 | 232 | @property 233 | def value(self): 234 | return self.chip.read(self.address) 235 | 236 | @value.setter 237 | def value(self, v): 238 | self.chip.write(v, self.address) 239 | 240 | def all_high(self): 241 | self.value = 0xFF 242 | 243 | def all_low(self): 244 | self.value = 0x00 245 | 246 | all_on = all_high 247 | all_off = all_low 248 | 249 | def toggle(self): 250 | self.value = 0xFF ^ self.value 251 | 252 | 253 | class MCP23S17RegisterNeg(MCP23S17Register): 254 | """An negated 8-bit register inside an MCP23S17.""" 255 | def __init__(self, address, chip): 256 | super(MCP23S17RegisterNeg, self).__init__(address, chip) 257 | self.lower_nibble = MCP23S17RegisterNibbleNeg(LOWER_NIBBLE, 258 | self.address, 259 | self.chip) 260 | self.upper_nibble = MCP23S17RegisterNibbleNeg(UPPER_NIBBLE, 261 | self.address, 262 | self.chip) 263 | self.bits = [MCP23S17RegisterBitNeg(i, self.address, self.chip) 264 | for i in range(8)] 265 | 266 | @property 267 | def value(self): 268 | return 0xFF ^ self.chip.read(self.address) 269 | 270 | @value.setter 271 | def value(self, v): 272 | self.chip.write(0xFF ^ v, self.address) 273 | 274 | 275 | class MCP23S17RegisterNibble(MCP23S17RegisterBase): 276 | """An 4-bit nibble inside a register inside an MCP23S17.""" 277 | def __init__(self, nibble, address, chip): 278 | super(MCP23S17RegisterNibble, self).__init__(address, chip) 279 | self.nibble = nibble 280 | range_start = 0 if self.nibble == LOWER_NIBBLE else 4 281 | range_end = 4 if self.nibble == LOWER_NIBBLE else 8 282 | self.bits = [MCP23S17RegisterBit(i, self.address, self.chip) 283 | for i in range(range_start, range_end)] 284 | 285 | @property 286 | def value(self): 287 | if self.nibble == LOWER_NIBBLE: 288 | return self.chip.read(self.address) & 0xF 289 | elif self.nibble == UPPER_NIBBLE: 290 | return (self.chip.read(self.address) & 0xF0) >> 4 291 | 292 | @value.setter 293 | def value(self, v): 294 | register_value = self.chip.read(self.address) 295 | if self.nibble == LOWER_NIBBLE: 296 | register_value &= 0xF0 # clear 297 | register_value ^= (v & 0x0F) # set 298 | elif self.nibble == UPPER_NIBBLE: 299 | register_value &= 0x0F # clear 300 | register_value ^= ((v << 4) & 0xF0) # set 301 | self.chip.write(register_value, self.address) 302 | 303 | def all_high(self): 304 | self.value = 0xF 305 | 306 | def all_low(self): 307 | self.value = 0x0 308 | 309 | all_on = all_high 310 | all_off = all_low 311 | 312 | def toggle(self): 313 | self.value = 0xF ^ self.value 314 | 315 | 316 | class MCP23S17RegisterNibbleNeg(MCP23S17RegisterNibble): 317 | """A negated 4-bit nibble inside a register inside an MCP23S17.""" 318 | def __init__(self, nibble, address, chip): 319 | super(MCP23S17RegisterNibbleNeg, self).__init__(nibble, address, chip) 320 | self.nibble = nibble 321 | range_start = 0 if self.nibble == LOWER_NIBBLE else 4 322 | range_end = 4 if self.nibble == LOWER_NIBBLE else 8 323 | self.bits = [MCP23S17RegisterBitNeg(i, self.address, self.chip) 324 | for i in range(range_start, range_end)] 325 | 326 | @property 327 | def value(self): 328 | if self.nibble == LOWER_NIBBLE: 329 | v = self.chip.read(self.address) & 0xF 330 | elif self.nibble == UPPER_NIBBLE: 331 | v = (self.chip.read(self.address) & 0xF0) >> 4 332 | return 0xF ^ v 333 | 334 | @value.setter 335 | def value(self, v): 336 | register_value = self.chip.read(self.address) 337 | if self.nibble == LOWER_NIBBLE: 338 | register_value &= 0xF0 # clear 339 | register_value ^= (v & 0x0F ^ 0x0F) # set 340 | elif self.nibble == UPPER_NIBBLE: 341 | register_value &= 0x0F # clear 342 | register_value ^= ((v << 4) & 0xF0 ^ 0xF0) # set 343 | self.chip.write(register_value, self.address) 344 | 345 | 346 | class MCP23S17RegisterBit(MCP23S17RegisterBase): 347 | """A bit inside register inside an MCP23S17.""" 348 | def __init__(self, bit_num, address, chip): 349 | super(MCP23S17RegisterBit, self).__init__(address, chip) 350 | self.bit_num = bit_num 351 | 352 | @property 353 | def value(self): 354 | return self.chip.read_bit(self.bit_num, self.address) 355 | 356 | @value.setter 357 | def value(self, v): 358 | self.chip.write_bit(v, self.bit_num, self.address) 359 | 360 | def set_high(self): 361 | self.value = 1 362 | 363 | def set_low(self): 364 | self.value = 0 365 | 366 | turn_on = set_high 367 | turn_off = set_low 368 | 369 | def toggle(self): 370 | self.value = 1 ^ self.value 371 | 372 | 373 | class MCP23S17RegisterBitNeg(MCP23S17RegisterBit): 374 | """A negated bit inside register inside an MCP23S17.""" 375 | def __init__(self, bit_num, address, chip): 376 | super(MCP23S17RegisterBitNeg, self).__init__(bit_num, address, chip) 377 | 378 | @property 379 | def value(self): 380 | return 1 ^ self.chip.read_bit(self.bit_num, self.address) 381 | 382 | @value.setter 383 | def value(self, v): 384 | self.chip.write_bit(v ^ 1, self.bit_num, self.address) 385 | -------------------------------------------------------------------------------- /pifacecommon/spi.py: -------------------------------------------------------------------------------- 1 | import posix 2 | import ctypes 3 | from fcntl import ioctl 4 | from .linux_spi_spidev import spi_ioc_transfer, SPI_IOC_MESSAGE 5 | 6 | 7 | SPIDEV = '/dev/spidev' 8 | SPI_HELP_LINK = "http://piface.github.io/pifacecommon/installation.html" \ 9 | "#enable-the-spi-module" 10 | 11 | 12 | class SPIInitError(Exception): 13 | pass 14 | 15 | 16 | class SPIDevice(object): 17 | """An SPI Device at /dev/spi..""" 18 | def __init__(self, bus=0, chip_select=0, spi_callback=None, speed_hz=100000): 19 | """Initialises the SPI device file descriptor. 20 | 21 | :param bus: The SPI device bus number 22 | :type bus: int 23 | :param chip_select: The SPI device chip_select number 24 | :param chip_select: int 25 | :raises: InitError 26 | """ 27 | self.bus = bus 28 | self.chip_select = chip_select 29 | self.spi_callback = spi_callback 30 | self.speed_hz = speed_hz 31 | self.fd = None 32 | spi_device = "%s%d.%d" % (SPIDEV, self.bus, self.chip_select) 33 | self.open_fd(spi_device) 34 | 35 | # def __del__(self): 36 | # if self.fd is not None: 37 | # self.close_fd() 38 | 39 | def open_fd(self, spi_device): 40 | try: 41 | self.fd = posix.open(spi_device, posix.O_RDWR) 42 | except OSError as e: 43 | raise SPIInitError( 44 | "I can't see %s. Have you enabled the SPI module? (%s)" 45 | % (spi_device, SPI_HELP_LINK) 46 | ) # from e # from is only available in Python 3 47 | 48 | def close_fd(self): 49 | posix.close(self.fd) 50 | self.fd = None 51 | 52 | def spisend(self, bytes_to_send): 53 | """Sends bytes via the SPI bus. 54 | 55 | :param bytes_to_send: The bytes to send on the SPI device. 56 | :type bytes_to_send: bytes 57 | :returns: bytes -- returned bytes from SPI device 58 | :raises: InitError 59 | """ 60 | # make some buffer space to store reading/writing 61 | wbuffer = ctypes.create_string_buffer(bytes_to_send, 62 | len(bytes_to_send)) 63 | rbuffer = ctypes.create_string_buffer(len(bytes_to_send)) 64 | 65 | # create the spi transfer struct 66 | transfer = spi_ioc_transfer( 67 | tx_buf=ctypes.addressof(wbuffer), 68 | rx_buf=ctypes.addressof(rbuffer), 69 | len=ctypes.sizeof(wbuffer), 70 | speed_hz=ctypes.c_uint32(self.speed_hz) 71 | ) 72 | 73 | if self.spi_callback is not None: 74 | self.spi_callback(bytes_to_send) 75 | # send the spi command 76 | ioctl(self.fd, SPI_IOC_MESSAGE(1), transfer) 77 | return ctypes.string_at(rbuffer, ctypes.sizeof(rbuffer)) 78 | -------------------------------------------------------------------------------- /pifacecommon/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '4.2.2' 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import errno 3 | import subprocess 4 | from distutils.core import setup 5 | 6 | 7 | VERSION_FILE = 'pifacecommon/version.py' 8 | PY3 = sys.version_info[0] >= 3 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='pifacecommon', 25 | version=get_version(), 26 | description='The PiFace common functions module.', 27 | author='Thomas Preston', 28 | author_email='thomas.preston@openlx.org.uk', 29 | license='GPLv3+', 30 | url='https://github.com/piface/pifacecommon', 31 | packages=['pifacecommon'], 32 | long_description=open('README.md').read() + open('CHANGELOG').read(), 33 | classifiers=[ 34 | "License :: OSI Approved :: GNU Affero General Public License v3 or " 35 | "later (AGPLv3+)", 36 | "Programming Language :: Python :: 3", 37 | "Programming Language :: Python :: 2", 38 | "Development Status :: 5 - Production/Stable", 39 | "Intended Audience :: Developers", 40 | "Topic :: Software Development :: Libraries :: Python Modules", 41 | ], 42 | keywords='piface raspberrypi openlx', 43 | ) 44 | --------------------------------------------------------------------------------