├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── PWM.md ├── README.md ├── examples ├── LCD7.py ├── RedBlueLED.py ├── aiohttp │ ├── README.md │ ├── main.py │ └── static │ │ └── index.html ├── button.py ├── event.py ├── led.py └── sonar.py ├── gpiodev ├── __init__.py ├── gpio.py ├── lcd7.py └── src │ ├── Makefile │ ├── gpioctl.c │ └── gpioctl.h ├── setup.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.o 3 | *.so 4 | libgpioctl.so.* 5 | *~ 6 | *.pyc 7 | build/ 8 | dist/ 9 | venv* 10 | *.egg-info 11 | .tox/ 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | 5 | cache: 6 | - pip: true 7 | 8 | install: 9 | - pip install flake8 10 | 11 | script: 12 | - flake8 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | include gpiodev/src/gpioctl.h 4 | -------------------------------------------------------------------------------- /PWM.md: -------------------------------------------------------------------------------- 1 | # How to enable PWM on Fedora 2 | 3 | ## Idea 4 | 5 | PWM device defined in Device Tree as `pwm` node: 6 | 7 | https://github.com/torvalds/linux/blob/522214d9be9c9f00f34ed89cb95e901b7ac31c59/arch/arm/boot/dts/bcm2835-rpi.dtsi#L72 8 | 9 | PWM node is an abstract object which is an umbrella on top of GPIO group and clocks. 10 | 11 | There are many GPIO groups on Raspberry Pi, which are configured in 12 | https://github.com/torvalds/linux/blob/522214d9be9c9f00f34ed89cb95e901b7ac31c59/arch/arm/boot/dts/bcm283x.dtsi#L114 13 | 14 | By default PWM node uses `pwm0_gpio40` and `pwm1_gpio45`. Pins 40 and 15 | 45 are not exposed in Raspberry PI - these are (I guess) pins which 16 | are used internally by audio output. 17 | 18 | To enable PWM on exposed pins 12 and 13 we need to change the value of 19 | `pinctrl-0` parameter in the device tree. 20 | 21 | ## Patch device tree 22 | 23 | There are probably easier ways to patch Device Tree (overlays..). But here is the way to recompile the entire Device Tree without recompiling the kernel. 24 | 25 | ### Install tools 26 | 27 | (root)# dnf install rpmdevtools git bc openssl-devel 28 | 29 | ### Get kernel sources 30 | 31 | Commands below do not need require root privileges. 32 | 33 | Fetch the kernel srpm file: 34 | 35 | $ dnf download --source kernel 36 | 37 | Unpack srpm to `~/rpmbuild`: 38 | 39 | $ rpm -i kernel-4.14.8-300.fc27.src.rpm 40 | 41 | Prepare kernel source tree: 42 | 43 | $ rpmbuild --nodeps -bp --with baseonly --target armv7l ~/rpmbuild/SPECS/kernel.spec 44 | 45 | Switch to the directory wuth unpacked kernel sources: 46 | 47 | $ cd ~/rpmbuild/BUILD/kernel-4.14.fc27/linux-4.14.8-300.fc27.armv7l/ 48 | 49 | Get the Fedora kernel `.config` file 50 | 51 | $ cp configs/kernel-4.14.8-armv7hl.config .config 52 | 53 | ### Build new dtb-files 54 | 55 | Modify Device Tree in `arch/arm/boot/dts/` folder. For example this patch enables PWM on GPIO12 and GPIO13: 56 | 57 | ``` 58 | $ git diff arch/arm/boot/dts/bcm2835-rpi.dtsi 59 | diff --git a/arch/arm/boot/dts/bcm2835-rpi.dtsi b/arch/arm/boot/dts/bcm2835-rpi.dtsi 60 | index e36c392..398f822 100644 61 | --- a/arch/arm/boot/dts/bcm2835-rpi.dtsi 62 | +++ b/arch/arm/boot/dts/bcm2835-rpi.dtsi 63 | @@ -77,7 +77,7 @@ 64 | 65 | &pwm { 66 | pinctrl-names = "default"; 67 | - pinctrl-0 = <&pwm0_gpio40 &pwm1_gpio45>; 68 | + pinctrl-0 = <&pwm0_gpio12 &pwm1_gpio13>; 69 | status = "okay"; 70 | }; 71 | 72 | ``` 73 | 74 | Compile Device Tree: 75 | 76 | $ make V=1 ARCH=arm dtbs dtbs_install INSTALL_DTBS_PATH=custom-dts 77 | 78 | Now in `custom-dts/` we have new .dtb files. 79 | 80 | ## Configure boot loader to use custom dts files 81 | 82 | In Fedora for ARM U-Boot Bootloader is used to run Extlinux 83 | Bootloader, which then chooses which kernel, initrd and dtb images to 84 | boot. 85 | 86 | The following must be done as root. 87 | 88 | Copy custom device tree to `/boot`: 89 | 90 | # cp -r /custom-dts /boot/custom 91 | 92 | Modify `/boot/extlinux/extlinux.conf` to use dtb files from custom 93 | device tree (add new item with custom `fdtdir` parameter and choose it 94 | as default). 95 | 96 | ``` 97 | # extlinux.conf generated by appliance-creator 98 | ui menu.c32 99 | menu autoboot Welcome to Fedora. Automatic boot in # second{,s}. Press a key for options. 100 | menu title Fedora Boot Options. 101 | menu hidden 102 | timeout 20 103 | totaltimeout 600 104 | 105 | default=Fedora (Customized) 106 | 107 | label Fedora (Customized) 108 | kernel /vmlinuz-4.14.8-300.fc27.armv7hl 109 | append ro root=UUID=b35d7f9e-3d7c-4e43-8ba9-4c5439ca27e3 LANG=en_US.UTF-8 110 | fdtdir /custom/ 111 | initrd /initramfs-4.14.8-300.fc27.armv7hl.img 112 | 113 | label Fedora (4.14.8-300.fc27.armv7hl) 27 (Twenty Seven) 114 | kernel /vmlinuz-4.14.8-300.fc27.armv7hl 115 | append ro root=UUID=b35d7f9e-3d7c-4e43-8ba9-4c5439ca27e3 LANG=en_US.UTF-8 116 | fdtdir /dtb-4.14.8-300.fc27.armv7hl/ 117 | initrd /initramfs-4.14.8-300.fc27.armv7hl.img 118 | 119 | label Fedora-Minimal-armhfp-27-1.6 (4.13.9-300.fc27.armv7hl) 120 | kernel /vmlinuz-4.13.9-300.fc27.armv7hl 121 | append ro root=UUID=b35d7f9e-3d7c-4e43-8ba9-4c5439ca27e3 122 | fdtdir /dtb-4.13.9-300.fc27.armv7hl/ 123 | initrd /initramfs-4.13.9-300.fc27.armv7hl.img 124 | ``` 125 | 126 | Reboot! 127 | 128 | ## Test PWM 129 | 130 | As root: 131 | 132 | ``` 133 | cd /sys/class/pwm/ 134 | cd pwmchip0/ 135 | echo 0 > export 136 | cd pwm0/ 137 | echo 100000 > period 138 | echo 10000 > duty_cycle 139 | echo 1 > enable 140 | ``` 141 | 142 | Connect LED to GPIO12 and check that it is dimmed. 143 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Managing GPIO pins via character device 2 | 3 | ## Basics 4 | 5 | For the set of GPIO lines (pins) we create an object called `GPIOHandle`, which manages their state. State is a tuple of 0's and 1's, one number per line. 6 | 7 | This library doesn't require root access to the system, but it needs a read-write access to the gpiochip device. By default it uses `/dev/gpiochip0`. 8 | 9 | To allow read-write access to the device for the user, run: 10 | 11 | $ sudo chmod a+rw /dev/gpiochip0 12 | 13 | Note that the system might have several GPIO chips, some of them can be exposed to the user (as /dev/gpiochip0 on Raspberry Pi) and some of them might be responsible for system functions, like WakeOnLan or system LED lights. Be carefull when choosing the device and allowing user access to it. 14 | 15 | You can check the info on the GPIOChip device, by accessing its info() method. See example below. 16 | 17 | ## Example 18 | 19 | ``` 20 | from gpiodev import GPIOHandle 21 | import time 22 | 23 | # Request handle for lines 12 and 23 from default /dev/gpiochip0 24 | 25 | DoubleLED = GPIOHandle((12,23)) 26 | 27 | # Define states of the Double LED 28 | 29 | all = (1, 1) 30 | none = (0, 0) 31 | first = (1, 0) 32 | second = (0, 1) 33 | 34 | # Loop through the states 35 | 36 | for state in [all, none, first, second, none, all, none]: 37 | DoubleLED.set_values(state) 38 | print(DoubleLED.get_values()) 39 | time.sleep(1) 40 | ``` 41 | 42 | ## Use another device 43 | 44 | To use another gpiochip device, for example `/dev/gpiochip1`, you can use a different way to setup a handle: 45 | 46 | ``` 47 | from gpiodev import GPIOChip 48 | 49 | GPIO = GPIOChip("/dev/gpiochip1") 50 | 51 | # Check info on the gpio chip 52 | 53 | print(GPIO.info()) 54 | 55 | # Request handle for lines 12 and 23 from /dev/gpiochip1 56 | 57 | DoubleLED = GPIO.get_handle((12,23)) # This will fail on RaspberryPi as /dev/gpiochip1 is a system gpio chip, with only 8 lines. 58 | 59 | ``` 60 | 61 | ## Background 62 | 63 | New GPIO interface has been 64 | [introduced](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1a46712aa99594eabe1e9aeedf115dfff0db1dfd) in the kernel. 65 | 66 | It exposes GPIO interface a character device(`/dev/gpiochip0`) and 67 | provides several [ioctl 68 | syscalls](https://github.com/torvalds/linux/blob/master/include/uapi/linux/gpio.h) 69 | for bulk operations on sets of GPIO pins. 70 | 71 | Unlike Python bindings to the [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/) C-library, we work with the kernel interface (ioctl calls) directly. 72 | 73 | In [gpiodev/src/gpioctl.c](gpiodev/src/gpioctl.c) we wrap the ioctl calls into 74 | C-functions suitable for later use. 75 | 76 | In [gpiodev/gpio.py](gpiodev/gpio.py) the ctypes bindings are created and then 77 | used to define the main GPIOHandle class. 78 | 79 | ---- 80 | 81 | Tested on [Fedora 26+ armhfp](https://arm.fedoraproject.org), Raspberry Pi 3 Model B. 82 | -------------------------------------------------------------------------------- /examples/LCD7.py: -------------------------------------------------------------------------------- 1 | from gpiodev.lcd7 import LCD7 2 | import asyncio 3 | 4 | 5 | LCD = LCD7( 6 | digits=(26, 22, 17, 18), 7 | segments=(19, 6, 4, 23, 21, 27, 16), 8 | ) 9 | 10 | 11 | async def async_write(strings, delay=0.1): 12 | for string in strings: 13 | print(string) 14 | LCD.state = string 15 | if not string: 16 | LCD.state = string 17 | return 18 | await asyncio.sleep(delay + 0.5 * len(string)) 19 | 20 | 21 | async def asynchronous(): 22 | futures = [ 23 | LCD.async_show_string(" "), 24 | async_write([ 25 | "hello ", 26 | "1234 ", 27 | " 15 ", 28 | "6789", 29 | None, 30 | ] 31 | )] 32 | await asyncio.wait(futures) 33 | 34 | 35 | ioloop = asyncio.get_event_loop() 36 | ioloop.run_until_complete(asynchronous()) 37 | ioloop.close() 38 | -------------------------------------------------------------------------------- /examples/RedBlueLED.py: -------------------------------------------------------------------------------- 1 | from gpiodev import GPIOHandle 2 | import time 3 | 4 | RedBlueLED = GPIOHandle((26, 21)) 5 | 6 | print(RedBlueLED.get_values()) 7 | 8 | states = [ 9 | (1, 0), 10 | (0, 1), 11 | (1, 1), 12 | ] 13 | 14 | for state in states: 15 | RedBlueLED.set_values(state) 16 | print(RedBlueLED.get_values()) 17 | time.sleep(5) 18 | -------------------------------------------------------------------------------- /examples/aiohttp/README.md: -------------------------------------------------------------------------------- 1 | aiohttp Websocket Connection example 2 | ==================================== 3 | In this example you can control the state of a some LEDs via WebSocket. 4 | 5 | Installation 6 | ------------ 7 | You need to install aiohttp: 8 | 9 | ```pip install aiohttp``` 10 | 11 | It is not needed for the general GPIO-lib so it is not part of the installation process. 12 | 13 | Configuration 14 | ------------- 15 | Make sure to switch the ip address and port number in the index.html-File to the one of your raspberry pi (line 19), so the Browser can connect to it using the WebSocket. 16 | 17 | You can configure the GPIO-pins you like to use. See GPIO_LINES in the main.py. 18 | 19 | Note that the fedora firewall prevents access on port 8080 by default, so allow that port to be accessed by other machines in your network e.g. `firewall-cmd --zone=dmz --add-port=8080/tcp`, take a look at the [documentation](https://docs-old.fedoraproject.org/en-US/Fedora/19/html/Security_Guide/sec-Open_Ports_in_the_firewall-CLI.html) 20 | 21 | Additional notes 22 | ---------------- 23 | aiohttp still waits for a request when you press CTRL+c to stop it, so you need to refresh the page after pressing CTRL+c to stop the server. 24 | -------------------------------------------------------------------------------- /examples/aiohttp/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import asyncio 4 | from aiohttp.web import (Application, Response, WebSocketResponse, WSMsgType, 5 | run_app, FileResponse) 6 | 7 | from gpiodev import GPIOHandle 8 | 9 | 10 | HOST = os.getenv('HOST', '0.0.0.0') 11 | PORT = int(os.getenv('PORT', 8080)) 12 | 13 | # GPIO pin numbers for your board 14 | GPIO_LINES = (18, 4) 15 | 16 | gpio_led = GPIOHandle(GPIO_LINES, mode="out") 17 | 18 | 19 | async def index_handler(request): 20 | ''' 21 | send static index file 22 | ''' 23 | return FileResponse('./static/index.html') 24 | 25 | 26 | async def websocket_handler(request): 27 | ''' 28 | use websocket to handle button clicks/LED changes 29 | ''' 30 | resp = WebSocketResponse() 31 | ok, protocol = resp.can_prepare(request) 32 | if not ok: 33 | return Response(body='This is a WebSocket, not a WebSite', 34 | content_type='text/html') 35 | await resp.prepare(request) 36 | try: 37 | # new connection - send current GPIO configuration 38 | led_states = gpio_led.get_values() 39 | resp.send_str(json.dumps({ 40 | 'states': led_states, 41 | 'lines': GPIO_LINES 42 | })) 43 | request.app['sockets'].append(resp) 44 | 45 | # async wait for new WebSocket messages 46 | async for msg in resp: 47 | if msg.type == WSMsgType.TEXT: 48 | led_states = gpio_led.get_values() 49 | data = json.loads(msg.data) 50 | 51 | # switch selected GPIO by its pin number 52 | if 'switch_gpio' in data: 53 | led_nr = GPIO_LINES.index(data['switch_gpio']) 54 | led_states[led_nr] = int(not led_states[led_nr]) 55 | gpio_led.set_values(tuple(led_states)) 56 | 57 | # update LED states to all connected clients 58 | for ws in request.app['sockets']: 59 | await ws.send_str(json.dumps({'states': led_states})) 60 | return resp 61 | finally: 62 | # remove disconnected connections. 63 | # we do not need to send them the state update anymore 64 | request.app['sockets'].remove(resp) 65 | 66 | 67 | async def on_shutdown(app): 68 | ''' 69 | close all connections on shutdown 70 | ''' 71 | for ws in app['sockets']: 72 | await ws.close() 73 | 74 | 75 | async def init(loop): 76 | app = Application(loop=loop) 77 | app['sockets'] = [] 78 | app.router.add_route('GET', '/ws', websocket_handler) 79 | app.router.add_route('GET', '/', index_handler) 80 | app.on_shutdown.append(on_shutdown) 81 | return app 82 | 83 | 84 | def main(): 85 | # aiohttp setup 86 | loop = asyncio.get_event_loop() 87 | app = loop.run_until_complete(init(loop)) 88 | 89 | run_app(app) 90 | 91 | 92 | if __name__ == '__main__': 93 | main() 94 | -------------------------------------------------------------------------------- /examples/aiohttp/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WebSocket demo 5 | 6 | 7 | 8 | 9 | 14 | 15 | 16 |
17 | 48 | 49 | -------------------------------------------------------------------------------- /examples/button.py: -------------------------------------------------------------------------------- 1 | from gpiodev import GPIOHandle 2 | import time 3 | 4 | RedLED = GPIOHandle((19,), mode="out") 5 | Button = GPIOHandle((18,), mode="in") 6 | 7 | while True: 8 | 9 | state = Button.get_values()[0] 10 | print(state) 11 | RedLED.set_values((state,)) 12 | time.sleep(0.1) 13 | -------------------------------------------------------------------------------- /examples/event.py: -------------------------------------------------------------------------------- 1 | from gpiodev import GPIOEventHandle 2 | 3 | Button = GPIOEventHandle(17, mode="rising") 4 | 5 | while True: 6 | print("reading") 7 | print(Button.get()) 8 | -------------------------------------------------------------------------------- /examples/led.py: -------------------------------------------------------------------------------- 1 | from gpiodev import GPIOChip 2 | import time 3 | 4 | GPIO = GPIOChip() 5 | 6 | DoubleLED = GPIO.get_handle( 7 | (12, 23), 8 | label="DoubleLED", 9 | ) 10 | 11 | all = (1, 1) 12 | none = (0, 0) 13 | first = (1, 0) 14 | second = (0, 1) 15 | 16 | print(GPIO.line_info(12)) 17 | 18 | 19 | for state in [all, none, first, second, all, none]*10: 20 | DoubleLED.set_values(state) 21 | print(DoubleLED.get_values()) 22 | time.sleep(1) 23 | -------------------------------------------------------------------------------- /examples/sonar.py: -------------------------------------------------------------------------------- 1 | from gpiodev import GPIOHandle, GPIOEventHandle 2 | import time 3 | 4 | 5 | class Sonar(): 6 | 7 | def __init__(self, echo_pin, trigger_pin): 8 | self.echo_pin = echo_pin 9 | self.trigger_pin = trigger_pin 10 | 11 | self.trigger_handle = GPIOHandle((self.trigger_pin,), mode="out") 12 | self.echo_handle = GPIOEventHandle(self.echo_pin, mode="both") 13 | 14 | def trigger(self): 15 | self.trigger_handle.flip() 16 | self.trigger_handle.flip() 17 | 18 | def measure(self): 19 | self.trigger() 20 | start = self.echo_handle.get()[0] 21 | print("Start", start) 22 | stop = self.echo_handle.get()[0] 23 | print("Stop", stop) 24 | 25 | return (stop - start)*340.0/2.0 26 | 27 | 28 | S = Sonar(echo_pin=20, trigger_pin=21) 29 | 30 | while True: 31 | print(S.measure()) 32 | time.sleep(5) 33 | -------------------------------------------------------------------------------- /gpiodev/__init__.py: -------------------------------------------------------------------------------- 1 | from .gpio import GPIOChip, GPIOHandle, GPIOEventHandle 2 | 3 | __all__ = [ 4 | "GPIOChip", 5 | "GPIOHandle", 6 | "GPIOEventHandle", 7 | ] 8 | -------------------------------------------------------------------------------- /gpiodev/gpio.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import ctypes.util 3 | import os 4 | 5 | 6 | ######################################################## 7 | # constants from linux/gpio.h 8 | ######################################################## 9 | 10 | 11 | GPIOHANDLES_MAX = 64 12 | 13 | GPIOHANDLE_REQUEST_INPUT = 1 << 0 14 | GPIOHANDLE_REQUEST_OUTPUT = 1 << 1 15 | GPIOHANDLE_REQUEST_ACTIVE_LOW = 1 << 2 16 | GPIOHANDLE_REQUEST_OPEN_DRAIN = 1 << 3 17 | GPIOHANDLE_REQUEST_OPEN_SOURCE = 1 << 4 18 | 19 | 20 | GPIOEVENT_REQUEST_RISING_EDGE = 1 << 0 21 | GPIOEVENT_REQUEST_FALLING_EDGE = 1 << 1 22 | GPIOEVENT_REQUEST_BOTH_EDGES = (1 << 0 | 1 << 1) 23 | 24 | 25 | ######################################################## 26 | # helpers 27 | ######################################################## 28 | 29 | 30 | def get_library(name): 31 | '''Find library in a current directory 32 | 33 | We add 'lib' and '.so' to the name. 34 | ''' 35 | 36 | path = os.path.dirname(__file__) 37 | files = os.listdir(path) 38 | 39 | for file in files: 40 | if file.startswith("lib{name}".format(name=name)): 41 | if file.endswith(".so"): 42 | return os.path.join(path, file) 43 | return None 44 | 45 | 46 | libgpioctl = ctypes.CDLL(get_library("gpioctl")) 47 | 48 | libc = ctypes.CDLL(ctypes.util.find_library('c')) 49 | f_read = libc.read 50 | 51 | c32 = ctypes.c_char * 32 52 | 53 | cul_MAX = ctypes.c_ulong * GPIOHANDLES_MAX 54 | cu8_MAX = ctypes.c_ubyte * GPIOHANDLES_MAX 55 | 56 | 57 | ######################################################## 58 | # ctypes structures 59 | ######################################################## 60 | 61 | 62 | class _gpiochip_info (ctypes.Structure): 63 | _fields_ = [ 64 | ("name", c32), 65 | ("label", c32), 66 | ("lines", ctypes.c_long), 67 | ] 68 | 69 | 70 | class _gpioline_info (ctypes.Structure): 71 | _fields_ = [ 72 | ("line", ctypes.c_long), 73 | ("flags", ctypes.c_ulong), 74 | ("name", c32), 75 | ("consumer", c32), 76 | ] 77 | 78 | 79 | class _gpiohandle_request (ctypes.Structure): 80 | _fields_ = [ 81 | ('lineoffsets', cul_MAX), 82 | ('flags', ctypes.c_ulong), 83 | ('default_values', cu8_MAX), 84 | ('consumer_label', c32), 85 | ('lines', ctypes.c_ulong), 86 | ('fd', ctypes.c_int), 87 | ] 88 | 89 | 90 | class _gpioevent_request (ctypes.Structure): 91 | _fields_ = [ 92 | ('lineoffset', ctypes.c_ulong), 93 | ('handleflags', ctypes.c_ulong), 94 | ('eventflags', ctypes.c_ulong), 95 | ('consumer_label', c32), 96 | ('fd', ctypes.c_int), 97 | ] 98 | 99 | 100 | class _gpiohandle_data (ctypes.Structure): 101 | _fields_ = [ 102 | ('values', cu8_MAX), 103 | ] 104 | 105 | 106 | class gpioevent_data (ctypes.Structure): 107 | _fields_ = [ 108 | ("timestamp", ctypes.c_ulonglong), 109 | ('id', ctypes.c_ulong), 110 | ] 111 | 112 | ######################################################## 113 | 114 | 115 | _GPIO = "/dev/gpiochip0" 116 | 117 | 118 | class GPIOError(IOError): 119 | pass 120 | 121 | 122 | class _GPIOChip(): 123 | 124 | def __init__(self, path): 125 | self.path = path 126 | 127 | self.fd = os.open(self.path, os.O_RDWR) 128 | 129 | def info(self): 130 | _info = _gpiochip_info() 131 | status = libgpioctl.get_chipinfo(self.fd, ctypes.byref(_info)) 132 | if status != 0: 133 | raise GPIOError("get_chipinfo call returned non-zero status") 134 | 135 | info = { 136 | "name": _info.name, 137 | "label": _info.label, 138 | "lines": _info.lines, 139 | } 140 | 141 | return info 142 | 143 | def line_info(self, line): 144 | _info = _gpioline_info(line=line) 145 | 146 | status = libgpioctl.get_lineinfo(self.fd, ctypes.byref(_info)) 147 | if status != 0: 148 | raise GPIOError("get_chipinfo call returned non-zero status") 149 | 150 | info = { 151 | "line": _info.line, 152 | "flags": _info.flags, 153 | "name": _info.name, 154 | "consumer": _info.consumer, 155 | } 156 | 157 | return info 158 | 159 | def get_handle(self, *args, **kwargs): 160 | return GPIOHandle(*args, **kwargs, gpio=self) 161 | 162 | def get_event_handle(self, *args, **kwargs): 163 | return GPIOEventHandle(*args, **kwargs, gpio=self) 164 | 165 | 166 | class GPIOChip(): 167 | 168 | _chips = {} 169 | 170 | def __new__(cls, name=_GPIO): 171 | if name not in cls._chips: 172 | chip = _GPIOChip(name) 173 | cls._chips[name] = chip 174 | return cls._chips[name] 175 | 176 | 177 | class GPIOHandle: 178 | 179 | _FLAGS = { 180 | 'out': GPIOHANDLE_REQUEST_OUTPUT, 181 | 'in': GPIOHANDLE_REQUEST_INPUT, 182 | } 183 | 184 | def __init__( 185 | self, 186 | lines, 187 | mode="out", 188 | defaults=None, 189 | label='', 190 | gpio=None, 191 | ): 192 | self.num_lines = len(lines) 193 | 194 | if self.num_lines > GPIOHANDLES_MAX: 195 | raise GPIOError( 196 | "Can not create handle: " 197 | "number of lines {0} exceeds the limit ({1})" 198 | .format(self.num_lines, GPIOHANDLES_MAX) 199 | ) 200 | 201 | self.flags = self._FLAGS.get(mode, mode) 202 | 203 | if not defaults: 204 | defaults = (0,) * self.num_lines 205 | 206 | self.defaults = tuple(defaults) 207 | self.lines = tuple(lines) 208 | self.label = label 209 | 210 | if not gpio: 211 | gpio = GPIOChip(_GPIO) 212 | self.gpio = gpio 213 | 214 | _request = _gpiohandle_request( 215 | lineoffsets=self.lines, 216 | flags=self.flags, 217 | default_values=self.defaults, 218 | consumer_label=self.label.encode('utf-8'), 219 | lines=self.num_lines, 220 | ) 221 | 222 | status = libgpioctl.get_linehandle( 223 | self.gpio.fd, 224 | ctypes.byref(_request), 225 | ) 226 | 227 | if status != 0: 228 | raise GPIOError("get_linehandle call returned non-zero status") 229 | 230 | self.handle = _request.fd 231 | 232 | def set_values(self, values): 233 | values = tuple(values) 234 | if len(values) != self.num_lines: 235 | raise GPIOError( 236 | "Number of values {0} doesn't match number of lines {1}" 237 | .format(len(values), self.num_lines) 238 | ) 239 | 240 | if self.flags & GPIOHANDLE_REQUEST_OUTPUT == 0: 241 | raise GPIOError("Can not set values, as we are not in output mode") 242 | 243 | _data = _gpiohandle_data(values) 244 | status = libgpioctl.set_line_values(self.handle, ctypes.byref(_data)) 245 | if status != 0: 246 | raise GPIOError("set_line_values call returned non-zero status") 247 | 248 | def get_values(self): 249 | _data = _gpiohandle_data() 250 | status = libgpioctl.get_line_values(self.handle, ctypes.byref(_data)) 251 | if status != 0: 252 | raise GPIOError("get_line_values call returned non-zero status") 253 | 254 | return tuple(_data.values[:self.num_lines]) 255 | 256 | def flip(self): 257 | """Change all values to the opposite""" 258 | 259 | current_values = self.get_values() 260 | new_values = tuple([1 - value for value in current_values]) 261 | self.set_values(new_values) 262 | 263 | 264 | class GPIOEventHandle: 265 | 266 | _FLAGS = { 267 | "rising": GPIOEVENT_REQUEST_RISING_EDGE, 268 | "falling": GPIOEVENT_REQUEST_FALLING_EDGE, 269 | "both": GPIOEVENT_REQUEST_BOTH_EDGES, 270 | } 271 | 272 | def __init__( 273 | self, 274 | line, 275 | mode="both", 276 | label='', 277 | gpio=None, 278 | ): 279 | self.line = line 280 | 281 | self.flags = self._FLAGS.get(mode, mode) 282 | 283 | if self.line > GPIOHANDLES_MAX: 284 | raise GPIOError( 285 | "Can not read line {0}. Line offset exceeds the limit ({1})" 286 | .format(self.line, GPIOHANDLES_MAX) 287 | ) 288 | 289 | self.label = label 290 | if not gpio: 291 | self.gpio = GPIOChip(_GPIO) 292 | 293 | handle_flags = GPIOHANDLE_REQUEST_INPUT 294 | 295 | _request = _gpioevent_request( 296 | lineoffset=self.line, 297 | handleflags=handle_flags, 298 | eventflags=self.flags, 299 | consumer_label=self.label.encode('utf-8'), 300 | ) 301 | 302 | status = libgpioctl.get_lineevent( 303 | self.gpio.fd, 304 | ctypes.byref(_request), 305 | ) 306 | 307 | if status != 0: 308 | raise GPIOError("get_lineevent call returned non-zero status") 309 | 310 | self.handle = _request.fd 311 | 312 | def get(self): 313 | _data = gpioevent_data() 314 | 315 | status = f_read(self.handle, ctypes.byref(_data), ctypes.sizeof(_data)) 316 | if status != ctypes.sizeof(_data): 317 | raise GPIOError("get_event_data error") 318 | return (float(_data.timestamp) / 1e9, _data.id) 319 | -------------------------------------------------------------------------------- /gpiodev/lcd7.py: -------------------------------------------------------------------------------- 1 | from gpiodev import GPIOHandle 2 | import asyncio 3 | 4 | ''' 5 | 6 | LCD7 is a device with four 7-segment LED digits to show. 7 segments 7 | are not enough to show arbitraty letters, but it can be used as clocks 8 | or counter. 9 | 10 | Though there are 4x7 = 28 LED segments to switch on and off, it uses 11 | only 12 GPIO pins. 4 pins are used to choose the active digit, 7 pins 12 | - to switch on segments for a digit, and one additional pin controls 13 | central dots (not implemented here). 14 | 15 | Abstract pins used in LCD7 class implementation are: 16 | 17 | Digits: 18 | 19 | ``` 20 | 0 1 2 3 21 | ``` 22 | 23 | Segments: 24 | 25 | ``` 26 | --0-- 27 | | | 28 | 1 2 29 | | | 30 | --3-- 31 | | | 32 | 4 5 33 | | | 34 | --6-- 35 | ``` 36 | 37 | If we enumerate physical pins on a device in a following manner: 38 | 39 | ``` 40 | 12 11 10 9 8 7 41 | | | | | | | 42 | __ __ __ __ 43 | | | | | | | | | 44 | |__| |__| . |__| |__| 45 | | | | | . | | | | 46 | |__|. |__|. |__|. |__|. 47 | 48 | | | | | | | 49 | 1 2 3 4 5 6 50 | ``` 51 | 52 | Then to setup the LCD7 class one needs to specify the input pins 53 | in the following order: 54 | 55 | ``` 56 | Digits Segments Dots 57 | 58 | 0) 12 0) 11 0) 3 (not used) 59 | 1) 9 1) 10 60 | 2) 8 2) 7 61 | 3) 6 3) 5 62 | 4) 1 63 | 5) 4 64 | 6) 2 65 | ``` 66 | 67 | The mapping might be different for your device though. 68 | 69 | ''' 70 | 71 | 72 | DIGIT = [ 73 | (0, 1, 1, 1), 74 | (1, 0, 1, 1), 75 | (1, 1, 0, 1), 76 | (1, 1, 1, 0), 77 | ] 78 | 79 | SYMBOL = { 80 | " ": (0, 0, 0, 0, 0, 0, 0), 81 | "0": (1, 1, 1, 0, 1, 1, 1), 82 | "1": (0, 0, 1, 0, 0, 1, 0), 83 | "2": (1, 0, 1, 1, 1, 0, 1), 84 | "3": (1, 0, 1, 1, 0, 1, 1), 85 | "4": (0, 1, 1, 1, 0, 1, 0), 86 | "5": (1, 1, 0, 1, 0, 1, 1), 87 | "6": (1, 1, 0, 1, 1, 1, 1), 88 | "7": (1, 0, 1, 0, 0, 1, 0), 89 | "8": (1, 1, 1, 1, 1, 1, 1), 90 | "9": (1, 1, 1, 1, 0, 1, 1), 91 | "a": (1, 1, 1, 1, 1, 1, 0), 92 | "b": (0, 1, 0, 1, 1, 1, 1), 93 | "c": (1, 1, 0, 0, 1, 0, 1), 94 | "d": (0, 0, 1, 1, 1, 1, 1), 95 | "e": (1, 1, 0, 1, 1, 0, 1), 96 | "f": (1, 1, 0, 1, 1, 0, 0), 97 | "g": (1, 1, 0, 0, 1, 1, 1), 98 | "h": (0, 1, 1, 1, 1, 1, 0), 99 | "i": (0, 0, 1, 0, 0, 1, 0), 100 | "j": (0, 0, 1, 0, 0, 1, 1), 101 | "k": (0, 1, 1, 1, 1, 1, 0), 102 | "l": (0, 1, 0, 0, 1, 0, 1), 103 | "m": (1, 0, 0, 0, 0, 1, 1), 104 | "n": (0, 0, 0, 0, 1, 1, 1), 105 | "o": (1, 1, 1, 0, 1, 1, 1), 106 | "p": (1, 1, 1, 1, 1, 0, 0), 107 | "q": (1, 1, 1, 1, 0, 0, 1), 108 | "r": (0, 0, 0, 1, 1, 0, 0), 109 | "s": (1, 1, 0, 1, 0, 1, 1), 110 | } 111 | 112 | 113 | def _render_gpio_state(digit, symbol): 114 | '''Return tuple with values for GPIOHandle pins. 115 | 116 | digit is a number from 0 to 3 117 | symbol is one character 118 | 119 | If symbol is not present in SYMBOL dictionary - show nothing. 120 | 121 | ''' 122 | return DIGIT[digit] + SYMBOL.get(symbol, SYMBOL[" "]) 123 | 124 | 125 | class LCD7(GPIOHandle): 126 | 127 | def __init__(self, digits, segments): 128 | self.digits = digits 129 | self.segments = segments 130 | self.window_size = len(digits) 131 | 132 | lines = self.digits + self.segments 133 | defaults = ( 134 | (1,)*len(self.digits) 135 | + (0,)*len(self.segments) 136 | ) 137 | GPIOHandle.__init__( 138 | self, 139 | lines, 140 | defaults=defaults, 141 | mode="out", 142 | ) 143 | self.state = None 144 | 145 | async def async_show_state(self, state=None, led_delay=0.005): 146 | '''Show current state on the display. 147 | 148 | We loop through characters and render them on a corresponding 149 | digits. 150 | 151 | State should be a four character iterable (for example, string). 152 | If state is given, reset the LCD display to it. If state is 153 | not provided, check for the self.state class variable. 154 | 155 | Looping is done asynchronously in a background. Loop will stop 156 | as soon as the self.state class variable is set to None. 157 | 158 | ''' 159 | if state: 160 | self.state = state 161 | 162 | while self.state: 163 | for index, symbol in enumerate(self.state): 164 | self.set_values(_render_gpio_state(index, symbol)) 165 | await asyncio.sleep(led_delay) 166 | 167 | async def async_show_string(self, string=None, delay=0.5, led_delay=0.005): 168 | '''Show the string on display. 169 | 170 | Create a sliding window on the string and loop through the string 171 | characters rendering the window on a display. 172 | 173 | delay (in seconds) specifies the delay between window shifts. 174 | 175 | led_delay (in seconds) is the maximum delay we can allow for a 176 | segment to be off, without it being dimmed. 177 | 178 | If string is given, reset the LCD display state to it. If it 179 | is not provided, check for the self.state class variable. 180 | 181 | Looping is done asynchronously in a background. Loop will stop 182 | as soon as the self.state class variable is set to None. 183 | 184 | Note that the change of the state will be noticed only at the end 185 | of the sliding cycle: we show the full string first before switching 186 | to a new one . 187 | 188 | ''' 189 | 190 | string_ticks = int(delay / led_delay / self.window_size) 191 | 192 | if string: 193 | self.state = string 194 | 195 | while self.state: 196 | string = self.state 197 | size = len(string) 198 | for cursor in range(size): 199 | print("!!%s" % string) 200 | for counter in range(string_ticks): 201 | for index in range(self.window_size): 202 | symbol = string[(cursor + index) % size] 203 | self.set_values(_render_gpio_state(index, symbol)) 204 | 205 | await asyncio.sleep(led_delay) 206 | 207 | self.set_values(self.defaults) 208 | -------------------------------------------------------------------------------- /gpiodev/src/Makefile: -------------------------------------------------------------------------------- 1 | VERSION=0.0.1 2 | 3 | %.o: %.c %.h 4 | gcc -c -fPIC -o $@ $< 5 | 6 | libgpioctl: gpioctl.o 7 | gcc -shared -fPIC -Wl,-soname=$@.so -o $@.so.$(VERSION) $^ -lc 8 | 9 | build: libgpioctl 10 | 11 | clean: 12 | rm -f libgpioctl.so.$(VERSION) *.o 13 | -------------------------------------------------------------------------------- /gpiodev/src/gpioctl.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | #include "gpioctl.h" 8 | 9 | 10 | int get_chipinfo(int fd, struct gpiochip_info* info){ 11 | int status; 12 | status = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, info); 13 | return status; 14 | }; 15 | 16 | int get_lineinfo(int fd, struct gpioline_info *info) { 17 | int status; 18 | 19 | status = ioctl(fd, GPIO_GET_LINEINFO_IOCTL, info); 20 | return status; 21 | }; 22 | 23 | int get_linehandle(int fd, struct gpiohandle_request *req) { 24 | int status; 25 | 26 | status = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, req); 27 | return status; 28 | }; 29 | 30 | int get_lineevent(int fd, struct gpioevent_request *req) { 31 | int status; 32 | 33 | status = ioctl(fd, GPIO_GET_LINEEVENT_IOCTL, req); 34 | return status; 35 | }; 36 | 37 | int get_line_values(int fd, struct gpiohandle_data *data) { 38 | int status; 39 | 40 | status = ioctl(fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, data); 41 | 42 | return status; 43 | }; 44 | 45 | int set_line_values(int fd, struct gpiohandle_data *data) { 46 | int status; 47 | 48 | status = ioctl(fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, data); 49 | return status; 50 | }; 51 | -------------------------------------------------------------------------------- /gpiodev/src/gpioctl.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int get_chipinfo(int fd, struct gpiochip_info* info); 4 | 5 | int get_lineinfo(int fd, struct gpioline_info *info); 6 | 7 | int get_linehandle(int fd, struct gpiohandle_request *req); 8 | 9 | int get_lineevent(int fd, struct gpioevent_request *req); 10 | 11 | int get_line_values(int fd, struct gpiohandle_data *data); 12 | 13 | int set_line_values(int fd, struct gpiohandle_data *data); 14 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | try: 5 | from setuptools import setup, find_packages 6 | except ImportError: 7 | from distutils.core import setup, find_packages 8 | 9 | from distutils.extension import Extension 10 | 11 | setup( 12 | name='gpiodev', 13 | version='0.0.1', 14 | description='Library to operate GPIO pins via character device', 15 | long_description=''.join(open('README.md').readlines()), 16 | long_description_content_type="text/markdown", 17 | keywords='gpio, raspberry-pi', 18 | author='Aleksandra Fedorova', 19 | author_email='alpha@bookwar.info', 20 | url="https://github.com/bookwar/python-gpiodev", 21 | license='Apache 2.0', 22 | packages=find_packages(), 23 | package_data={ 24 | 'gpiodev': ['libgpioctl.so'], 25 | }, 26 | ext_modules=[ 27 | Extension('gpiodev.libgpioctl', ['gpiodev/src/gpioctl.c']), 28 | ], 29 | headers=['gpiodev/src/gpioctl.h'], 30 | classifiers=[ 31 | 'Development Status :: 3 - Alpha', 32 | 'Intended Audience :: Developers', 33 | 'License :: OSI Approved :: Apache Software License', 34 | 'Operating System :: POSIX :: Linux', 35 | 'Programming Language :: Python', 36 | ] 37 | ) 38 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py36,flake8 3 | 4 | [testenv:flake8] 5 | basepython = python3 6 | skip_install = True 7 | deps = flake8 8 | commands = flake8 . 9 | 10 | [flake8] 11 | exclude = .git,__pycache__,docs,build,dist,.tox,venv3 12 | --------------------------------------------------------------------------------