[
  {
    "path": ".github/CODEOWNERS",
    "content": "* @rust-embedded/embedded-linux\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "on:\n  push: # Run CI for all branches except GitHub merge queue tmp branches\n    branches-ignore:\n    - \"gh-readonly-queue/**\"\n  pull_request: # Run CI for PRs on any branch\n  merge_group: # Run CI for the GitHub merge queue\n\nname: Continuous integration\n\njobs:\n  ci-linux:\n    name: CI\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n      matrix:\n        rust: [stable]\n        target: [x86_64-unknown-linux-gnu, armv7-unknown-linux-gnueabihf]\n        features:\n          - ''\n          - 'async-tokio,gpio_cdev,gpio_sysfs,i2c,spi'\n\n        include:\n          - rust: 1.84.0 # MSRV\n            target: x86_64-unknown-linux-gnu\n\n          # Test nightly but don't fail\n          - rust: nightly\n            experimental: true\n            target: x86_64-unknown-linux-gnu\n\n    steps:\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@master\n        with:\n          toolchain: ${{ matrix.rust }}\n          target: ${{ matrix.target }}\n\n      - name: Install armv7 libraries\n        if: ${{ matrix.target == 'armv7-unknown-linux-gnueabihf' }}\n        run: |\n            sudo apt-get update\n            sudo apt-get install -y libc6-armhf-cross libc6-dev-armhf-cross gcc-arm-linux-gnueabihf\n\n      - run: cargo check --target=${{ matrix.target }} --features=${{ matrix.features }}\n"
  },
  {
    "path": ".github/workflows/clippy.yml",
    "content": "on:\n  push: # Run CI for all branches except GitHub merge queue tmp branches\n    branches-ignore:\n    - \"gh-readonly-queue/**\"\n  pull_request: # Run CI for PRs on any branch\n  merge_group: # Run CI for the GitHub merge queue\n\nname: Clippy check\njobs:\n  clippy_check:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@master\n        with:\n          toolchain: 1.84.0\n          components: clippy\n      - run: cargo clippy --all-features -- --deny=warnings\n"
  },
  {
    "path": ".github/workflows/rustfmt.yml",
    "content": "on:\n  push: # Run CI for all branches except GitHub merge queue tmp branches\n    branches-ignore:\n    - \"gh-readonly-queue/**\"\n  pull_request: # Run CI for PRs on any branch\n  merge_group: # Run CI for the GitHub merge queue\n\nname: Code formatting check\n\njobs:\n  fmt:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@master\n        with:\n          toolchain: nightly\n          components: rustfmt\n      - run: cargo fmt --check\n"
  },
  {
    "path": ".gitignore",
    "content": "\n/target/\n**/*.rs.bk\nCargo.lock\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](http://keepachangelog.com/)\nand this project adheres to [Semantic Versioning](http://semver.org/).\n\n## [Unreleased]\n\n### Changed\n\n- MSRV is now 1.84.0.\n- Set `resolver = \"3\"`, which implies `resolver.incompatible-rust-versions = \"fallback\"`\n\n### Added\n\n- Added async `DelayNs` implementation for `tokio`.\n- Added feature flag for `serial`.\n\n### Fixed\n\n- Fix UB (and remove unsafe block) in handling of SpiOperation::TransferInPlace\n\n## [v0.4.0] - 2024-01-10\n\n### Changed\n- Updated to `embedded-hal` `1.0.0` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100---2023-12-28))\n- Updated to `embedded-hal-nb` `1.0.0` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal-nb/CHANGELOG.md#v100---2023-12-28))\n\n## [v0.4.0-alpha.4] - 2024-01-03\n\n### Changed\n- [breaking-change] Replace serial-rs with the serialport-rs crate. `Serial::open` now needs a baud-rate argument as well.\n- [breaking-change] Split `Spidev` into `SpidevDevice` and `SpidevBus`, implementing the respective `SpiDevice` and `SpiBus` traits (#100)\n- Updated to `embedded-hal` `1.0.0-rc.3` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100-rc3---2023-12-14))\n- Updated to `embedded-hal-nb` `1.0.0-rc.3` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal-nb/CHANGELOG.md#v100-rc3---2023-12-14))\n- Updated to `spidev` `0.6.0` release([API changes](https://github.com/rust-embedded/rust-spidev/blob/master/CHANGELOG.md#060--2023-08-03))\n- Updated to `i2cdev` `0.6.0` release([API changes](https://github.com/rust-embedded/rust-i2cdev/blob/master/CHANGELOG.md#v060---2023-08-03))\n- Updated to `gpio_cdev` `0.6.0` release([API changes](https://github.com/rust-embedded/gpio-cdev/blob/master/CHANGELOG.md#v060--2023-09-11))\n- Updated to `nix` `0.27.1`\n- MSRV is now 1.65.0.\n\n### Fixed\n- Fix using SPI transfer with unequal buffer sizes (#97, #98).\n\n## [v0.4.0-alpha.3] - 2022-08-04\n\n### Added\n\n- Added feature flag for `spi` and `i2c`\n\n### Changed\n\n- Updated to `embedded-hal` `1.0.0-alpha.8` release ([API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100-alpha8---2022-04-15))\n\n## [v0.4.0-alpha.2] - 2022-02-15\n\n### Added\n\n- Mappings for `embedded-hal` error kinds\n### Changed\n\n- Updated to `embedded-hal` `1.0.0-alpha.7` release (significant [API changes](https://github.com/rust-embedded/embedded-hal/blob/master/embedded-hal/CHANGELOG.md#v100-alpha7---2022-02-09))\n- Updated dependencies to force use of newer nix version\n  - `spidev` to version `0.5.1`\n  - `i2cdev` to version `0.5.1`\n  - `gpio-cdev` to version `0.5.1`\n  - `sysfs_gpio` to version `0.6.1`\n\n## [v0.4.0-alpha.1] - 2021-10-07\n\n### Added\n\n- Implement `embedded_hal::digital::blocking::IoPin` for `CdevPin` and `SysfsPin`\n- `CountDown` implementation for `SysTimer`.\n- `Default` implementation for `SysTimer`.\n\n### Changed\n\n- Modified `OutputPin` behavior for active-low pins to match `InputPin` behavior.\n- Set default features to build both sysfs and cdev pin types.\n- Removed `Pin` export, use `CdevPin` or `SysfsPin`.\n- Adapted to `embedded-hal` `1.0.0-alpha.5` release.\n- Increased the Minimum Supported Rust Version to `1.46.0` due to an update of `bitflags`.\n- Updated `spidev` to version `0.5`.\n- Updated `i2cdev` to version `0.5`.\n- Updated `gpio-cdev` to version `0.5`.\n- Updated `sysfs_gpio` to version `0.6`.\n- Updated `nb` to version `1`.\n\n## [v0.3.2] - 2021-10-25\n\n### Fixed\n- Readd `Pin` type export as an alias to `SysfsPin` for compatibility with the `0.3.0` version.\n\n## [v0.3.1] - 2021-09-27\n### Added\n\n- Added implementation of transactional SPI and I2C traits.\n- `CountDown` implementation for `SysTimer`.\n- `Default` implementation for `SysTimer`.\n\n### Changed\n\n- Set default features to build both sysfs and cdev pin types.\n- Removed `Pin` export, use `CdevPin` or `SysfsPin`.\n- Updated `embedded-hal` to version `0.2.6`.\n- Updated `nb` to version `0.1.3`.\n- Updated `gpio-cdev` to version `0.5`.\n- Updated `i2cdev` to version `0.5`.\n- Updated `spidev` to version `0.5`.\n- Updated `sysfs-gpio` to version `0.6`.\n- Updated `cast` to version `0.3`.\n\n### Fixed\n\n- Modified `OutputPin` behavior for active-low pins to match `InputPin` behavior.\n\n## [v0.3.0] - 2019-11-25\n\n### Added\n\n- Added serial::Read/Write implementation.\n- Added feature flag for Chardev GPIO\n\n### Fixed\n\n- Do write and read in one transaction in WriteRead implementation.\n- Removed #[deny(warnings)]\n\n### Changed\n\n- Use embedded-hal::digital::v2 traits.\n- Updated to i2cdev 0.4.3 (necessary for trasactional write-read).\n- Updated to spidev 0.4\n- Added feature flag for Sysfs GPIO\n\n## [v0.2.2] - 2018-12-21\n\n### Changed\n\n- updated to i2cdev 0.4.1 (removes superflous dependencies)\n\n## [v0.2.1] - 2018-10-25\n\n### Added\n\n- implementation of the unproven `embedded_hal::::digital::InputPin` trait.\n\n## [v0.2.0] - 2018-05-14\n\n### Changed\n\n- [breaking-change] moved to v0.2.x of `embedded-hal`.\n\n## [v0.1.1] - 2018-02-13\n\n### Added\n\n- implementation of `embedded_hal::blocking::Delay*` traits in the form of the `Delay` zero sized\n  type.\n\n- implementation of the `embedded_hal::blocking::i2c` traits in the form of the `I2cdev` newtype.\n\n## v0.1.0 - 2018-01-17\n\nInitial release\n\n[Unreleased]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0...HEAD\n[v0.4.0]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.4...v0.4.0\n[v0.4.0-alpha.4]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.3...v0.4.0-alpha.4\n[v0.4.0-alpha.3]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.2...v0.4.0-alpha.3\n[v0.4.0-alpha.2]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.4.0-alpha.1...v0.4.0-alpha.2\n[v0.4.0-alpha.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.3.0...v0.4.0-alpha.1\n[v0.3.2]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.3.1...v0.3.2\n[v0.3.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.3.0...v0.3.1\n[v0.3.0]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.2.2...v0.3.0\n[v0.2.2]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.2.1...v0.2.2\n[v0.2.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.2.0...v0.2.1\n[v0.2.0]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.1.1...v0.2.0\n[v0.1.1]: https://github.com/rust-embedded/linux-embedded-hal/compare/v0.1.0...v0.1.1\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# The Rust Code of Conduct\n\n## Conduct\n\n**Contact**: [HAL team](https://github.com/rust-embedded/wg#the-hal-team)\n\n* 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.\n* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all.\n* Please be kind and courteous. There's no need to be mean or rude.\n* 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.\n* 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.\n* 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.\n* 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 [HAL 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.\n* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.\n\n## Moderation\n\nThese are the policies for upholding our community's standards of conduct.\n\n1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.)\n2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed.\n3. Moderators will first respond to such remarks with a warning.\n4. If the warning is unheeded, the user will be \"kicked,\" i.e., kicked out of the communication channel to cool off.\n5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded.\n6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology.\n7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed.\n8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others.\n\nIn the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely.\n\nAnd if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust.\n\nThe enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org).\n\n*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).*\n\n[team]: https://github.com/rust-embedded/wg#the-hal-team\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nauthors = [\n    \"The Embedded Linux Team <embedded-linux@teams.rust-embedded.org>\",\n    \"Jorge Aparicio <jorge@japaric.io>\"\n]\ncategories = [\"embedded\", \"hardware-support\"]\ndescription = \"Implementation of the `embedded-hal` traits for Linux devices\"\nkeywords = [\"Linux\", \"hal\"]\nlicense = \"MIT OR Apache-2.0\"\nname = \"linux-embedded-hal\"\nrepository = \"https://github.com/rust-embedded/linux-embedded-hal\"\nversion = \"0.5.0-alpha.0\"\nedition = \"2018\"\nrust-version = \"1.84\"\nresolver = \"3\"\n\n[features]\ngpio_sysfs = [\"sysfs_gpio\"]\ngpio_cdev = [\"gpio-cdev\"]\nasync-tokio = [\"gpio-cdev/async-tokio\", \"dep:embedded-hal-async\", \"tokio/time\"]\ni2c = [\"i2cdev\", \"nix\"]\nspi = [\"spidev\"]\nserial = [\"serialport\", \"embedded-hal-nb\"]\n\ndefault = [ \"gpio_cdev\", \"gpio_sysfs\", \"i2c\", \"spi\", \"serial\" ]\n\n[dependencies]\nembedded-hal = \"1\"\nembedded-hal-nb = { version = \"1\", optional = true }\nembedded-hal-async = { version = \"1\", optional = true }\ngpio-cdev = { version = \"0.6.0\", optional = true }\nsysfs_gpio = { version = \"0.6.1\", optional = true }\ni2cdev = { version = \"0.6.0\", optional = true }\nnb = \"1\"\nserialport = { version = \"4.2.0\", default-features = false, optional = true }\nspidev = { version = \"0.6.1\", optional = true }\nnix = { version = \"0.27.1\", optional = true }\ntokio = { version = \"1\", default-features = false, optional = true }\n\n[dev-dependencies]\nopenpty = \"0.2.0\"\n\n[dependencies.cast]\n# we don't need the `Error` implementation\ndefault-features = false\nversion = \"0.3\"\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                              Apache License\n                        Version 2.0, January 2004\n                     http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n   \"License\" shall mean the terms and conditions for use, reproduction,\n   and distribution as defined by Sections 1 through 9 of this document.\n\n   \"Licensor\" shall mean the copyright owner or entity authorized by\n   the copyright owner that is granting the License.\n\n   \"Legal Entity\" shall mean the union of the acting entity and all\n   other entities that control, are controlled by, or are under common\n   control with that entity. For the purposes of this definition,\n   \"control\" means (i) the power, direct or indirect, to cause the\n   direction or management of such entity, whether by contract or\n   otherwise, or (ii) ownership of fifty percent (50%) or more of the\n   outstanding shares, or (iii) beneficial ownership of such entity.\n\n   \"You\" (or \"Your\") shall mean an individual or Legal Entity\n   exercising permissions granted by this License.\n\n   \"Source\" form shall mean the preferred form for making modifications,\n   including but not limited to software source code, documentation\n   source, and configuration files.\n\n   \"Object\" form shall mean any form resulting from mechanical\n   transformation or translation of a Source form, including but\n   not limited to compiled object code, generated documentation,\n   and conversions to other media types.\n\n   \"Work\" shall mean the work of authorship, whether in Source or\n   Object form, made available under the License, as indicated by a\n   copyright notice that is included in or attached to the work\n   (an example is provided in the Appendix below).\n\n   \"Derivative Works\" shall mean any work, whether in Source or Object\n   form, that is based on (or derived from) the Work and for which the\n   editorial revisions, annotations, elaborations, or other modifications\n   represent, as a whole, an original work of authorship. For the purposes\n   of this License, Derivative Works shall not include works that remain\n   separable from, or merely link (or bind by name) to the interfaces of,\n   the Work and Derivative Works thereof.\n\n   \"Contribution\" shall mean any work of authorship, including\n   the original version of the Work and any modifications or additions\n   to that Work or Derivative Works thereof, that is intentionally\n   submitted to Licensor for inclusion in the Work by the copyright owner\n   or by an individual or Legal Entity authorized to submit on behalf of\n   the copyright owner. For the purposes of this definition, \"submitted\"\n   means any form of electronic, verbal, or written communication sent\n   to the Licensor or its representatives, including but not limited to\n   communication on electronic mailing lists, source code control systems,\n   and issue tracking systems that are managed by, or on behalf of, the\n   Licensor for the purpose of discussing and improving the Work, but\n   excluding communication that is conspicuously marked or otherwise\n   designated in writing by the copyright owner as \"Not a Contribution.\"\n\n   \"Contributor\" shall mean Licensor and any individual or Legal Entity\n   on behalf of whom a Contribution has been received by Licensor and\n   subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   copyright license to reproduce, prepare Derivative Works of,\n   publicly display, publicly perform, sublicense, and distribute the\n   Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n   this License, each Contributor hereby grants to You a perpetual,\n   worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n   (except as stated in this section) patent license to make, have made,\n   use, offer to sell, sell, import, and otherwise transfer the Work,\n   where such license applies only to those patent claims licensable\n   by such Contributor that are necessarily infringed by their\n   Contribution(s) alone or by combination of their Contribution(s)\n   with the Work to which such Contribution(s) was submitted. If You\n   institute patent litigation against any entity (including a\n   cross-claim or counterclaim in a lawsuit) alleging that the Work\n   or a Contribution incorporated within the Work constitutes direct\n   or contributory patent infringement, then any patent licenses\n   granted to You under this License for that Work shall terminate\n   as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n   Work or Derivative Works thereof in any medium, with or without\n   modifications, and in Source or Object form, provided that You\n   meet the following conditions:\n\n   (a) You must give any other recipients of the Work or\n       Derivative Works a copy of this License; and\n\n   (b) You must cause any modified files to carry prominent notices\n       stating that You changed the files; and\n\n   (c) You must retain, in the Source form of any Derivative Works\n       that You distribute, all copyright, patent, trademark, and\n       attribution notices from the Source form of the Work,\n       excluding those notices that do not pertain to any part of\n       the Derivative Works; and\n\n   (d) If the Work includes a \"NOTICE\" text file as part of its\n       distribution, then any Derivative Works that You distribute must\n       include a readable copy of the attribution notices contained\n       within such NOTICE file, excluding those notices that do not\n       pertain to any part of the Derivative Works, in at least one\n       of the following places: within a NOTICE text file distributed\n       as part of the Derivative Works; within the Source form or\n       documentation, if provided along with the Derivative Works; or,\n       within a display generated by the Derivative Works, if and\n       wherever such third-party notices normally appear. The contents\n       of the NOTICE file are for informational purposes only and\n       do not modify the License. You may add Your own attribution\n       notices within Derivative Works that You distribute, alongside\n       or as an addendum to the NOTICE text from the Work, provided\n       that such additional attribution notices cannot be construed\n       as modifying the License.\n\n   You may add Your own copyright statement to Your modifications and\n   may provide additional or different license terms and conditions\n   for use, reproduction, or distribution of Your modifications, or\n   for any such Derivative Works as a whole, provided Your use,\n   reproduction, and distribution of the Work otherwise complies with\n   the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n   any Contribution intentionally submitted for inclusion in the Work\n   by You to the Licensor shall be under the terms and conditions of\n   this License, without any additional terms or conditions.\n   Notwithstanding the above, nothing herein shall supersede or modify\n   the terms of any separate license agreement you may have executed\n   with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n   names, trademarks, service marks, or product names of the Licensor,\n   except as required for reasonable and customary use in describing the\n   origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n   agreed to in writing, Licensor provides the Work (and each\n   Contributor provides its Contributions) on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n   implied, including, without limitation, any warranties or conditions\n   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n   PARTICULAR PURPOSE. You are solely responsible for determining the\n   appropriateness of using or redistributing the Work and assume any\n   risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n   whether in tort (including negligence), contract, or otherwise,\n   unless required by applicable law (such as deliberate and grossly\n   negligent acts) or agreed to in writing, shall any Contributor be\n   liable to You for damages, including any direct, indirect, special,\n   incidental, or consequential damages of any character arising as a\n   result of this License or out of the use or inability to use the\n   Work (including but not limited to damages for loss of goodwill,\n   work stoppage, computer failure or malfunction, or any and all\n   other commercial damages or losses), even if such Contributor\n   has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n   the Work or Derivative Works thereof, You may choose to offer,\n   and charge a fee for, acceptance of support, warranty, indemnity,\n   or other liability obligations and/or rights consistent with this\n   License. However, in accepting such obligations, You may act only\n   on Your own behalf and on Your sole responsibility, not on behalf\n   of any other Contributor, and only if You agree to indemnify,\n   defend, and hold each Contributor harmless for any liability\n   incurred by, or claims asserted against, such Contributor by reason\n   of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n   To apply the Apache License to your work, attach the following\n   boilerplate notice, with the fields enclosed by brackets \"[]\"\n   replaced with your own identifying information. (Don't include\n   the brackets!)  The text should be enclosed in the appropriate\n   comment syntax for the file format. We also recommend that a\n   file or class name and description of purpose be included on the\n   same \"printed page\" as the copyright notice for easier\n   identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Copyright (c) 2018 Jorge Aparicio\nCopyright (c) 2019-2024 The Rust embedded linux team and contributors.\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "[![crates.io](https://img.shields.io/crates/d/linux-embedded-hal.svg)](https://crates.io/crates/linux-embedded-hal)\n[![crates.io](https://img.shields.io/crates/v/linux-embedded-hal.svg)](https://crates.io/crates/linux-embedded-hal)\n[![Documentation](https://docs.rs/linux-embedded-hal/badge.svg)](https://docs.rs/linux-embedded-hal)\n![Minimum Supported Rust Version](https://img.shields.io/badge/rustc-1.84+-blue.svg)\n\n# `linux-embedded-hal`\n\n> Implementation of the [`embedded-hal`] traits for Linux devices\n\nThis project is developed and maintained by the [Embedded Linux team][team].\n\n[`embedded-hal`]: https://crates.io/crates/embedded-hal\n\n## [Documentation](https://docs.rs/linux-embedded-hal)\n\n## GPIO character device\n\nSince Linux kernel v4.4 the use of sysfs GPIO was deprecated and replaced by the character device GPIO.\nSee [gpio-cdev documentation](https://github.com/rust-embedded/gpio-cdev#sysfs-gpio-vs-gpio-character-device) for details.\n\nThis crate includes feature flag `gpio_cdev` that exposes `CdevPin` as wrapper around `LineHandle` from [gpio-cdev](https://crates.io/crates/gpio-cdev).\nTo enable it update your Cargo.toml. Please note that in order to prevent `LineHandle` fd from closing you should\nassign to a variable, see [cdev issue](https://github.com/rust-embedded/gpio-cdev/issues/29) for more details.\n```\nlinux-embedded-hal = { version = \"0.4\", features = [\"gpio_cdev\"] }\n```\n\n`SysfsPin` can be still used with feature flag `gpio_sysfs`.\n\nWith `default-features = false` you can enable the features `gpio_cdev`, `gpio_sysfs`, `i2c`, and `spi` as needed.\n\n## Minimum Supported Rust Version (MSRV)\n\nThis crate is guaranteed to compile on stable Rust 1.84.0 and up. It *might*\ncompile with older versions but that may change in any new patch release.\n\n## License\n\nLicensed under either of\n\n- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or\n  http://www.apache.org/licenses/LICENSE-2.0)\n- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)\n\nat your option.\n\n### Contribution\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\nfor inclusion in the work by you, as defined in the Apache-2.0 license, shall be\ndual licensed as above, without any additional terms or conditions.\n\n## Code of Conduct\n\nContribution to this crate is organized under the terms of the [Rust Code of\nConduct][CoC], the maintainer of this crate, the [HAL team][team], promises\nto intervene to uphold that code of conduct.\n\n[CoC]: CODE_OF_CONDUCT.md\n[team]: https://github.com/rust-embedded/wg/#the-embedded-linux-team\n"
  },
  {
    "path": "examples/transactional-i2c.rs",
    "content": "use embedded_hal::i2c::{I2c, Operation as I2cOperation};\nuse linux_embedded_hal::I2cdev;\n\nconst ADDR: u8 = 0x12;\n\nstruct Driver<I2C> {\n    i2c: I2C,\n}\n\nimpl<I2C> Driver<I2C>\nwhere\n    I2C: I2c,\n{\n    pub fn new(i2c: I2C) -> Self {\n        Driver { i2c }\n    }\n\n    fn read_something(&mut self) -> Result<u8, I2C::Error> {\n        let mut read_buffer = [0];\n        let mut ops = [\n            I2cOperation::Write(&[0xAB]),\n            I2cOperation::Read(&mut read_buffer),\n        ];\n        self.i2c.transaction(ADDR, &mut ops).and(Ok(read_buffer[0]))\n    }\n}\n\nfn main() {\n    let dev = I2cdev::new(\"/dev/i2c-1\").unwrap();\n    let mut driver = Driver::new(dev);\n    let value = driver.read_something().unwrap();\n    println!(\"Read value: {}\", value);\n}\n"
  },
  {
    "path": "src/cdev_pin.rs",
    "content": "//! Implementation of [`embedded-hal`] digital input/output traits using a Linux CDev pin\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse std::fmt;\n\n/// Newtype around [`gpio_cdev::LineHandle`] that implements the `embedded-hal` traits\n///\n/// [`gpio_cdev::LineHandle`]: https://docs.rs/gpio-cdev/0.5.0/gpio_cdev/struct.LineHandle.html\npub struct CdevPin(pub gpio_cdev::LineHandle, gpio_cdev::LineInfo);\n\nimpl CdevPin {\n    /// See [`gpio_cdev::Line::request`][0] for details.\n    ///\n    /// [0]: https://docs.rs/gpio-cdev/0.5.0/gpio_cdev/struct.Line.html#method.request\n    pub fn new(handle: gpio_cdev::LineHandle) -> Result<Self, gpio_cdev::errors::Error> {\n        let info = handle.line().info()?;\n        Ok(CdevPin(handle, info))\n    }\n\n    fn get_input_flags(&self) -> gpio_cdev::LineRequestFlags {\n        if self.1.is_active_low() {\n            return gpio_cdev::LineRequestFlags::INPUT | gpio_cdev::LineRequestFlags::ACTIVE_LOW;\n        }\n        gpio_cdev::LineRequestFlags::INPUT\n    }\n\n    fn get_output_flags(&self) -> gpio_cdev::LineRequestFlags {\n        let mut flags = gpio_cdev::LineRequestFlags::OUTPUT;\n        if self.1.is_active_low() {\n            flags.insert(gpio_cdev::LineRequestFlags::ACTIVE_LOW);\n        }\n        if self.1.is_open_drain() {\n            flags.insert(gpio_cdev::LineRequestFlags::OPEN_DRAIN);\n        } else if self.1.is_open_source() {\n            flags.insert(gpio_cdev::LineRequestFlags::OPEN_SOURCE);\n        }\n        flags\n    }\n\n    /// Set this pin to input mode\n    pub fn into_input_pin(self) -> Result<CdevPin, gpio_cdev::errors::Error> {\n        if self.1.direction() == gpio_cdev::LineDirection::In {\n            return Ok(self);\n        }\n        let line = self.0.line().clone();\n        let input_flags = self.get_input_flags();\n        let consumer = self.1.consumer().unwrap_or(\"\").to_owned();\n\n        // Drop self to free the line before re-requesting it in a new mode.\n        std::mem::drop(self);\n\n        CdevPin::new(line.request(input_flags, 0, &consumer)?)\n    }\n\n    /// Set this pin to output mode\n    pub fn into_output_pin(\n        self,\n        state: embedded_hal::digital::PinState,\n    ) -> Result<CdevPin, gpio_cdev::errors::Error> {\n        if self.1.direction() == gpio_cdev::LineDirection::Out {\n            return Ok(self);\n        }\n\n        let line = self.0.line().clone();\n        let output_flags = self.get_output_flags();\n        let consumer = self.1.consumer().unwrap_or(\"\").to_owned();\n\n        // Drop self to free the line before re-requesting it in a new mode.\n        std::mem::drop(self);\n\n        let is_active_low = output_flags.intersects(gpio_cdev::LineRequestFlags::ACTIVE_LOW);\n        CdevPin::new(line.request(\n            output_flags,\n            state_to_value(state, is_active_low),\n            &consumer,\n        )?)\n    }\n}\n\n/// Converts a pin state to the gpio_cdev compatible numeric value, accounting\n/// for the active_low condition.\nfn state_to_value(state: embedded_hal::digital::PinState, is_active_low: bool) -> u8 {\n    if is_active_low {\n        match state {\n            embedded_hal::digital::PinState::High => 0,\n            embedded_hal::digital::PinState::Low => 1,\n        }\n    } else {\n        match state {\n            embedded_hal::digital::PinState::High => 1,\n            embedded_hal::digital::PinState::Low => 0,\n        }\n    }\n}\n\n/// Error type wrapping [gpio_cdev::errors::Error](gpio_cdev::errors::Error) to implement [embedded_hal::digital::Error]\n#[derive(Debug)]\npub struct CdevPinError {\n    err: gpio_cdev::errors::Error,\n}\n\nimpl CdevPinError {\n    /// Fetch inner (concrete) [`gpio_cdev::errors::Error`]\n    pub fn inner(&self) -> &gpio_cdev::errors::Error {\n        &self.err\n    }\n}\n\nimpl From<gpio_cdev::errors::Error> for CdevPinError {\n    fn from(err: gpio_cdev::errors::Error) -> Self {\n        Self { err }\n    }\n}\n\nimpl fmt::Display for CdevPinError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{}\", self.err)\n    }\n}\n\nimpl std::error::Error for CdevPinError {\n    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n        Some(&self.err)\n    }\n}\n\nimpl embedded_hal::digital::Error for CdevPinError {\n    fn kind(&self) -> embedded_hal::digital::ErrorKind {\n        use embedded_hal::digital::ErrorKind;\n        ErrorKind::Other\n    }\n}\n\nimpl embedded_hal::digital::ErrorType for CdevPin {\n    type Error = CdevPinError;\n}\n\nimpl embedded_hal::digital::OutputPin for CdevPin {\n    fn set_low(&mut self) -> Result<(), Self::Error> {\n        self.0\n            .set_value(state_to_value(\n                embedded_hal::digital::PinState::Low,\n                self.1.is_active_low(),\n            ))\n            .map_err(CdevPinError::from)\n    }\n\n    fn set_high(&mut self) -> Result<(), Self::Error> {\n        self.0\n            .set_value(state_to_value(\n                embedded_hal::digital::PinState::High,\n                self.1.is_active_low(),\n            ))\n            .map_err(CdevPinError::from)\n    }\n}\n\nimpl embedded_hal::digital::InputPin for CdevPin {\n    fn is_high(&mut self) -> Result<bool, Self::Error> {\n        self.0\n            .get_value()\n            .map(|val| {\n                val == state_to_value(\n                    embedded_hal::digital::PinState::High,\n                    self.1.is_active_low(),\n                )\n            })\n            .map_err(CdevPinError::from)\n    }\n\n    fn is_low(&mut self) -> Result<bool, Self::Error> {\n        self.is_high().map(|val| !val)\n    }\n}\n\nimpl core::ops::Deref for CdevPin {\n    type Target = gpio_cdev::LineHandle;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nimpl core::ops::DerefMut for CdevPin {\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        &mut self.0\n    }\n}\n"
  },
  {
    "path": "src/delay.rs",
    "content": "//! Implementation of [`embedded-hal`] delay traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse embedded_hal::delay::DelayNs;\nuse std::thread;\nuse std::time::Duration;\n\n/// Empty struct that provides delay functionality on top of `thread::sleep`,\n/// and `tokio::time::sleep` if the `async-tokio` feature is enabled.\npub struct Delay;\n\nimpl DelayNs for Delay {\n    fn delay_ns(&mut self, n: u32) {\n        thread::sleep(Duration::from_nanos(n.into()));\n    }\n\n    fn delay_us(&mut self, n: u32) {\n        thread::sleep(Duration::from_micros(n.into()));\n    }\n\n    fn delay_ms(&mut self, n: u32) {\n        thread::sleep(Duration::from_millis(n.into()));\n    }\n}\n\n#[cfg(feature = \"async-tokio\")]\nimpl embedded_hal_async::delay::DelayNs for Delay {\n    async fn delay_ns(&mut self, n: u32) {\n        tokio::time::sleep(Duration::from_nanos(n.into())).await;\n    }\n\n    async fn delay_us(&mut self, n: u32) {\n        tokio::time::sleep(Duration::from_micros(n.into())).await;\n    }\n\n    async fn delay_ms(&mut self, n: u32) {\n        tokio::time::sleep(Duration::from_millis(n.into())).await;\n    }\n}\n"
  },
  {
    "path": "src/i2c.rs",
    "content": "//! Implementation of [`embedded-hal`] I2C traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse std::fmt;\nuse std::ops;\nuse std::path::{Path, PathBuf};\n\nuse embedded_hal::i2c::NoAcknowledgeSource;\n\n/// Newtype around [`i2cdev::linux::LinuxI2CDevice`] that implements the `embedded-hal` traits\n///\n/// [`i2cdev::linux::LinuxI2CDevice`]: https://docs.rs/i2cdev/0.5.0/i2cdev/linux/struct.LinuxI2CDevice.html\npub struct I2cdev {\n    inner: i2cdev::linux::LinuxI2CDevice,\n    path: PathBuf,\n    address: Option<u16>,\n}\n\nimpl I2cdev {\n    /// See [`i2cdev::linux::LinuxI2CDevice::new`][0] for details.\n    ///\n    /// [0]: https://docs.rs/i2cdev/0.5.0/i2cdev/linux/struct.LinuxI2CDevice.html#method.new\n    pub fn new<P>(path: P) -> Result<Self, i2cdev::linux::LinuxI2CError>\n    where\n        P: AsRef<Path>,\n    {\n        let dev = I2cdev {\n            path: path.as_ref().to_path_buf(),\n            inner: i2cdev::linux::LinuxI2CDevice::new(path, 0)?,\n            address: None,\n        };\n        Ok(dev)\n    }\n\n    fn set_address(&mut self, address: u16) -> Result<(), i2cdev::linux::LinuxI2CError> {\n        if self.address != Some(address) {\n            self.inner = i2cdev::linux::LinuxI2CDevice::new(&self.path, address)?;\n            self.address = Some(address);\n        }\n        Ok(())\n    }\n}\n\nimpl ops::Deref for I2cdev {\n    type Target = i2cdev::linux::LinuxI2CDevice;\n\n    fn deref(&self) -> &Self::Target {\n        &self.inner\n    }\n}\n\nimpl ops::DerefMut for I2cdev {\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        &mut self.inner\n    }\n}\n\nmod embedded_hal_impl {\n    use super::*;\n    use embedded_hal::i2c::ErrorType;\n    use embedded_hal::i2c::{I2c, Operation as I2cOperation, SevenBitAddress, TenBitAddress};\n    use i2cdev::core::{I2CMessage, I2CTransfer};\n    use i2cdev::linux::LinuxI2CMessage;\n    impl ErrorType for I2cdev {\n        type Error = I2CError;\n    }\n\n    impl I2c<TenBitAddress> for I2cdev {\n        fn transaction(\n            &mut self,\n            address: u16,\n            operations: &mut [I2cOperation],\n        ) -> Result<(), Self::Error> {\n            // Map operations from generic to linux objects\n            let mut messages: Vec<_> = operations\n                .as_mut()\n                .iter_mut()\n                .map(|a| match a {\n                    I2cOperation::Write(w) => LinuxI2CMessage::write(w),\n                    I2cOperation::Read(r) => LinuxI2CMessage::read(r),\n                })\n                .collect();\n\n            self.set_address(address)?;\n            self.inner\n                .transfer(&mut messages)\n                .map(drop)\n                .map_err(|err| I2CError { err })\n        }\n    }\n\n    impl I2c<SevenBitAddress> for I2cdev {\n        fn transaction(\n            &mut self,\n            address: u8,\n            operations: &mut [I2cOperation],\n        ) -> Result<(), Self::Error> {\n            I2c::<TenBitAddress>::transaction(self, u16::from(address), operations)\n        }\n    }\n}\n\n/// Error type wrapping [LinuxI2CError](i2cdev::linux::LinuxI2CError) to implement [embedded_hal::i2c::ErrorKind]\n#[derive(Debug)]\npub struct I2CError {\n    err: i2cdev::linux::LinuxI2CError,\n}\n\nimpl I2CError {\n    /// Fetch inner (concrete) [`LinuxI2CError`]\n    pub fn inner(&self) -> &i2cdev::linux::LinuxI2CError {\n        &self.err\n    }\n}\n\nimpl From<i2cdev::linux::LinuxI2CError> for I2CError {\n    fn from(err: i2cdev::linux::LinuxI2CError) -> Self {\n        Self { err }\n    }\n}\n\nimpl fmt::Display for I2CError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{}\", self.err)\n    }\n}\n\nimpl std::error::Error for I2CError {\n    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n        Some(&self.err)\n    }\n}\n\nimpl embedded_hal::i2c::Error for I2CError {\n    fn kind(&self) -> embedded_hal::i2c::ErrorKind {\n        use embedded_hal::i2c::ErrorKind;\n        use nix::errno::Errno::*;\n\n        let errno = match &self.err {\n            i2cdev::linux::LinuxI2CError::Errno(e) => nix::Error::from_i32(*e),\n            i2cdev::linux::LinuxI2CError::Io(e) => match e.raw_os_error() {\n                Some(r) => nix::Error::from_i32(r),\n                None => return ErrorKind::Other,\n            },\n        };\n\n        // https://www.kernel.org/doc/html/latest/i2c/fault-codes.html\n        match errno {\n            EBUSY | EINVAL | EIO => ErrorKind::Bus,\n            EAGAIN => ErrorKind::ArbitrationLoss,\n            ENODEV => ErrorKind::NoAcknowledge(NoAcknowledgeSource::Data),\n            ENXIO => ErrorKind::NoAcknowledge(NoAcknowledgeSource::Address),\n            _ => ErrorKind::Other,\n        }\n    }\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "//! Implementation of [`embedded-hal`] traits for Linux devices\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n//!\n//! # Drivers\n//!\n//! This crate lets you use a bunch of platform agnostic drivers that are based on the\n//! `embedded-hal` traits. You can find them on crates.io by [searching for the embedded-hal\n//! keyword][0].\n//!\n//! [0]: https://crates.io/keywords/embedded-hal\n\n#![deny(missing_docs)]\n\n#[cfg(feature = \"i2c\")]\npub use i2cdev;\npub use nb;\n#[cfg(feature = \"serial\")]\npub use serialport;\n#[cfg(feature = \"spi\")]\npub use spidev;\n\n#[cfg(feature = \"gpio_sysfs\")]\npub use sysfs_gpio;\n\n#[cfg(feature = \"gpio_cdev\")]\npub use gpio_cdev;\n#[cfg(feature = \"gpio_sysfs\")]\n/// Sysfs Pin wrapper module\nmod sysfs_pin;\n\n#[cfg(feature = \"gpio_cdev\")]\n/// Cdev Pin wrapper module\nmod cdev_pin;\n\n#[cfg(feature = \"gpio_cdev\")]\n/// Cdev pin re-export\npub use cdev_pin::{CdevPin, CdevPinError};\n\n#[cfg(feature = \"gpio_sysfs\")]\n/// Sysfs pin re-export\npub use sysfs_pin::{SysfsPin, SysfsPinError};\n\nmod delay;\n#[cfg(feature = \"i2c\")]\nmod i2c;\n#[cfg(feature = \"serial\")]\nmod serial;\n#[cfg(feature = \"spi\")]\nmod spi;\nmod timer;\n\npub use crate::delay::Delay;\n#[cfg(feature = \"i2c\")]\npub use crate::i2c::{I2CError, I2cdev};\n#[cfg(feature = \"serial\")]\npub use crate::serial::{Serial, SerialError};\n#[cfg(feature = \"spi\")]\npub use crate::spi::{SPIError, SpidevBus, SpidevDevice};\npub use crate::timer::{CountDown, Periodic, SysTimer};\n"
  },
  {
    "path": "src/serial.rs",
    "content": "//! Implementation of [`embedded-hal`] serial traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse serialport::{SerialPortBuilder, TTYPort};\nuse std::fmt;\nuse std::io::{ErrorKind as IoErrorKind, Read, Write};\n\n/// Newtype around [`serialport::TTYPort`] that implements\n/// the `embedded-hal` traits.\npub struct Serial(pub TTYPort);\n\nimpl Serial {\n    /// Open a `serialport::TTYPort` by providing the port path and baud rate\n    pub fn open(path: String, baud_rate: u32) -> Result<Serial, serialport::Error> {\n        Ok(Serial(serialport::new(path, baud_rate).open_native()?))\n    }\n\n    /// Open a `serialport::TTYPort` by providing `serialport::SerialPortBuilder`\n    pub fn open_from_builder(builder: SerialPortBuilder) -> Result<Serial, serialport::Error> {\n        Ok(Serial(builder.open_native()?))\n    }\n}\n\n/// Helper to convert std::io::Error to the nb::Error\nfn translate_io_errors(err: std::io::Error) -> nb::Error<SerialError> {\n    match err.kind() {\n        IoErrorKind::WouldBlock | IoErrorKind::TimedOut | IoErrorKind::Interrupted => {\n            nb::Error::WouldBlock\n        }\n        err => nb::Error::Other(SerialError { err }),\n    }\n}\n\nimpl embedded_hal_nb::serial::ErrorType for Serial {\n    type Error = SerialError;\n}\n\nimpl embedded_hal_nb::serial::Read<u8> for Serial {\n    fn read(&mut self) -> nb::Result<u8, Self::Error> {\n        let mut buffer = [0; 1];\n        let bytes_read = self.0.read(&mut buffer).map_err(translate_io_errors)?;\n        if bytes_read == 1 {\n            Ok(buffer[0])\n        } else {\n            Err(nb::Error::WouldBlock)\n        }\n    }\n}\n\nimpl embedded_hal_nb::serial::Write<u8> for Serial {\n    fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {\n        self.0.write(&[word]).map_err(translate_io_errors)?;\n        Ok(())\n    }\n\n    fn flush(&mut self) -> nb::Result<(), Self::Error> {\n        self.0.flush().map_err(translate_io_errors)\n    }\n}\n\n/// Error type wrapping [io::ErrorKind](IoErrorKind) to implement [embedded_hal::serial::ErrorKind]\n#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\npub struct SerialError {\n    err: IoErrorKind,\n}\n\nimpl SerialError {\n    /// Fetch inner (concrete) [`IoErrorKind`]\n    pub fn inner(&self) -> &IoErrorKind {\n        &self.err\n    }\n}\n\nimpl fmt::Display for SerialError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{}\", self.err)\n    }\n}\n\nimpl std::error::Error for SerialError {}\n\nimpl embedded_hal_nb::serial::Error for SerialError {\n    #[allow(clippy::match_single_binding)]\n    fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {\n        use embedded_hal_nb::serial::ErrorKind::*;\n        // TODO: match any errors here if we can find any that are relevant\n        Other\n    }\n}\n\n#[cfg(test)]\nmod test {\n    use embedded_hal_nb::serial::{Read, Write};\n    use std::io::{Read as IoRead, Write as IoWrite};\n\n    use super::*;\n\n    fn create_pty_and_serial() -> (std::fs::File, Serial) {\n        let (master, _slave, name) =\n            openpty::openpty(None, None, None).expect(\"Creating pty failed\");\n        let serial = Serial::open(name, 9600).expect(\"Creating TTYPort failed\");\n        (master, serial)\n    }\n\n    #[test]\n    fn create_serial_from_builder() {\n        let (_master, _slave, name) =\n            openpty::openpty(None, None, None).expect(\"Creating pty failed\");\n        let builder = serialport::new(name, 9600);\n        let _serial = Serial::open_from_builder(builder).expect(\"Creating TTYPort failed\");\n    }\n\n    #[test]\n    fn test_empty_read() {\n        let (mut _master, mut serial) = create_pty_and_serial();\n        assert_eq!(Err(nb::Error::WouldBlock), serial.read());\n    }\n\n    #[test]\n    fn test_read() {\n        let (mut master, mut serial) = create_pty_and_serial();\n        master.write_all(&[1]).expect(\"Write failed\");\n        assert_eq!(Ok(1), serial.read());\n    }\n\n    #[test]\n    fn test_write() {\n        let (mut master, mut serial) = create_pty_and_serial();\n        serial.write(2).expect(\"Write failed\");\n        let mut buf = [0; 2];\n        assert_eq!(1, master.read(&mut buf).unwrap());\n        assert_eq!(buf, [2, 0]);\n    }\n}\n"
  },
  {
    "path": "src/spi.rs",
    "content": "//! Implementation of [`embedded-hal`] SPI traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n//!\n\nuse std::cmp::Ordering;\nuse std::fmt;\nuse std::io;\nuse std::ops;\nuse std::path::Path;\n\n/// Spidev wrapper providing the embedded-hal [`SpiDevice`] trait.\n///\n/// Use this struct when you want a single spidev device, using a Linux-managed CS (chip-select) pin,\n/// which is already defined in your device tree. Linux will handle sharing the bus\n/// between different SPI devices, even between different processes.\n///\n/// You get an object that implements [`SpiDevice`], which is what most drivers require,\n/// but does not implement [`SpiBus`]. In some rare cases, you may require [`SpiBus`]\n/// instead; for that refer to [`SpidevBus`] below. You may also want to use [`SpiBus`]\n/// if you want to handle all the CS pins yourself using GPIO.\n///\n/// This struct wraps a [`spidev::Spidev`] struct, so it can be constructed directly\n/// and the inner struct accessed if needed, for example to (re)configure the SPI settings.\n///\n/// Note that [delay operations] on this device are capped to 65535 microseconds.\n///\n/// [`SpiDevice`]: embedded_hal::spi::SpiDevice\n/// [`SpiBus`]: embedded_hal::spi::SpiBus\n/// [`spidev::Spidev`]: spidev::Spidev\n/// [delay operations]: embedded_hal::spi::Operation::DelayUs\npub struct SpidevDevice(pub spidev::Spidev);\n\n/// Spidev wrapper providing the embedded-hal [`SpiBus`] trait.\n///\n/// Use this struct when you require direct access to the underlying SPI bus, for\n/// example when you want to use GPIOs as software-controlled CS (chip-select) pins to share the\n/// bus with multiple devices, or because a driver requires the entire bus (for\n/// example to drive smart LEDs).\n///\n/// Do not use this struct if you're accessing SPI devices that already appear in your\n/// device tree; you will not be able to drive CS pins that are already used by `spidev`\n/// as GPIOs. Instead use [`SpidevDevice`].\n///\n/// This struct must still be created from a [`spidev::Spidev`] device, but there are two\n/// important notes:\n///\n/// 1. The CS pin associated with this `spidev` device will be driven whenever any device accesses\n///    this bus, so it should be an unconnected or unused pin.\n/// 2. No other `spidev` device on the same bus may be used as long as this `SpidevBus` exists,\n///    as Linux will _not_ do anything to ensure this bus has exclusive access.\n///\n/// It is recommended to use a dummy `spidev` device associated with an unused CS pin, and then use\n/// regular GPIOs as CS pins if required. If you are planning to share this bus using GPIOs, the\n/// [`embedded-hal-bus`] crate may be of interest.\n///\n/// If necessary, you can [configure] the underlying [`spidev::Spidev`] instance with the\n/// [`SPI_NO_CS`] flag set to prevent any CS pin activity.\n///\n/// [`SpiDevice`]: embedded_hal::spi::SpiDevice\n/// [`SpiBus`]: embedded_hal::spi::SpiBus\n/// [`embedded-hal-bus`]: https://docs.rs/embedded-hal-bus/\n/// [`spidev::Spidev`]: spidev::Spidev\n/// [delay operations]: embedded_hal::spi::Operation::DelayUs\n/// [configure]: spidev::Spidev::configure\n/// [`SPI_NO_CS`]: spidev::SpiModeFlags::SPI_NO_CS\npub struct SpidevBus(pub spidev::Spidev);\n\nimpl SpidevDevice {\n    /// See [`spidev::Spidev::open`] for details.\n    ///\n    /// The provided `path` is for the specific device you wish to access.\n    /// Access to the bus is shared with other devices via the Linux kernel.\n    pub fn open<P>(path: P) -> Result<Self, SPIError>\n    where\n        P: AsRef<Path>,\n    {\n        spidev::Spidev::open(path)\n            .map(SpidevDevice)\n            .map_err(|e| e.into())\n    }\n}\n\nimpl SpidevBus {\n    /// See [`spidev::Spidev::open`] for details.\n    ///\n    /// The provided `path` must be the _only_ device in use on its bus,\n    /// and note its own CS pin will be asserted for all device access,\n    /// so the path should be to a dummy device used only to access\n    /// the underlying bus.\n    pub fn open<P>(path: P) -> Result<Self, SPIError>\n    where\n        P: AsRef<Path>,\n    {\n        spidev::Spidev::open(path)\n            .map(SpidevBus)\n            .map_err(|e| e.into())\n    }\n}\n\nimpl ops::Deref for SpidevDevice {\n    type Target = spidev::Spidev;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nimpl ops::DerefMut for SpidevDevice {\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        &mut self.0\n    }\n}\n\nimpl ops::Deref for SpidevBus {\n    type Target = spidev::Spidev;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nimpl ops::DerefMut for SpidevBus {\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        &mut self.0\n    }\n}\n\nmod embedded_hal_impl {\n    use super::*;\n    use embedded_hal::spi::ErrorType;\n    use embedded_hal::spi::{Operation as SpiOperation, SpiBus, SpiDevice};\n    use spidev::SpidevTransfer;\n    use std::convert::TryInto;\n    use std::io::{Read, Write};\n\n    impl ErrorType for SpidevDevice {\n        type Error = SPIError;\n    }\n\n    impl ErrorType for SpidevBus {\n        type Error = SPIError;\n    }\n\n    impl SpiBus<u8> for SpidevBus {\n        fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {\n            self.0.read_exact(words).map_err(|err| SPIError { err })\n        }\n\n        fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {\n            self.0.write_all(words).map_err(|err| SPIError { err })\n        }\n\n        fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {\n            let read_len = read.len();\n            match read_len.cmp(&write.len()) {\n                Ordering::Less => self.0.transfer_multiple(&mut [\n                    SpidevTransfer::read_write(&write[..read_len], read),\n                    SpidevTransfer::write(&write[read_len..]),\n                ]),\n                Ordering::Equal => self\n                    .0\n                    .transfer(&mut SpidevTransfer::read_write(write, read)),\n                Ordering::Greater => {\n                    let (read1, read2) = read.split_at_mut(write.len());\n                    self.0.transfer_multiple(&mut [\n                        SpidevTransfer::read_write(write, read1),\n                        SpidevTransfer::read(read2),\n                    ])\n                }\n            }\n            .map_err(|err| SPIError { err })\n        }\n\n        fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {\n            self.0\n                .transfer(&mut SpidevTransfer::read_write_in_place(words))\n                .map_err(|err| SPIError { err })\n        }\n\n        fn flush(&mut self) -> Result<(), Self::Error> {\n            self.0.flush().map_err(|err| SPIError { err })\n        }\n    }\n\n    impl SpiDevice for SpidevDevice {\n        /// Perform a transaction against the device. [Read more][transaction]\n        ///\n        /// [Delay operations][delay] are capped to 65535 microseconds.\n        ///\n        /// [transaction]: SpiDevice::transaction\n        /// [delay]: SpiOperation::DelayUs\n        fn transaction(\n            &mut self,\n            operations: &mut [SpiOperation<'_, u8>],\n        ) -> Result<(), Self::Error> {\n            let mut transfers = Vec::with_capacity(operations.len());\n            for op in operations {\n                match op {\n                    SpiOperation::Read(buf) => transfers.push(SpidevTransfer::read(buf)),\n                    SpiOperation::Write(buf) => transfers.push(SpidevTransfer::write(buf)),\n                    SpiOperation::Transfer(read, write) => match read.len().cmp(&write.len()) {\n                        Ordering::Less => {\n                            let n = read.len();\n                            transfers.push(SpidevTransfer::read_write(&write[..n], read));\n                            transfers.push(SpidevTransfer::write(&write[n..]));\n                        }\n                        Ordering::Equal => transfers.push(SpidevTransfer::read_write(write, read)),\n                        Ordering::Greater => {\n                            let (read1, read2) = read.split_at_mut(write.len());\n                            transfers.push(SpidevTransfer::read_write(write, read1));\n                            transfers.push(SpidevTransfer::read(read2));\n                        }\n                    },\n                    SpiOperation::TransferInPlace(buf) => {\n                        transfers.push(SpidevTransfer::read_write_in_place(buf));\n                    }\n                    SpiOperation::DelayNs(ns) => {\n                        let us = {\n                            if *ns == 0 {\n                                0\n                            } else {\n                                let us = *ns / 1000;\n                                if us == 0 {\n                                    1\n                                } else {\n                                    (us).try_into().unwrap_or(u16::MAX)\n                                }\n                            }\n                        };\n                        transfers.push(SpidevTransfer::delay(us));\n                    }\n                }\n            }\n            self.0\n                .transfer_multiple(&mut transfers)\n                .map_err(|err| SPIError { err })?;\n            self.flush()?;\n            Ok(())\n        }\n    }\n}\n\n/// Error type wrapping [io::Error](io::Error) to implement [embedded_hal::spi::ErrorKind]\n#[derive(Debug)]\npub struct SPIError {\n    err: io::Error,\n}\n\nimpl SPIError {\n    /// Fetch inner (concrete) [`LinuxI2CError`]\n    pub fn inner(&self) -> &io::Error {\n        &self.err\n    }\n}\n\nimpl From<io::Error> for SPIError {\n    fn from(err: io::Error) -> Self {\n        Self { err }\n    }\n}\n\nimpl embedded_hal::spi::Error for SPIError {\n    #[allow(clippy::match_single_binding)]\n    fn kind(&self) -> embedded_hal::spi::ErrorKind {\n        use embedded_hal::spi::ErrorKind;\n        // TODO: match any errors here if we can find any that are relevant\n        ErrorKind::Other\n    }\n}\n\nimpl fmt::Display for SPIError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{}\", self.err)\n    }\n}\n\nimpl std::error::Error for SPIError {\n    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n        Some(&self.err)\n    }\n}\n"
  },
  {
    "path": "src/sysfs_pin.rs",
    "content": "//! Implementation of [`embedded-hal`] digital input/output traits using a Linux Sysfs pin\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse std::fmt;\nuse std::path::Path;\n\n/// Newtype around [`sysfs_gpio::Pin`] that implements the `embedded-hal` traits\n///\n/// [`sysfs_gpio::Pin`]: https://docs.rs/sysfs_gpio/0.6.0/sysfs_gpio/struct.Pin.html\npub struct SysfsPin(pub sysfs_gpio::Pin);\n\nimpl SysfsPin {\n    /// See [`sysfs_gpio::Pin::new`][0] for details.\n    ///\n    /// [0]: https://docs.rs/sysfs_gpio/0.6.0/sysfs_gpio/struct.Pin.html#method.new\n    pub fn new(pin_num: u64) -> Self {\n        SysfsPin(sysfs_gpio::Pin::new(pin_num))\n    }\n\n    /// See [`sysfs_gpio::Pin::from_path`][0] for details.\n    ///\n    /// [0]: https://docs.rs/sysfs_gpio/0.6.0/sysfs_gpio/struct.Pin.html#method.from_path\n    pub fn from_path<P>(path: P) -> sysfs_gpio::Result<Self>\n    where\n        P: AsRef<Path>,\n    {\n        sysfs_gpio::Pin::from_path(path).map(SysfsPin)\n    }\n\n    /// Convert this pin to an input pin\n    pub fn into_input_pin(self) -> Result<SysfsPin, sysfs_gpio::Error> {\n        self.set_direction(sysfs_gpio::Direction::In)?;\n        Ok(self)\n    }\n\n    /// Convert this pin to an output pin\n    pub fn into_output_pin(\n        self,\n        state: embedded_hal::digital::PinState,\n    ) -> Result<SysfsPin, sysfs_gpio::Error> {\n        self.set_direction(match state {\n            embedded_hal::digital::PinState::High => sysfs_gpio::Direction::High,\n            embedded_hal::digital::PinState::Low => sysfs_gpio::Direction::Low,\n        })?;\n        Ok(self)\n    }\n}\n\n/// Error type wrapping [sysfs_gpio::Error](sysfs_gpio::Error) to implement [embedded_hal::digital::Error]\n#[derive(Debug)]\npub struct SysfsPinError {\n    err: sysfs_gpio::Error,\n}\n\nimpl SysfsPinError {\n    /// Fetch inner (concrete) [`sysfs_gpio::Error`]\n    pub fn inner(&self) -> &sysfs_gpio::Error {\n        &self.err\n    }\n}\n\nimpl From<sysfs_gpio::Error> for SysfsPinError {\n    fn from(err: sysfs_gpio::Error) -> Self {\n        Self { err }\n    }\n}\n\nimpl fmt::Display for SysfsPinError {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        write!(f, \"{}\", self.err)\n    }\n}\n\nimpl std::error::Error for SysfsPinError {\n    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n        Some(&self.err)\n    }\n}\n\nimpl embedded_hal::digital::Error for SysfsPinError {\n    fn kind(&self) -> embedded_hal::digital::ErrorKind {\n        use embedded_hal::digital::ErrorKind;\n        ErrorKind::Other\n    }\n}\n\nimpl embedded_hal::digital::ErrorType for SysfsPin {\n    type Error = SysfsPinError;\n}\n\nimpl embedded_hal::digital::OutputPin for SysfsPin {\n    fn set_low(&mut self) -> Result<(), Self::Error> {\n        if self.0.get_active_low().map_err(SysfsPinError::from)? {\n            self.0.set_value(1).map_err(SysfsPinError::from)\n        } else {\n            self.0.set_value(0).map_err(SysfsPinError::from)\n        }\n    }\n\n    fn set_high(&mut self) -> Result<(), Self::Error> {\n        if self.0.get_active_low().map_err(SysfsPinError::from)? {\n            self.0.set_value(0).map_err(SysfsPinError::from)\n        } else {\n            self.0.set_value(1).map_err(SysfsPinError::from)\n        }\n    }\n}\n\nimpl embedded_hal::digital::InputPin for SysfsPin {\n    fn is_high(&mut self) -> Result<bool, Self::Error> {\n        if !self.0.get_active_low().map_err(SysfsPinError::from)? {\n            self.0\n                .get_value()\n                .map(|val| val != 0)\n                .map_err(SysfsPinError::from)\n        } else {\n            self.0\n                .get_value()\n                .map(|val| val == 0)\n                .map_err(SysfsPinError::from)\n        }\n    }\n\n    fn is_low(&mut self) -> Result<bool, Self::Error> {\n        self.is_high().map(|val| !val).map_err(SysfsPinError::from)\n    }\n}\n\nimpl core::ops::Deref for SysfsPin {\n    type Target = sysfs_gpio::Pin;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\nimpl core::ops::DerefMut for SysfsPin {\n    fn deref_mut(&mut self) -> &mut Self::Target {\n        &mut self.0\n    }\n}\n"
  },
  {
    "path": "src/timer.rs",
    "content": "//! Implementation of [`embedded-hal`] timer traits\n//!\n//! [`embedded-hal`]: https://docs.rs/embedded-hal\n\nuse core::convert::Infallible;\nuse std::time::{Duration, Instant};\n\n/// Marker trait that indicates that a timer is periodic\npub trait Periodic {}\n\n/// A count down timer\n///\n/// Note that this is borrowed from `embedded-hal` 0.2.x and will be in use until the `1.x` version provides one.\n///\n/// # Contract\n///\n/// - `self.start(count); block!(self.wait());` MUST block for AT LEAST the time specified by\n///   `count`.\n///\n/// *Note* that the implementer doesn't necessarily have to be a *downcounting* timer; it could also\n/// be an *upcounting* timer as long as the above contract is upheld.\n///\n/// # Examples\n///\n/// You can use this timer to create delays\n///\n/// ```\n/// use std::time::Duration;\n/// use nb::block;\n/// use linux_embedded_hal::{CountDown, SysTimer};\n///\n/// fn main() {\n///     let mut led: Led = {\n///         // ..\n/// #       Led\n///     };\n///     let mut timer = SysTimer::new();\n///\n///     Led.on();\n///     timer.start(Duration::from_millis(1000)).unwrap();\n///     block!(timer.wait()); // blocks for 1 second\n///     Led.off();\n/// }\n///\n/// # use core::convert::Infallible;\n/// # struct Seconds(u32);\n/// # trait U32Ext { fn s(self) -> Seconds; }\n/// # impl U32Ext for u32 { fn s(self) -> Seconds { Seconds(self) } }\n/// # struct Led;\n/// # impl Led {\n/// #     pub fn off(&mut self) {}\n/// #     pub fn on(&mut self) {}\n/// # }\n/// ```\npub trait CountDown {\n    /// An enumeration of `CountDown` errors.\n    ///\n    /// For infallible implementations, will be `Infallible`\n    type Error: core::fmt::Debug;\n\n    /// The unit of time used by this timer\n    type Time;\n\n    /// Starts a new count down\n    fn start<T>(&mut self, count: T) -> Result<(), Self::Error>\n    where\n        T: Into<Self::Time>;\n\n    /// Non-blockingly \"waits\" until the count down finishes\n    ///\n    /// # Contract\n    ///\n    /// - If `Self: Periodic`, the timer will start a new count down right after the last one\n    ///   finishes.\n    /// - Otherwise the behavior of calling `wait` after the last call returned `Ok` is UNSPECIFIED.\n    ///   Implementers are suggested to panic on this scenario to signal a programmer error.\n    fn wait(&mut self) -> nb::Result<(), Self::Error>;\n}\n\nimpl<T: CountDown> CountDown for &mut T {\n    type Error = T::Error;\n\n    type Time = T::Time;\n\n    fn start<TIME>(&mut self, count: TIME) -> Result<(), Self::Error>\n    where\n        TIME: Into<Self::Time>,\n    {\n        T::start(self, count)\n    }\n\n    fn wait(&mut self) -> nb::Result<(), Self::Error> {\n        T::wait(self)\n    }\n}\n\n/// A periodic timer based on [`std::time::Instant`][instant], which is a\n/// monotonically nondecreasing clock.\n///\n/// [instant]: https://doc.rust-lang.org/std/time/struct.Instant.html\npub struct SysTimer {\n    start: Instant,\n    duration: Duration,\n}\n\nimpl SysTimer {\n    /// Create a new timer instance.\n    ///\n    /// The `duration` will be initialized to 0, so make sure to call `start`\n    /// with your desired timer duration before calling `wait`.\n    pub fn new() -> SysTimer {\n        SysTimer {\n            start: Instant::now(),\n            duration: Duration::from_millis(0),\n        }\n    }\n}\n\nimpl Default for SysTimer {\n    fn default() -> SysTimer {\n        SysTimer::new()\n    }\n}\n\nimpl CountDown for SysTimer {\n    type Error = Infallible;\n    type Time = Duration;\n\n    fn start<T>(&mut self, count: T) -> Result<(), Self::Error>\n    where\n        T: Into<Self::Time>,\n    {\n        self.start = Instant::now();\n        self.duration = count.into();\n        Ok(())\n    }\n\n    fn wait(&mut self) -> nb::Result<(), Self::Error> {\n        if (Instant::now() - self.start) >= self.duration {\n            // Restart the timer to fulfill the contract by `Periodic`\n            self.start = Instant::now();\n            Ok(())\n        } else {\n            Err(nb::Error::WouldBlock)\n        }\n    }\n}\n\nimpl Periodic for SysTimer {}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    /// Ensure that a 100 ms delay takes at least 100 ms,\n    /// but not longer than 500 ms.\n    #[test]\n    fn test_delay() {\n        let mut timer = SysTimer::new();\n        let before = Instant::now();\n        timer.start(Duration::from_millis(100)).unwrap();\n        nb::block!(timer.wait()).unwrap();\n        let after = Instant::now();\n        let duration_ms = (after - before).as_millis();\n        assert!(duration_ms >= 100);\n        assert!(duration_ms < 500);\n    }\n\n    /// Ensure that the timer is periodic.\n    #[test]\n    fn test_periodic() {\n        let mut timer = SysTimer::new();\n        let before = Instant::now();\n        timer.start(Duration::from_millis(100)).unwrap();\n        nb::block!(timer.wait()).unwrap();\n        let after1 = Instant::now();\n        let duration_ms_1 = (after1 - before).as_millis();\n        assert!(duration_ms_1 >= 100);\n        assert!(duration_ms_1 < 500);\n        nb::block!(timer.wait()).unwrap();\n        let after2 = Instant::now();\n        let duration_ms_2 = (after2 - after1).as_millis();\n        assert!(duration_ms_2 >= 100);\n        assert!(duration_ms_2 < 500);\n    }\n}\n"
  }
]