├── .github ├── CODEOWNERS ├── bors.toml └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── blinky.rs ├── interrupt.rs ├── poll.rs └── tokio.rs ├── src ├── error.rs └── lib.rs └── triagebot.toml /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @rust-embedded/embedded-linux 2 | -------------------------------------------------------------------------------- /.github/bors.toml: -------------------------------------------------------------------------------- 1 | block_labels = ["needs-decision"] 2 | delete_merged_branches = true 3 | required_approvals = 1 4 | status = [ 5 | "CI (stable, aarch64-unknown-linux-gnu)", 6 | "CI (stable, arm-unknown-linux-gnueabi)", 7 | "CI (stable, armv7-unknown-linux-gnueabihf)", 8 | "CI (stable, i686-unknown-linux-gnu)", 9 | "CI (stable, i686-unknown-linux-musl)", 10 | "CI (stable, mips-unknown-linux-gnu)", 11 | "CI (stable, mips64-unknown-linux-gnuabi64)", 12 | "CI (stable, mips64el-unknown-linux-gnuabi64)", 13 | "CI (stable, mipsel-unknown-linux-gnu)", 14 | "CI (stable, powerpc-unknown-linux-gnu)", 15 | "CI (stable, powerpc64le-unknown-linux-gnu)", 16 | "CI (stable, s390x-unknown-linux-gnu)", 17 | "CI (stable, x86_64-unknown-linux-gnu)", 18 | "CI (stable, x86_64-unknown-linux-musl)", 19 | "CI (stable, x86_64-apple-darwin)", 20 | 21 | "CI (stable, --features=async-tokio, x86_64-unknown-linux-gnu)", 22 | "CI (stable, --features=mio-evented, x86_64-unknown-linux-gnu)", 23 | 24 | "CI (1.46.0, --features=async-tokio, x86_64-unknown-linux-gnu)", 25 | "CI (1.46.0, --features=mio-evented, x86_64-unknown-linux-gnu)", 26 | "CI (1.46.0, x86_64-unknown-linux-gnu)", 27 | "CI (1.46.0, x86_64-apple-darwin)", 28 | 29 | "checks" 30 | ] 31 | timeout_sec = 3600 32 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: # Run CI for all branches except GitHub merge queue tmp branches 3 | branches-ignore: 4 | - "gh-readonly-queue/**" 5 | pull_request: # Run CI for PRs on any branch 6 | merge_group: # Run CI for the GitHub merge queue 7 | 8 | name: Build 9 | 10 | env: 11 | RUSTFLAGS: '--deny warnings' 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | rust: [stable] 19 | FEATURES: ["", "--features=async-tokio", "--features=mio-evented"] 20 | TARGET: 21 | - aarch64-unknown-linux-gnu 22 | - aarch64-unknown-linux-musl 23 | - arm-unknown-linux-gnueabi 24 | - arm-unknown-linux-gnueabihf 25 | - armv7-unknown-linux-gnueabihf 26 | - i686-unknown-linux-gnu 27 | - i686-unknown-linux-musl 28 | - powerpc-unknown-linux-gnu 29 | - powerpc64-unknown-linux-gnu 30 | - powerpc64le-unknown-linux-gnu 31 | - riscv64gc-unknown-linux-gnu 32 | - s390x-unknown-linux-gnu 33 | - x86_64-unknown-linux-gnu 34 | - x86_64-unknown-linux-musl 35 | 36 | include: 37 | # MSRV 38 | - rust: 1.70.0 39 | TARGET: x86_64-unknown-linux-gnu 40 | 41 | # Test nightly but don't fail 42 | - rust: nightly 43 | TARGET: x86_64-unknown-linux-gnu 44 | experimental: true 45 | 46 | steps: 47 | - uses: actions/checkout@v2 48 | - uses: actions-rs/toolchain@v1 49 | with: 50 | profile: minimal 51 | toolchain: ${{ matrix.rust }} 52 | target: ${{ matrix.TARGET }} 53 | override: true 54 | 55 | - name: Build 56 | uses: actions-rs/cargo@v1 57 | with: 58 | command: build 59 | args: --target=${{ matrix.TARGET }} ${{ matrix.FEATURES }} 60 | 61 | - name: Build all features 62 | uses: actions-rs/cargo@v1 63 | with: 64 | command: build 65 | args: --target=${{ matrix.TARGET }} --all-features 66 | 67 | - name: Test 68 | uses: actions-rs/cargo@v1 69 | with: 70 | use-cross: true 71 | command: test 72 | args: --target=${{ matrix.TARGET }} ${{ matrix.FEATURES }} 73 | 74 | - name: Test all features 75 | uses: actions-rs/cargo@v1 76 | with: 77 | use-cross: true 78 | command: test 79 | args: --target=${{ matrix.TARGET }} --all-features 80 | 81 | checks: 82 | runs-on: ubuntu-latest 83 | 84 | steps: 85 | - uses: actions/checkout@v2 86 | - uses: actions-rs/toolchain@v1 87 | with: 88 | profile: minimal 89 | toolchain: stable 90 | components: rustfmt 91 | 92 | - name: Doc 93 | uses: actions-rs/cargo@v1 94 | with: 95 | command: doc 96 | 97 | - name: Formatting 98 | uses: actions-rs/cargo@v1 99 | with: 100 | command: fmt 101 | args: --all -- --check 102 | 103 | clippy: 104 | runs-on: ubuntu-latest 105 | env: 106 | RUSTFLAGS: '--allow warnings' 107 | steps: 108 | - uses: actions/checkout@v2 109 | - uses: actions-rs/toolchain@v1 110 | with: 111 | profile: minimal 112 | toolchain: 1.70.0 113 | components: clippy 114 | 115 | - uses: actions-rs/clippy-check@v1 116 | with: 117 | token: ${{ secrets.GITHUB_TOKEN }} 118 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | *.bk 7 | 8 | # Executables 9 | *.exe 10 | 11 | # Generated by Cargo 12 | Cargo.lock 13 | /target/ 14 | 15 | # Intellij IDEA 16 | .idea 17 | 18 | # macOS DS_Store files 19 | .DS_Store 20 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## [master] - Unreleased 4 | 5 | ### Changed 6 | 7 | - Updated `mio` to version `1`. 8 | - Updated `nix` to version `0.26`. 9 | - Minimum supported Rust version updated to 1.70.0 10 | 11 | ## [0.6.2] - 2024-05-13 12 | 13 | - Minimum supported Rust version updated to 1.65.0 14 | - The crate's `Error` type can now be converted to a `std::io::Error` using `From` / `Into`. 15 | 16 | ## [0.6.1] - 2021-11-22 17 | 18 | ### Changed 19 | 20 | - Updated `nix` to version `0.23`. 21 | - Updated `mio` to version `0.8`. 22 | 23 | ## [0.6.0] - 2021-09-24 24 | 25 | ### Changed 26 | 27 | - [breaking-change] Renamed `use_tokio` feature `async-tokio`. 28 | - Migrated to `tokio` crate version 1. 29 | - Updated `nix` to version 0.22. 30 | - Updated `mio` to version 0.7. 31 | - Updated `futures` to version 0.3. 32 | - Minimmum supported Rust version updated to 1.46.0. 33 | 34 | ## [0.5.3] - 2018-04-19 35 | 36 | ### Fixed 37 | 38 | - Relaxed path restrictions on `Pin::from_path` to allow for directories 39 | outside of `/sys/class/gpio`, required for some SOCs that symlink outside of 40 | that directory. 41 | 42 | ## [0.5.2] - 2018-03-02 43 | 44 | ### Changed 45 | 46 | - Add support for `active_low` configuration. 47 | - Remove dependency on regexp 48 | - Update nix to 0.10.0 49 | 50 | ## [0.5.1] - 2016-06-17 51 | 52 | ### Changed 53 | 54 | - The crate now compiles (to more-or-less nothing) on OSX which can be useful in some 55 | contexts. 56 | - Multiple warnings from clippy were addressed 57 | - Support for some older versions of rust was dropped and things like `?` are now used in the codebase. 58 | - Additional traits like `Copy` added where appropriate in some places. 59 | 60 | ## [0.5.0] - 2016-12-18 61 | 62 | ### Changed 63 | 64 | - Support for asynchronous polling for changes using tokio/futures 65 | is now supported. 66 | - Minimum supported version Rust for 0.5.0+ is now 1.10.0 67 | 68 | ## [0.4.4] - 2016-08-26 69 | 70 | ### Fixed 71 | 72 | - A couple issues were fixed that limited the circumstances where 73 | `Pin::from_path` would work in various environments. 74 | 75 | ## [0.4.3] - 2016-06-22 76 | 77 | ### Changed 78 | 79 | - Added `from_path` constructor to allow for use of the library with symlinked 80 | GPIOs to interact with things like the IOs exported by 81 | [gpio-utils](https://github.com/rust-embedded/gpio-utils). 82 | - Bumped Nix dependency to version 0.6.0 (removes some compile warnings) 83 | 84 | ## [0.4.2] - 2016-04-17 85 | 86 | ### Changed 87 | 88 | - `Pin` now has an `is_exported()` function 89 | 90 | ### Fixed 91 | 92 | - Moved to nix 0.5 which fixes problems on some architectures 93 | 94 | ## [0.4.1] - 2016-04-8 95 | 96 | ### Changed 97 | 98 | - A few additional traits are derived for types exposed by the library. 99 | - Links/Docs updated with move to rust-embedded Github org 100 | 101 | ## [0.4.0] - 2015-12-04 102 | 103 | ### Changed 104 | 105 | - We now expose our own `Error` type than using io::Result. 106 | This allows for better errors to be provided from the library. 107 | This breaks backwards compatability. 108 | 109 | ### Fixed 110 | 111 | - Only open file for reading when reading value from file 112 | 113 | ## [0.3.3] - 2015-09-25 114 | 115 | ### Added 116 | 117 | - `get_pin` method added for accessing pin number 118 | - `get_direction` method added for querying Pin direction 119 | 120 | ### Changed 121 | 122 | - Updates/Fixes to documentation 123 | - Non-functional code refactoring and cleanup 124 | 125 | ## [0.3.2] - 2015-07-13 126 | 127 | ### Fixed 128 | 129 | - We now work with the latest version of nix 130 | 131 | ## [0.3.1] - 2015-05-21 132 | 133 | ### Fixed 134 | 135 | - Converting from a nix error to an io::Error has been simplified and 136 | updated to work with future versions of nix 137 | 138 | ### Changed 139 | 140 | - Documentation now refers to package as `sysfs-gpio` with a dash 141 | instead of an underscore as per common convention. The package 142 | name on crates.io cannot be changed right now, however. 143 | - Documentation updates. 144 | 145 | ## [0.3.0] - 2015-04-20 146 | 147 | ### Fixed 148 | 149 | - Updates to work with latest rust nightlies 150 | 151 | ### Added 152 | 153 | - Support for interrupts on pins was added via epoll. This is an 154 | efficient and performant way to wait for a pin to change state 155 | before performing some operation. 156 | 157 | ## [0.2.1] - 2015-04-06 158 | 159 | ### Fixed 160 | 161 | - Library updated to work with latest nightlies (~1.0.0 beta). Due to 162 | std situation, still need to depend on a few deprecated features for 163 | the examples (synchronous timers). 164 | 165 | ## [0.2.0] - 2015-03-19 166 | 167 | ### Changed 168 | - The `core` module has been removed in favor of putting all 169 | structs, functions, and macros directly in the `sysfs_gpio` 170 | crate. 171 | 172 | ### Added 173 | - Project now publishes documentation and has travisci support 174 | - Added `with_exported` method taking a closure for more convenient 175 | export/unexport in all cases. 176 | 177 | ### Fixed 178 | - Fixed a critical bug that resulted in `unexport` never actually 179 | unexporting GPIOs. 180 | 181 | ## [0.1.1] - 2015-03-17 182 | 183 | ### Added 184 | - Added `try_unexport!` macro 185 | - Include additional documentation for cross-compilation 186 | - Added `poll` example showing input functionalty 187 | 188 | ### Fixed 189 | - Fixed bug preventing the correct operation of `get_value`. In 0.1.1, 190 | this function would always fail. 191 | 192 | ## [0.1.0] - 2015-03-15 193 | 194 | ### Added 195 | - Initial version of the library with basic functionality 196 | - Support for `export`/`unexport`/`get_value`/`set_value`/`set_direction` 197 | 198 | [master]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.6.2...master 199 | [0.6.2]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.6.1...0.6.2 200 | [0.6.1]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.6.0...0.6.1 201 | [0.6.0]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.5.3...0.6.0 202 | [0.5.3]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.5.2...0.5.3 203 | [0.5.2]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.5.1...0.5.2 204 | [0.5.1]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.5.0...0.5.1 205 | [0.5.0]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.4.4...0.5.0 206 | [0.4.4]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.4.3...0.4.4 207 | [0.4.3]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.4.2...0.4.3 208 | [0.4.2]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.4.1...0.4.2 209 | [0.4.1]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.4.0...0.4.1 210 | [0.4.0]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.3.3...0.4.0 211 | [0.3.3]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.3.2...0.3.3 212 | [0.3.2]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.3.1...0.3.2 213 | [0.3.1]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.3.0...0.3.1 214 | [0.3.0]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.2.1...0.3.0 215 | [0.2.1]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.2.0...0.2.1 216 | [0.2.0]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.1.1...0.2.0 217 | [0.1.1]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/0.1.0...0.1.1 218 | [0.1.0]: https://github.com/rust-embedded/rust-sysfs-gpio/compare/33b28ae3115d91ae6612245e5b8d8c636dcdb69c...0.1.0 219 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # The Rust Code of Conduct 2 | 3 | ## Conduct 4 | 5 | **Contact**: [Embedded Linux Team][team] 6 | 7 | * We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. 8 | * On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. 9 | * Please be kind and courteous. There's no need to be mean or rude. 10 | * Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. 11 | * Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. 12 | * We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. 13 | * Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [Embedded Linux Team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. 14 | * Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. 15 | 16 | ## Moderation 17 | 18 | These are the policies for upholding our community's standards of conduct. 19 | 20 | 1. Remarks that violate the Rust standards of conduct, including hateful, 21 | hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is 22 | allowed, but never targeting another user, and never in a hateful manner.) 23 | 2. Remarks that moderators find inappropriate, whether listed in the code of 24 | conduct or not, are also not allowed. 25 | 3. Moderators will first respond to such remarks with a warning. 26 | 4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of 27 | the communication channel to cool off. 28 | 5. If the user comes back and continues to make trouble, they will be banned, 29 | i.e., indefinitely excluded. 30 | 6. Moderators may choose at their discretion to un-ban the user if it was a 31 | first offense and they offer the offended party a genuine apology. 32 | 7. If a moderator bans someone and you think it was unjustified, please take it 33 | up with that moderator, or with a different moderator, **in private**. 34 | Complaints about bans in-channel are not allowed. 35 | 8. Moderators are held to a higher standard than other community members. If a 36 | moderator creates an inappropriate situation, they should expect less leeway 37 | than others. 38 | 39 | In the Rust community we strive to go the extra step to look out for each other. 40 | Don't just aim to be technically unimpeachable, try to be your best self. In 41 | particular, avoid flirting with offensive or sensitive issues, particularly if 42 | they're off-topic; this all too often leads to unnecessary fights, hurt 43 | feelings, and damaged trust; worse, it can drive people away from the community 44 | entirely. 45 | 46 | And if someone takes issue with something you said or did, resist the urge to be 47 | defensive. Just stop doing what it was they complained about and apologize. Even 48 | if you feel you were misinterpreted or unfairly accused, chances are good there 49 | was something you could've communicated better — remember that it's your 50 | responsibility to make your fellow Rustaceans comfortable. Everyone wants to get 51 | along and we are all here first and foremost because we want to talk about cool 52 | technology. You will find that people will be eager to assume good intent and 53 | forgive as long as you earn their trust. 54 | 55 | The enforcement policies listed above apply to all official embedded WG venues; 56 | including official IRC channels (#rust-embedded); GitHub repositories under 57 | rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). 58 | 59 | *Adapted from the [Node.js Policy on 60 | Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the 61 | [Contributor Covenant 62 | v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* 63 | 64 | [team]: https://github.com/rust-embedded/wg#the-embedded-linux-team 65 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sysfs_gpio" 3 | version = "0.6.2" 4 | authors = [ 5 | "Paul Osborne ", 6 | "The Embedded Linux Team ", 7 | ] 8 | license = "MIT/Apache-2.0" 9 | repository = "https://github.com/rust-embedded/rust-sysfs-gpio" 10 | homepage = "https://github.com/rust-embedded/rust-sysfs-gpio" 11 | documentation = "https://docs.rs/sysfs_gpio/" 12 | description = "Provides access to GPIOs using the Linux sysfs interface." 13 | readme = "README.md" 14 | edition = "2021" 15 | 16 | [features] 17 | mio-evented = ["mio"] 18 | async-tokio = ["futures", "tokio", "mio-evented"] 19 | 20 | [dependencies] 21 | futures = { version = "0.3", optional = true } 22 | nix = "0.26" 23 | mio = { version = "1", optional = true, features = ["os-ext"]} 24 | tokio = { version = "1", optional = true, features = ["net"] } 25 | 26 | [dev-dependencies] 27 | tokio = { version = "1", features = ["rt-multi-thread", "macros"] } 28 | 29 | [[example]] 30 | name = "tokio" 31 | required-features = ["async-tokio"] 32 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Paul Osborne 4 | Copyright (c) 2021-2025 The Rust Embedded Linux Team 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | sysfs_gpio 2 | ========== 3 | 4 | [![Build Status](https://github.com/rust-embedded/rust-sysfs-gpio/workflows/CI/badge.svg)](https://github.com/rust-embedded/rust-sysfs-gpio/actions) 5 | [![Version](https://img.shields.io/crates/v/sysfs-gpio.svg)](https://crates.io/crates/sysfs-gpio) 6 | ![Minimum Supported Rust Version](https://img.shields.io/badge/rustc-1.70+-blue.svg) 7 | [![License](https://img.shields.io/crates/l/sysfs-gpio.svg)](https://github.com/rust-embedded/rust-sysfs-gpio/blob/master/README.md#license) 8 | 9 | - [API Documentation](https://docs.rs/sysfs_gpio) 10 | 11 | The `sysfs_gpio` crate provides access to the Linux sysfs GPIO interface 12 | (https://www.kernel.org/doc/Documentation/gpio/sysfs.txt). It seeks to provide 13 | an API that is safe, convenient, and efficient and supports exporting, 14 | unexporting, reading, writing and waiting for interrupts on pins. 15 | 16 | Many devices such as the Raspberry Pi or Beaglebone Black provide 17 | userspace access to a number of GPIO peripherals. The standard kernel 18 | API for providing access to these GPIOs is via sysfs. 19 | 20 | You might want to also check out the 21 | [gpio-utils Project](https://github.com/rust-embedded/gpio-utils) for a 22 | convenient way to associate names with pins and export them as part of system 23 | boot. That project uses this library. 24 | 25 | ## Install/Use 26 | 27 | To use `sysfs_gpio`, first add this to your `Cargo.toml`: 28 | 29 | ```toml 30 | [dependencies] 31 | sysfs_gpio = "0.6" 32 | ``` 33 | 34 | Then, add this to your crate root: 35 | 36 | ```rust 37 | use sysfs_gpio; 38 | ``` 39 | 40 | ## Example/API 41 | 42 | Blinking an LED: 43 | 44 | ```rust 45 | use sysfs_gpio::{Direction, Pin}; 46 | use std::thread::sleep; 47 | use std::time::Duration; 48 | 49 | fn main() { 50 | let my_led = Pin::new(127); // number depends on chip, etc. 51 | my_led.with_exported(|| { 52 | my_led.set_direction(Direction::Out).unwrap(); 53 | loop { 54 | my_led.set_value(0).unwrap(); 55 | sleep(Duration::from_millis(200)); 56 | my_led.set_value(1).unwrap(); 57 | sleep(Duration::from_millis(200)); 58 | } 59 | }).unwrap(); 60 | } 61 | ``` 62 | 63 | More Examples: 64 | 65 | - [Blink an LED](examples/blinky.rs) 66 | - [Poll a GPIO Input](examples/poll.rs) 67 | - [Receive interrupt on GPIO Change](examples/interrupt.rs) 68 | - [Poll several pins asynchronously with Tokio](examples/tokio.rs) 69 | - [gpio-utils Project (uses most features)](https://github.com/rust-embedded/gpio-utils) 70 | 71 | ## Features 72 | 73 | The following features are planned for the library: 74 | 75 | - [x] Support for exporting a GPIO 76 | - [x] Support for unexporting a GPIO 77 | - [x] Support for setting the direction of a GPIO (in/out) 78 | - [x] Support for reading the value of a GPIO input 79 | - [x] Support for writing the value of a GPIO output 80 | - [ ] Support for configuring whether a pin is active low/high 81 | - [x] Support for configuring interrupts on GPIO 82 | - [x] Support for polling on GPIO with configured interrupt 83 | - [x] Support for asynchronous polling using `mio` or `tokio` (requires 84 | enabling the `mio-evented` or `async-tokio` crate features, respectively) 85 | 86 | ## Minimum Supported Rust Version (MSRV) 87 | 88 | This crate is guaranteed to compile on stable Rust 1.70.0 and up. It *might* 89 | compile with older versions but that may change in any new patch release. 90 | 91 | ## Cross Compiling 92 | 93 | Most likely, the machine you are running on is not your development 94 | machine (although it could be). In those cases, you will need to 95 | cross-compile. The [rust-cross guide](https://github.com/japaric/rust-cross) 96 | provides excellent, detailed instructions for cross-compiling. 97 | 98 | ## Running the Example 99 | 100 | Cross-compiling can be done by specifying an appropriate target. You 101 | can then move that to your device by whatever means and run it. 102 | 103 | ``` 104 | $ cargo build --target=arm-unknown-linux-gnueabihf --example blinky 105 | $ scp target/arm-unknown-linux-gnueabihf/debug/examples/blinky ... 106 | ``` 107 | 108 | ## License 109 | 110 | Licensed under either of 111 | 112 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or 113 | http://www.apache.org/licenses/LICENSE-2.0) 114 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 115 | 116 | at your option. 117 | 118 | ### Contribution 119 | 120 | Unless you explicitly state otherwise, any contribution intentionally submitted 121 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 122 | dual licensed as above, without any additional terms or conditions. 123 | 124 | ## Code of Conduct 125 | 126 | Contribution to this crate is organized under the terms of the [Rust Code of 127 | Conduct][CoC], the maintainer of this crate, the [Embedded Linux Team][team], promises 128 | to intervene to uphold that code of conduct. 129 | 130 | [CoC]: CODE_OF_CONDUCT.md 131 | [team]: https://github.com/rust-embedded/wg#the-embedded-linux-team 132 | -------------------------------------------------------------------------------- /examples/blinky.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015, Paul Osborne 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use std::env; 10 | use std::thread::sleep; 11 | use std::time::Duration; 12 | use sysfs_gpio::{Direction, Pin}; 13 | 14 | struct Arguments { 15 | pin: u64, 16 | duration_ms: u64, 17 | period_ms: u64, 18 | } 19 | 20 | // Export a GPIO for use. This will not fail if already exported 21 | fn blink_my_led(led: u64, duration_ms: u64, period_ms: u64) -> sysfs_gpio::Result<()> { 22 | let my_led = Pin::new(led); 23 | my_led.with_exported(|| { 24 | my_led.set_direction(Direction::Low)?; 25 | let iterations = duration_ms / period_ms / 2; 26 | for _ in 0..iterations { 27 | my_led.set_value(0)?; 28 | sleep(Duration::from_millis(period_ms)); 29 | my_led.set_value(1)?; 30 | sleep(Duration::from_millis(period_ms)); 31 | } 32 | my_led.set_value(0)?; 33 | Ok(()) 34 | }) 35 | } 36 | 37 | fn print_usage() { 38 | println!("Usage: ./blinky "); 39 | } 40 | 41 | fn get_args() -> Option { 42 | let args: Vec = env::args().collect(); 43 | if args.len() != 4 { 44 | return None; 45 | } 46 | let pin = match args[1].parse::() { 47 | Ok(pin) => pin, 48 | Err(_) => return None, 49 | }; 50 | let duration_ms = match args[2].parse::() { 51 | Ok(ms) => ms, 52 | Err(_) => return None, 53 | }; 54 | let period_ms = match args[3].parse::() { 55 | Ok(ms) => ms, 56 | Err(_) => return None, 57 | }; 58 | Some(Arguments { 59 | pin, 60 | duration_ms, 61 | period_ms, 62 | }) 63 | } 64 | 65 | fn main() { 66 | match get_args() { 67 | None => print_usage(), 68 | Some(args) => match blink_my_led(args.pin, args.duration_ms, args.period_ms) { 69 | Ok(()) => println!("Success!"), 70 | Err(err) => println!("We have a blinking problem: {}", err), 71 | }, 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /examples/interrupt.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015, Paul Osborne 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use std::env; 10 | use std::io::prelude::*; 11 | use std::io::stdout; 12 | use sysfs_gpio::{Direction, Edge, Pin}; 13 | 14 | fn interrupt(pin: u64) -> sysfs_gpio::Result<()> { 15 | let input = Pin::new(pin); 16 | input.with_exported(|| { 17 | input.set_direction(Direction::In)?; 18 | input.set_edge(Edge::BothEdges)?; 19 | let mut poller = input.get_poller()?; 20 | loop { 21 | match poller.poll(1000)? { 22 | Some(value) => println!("{}", value), 23 | None => { 24 | let mut stdout = stdout(); 25 | stdout.write_all(b".")?; 26 | stdout.flush()?; 27 | } 28 | } 29 | } 30 | }) 31 | } 32 | 33 | fn main() { 34 | let args: Vec = env::args().collect(); 35 | if args.len() != 2 { 36 | println!("Usage: ./interrupt "); 37 | } else { 38 | match args[1].parse::() { 39 | Ok(pin) => match interrupt(pin) { 40 | Ok(()) => println!("Interrupting Complete!"), 41 | Err(err) => println!("Error: {}", err), 42 | }, 43 | Err(_) => println!("Usage: ./interrupt "), 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /examples/poll.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015, Paul Osborne 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use std::env; 10 | use std::thread::sleep; 11 | use std::time::Duration; 12 | use sysfs_gpio::{Direction, Pin}; 13 | 14 | fn poll(pin_num: u64) -> sysfs_gpio::Result<()> { 15 | // NOTE: this currently runs forever and as such if 16 | // the app is stopped (Ctrl-C), no cleanup will happen 17 | // and the GPIO will be left exported. Not much 18 | // can be done about this as Rust signal handling isn't 19 | // really present at the moment. Revisit later. 20 | let input = Pin::new(pin_num); 21 | input.with_exported(|| { 22 | input.set_direction(Direction::In)?; 23 | let mut prev_val: u8 = 255; 24 | loop { 25 | let val = input.get_value()?; 26 | if val != prev_val { 27 | println!("Pin State: {}", if val == 0 { "Low" } else { "High" }); 28 | prev_val = val; 29 | } 30 | sleep(Duration::from_millis(10)); 31 | } 32 | }) 33 | } 34 | 35 | fn main() { 36 | let args: Vec = env::args().collect(); 37 | if args.len() != 2 { 38 | println!("Usage: ./poll "); 39 | } else { 40 | match args[1].parse::() { 41 | Ok(pin) => match poll(pin) { 42 | Ok(()) => println!("Polling Complete!"), 43 | Err(err) => println!("Error: {}", err), 44 | }, 45 | Err(_) => println!("Usage: ./poll "), 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /examples/tokio.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020. The sysfs-gpio Authors. 2 | 3 | use futures::future::join_all; 4 | use futures::StreamExt; 5 | use std::env; 6 | use sysfs_gpio::{Direction, Edge, Pin}; 7 | 8 | async fn monitor_pin(pin: Pin) -> Result<(), sysfs_gpio::Error> { 9 | pin.export()?; 10 | pin.set_direction(Direction::In)?; 11 | pin.set_edge(Edge::BothEdges)?; 12 | let mut gpio_events = pin.get_value_stream()?; 13 | while let Some(evt) = gpio_events.next().await { 14 | let val = evt.unwrap(); 15 | println!("Pin {} changed value to {}", pin.get_pin_num(), val); 16 | } 17 | Ok(()) 18 | } 19 | 20 | async fn stream(pin_nums: Vec) { 21 | // NOTE: this currently runs forever and as such if 22 | // the app is stopped (Ctrl-C), no cleanup will happen 23 | // and the GPIO will be left exported. Not much 24 | // can be done about this as Rust signal handling isn't 25 | // really present at the moment. Revisit later. 26 | join_all(pin_nums.into_iter().map(|p| { 27 | let pin = Pin::new(p); 28 | tokio::task::spawn(monitor_pin(pin)) 29 | })) 30 | .await; 31 | } 32 | 33 | #[tokio::main] 34 | async fn main() { 35 | let pins: Vec = env::args() 36 | .skip(1) 37 | .map(|a| a.parse().expect("Pins must be specified as integers")) 38 | .collect(); 39 | if pins.is_empty() { 40 | println!("Usage: ./tokio [pin ...]"); 41 | } else { 42 | stream(pins).await; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::convert; 2 | use std::fmt; 3 | use std::io; 4 | 5 | #[derive(Debug)] 6 | pub enum Error { 7 | /// Simple IO error 8 | Io(io::Error), 9 | /// Read unusual data from sysfs file. 10 | Unexpected(String), 11 | /// Invalid Path 12 | InvalidPath(String), 13 | /// Operation not supported on target os 14 | Unsupported(String), 15 | } 16 | 17 | impl ::std::error::Error for Error { 18 | fn cause(&self) -> Option<&dyn std::error::Error> { 19 | match *self { 20 | Error::Io(ref e) => Some(e), 21 | _ => None, 22 | } 23 | } 24 | } 25 | 26 | impl fmt::Display for Error { 27 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 28 | match *self { 29 | Error::Io(ref e) => e.fmt(f), 30 | Error::Unexpected(ref s) => write!(f, "Unexpected: {}", s), 31 | Error::InvalidPath(ref s) => write!(f, "Invalid Path: {}", s), 32 | Error::Unsupported(ref s) => write!(f, "Operation not supported on target os: {}", s), 33 | } 34 | } 35 | } 36 | 37 | impl convert::From for Error { 38 | fn from(e: io::Error) -> Error { 39 | Error::Io(e) 40 | } 41 | } 42 | #[cfg(not(target_os = "wasi"))] 43 | impl convert::From for Error { 44 | fn from(e: nix::Error) -> Error { 45 | Error::Io(e.into()) 46 | } 47 | } 48 | 49 | impl convert::From for io::Error { 50 | fn from(e: Error) -> io::Error { 51 | match e { 52 | Error::Io(err) => err, 53 | Error::Unexpected(err) => io::Error::new(io::ErrorKind::Unsupported, err), 54 | Error::InvalidPath(err) => io::Error::new(io::ErrorKind::InvalidInput, err), 55 | Error::Unsupported(err) => io::Error::new(io::ErrorKind::InvalidData, err), 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015, Paul Osborne 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | // 9 | // Portions of this implementation are based on work by Nat Pryce: 10 | // https://github.com/npryce/rusty-pi/blob/master/src/pi/gpio.rs 11 | 12 | //! GPIO access under Linux using the GPIO sysfs interface 13 | //! 14 | //! The methods exposed by this library are centered around 15 | //! the `Pin` struct and map pretty directly the API exposed 16 | //! by the kernel in syfs . 17 | //! 18 | //! # Examples 19 | //! 20 | //! Typical usage for systems where one wants to ensure that 21 | //! the pins in use are unexported upon completion looks like 22 | //! the following: 23 | //! 24 | //! ```no_run 25 | //! use sysfs_gpio::{Direction, Pin}; 26 | //! use std::thread::sleep; 27 | //! use std::time::Duration; 28 | //! 29 | //! let my_led = Pin::new(127); // number depends on chip, etc. 30 | //! my_led.with_exported(|| { 31 | //! my_led.set_direction(Direction::Out).unwrap(); 32 | //! loop { 33 | //! my_led.set_value(0).unwrap(); 34 | //! sleep(Duration::from_millis(200)); 35 | //! my_led.set_value(1).unwrap(); 36 | //! sleep(Duration::from_millis(200)); 37 | //! } 38 | //! }).unwrap(); 39 | //! ``` 40 | 41 | #![cfg_attr(feature = "async-tokio", allow(deprecated))] 42 | 43 | #[cfg(feature = "async-tokio")] 44 | extern crate futures; 45 | #[cfg(feature = "mio-evented")] 46 | extern crate mio; 47 | #[cfg(not(target_os = "wasi"))] 48 | extern crate nix; 49 | #[cfg(feature = "async-tokio")] 50 | extern crate tokio; 51 | 52 | use std::io; 53 | use std::io::prelude::*; 54 | #[cfg(any(target_os = "linux", target_os = "android", feature = "async-tokio"))] 55 | use std::io::SeekFrom; 56 | #[cfg(not(target_os = "wasi"))] 57 | use std::os::unix::prelude::*; 58 | use std::path::Path; 59 | use std::{fs, fs::File}; 60 | 61 | #[cfg(feature = "async-tokio")] 62 | use futures::{ready, Stream}; 63 | #[cfg(feature = "mio-evented")] 64 | use mio::event::Source; 65 | #[cfg(feature = "mio-evented")] 66 | use mio::unix::SourceFd; 67 | #[cfg(any(target_os = "linux", target_os = "android"))] 68 | use nix::sys::epoll::*; 69 | #[cfg(not(target_os = "wasi"))] 70 | use nix::unistd::close; 71 | #[cfg(feature = "async-tokio")] 72 | use std::task::Poll; 73 | #[cfg(feature = "async-tokio")] 74 | use tokio::io::unix::AsyncFd; 75 | 76 | pub use error::Error; 77 | 78 | mod error; 79 | 80 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 81 | pub struct Pin { 82 | pin_num: u64, 83 | } 84 | 85 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 86 | pub enum Direction { 87 | In, 88 | Out, 89 | High, 90 | Low, 91 | } 92 | 93 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 94 | pub enum Edge { 95 | NoInterrupt, 96 | RisingEdge, 97 | FallingEdge, 98 | BothEdges, 99 | } 100 | 101 | #[macro_export] 102 | macro_rules! try_unexport { 103 | ($gpio:ident, $e:expr) => { 104 | match $e { 105 | Ok(res) => res, 106 | Err(e) => { 107 | $gpio.unexport()?; 108 | return Err(e); 109 | } 110 | } 111 | }; 112 | } 113 | 114 | pub type Result = ::std::result::Result; 115 | 116 | /// Flush up to max bytes from the provided files input buffer 117 | /// 118 | /// Typically, one would just use seek() for this sort of thing, 119 | /// but for certain files (e.g. in sysfs), you need to actually 120 | /// read it. 121 | #[cfg(any(target_os = "linux", target_os = "android"))] 122 | fn flush_input_from_file(dev_file: &mut File, max: usize) -> io::Result { 123 | let mut s = String::with_capacity(max); 124 | dev_file.read_to_string(&mut s) 125 | } 126 | 127 | /// Get the pin value from the provided file 128 | #[cfg(any(target_os = "linux", target_os = "android", feature = "async-tokio"))] 129 | fn get_value_from_file(dev_file: &mut File) -> Result { 130 | let mut s = String::with_capacity(10); 131 | dev_file.seek(SeekFrom::Start(0))?; 132 | dev_file.read_to_string(&mut s)?; 133 | match s[..1].parse::() { 134 | Ok(n) => Ok(n), 135 | Err(_) => Err(Error::Unexpected(format!( 136 | "Unexpected value file contents: {:?}", 137 | s 138 | ))), 139 | } 140 | } 141 | 142 | impl Pin { 143 | /// Write all of the provided contents to the specified devFile 144 | fn write_to_device_file(&self, dev_file_name: &str, value: &str) -> io::Result<()> { 145 | let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name); 146 | let mut dev_file = File::create(&gpio_path)?; 147 | dev_file.write_all(value.as_bytes())?; 148 | Ok(()) 149 | } 150 | 151 | fn read_from_device_file(&self, dev_file_name: &str) -> io::Result { 152 | let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name); 153 | let mut dev_file = File::open(&gpio_path)?; 154 | let mut s = String::new(); 155 | dev_file.read_to_string(&mut s)?; 156 | Ok(s) 157 | } 158 | 159 | /// Create a new Pin with the provided `pin_num` 160 | /// 161 | /// This function does not export the provided pin_num. 162 | pub fn new(pin_num: u64) -> Pin { 163 | Pin { pin_num } 164 | } 165 | 166 | /// Create a new Pin with the provided path 167 | /// 168 | /// This form is useful when there are other scripts which may 169 | /// have already exported the GPIO and created a symlink with a 170 | /// nice name that you already have reference to. Otherwise, it 171 | /// is generally preferrable to use `new` directly. 172 | /// 173 | /// The provided path must be either the already exported 174 | /// directory for a GPIO or a symlink to one. If the directory 175 | /// does not look sufficiently like this (i.e. does not resolve to 176 | /// a path starting with /sys/class/gpioXXX), then this function 177 | /// will return an error. 178 | pub fn from_path>(path: T) -> Result { 179 | // Resolve all symbolic links in the provided path 180 | let pb = fs::canonicalize(path.as_ref())?; 181 | 182 | // determine if this is valid and figure out the pin_num 183 | if !fs::metadata(&pb)?.is_dir() { 184 | return Err(Error::Unexpected( 185 | "Provided path not a directory or symlink to \ 186 | a directory" 187 | .to_owned(), 188 | )); 189 | } 190 | let num = Pin::extract_pin_from_path(&pb)?; 191 | Ok(Pin::new(num)) 192 | } 193 | 194 | /// Extract pin number from paths like /sys/class/gpio/gpioXXX 195 | fn extract_pin_from_path>(path: P) -> Result { 196 | path.as_ref() 197 | .file_name() 198 | .and_then(|filename| filename.to_str()) 199 | .and_then(|filename_str| filename_str.trim_start_matches("gpio").parse::().ok()) 200 | .ok_or_else(|| Error::InvalidPath(format!("{:?}", path.as_ref()))) 201 | } 202 | 203 | /// Get the pin number 204 | pub fn get_pin_num(&self) -> u64 { 205 | self.pin_num 206 | } 207 | 208 | /// Run a closure with the GPIO exported 209 | /// 210 | /// Prior to the provided closure being executed, the GPIO 211 | /// will be exported. After the closure execution is complete, 212 | /// the GPIO will be unexported. 213 | /// 214 | /// # Example 215 | /// 216 | /// ```no_run 217 | /// use sysfs_gpio::{Pin, Direction}; 218 | /// 219 | /// let gpio = Pin::new(24); 220 | /// let res = gpio.with_exported(|| { 221 | /// println!("At this point, the Pin is exported"); 222 | /// gpio.set_direction(Direction::Low)?; 223 | /// gpio.set_value(1)?; 224 | /// // ... 225 | /// Ok(()) 226 | /// }); 227 | /// ``` 228 | #[inline] 229 | pub fn with_exported Result<()>>(&self, closure: F) -> Result<()> { 230 | self.export()?; 231 | match closure() { 232 | Ok(()) => { 233 | self.unexport()?; 234 | Ok(()) 235 | } 236 | Err(err) => { 237 | self.unexport()?; 238 | Err(err) 239 | } 240 | } 241 | } 242 | 243 | /// Determines whether the GPIO is exported 244 | /// 245 | /// This function will error out if the kernel does not support the GPIO 246 | /// sysfs interface (i.e. `/sys/class/gpio` does not exist). 247 | pub fn is_exported(&self) -> bool { 248 | fs::metadata(format!("/sys/class/gpio/gpio{}", self.pin_num)).is_ok() 249 | } 250 | 251 | /// Export the GPIO 252 | /// 253 | /// This is equivalent to `echo N > /sys/class/gpio/export` with 254 | /// the exception that the case where the GPIO is already exported 255 | /// is not an error. 256 | /// 257 | /// # Errors 258 | /// 259 | /// The main cases in which this function will fail and return an 260 | /// error are the following: 261 | /// 1. The system does not support the GPIO sysfs interface 262 | /// 2. The requested GPIO is out of range and cannot be exported 263 | /// 3. The requested GPIO is in use by the kernel and cannot 264 | /// be exported by use in userspace 265 | /// 266 | /// # Example 267 | /// ```no_run 268 | /// use sysfs_gpio::Pin; 269 | /// 270 | /// let gpio = Pin::new(24); 271 | /// match gpio.export() { 272 | /// Ok(()) => println!("Gpio {} exported!", gpio.get_pin()), 273 | /// Err(err) => println!("Gpio {} could not be exported: {}", gpio.get_pin(), err), 274 | /// } 275 | /// ``` 276 | pub fn export(&self) -> Result<()> { 277 | if fs::metadata(format!("/sys/class/gpio/gpio{}", self.pin_num)).is_err() { 278 | let mut export_file = File::create("/sys/class/gpio/export")?; 279 | export_file.write_all(format!("{}", self.pin_num).as_bytes())?; 280 | } 281 | Ok(()) 282 | } 283 | 284 | /// Unexport the GPIO 285 | /// 286 | /// This function will unexport the provided by from syfs if 287 | /// it is currently exported. If the pin is not currently 288 | /// exported, it will return without error. That is, whenever 289 | /// this function returns Ok, the GPIO is not exported. 290 | pub fn unexport(&self) -> Result<()> { 291 | if fs::metadata(format!("/sys/class/gpio/gpio{}", self.pin_num)).is_ok() { 292 | let mut unexport_file = File::create("/sys/class/gpio/unexport")?; 293 | unexport_file.write_all(format!("{}", self.pin_num).as_bytes())?; 294 | } 295 | Ok(()) 296 | } 297 | 298 | /// Get the pin number for the Pin 299 | pub fn get_pin(&self) -> u64 { 300 | self.pin_num 301 | } 302 | 303 | /// Get the direction of the Pin 304 | pub fn get_direction(&self) -> Result { 305 | match self.read_from_device_file("direction") { 306 | Ok(s) => match s.trim() { 307 | "in" => Ok(Direction::In), 308 | "out" => Ok(Direction::Out), 309 | "high" => Ok(Direction::High), 310 | "low" => Ok(Direction::Low), 311 | other => Err(Error::Unexpected(format!( 312 | "direction file contents {}", 313 | other 314 | ))), 315 | }, 316 | Err(e) => Err(::std::convert::From::from(e)), 317 | } 318 | } 319 | 320 | /// Set this GPIO as either an input or an output 321 | /// 322 | /// The basic values allowed here are `Direction::In` and 323 | /// `Direction::Out` which set the Pin as either an input 324 | /// or output respectively. In addition to those, two 325 | /// additional settings of `Direction::High` and 326 | /// `Direction::Low`. These both set the Pin as an output 327 | /// but do so with an initial value of high or low respectively. 328 | /// This allows for glitch-free operation. 329 | /// 330 | /// Note that this entry may not exist if the kernel does 331 | /// not support changing the direction of a pin in userspace. If 332 | /// this is the case, you will get an error. 333 | pub fn set_direction(&self, dir: Direction) -> Result<()> { 334 | self.write_to_device_file( 335 | "direction", 336 | match dir { 337 | Direction::In => "in", 338 | Direction::Out => "out", 339 | Direction::High => "high", 340 | Direction::Low => "low", 341 | }, 342 | )?; 343 | 344 | Ok(()) 345 | } 346 | 347 | /// Get the value of the Pin (0 or 1) 348 | /// 349 | /// If successful, 1 will be returned if the pin is high 350 | /// and 0 will be returned if the pin is low (this may or may 351 | /// not match the signal level of the actual signal depending 352 | /// on the GPIO "active_low" entry). 353 | pub fn get_value(&self) -> Result { 354 | match self.read_from_device_file("value") { 355 | Ok(s) => match s.trim() { 356 | "1" => Ok(1), 357 | "0" => Ok(0), 358 | other => Err(Error::Unexpected(format!("value file contents {}", other))), 359 | }, 360 | Err(e) => Err(::std::convert::From::from(e)), 361 | } 362 | } 363 | 364 | /// Set the value of the Pin 365 | /// 366 | /// This will set the value of the pin either high or low. 367 | /// A 0 value will set the pin low and any other value will 368 | /// set the pin high (1 is typical). 369 | pub fn set_value(&self, value: u8) -> Result<()> { 370 | self.write_to_device_file( 371 | "value", 372 | match value { 373 | 0 => "0", 374 | _ => "1", 375 | }, 376 | )?; 377 | 378 | Ok(()) 379 | } 380 | 381 | /// Get the currently configured edge for this pin 382 | /// 383 | /// This value will only be present if the Pin allows 384 | /// for interrupts. 385 | pub fn get_edge(&self) -> Result { 386 | match self.read_from_device_file("edge") { 387 | Ok(s) => match s.trim() { 388 | "none" => Ok(Edge::NoInterrupt), 389 | "rising" => Ok(Edge::RisingEdge), 390 | "falling" => Ok(Edge::FallingEdge), 391 | "both" => Ok(Edge::BothEdges), 392 | other => Err(Error::Unexpected(format!( 393 | "Unexpected file contents {}", 394 | other 395 | ))), 396 | }, 397 | Err(e) => Err(::std::convert::From::from(e)), 398 | } 399 | } 400 | 401 | /// Set the edge on which this GPIO will trigger when polled 402 | /// 403 | /// The configured edge determines what changes to the Pin will 404 | /// result in `poll()` returning. This call will return an Error 405 | /// if the pin does not allow interrupts. 406 | pub fn set_edge(&self, edge: Edge) -> Result<()> { 407 | self.write_to_device_file( 408 | "edge", 409 | match edge { 410 | Edge::NoInterrupt => "none", 411 | Edge::RisingEdge => "rising", 412 | Edge::FallingEdge => "falling", 413 | Edge::BothEdges => "both", 414 | }, 415 | )?; 416 | 417 | Ok(()) 418 | } 419 | 420 | /// Get polarity of the Pin (`true` is active low) 421 | pub fn get_active_low(&self) -> Result { 422 | match self.read_from_device_file("active_low") { 423 | Ok(s) => match s.trim() { 424 | "1" => Ok(true), 425 | "0" => Ok(false), 426 | other => Err(Error::Unexpected(format!( 427 | "active_low file contents {}", 428 | other 429 | ))), 430 | }, 431 | Err(e) => Err(::std::convert::From::from(e)), 432 | } 433 | } 434 | 435 | /// Set the polarity of the Pin (`true` is active low) 436 | /// 437 | /// This will affect "rising" and "falling" edge triggered 438 | /// configuration. 439 | pub fn set_active_low(&self, active_low: bool) -> Result<()> { 440 | self.write_to_device_file( 441 | "active_low", 442 | match active_low { 443 | true => "1", 444 | false => "0", 445 | }, 446 | )?; 447 | 448 | Ok(()) 449 | } 450 | 451 | /// Get a PinPoller object for this pin 452 | /// 453 | /// This pin poller object will register an interrupt with the 454 | /// kernel and allow you to poll() on it and receive notifications 455 | /// that an interrupt has occured with minimal delay. 456 | #[cfg(not(target_os = "wasi"))] 457 | pub fn get_poller(&self) -> Result { 458 | PinPoller::new(self.pin_num) 459 | } 460 | 461 | /// Get an AsyncPinPoller object for this pin 462 | /// 463 | /// The async pin poller object can be used with the `mio` crate. You should probably call 464 | /// `set_edge()` before using this. 465 | /// 466 | /// This method is only available when the `mio-evented` crate feature is enabled. 467 | #[cfg(feature = "mio-evented")] 468 | pub fn get_async_poller(&self) -> Result { 469 | AsyncPinPoller::new(self.pin_num) 470 | } 471 | 472 | /// Get a Stream of pin interrupts for this pin 473 | /// 474 | /// The PinStream object can be used with the `tokio` crate. You should probably call 475 | /// `set_edge()` before using this. 476 | /// 477 | /// This method is only available when the `async-tokio` crate feature is enabled. 478 | #[cfg(feature = "async-tokio")] 479 | pub fn get_stream(&self) -> Result { 480 | PinStream::init(*self) 481 | } 482 | 483 | /// Get a Stream of pin values for this pin 484 | /// 485 | /// The PinStream object can be used with the `tokio` crate. You should probably call 486 | /// `set_edge(Edge::BothEdges)` before using this. 487 | /// 488 | /// Note that the values produced are the value of the pin as soon as we get to handling the 489 | /// interrupt in userspace. Each time this stream produces a value, a change has occurred, but 490 | /// it could end up producing the same value multiple times if the value has changed back 491 | /// between when the interrupt occurred and when the value was read. 492 | /// 493 | /// This method is only available when the `async-tokio` crate feature is enabled. 494 | #[cfg(feature = "async-tokio")] 495 | pub fn get_value_stream(&self) -> Result { 496 | Ok(PinValueStream(PinStream::init(*self)?)) 497 | } 498 | } 499 | 500 | #[test] 501 | fn extract_pin_fom_path_test() { 502 | let tok1 = Pin::extract_pin_from_path("/sys/class/gpio/gpio951"); 503 | assert_eq!(951, tok1.unwrap()); 504 | let tok2 = Pin::extract_pin_from_path("/sys/CLASS/gpio/gpio951/"); 505 | assert_eq!(951, tok2.unwrap()); 506 | let tok3 = Pin::extract_pin_from_path("../../devices/soc0/gpiochip3/gpio/gpio124"); 507 | assert_eq!(124, tok3.unwrap()); 508 | let err1 = Pin::extract_pin_from_path("/sys/CLASS/gpio/gpio"); 509 | assert!(err1.is_err()); 510 | let err2 = Pin::extract_pin_from_path("/sys/class/gpio/gpioSDS"); 511 | assert!(err2.is_err()); 512 | } 513 | #[cfg(not(target_os = "wasi"))] 514 | #[derive(Debug)] 515 | pub struct PinPoller { 516 | pin_num: u64, 517 | epoll_fd: RawFd, 518 | devfile: File, 519 | } 520 | #[cfg(not(target_os = "wasi"))] 521 | impl PinPoller { 522 | /// Get the pin associated with this PinPoller 523 | /// 524 | /// Note that this will be a new Pin object with the 525 | /// proper pin number. 526 | pub fn get_pin(&self) -> Pin { 527 | Pin::new(self.pin_num) 528 | } 529 | 530 | /// Create a new PinPoller for the provided pin number 531 | #[cfg(any(target_os = "linux", target_os = "android"))] 532 | pub fn new(pin_num: u64) -> Result { 533 | let devfile: File = File::open(format!("/sys/class/gpio/gpio{}/value", pin_num))?; 534 | let devfile_fd = devfile.as_raw_fd(); 535 | let epoll_fd = epoll_create()?; 536 | let mut event = EpollEvent::new(EpollFlags::EPOLLPRI | EpollFlags::EPOLLET, 0u64); 537 | 538 | match epoll_ctl(epoll_fd, EpollOp::EpollCtlAdd, devfile_fd, &mut event) { 539 | Ok(_) => Ok(PinPoller { 540 | pin_num, 541 | devfile, 542 | epoll_fd, 543 | }), 544 | Err(err) => { 545 | let _ = close(epoll_fd); // cleanup 546 | Err(::std::convert::From::from(err)) 547 | } 548 | } 549 | } 550 | 551 | #[cfg(not(any(target_os = "linux", target_os = "android")))] 552 | pub fn new(_pin_num: u64) -> Result { 553 | Err(Error::Unsupported("PinPoller".into())) 554 | } 555 | 556 | /// Block until an interrupt occurs 557 | /// 558 | /// This call will block until an interrupt occurs. The types 559 | /// of interrupts which may result in this call returning 560 | /// may be configured by calling `set_edge()` prior to 561 | /// making this call. This call makes use of epoll under the 562 | /// covers. To poll on multiple GPIOs or other event sources, 563 | /// poll asynchronously using the integration with either `mio` 564 | /// or `tokio`. 565 | /// 566 | /// This function will return Some(value) of the pin if a change is 567 | /// detected or None if a timeout occurs. Note that the value provided 568 | /// is the value of the pin as soon as we get to handling the interrupt 569 | /// in userspace. Each time this function returns with a value, a change 570 | /// has occurred, but you could end up reading the same value multiple 571 | /// times as the value has changed back between when the interrupt 572 | /// occurred and the current time. 573 | #[cfg(any(target_os = "linux", target_os = "android"))] 574 | pub fn poll(&mut self, timeout_ms: isize) -> Result> { 575 | flush_input_from_file(&mut self.devfile, 255)?; 576 | let dummy_event = EpollEvent::new(EpollFlags::EPOLLPRI | EpollFlags::EPOLLET, 0u64); 577 | let mut events: [EpollEvent; 1] = [dummy_event]; 578 | let cnt = epoll_wait(self.epoll_fd, &mut events, timeout_ms)?; 579 | Ok(match cnt { 580 | 0 => None, // timeout 581 | _ => Some(get_value_from_file(&mut self.devfile)?), 582 | }) 583 | } 584 | 585 | #[cfg(not(any(target_os = "linux", target_os = "android")))] 586 | pub fn poll(&mut self, _timeout_ms: isize) -> Result> { 587 | Err(Error::Unsupported("PinPoller".into())) 588 | } 589 | } 590 | 591 | #[cfg(not(target_os = "wasi"))] 592 | impl Drop for PinPoller { 593 | fn drop(&mut self) { 594 | // we implement drop to close the underlying epoll fd as 595 | // it does not implement drop itself. This is similar to 596 | // how mio works 597 | close(self.epoll_fd).unwrap(); // panic! if close files 598 | } 599 | } 600 | 601 | #[cfg(feature = "mio-evented")] 602 | #[derive(Debug)] 603 | pub struct AsyncPinPoller { 604 | devfile: File, 605 | } 606 | 607 | #[cfg(feature = "mio-evented")] 608 | impl AsyncPinPoller { 609 | fn new(pin_num: u64) -> Result { 610 | let devfile = File::open(format!("/sys/class/gpio/gpio{}/value", pin_num))?; 611 | Ok(AsyncPinPoller { devfile }) 612 | } 613 | } 614 | 615 | #[cfg(feature = "mio-evented")] 616 | impl Source for AsyncPinPoller { 617 | fn register( 618 | &mut self, 619 | poll: &mio::Registry, 620 | token: mio::Token, 621 | interest: mio::Interest, 622 | ) -> io::Result<()> { 623 | SourceFd(&self.as_raw_fd()).register(poll, token, interest) 624 | } 625 | 626 | fn reregister( 627 | &mut self, 628 | poll: &mio::Registry, 629 | token: mio::Token, 630 | interest: mio::Interest, 631 | ) -> io::Result<()> { 632 | SourceFd(&self.as_raw_fd()).reregister(poll, token, interest) 633 | } 634 | 635 | fn deregister(&mut self, poll: &mio::Registry) -> io::Result<()> { 636 | SourceFd(&self.as_raw_fd()).deregister(poll) 637 | } 638 | } 639 | 640 | #[cfg(any(feature = "async-tokio", feature = "mio-evented"))] 641 | impl AsRawFd for AsyncPinPoller { 642 | fn as_raw_fd(&self) -> RawFd { 643 | self.devfile.as_raw_fd() 644 | } 645 | } 646 | 647 | #[cfg(feature = "async-tokio")] 648 | pub struct PinStream { 649 | evented: AsyncFd, 650 | skipped_first_event: bool, 651 | } 652 | 653 | #[cfg(feature = "async-tokio")] 654 | impl PinStream { 655 | pub fn init(pin: Pin) -> Result { 656 | Ok(PinStream { 657 | evented: AsyncFd::new(pin.get_async_poller()?)?, 658 | skipped_first_event: false, 659 | }) 660 | } 661 | } 662 | 663 | #[cfg(feature = "async-tokio")] 664 | impl Stream for PinStream { 665 | type Item = Result<()>; 666 | 667 | fn poll_next( 668 | mut self: std::pin::Pin<&mut Self>, 669 | cx: &mut std::task::Context<'_>, 670 | ) -> Poll> { 671 | loop { 672 | let mut guard = ready!(self.evented.poll_read_ready(cx))?; 673 | guard.clear_ready(); 674 | if self.skipped_first_event { 675 | return Poll::Ready(Some(Ok(()))); 676 | } else { 677 | self.skipped_first_event = true; 678 | } 679 | } 680 | } 681 | } 682 | 683 | #[cfg(feature = "async-tokio")] 684 | pub struct PinValueStream(PinStream); 685 | 686 | #[cfg(feature = "async-tokio")] 687 | impl PinValueStream { 688 | #[inline] 689 | fn get_value(&mut self) -> Result { 690 | get_value_from_file(&mut self.0.evented.get_mut().devfile) 691 | } 692 | } 693 | 694 | #[cfg(feature = "async-tokio")] 695 | impl Stream for PinValueStream { 696 | type Item = Result; 697 | 698 | fn poll_next( 699 | mut self: std::pin::Pin<&mut Self>, 700 | cx: &mut std::task::Context<'_>, 701 | ) -> Poll> { 702 | ready!(std::pin::Pin::new(&mut self.0).poll_next(cx)); 703 | Poll::Ready(Some(Ok(self.get_value()?))) 704 | } 705 | } 706 | -------------------------------------------------------------------------------- /triagebot.toml: -------------------------------------------------------------------------------- 1 | [assign] 2 | --------------------------------------------------------------------------------