├── .github ├── FUNDING.yml ├── dependabot.yml ├── release-drafter.yml └── workflows │ ├── hacs.yml │ ├── hassfest.yml │ ├── release-drafter.yml │ ├── stale.yaml │ └── test.yml ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── README.md ├── bandit.yaml ├── custom_components └── rpi_gpio │ ├── __init__.py │ ├── binary_sensor.py │ ├── const.py │ ├── cover.py │ ├── hub.py │ ├── manifest.json │ ├── services.yaml │ └── switch.py ├── hacs.json ├── pylintrc └── requirements_lint.txt /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ['https://paypal.me/levyshay'] 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: daily 12 | open-pull-requests-limit: 10 13 | - package-ecosystem: "pip" 14 | directory: "/" # Location of package manifests 15 | schedule: 16 | interval: "weekly" 17 | open-pull-requests-limit: 10 18 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | change-template: "- #$NUMBER - $TITLE (@$AUTHOR)" 2 | categories: 3 | - title: "⚠ Breaking Changes" 4 | labels: 5 | - "breaking-change" 6 | - title: "⬆️ Dependencies" 7 | collapse-after: 1 8 | labels: 9 | - "dependencies" 10 | template: | 11 | ## What’s Changed 12 | 13 | $CHANGES 14 | -------------------------------------------------------------------------------- /.github/workflows/hacs.yml: -------------------------------------------------------------------------------- 1 | name: HACS Action 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | schedule: 11 | - cron: "0 0 * * *" 12 | 13 | jobs: 14 | hacs: 15 | name: HACS Action 16 | runs-on: "ubuntu-latest" 17 | steps: 18 | - uses: "actions/checkout@v4.2.2" 19 | - name: HACS Action 20 | uses: "hacs/action@main" 21 | with: 22 | category: "integration" 23 | -------------------------------------------------------------------------------- /.github/workflows/hassfest.yml: -------------------------------------------------------------------------------- 1 | name: Validate with hassfest 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * *" 8 | 9 | jobs: 10 | validate: 11 | runs-on: "ubuntu-latest" 12 | steps: 13 | - uses: "actions/checkout@v4.2.2" 14 | - uses: "home-assistant/actions/hassfest@master" 15 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | # Drafts your next Release notes as Pull Requests are merged into "main" 13 | - uses: release-drafter/release-drafter@v6 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | -------------------------------------------------------------------------------- /.github/workflows/stale.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Stale 3 | 4 | # yamllint disable-line rule:truthy 5 | on: 6 | schedule: 7 | - cron: "0 8 * * *" 8 | workflow_call: 9 | workflow_dispatch: 10 | 11 | jobs: 12 | stale: 13 | name: 🧹 Clean up stale issues and PRs 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: 🚀 Run stale 17 | uses: actions/stale@v9.1.0 18 | with: 19 | repo-token: ${{ secrets.GITHUB_TOKEN }} 20 | days-before-stale: 14 21 | days-before-close: 7 22 | remove-stale-when-updated: true 23 | stale-issue-label: "stale" 24 | exempt-issue-labels: "no-stale,help-wanted" 25 | stale-issue-message: > 26 | There hasn't been any activity on this issue recently, so we 27 | clean up some of the older and inactive issues. 28 | 29 | Please make sure to update to the latest version and 30 | check if that solves the issue. Let us know if that works for you 31 | by leaving a comment 👍 32 | 33 | This issue has now been marked as stale and will be closed if no 34 | further activity occurs. Thanks! 35 | stale-pr-label: "stale" 36 | exempt-pr-labels: "no-stale" 37 | stale-pr-message: > 38 | There hasn't been any activity on this pull request recently. This 39 | pull request has been automatically marked as stale because of that 40 | and will be closed if no further activity occurs within 7 days. 41 | Thank you for your contributions. 42 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Test 5 | 6 | on: 7 | push: 8 | branches: [main] 9 | pull_request: 10 | branches: [main] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | python-version: 18 | - "3.9" 19 | - "3.10" 20 | 21 | steps: 22 | - uses: actions/checkout@v4.2.2 23 | with: 24 | fetch-depth: 2 25 | - name: Set up Python ${{ matrix.python-version }} 26 | uses: actions/setup-python@v5.6.0 27 | with: 28 | python-version: ${{ matrix.python-version }} 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install -r requirements_lint.txt 33 | - name: Lint 34 | run: pre-commit run 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Hide sublime text stuff 2 | *.sublime-project 3 | *.sublime-workspace 4 | 5 | # Hide some OS X stuff 6 | .DS_Store 7 | .AppleDouble 8 | .LSOverride 9 | Icon 10 | 11 | # Thumbnails 12 | ._* 13 | 14 | # IntelliJ IDEA 15 | .idea 16 | *.iml 17 | 18 | # pytest 19 | .pytest_cache 20 | .cache 21 | 22 | # GITHUB Proposed Python stuff: 23 | *.py[cod] 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Packages 29 | *.egg 30 | *.egg-info 31 | dist 32 | build 33 | eggs 34 | .eggs 35 | parts 36 | bin 37 | var 38 | sdist 39 | develop-eggs 40 | .installed.cfg 41 | lib 42 | lib64 43 | pip-wheel-metadata 44 | 45 | # Logs 46 | *.log 47 | pip-log.txt 48 | 49 | # Unit test / coverage reports 50 | .coverage 51 | .tox 52 | coverage.xml 53 | nosetests.xml 54 | htmlcov/ 55 | test-reports/ 56 | test-results.xml 57 | test-output.xml 58 | 59 | # Translations 60 | *.mo 61 | 62 | # Mr Developer 63 | .mr.developer.cfg 64 | .project 65 | .pydevproject 66 | 67 | .python-version 68 | 69 | # emacs auto backups 70 | *~ 71 | *# 72 | *.orig 73 | 74 | # venv stuff 75 | pyvenv.cfg 76 | pip-selfcheck.json 77 | venv 78 | .venv 79 | Pipfile* 80 | share/* 81 | Scripts/ 82 | 83 | # vimmy stuff 84 | *.swp 85 | *.swo 86 | tags 87 | ctags.tmp 88 | 89 | # vagrant stuff 90 | virtualization/vagrant/setup_done 91 | virtualization/vagrant/.vagrant 92 | virtualization/vagrant/config 93 | 94 | # Visual Studio Code 95 | .vscode/* 96 | !.vscode/cSpell.json 97 | !.vscode/extensions.json 98 | !.vscode/tasks.json 99 | 100 | # Typing 101 | .mypy_cache 102 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v4.4.0 4 | hooks: 5 | - id: trailing-whitespace 6 | - id: end-of-file-fixer 7 | - id: check-docstring-first 8 | - id: check-yaml 9 | - id: debug-statements 10 | - repo: https://github.com/PyCQA/flake8 11 | rev: 6.0.0 12 | hooks: 13 | - id: flake8 14 | args: 15 | - --max-line-length=500 16 | - --ignore=E203,E266,E501,W503 17 | - --max-complexity=18 18 | - --select=B,C,E,F,W,T4,B9 19 | - repo: https://github.com/ambv/black 20 | rev: 23.1.0 21 | hooks: 22 | - id: black 23 | language_version: python3 24 | - repo: https://github.com/asottile/pyupgrade 25 | rev: v3.3.1 26 | hooks: 27 | - id: pyupgrade 28 | args: ["--py39-plus"] 29 | - repo: https://github.com/PyCQA/isort 30 | rev: 5.12.0 31 | hooks: 32 | - id: isort 33 | args: 34 | - --multi-line=3 35 | - --trailing-comma 36 | - --force-grid-wrap=0 37 | - --use-parentheses 38 | - --line-width=88 39 | - -p=homeassistant 40 | - --force-sort-within-sections 41 | - repo: https://github.com/PyCQA/pydocstyle 42 | rev: 6.3.0 43 | hooks: 44 | - id: pydocstyle 45 | - repo: https://github.com/pre-commit/mirrors-mypy 46 | rev: "v0.991" 47 | hooks: 48 | - id: mypy 49 | - repo: https://github.com/codespell-project/codespell 50 | rev: v2.2.2 51 | hooks: 52 | - id: codespell 53 | args: 54 | - --ignore-words-list=hass 55 | - --skip="./.*,*.csv,*.json" 56 | - --quiet-level=2 57 | exclude_types: [csv, json] 58 | - repo: https://github.com/PyCQA/bandit 59 | rev: 1.7.4 60 | hooks: 61 | - id: bandit 62 | args: 63 | - --quiet 64 | - --format=custom 65 | - --configfile=bandit.yaml 66 | files: ^custom_components/.+\.py$ 67 | - repo: https://github.com/pre-commit/mirrors-prettier 68 | rev: v2.7.1 69 | hooks: 70 | - id: prettier 71 | stages: [manual] 72 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Home Assistant Raspberry Pi GPIO custom integration 2 | 3 | **This is a spin-off from the original Home Assistant integration, which was removed in Home Assistant Core version 2022.6.** 4 | 5 | The `rpi_gpio` integration supports the following platforms: `Binary Sensor`, `Cover`, `Switch` 6 | 7 | `rpi_gpio` is based on `gpiod` in [ha-gpio](https://codeberg.org/raboof/ha-gpio) and `ha_gpiod` in [ha_gpiod](https://github.com/jdeneef/ha_gpiod) 8 | 9 | # Installation 10 | 11 | ### HACS 12 | 13 | The recommend way to install `rpi_gpio` is through [HACS](https://hacs.xyz/). 14 | 15 | ### Manual installation 16 | 17 | Copy the `rpi_gpio` folder and all of its contents into your Home Assistant's `custom_components` folder. This folder is usually inside your `/config` folder. If you are running Hass.io, use SAMBA to copy the folder over. You may need to create the `custom_components` folder and then copy the `rpi_gpio` folder and all of its contents into it. 18 | 19 | # Usage 20 | 21 | The `rpi_gpio` platform will be initialized using the path to the gpio chip. When path is not in the config `/dev/gpiochip[0-5]` are tested for a gpiodevice having `pinctrl`, in sequence `[0,4,1,2,3,5]`. So with a raspberry pi you should be OK to leave the path empty. 22 | 23 | Raspberry Pi | GPIO Device 24 | --- | --- 25 | RPi3, RPi4 | `/dev/gpiochip0` 26 | RPi5 | `/dev/gpiochip4` 27 | 28 | ```yaml 29 | # setup gpiod chip; mostly not required 30 | rpi_gpio: 31 | path: '/dev/gpiochip0' 32 | ``` 33 | 34 | ### Options 35 | 36 | Key | Required | Default | Type | Description 37 | --- | --- | --- | --- | --- 38 | `gpiod` | only for path|- |- | `gpiod` platform config and initialization, only required when you need to specify a specific gpiodevice path (see path) 39 | `path` | no | discovered | string | path to gpio device, if not set auto discovered 40 | 41 | ## Binary Sensor 42 | 43 | The `rpi_gpio` binary sensor platform allows you to read sensor values of the GPIOs of your [Raspberry Pi](https://www.raspberrypi.org/). 44 | 45 | ### Configuration 46 | 47 | To use your Raspberry Pi's GPIO in your installation, add the following to your `configuration.yaml` file: 48 | 49 | ```yaml 50 | # Basic configuration.yaml entry 51 | binary_sensor: 52 | - platform: rpi_gpio 53 | sensors: 54 | - port: 11 55 | name: "PIR Office" 56 | - port: 12 57 | name: "PIR Bedroom" 58 | ``` 59 | 60 | ```yaml 61 | # Full configuration.yaml entry 62 | binary_sensor: 63 | - platform: rpi_gpio 64 | sensors: 65 | - port: 11 66 | name: "PIR Office" 67 | unique_id: "pir_office_sensor_port_11" 68 | bouncetime: 80 69 | invert_logic: true 70 | pull_mode: "DOWN" 71 | - port: 12 72 | name: "PIR Bedroom" 73 | unique_id: "pir_bedroom_sensor_port_12" 74 | ``` 75 | 76 | ### Options 77 | 78 | | Key | Required | Default | Type | Description | 79 | | -------------- | -------- | --------------------- | --------|------------------------------------------------------------------------------------------------------------ | 80 | | `sensors` | yes | | list | List of sensor IO ports ([BCM mode pin numbers](https://pinout.xyz/resources/raspberry-pi-pinout.png)) | 81 | | `name` | yes | | string | The name for the binary sensor entity | 82 | | `port` | yes | | integer | the GPIO port to be used | 83 | | `unique_id` | no | | string | An ID that uniquely identifies the sensor. Set this to a unique value to allow customization through the UI | 84 | | `bouncetime` | no | `50` | integer | The time in milliseconds for port debouncing | 85 | | `invert_logic` | no | `false` (ACTIVE HIGH) | boolean | If `true`, inverts the output logic to ACTIVE LOW | 86 | | `pull_mode` | no | `UP` | string | control bias setting of GPIO, used to define the electrical state of a GPIO line when not actively driven; `UP` set weak pull-up resistor on the line, ensuring that the line is pulled to a high level (3.3V or 5V) when not actively driven; `DOWN` sets weak pull-down resistor to pull to low level (0V), `DISABLED` remains floating, `AS_IS` not changed | 87 | 88 | For more details about the GPIO layout, visit the Wikipedia [article](https://en.wikipedia.org/wiki/Raspberry_Pi#General_purpose_input-output_(GPIO)_connector) about the Raspberry Pi. 89 | 90 | ## Cover 91 | 92 | The `rpi_gpio` cover platform allows you to use a Raspberry Pi to control your cover such as Garage doors. 93 | 94 | It uses two pins on the Raspberry Pi. 95 | 96 | - The `state_pin` will detect if the cover is closed, and 97 | - the `relay_pin` will trigger the cover to open or close. 98 | 99 | Although you do not need Andrews Hilliday's software controller when you run Home Assistant, he has written clear instructions on how to hook your garage door and sensors up to your Raspberry Pi, which can be found [here](https://github.com/andrewshilliday/garage-door-controller#hardware-setup). 100 | 101 | ### Configuration 102 | 103 | To enable Raspberry Pi Covers in your installation, add the following to your `configuration.yaml` file: 104 | 105 | ```yaml 106 | # Basic configuration.yaml entry 107 | cover: 108 | - platform: rpi_gpio 109 | covers: 110 | - relay_pin: 10 111 | state_pin: 11 112 | ``` 113 | 114 | ```yaml 115 | # Full configuration.yaml entry 116 | cover: 117 | - platform: rpi_gpio 118 | relay_time: 0.2 119 | invert_relay: false 120 | state_pull_mode: "UP" 121 | invert_state: true 122 | covers: 123 | - relay_pin: 10 124 | state_pin: 11 125 | name: "Left door" 126 | unique_id: "left_door_cover_port_11" 127 | - relay_pin: 12 128 | state_pin: 13 129 | name: "Right door" 130 | unique_id: "right_door_cover_port_13" 131 | ``` 132 | 133 | ### Options 134 | 135 | | Key | Required | Default | Type | Description | 136 | | ----------------- | -------- | ------- | ------- | ---------------------------------------------------------------------------------------------------------- | 137 | | `relay_time` | no | `0.2` | float | The time that the relay will be on for in seconds | 138 | | `invert_relay` | no | `false` | boolean | Invert the relay pin output so that it is active-high (True) | 139 | | `state_pull_mode` | no | `UP` | string | The direction the State pin is pulling. It can be `UP` or `DOWN` | 140 | | `invert_state` | no | `false` | boolean | Invert the value of the State pin so that 0 means closed | 141 | | `covers` | yes | | list | List of covers | 142 | | `relay_pin` | yes | | integer | The pin of your Raspberry Pi where the relay is connected | 143 | | `state_pin` | yes | | integer | The pin of your Raspberry Pi to retrieve the state | 144 | | `name` | no | | string | The name for the cover entity | 145 | | `unique_id` | no | | string | An ID that uniquely identifies the cover. Set this to a unique value to allow customization through the UI | 146 | 147 | ### Remote Raspberry Pi Cover 148 | 149 | If you don't have Home Assistant running on your Raspberry Pi and you want to use it as a remote cover instead, there is a project called [GarageQTPi](https://github.com/Jerrkawz/GarageQTPi) that will work remotely with the [MQTT Cover Component](/integrations/cover.mqtt/). Follow the GitHub instructions to install and configure GarageQTPi and once configured follow the Home Assistant instructions to configure the MQTT Cover. 150 | 151 | ## Switch 152 | 153 | The `rpi_gpio` switch platform allows you to control the GPIOs of your [Raspberry Pi](https://www.raspberrypi.org/). 154 | 155 | ### Configuration 156 | 157 | To use your Raspberry Pi's GPIO in your installation, add the following to your `configuration.yaml` file: 158 | 159 | ```yaml 160 | # Basic configuration.yaml entry 161 | switch: 162 | - platform: rpi_gpio 163 | switches: 164 | - port: 11 165 | name: "Fan Office" 166 | - port: 12 167 | name: "Light Desk" 168 | ``` 169 | 170 | ```yaml 171 | # Full configuration.yaml entry 172 | switch: 173 | - platform: rpi_gpio 174 | switches: 175 | - port: 11 176 | name: "Fan Office" 177 | unique_id: "fan_office_switch_port_11" 178 | persistent: true 179 | - port: 12 180 | name: "Light Desk" 181 | unique_id: "light_desk_switch_port_12" 182 | invert_logic: true 183 | ``` 184 | 185 | ### Options 186 | 187 | | Key | Required | Default | Type | Description | 188 | | -------------- | -------- | ------- | --------| ----------------------------------------------------------------------------------------------------------- | 189 | | `switches` | yes | | list | List of switch IO ports ([BCM mode pin numbers](https://pinout.xyz/resources/raspberry-pi-pinout.png)) | 190 | | `name` | yes | | string | The name for the switch entity | 191 | | `port` | yes | | integer | the GPIO port to be used | 192 | | `unique_id` | no | | string | An ID that uniquely identifies the switch. Set this to a unique value to allow customization through the UI, auto generated when not set manually in config | 193 | | `invert_logic` | no | `false` | boolean | If true, inverts the output logic to ACTIVE LOW | 194 | | `persistent` | no | `false` | boolean | If true, the switch state will be persistent in HA and will be restored if HA restart / crash | 195 | | `pull_mode` | no | `AS_IS` | string | Type of internal pull resistor to use: `UP` - pull-up resistor, `DOWN` - pull-down resistor, `AS-IS` no change | 196 | | `drive` |no | `PUSH_PULL`|string | control drive configuration of the GPIO, determines how the line behaves when it is set to output mode; `PUSH_PULL`, GPIO line can both source and sink current, can actively drive the line to both high and low states. `OPEN-DRAIN`, GPPIO can only sink current (drive the line to low) and is otherwise left floating, and `OPEN-SOURCE` the reverse. 197 | 198 | For more details about the GPIO layout, visit the Wikipedia [article](https://en.wikipedia.org/wiki/Raspberry_Pi#General_purpose_input-output_(GPIO)_connector) about the Raspberry Pi. 199 | 200 | A common question is what does Port refer to, this number is the actual GPIO #, not the pin #. 201 | For example, if you have a relay connected to pin 11 its GPIO # is 17. 202 | 203 | ```yaml 204 | # Basic configuration.yaml entry 205 | switch: 206 | - platform: rpi_gpio 207 | switches: 208 | - port: 17 209 | name: "Speaker Relay" 210 | ``` 211 | 212 | # Reporting issues 213 | *Before* reporting issues please enable debug logging as described [here](https://www.home-assistant.io/docs/configuration/troubleshooting/#enabling-debug-logging), check logs and report issue attaching the log file and the relevant YAML section. 214 | -------------------------------------------------------------------------------- /bandit.yaml: -------------------------------------------------------------------------------- 1 | # https://bandit.readthedocs.io/en/latest/config.html 2 | 3 | tests: 4 | - B103 5 | - B108 6 | - B306 7 | - B307 8 | - B313 9 | - B314 10 | - B315 11 | - B316 12 | - B317 13 | - B318 14 | - B319 15 | - B320 16 | - B325 17 | - B601 18 | - B602 19 | - B604 20 | - B608 21 | - B609 22 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/__init__.py: -------------------------------------------------------------------------------- 1 | """Support for controlling GPIO pins of a device.""" 2 | 3 | import logging 4 | _LOGGER = logging.getLogger(__name__) 5 | 6 | from homeassistant.core import HomeAssistant 7 | from homeassistant.helpers.typing import ConfigType 8 | 9 | from .const import DOMAIN 10 | from .hub import Hub 11 | 12 | import voluptuous as vol 13 | import homeassistant.helpers.config_validation as cv 14 | 15 | from homeassistant.const import CONF_PATH 16 | 17 | CONFIG_SCHEMA = vol.Schema( 18 | { 19 | DOMAIN: vol.Schema({ 20 | vol.Optional(CONF_PATH): vol.All(cv.string, vol.PathExists()) 21 | }) 22 | }, 23 | extra=vol.ALLOW_EXTRA 24 | ) 25 | 26 | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: 27 | """Set up the GPIO component.""" 28 | version = getattr(hass.data["integrations"][DOMAIN], "version", 0) 29 | _LOGGER.debug(f"{DOMAIN} integration starting. Version: {version}") 30 | path = config.get(DOMAIN, {}).get(CONF_PATH) 31 | hub = Hub(hass, path) 32 | hass.data[DOMAIN] = hub 33 | 34 | return True 35 | 36 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/binary_sensor.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from . import DOMAIN 4 | 5 | import logging 6 | _LOGGER = logging.getLogger(__name__) 7 | 8 | from homeassistant.core import HomeAssistant 9 | from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType 10 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 11 | from homeassistant.helpers.config_validation import PLATFORM_SCHEMA 12 | from homeassistant.components.binary_sensor import BinarySensorEntity 13 | from homeassistant.const import CONF_SENSORS, CONF_NAME, CONF_PORT, CONF_UNIQUE_ID 14 | from .hub import BIAS 15 | 16 | CONF_INVERT_LOGIC = "invert_logic" 17 | DEFAULT_INVERT_LOGIC = False 18 | CONF_BOUNCETIME = "bouncetime" 19 | DEFAULT_BOUNCETIME = 50 20 | CONF_PULL_MODE = "pull_mode" 21 | DEFAULT_PULL_MODE = "UP" 22 | 23 | import homeassistant.helpers.config_validation as cv 24 | import voluptuous as vol 25 | 26 | PLATFORM_SCHEMA = vol.All( 27 | PLATFORM_SCHEMA.extend({ 28 | vol.Exclusive(CONF_SENSORS, CONF_SENSORS): vol.All( 29 | cv.ensure_list, [{ 30 | vol.Required(CONF_NAME): cv.string, 31 | vol.Required(CONF_PORT): cv.positive_int, 32 | vol.Optional(CONF_PULL_MODE, default=DEFAULT_PULL_MODE): cv.string, 33 | vol.Optional(CONF_BOUNCETIME, default=DEFAULT_BOUNCETIME): cv.positive_int, 34 | vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, 35 | vol.Optional(CONF_UNIQUE_ID): cv.string, 36 | }] 37 | ) 38 | }) 39 | ) 40 | 41 | 42 | async def async_setup_platform( 43 | hass: HomeAssistant, 44 | config: ConfigType, 45 | async_add_entities: AddEntitiesCallback, 46 | discovery_info: DiscoveryInfoType | None = None) -> None: 47 | 48 | _LOGGER.debug(f"setup_platform: {config}") 49 | hub = hass.data[DOMAIN] 50 | if not hub._online: 51 | _LOGGER.error("hub not online, bailing out") 52 | 53 | sensors = [] 54 | for sensor in config.get(CONF_SENSORS): 55 | try: 56 | sensors.append( 57 | GPIODBinarySensor( 58 | hub, 59 | sensor[CONF_NAME], 60 | sensor[CONF_PORT], 61 | sensor.get(CONF_UNIQUE_ID) or f"{DOMAIN}_{sensor[CONF_PORT]}_{sensor[CONF_NAME].lower().replace(' ', '_')}", 62 | sensor.get(CONF_INVERT_LOGIC), 63 | sensor.get(CONF_PULL_MODE), 64 | sensor.get(CONF_BOUNCETIME) 65 | ) 66 | ) 67 | except Exception as e: 68 | _LOGGER.error(f"Failed to add binary sensor {sensor[CONF_NAME]} for port {sensor[CONF_PORT]}: {e}") 69 | 70 | async_add_entities(sensors) 71 | 72 | 73 | class GPIODBinarySensor(BinarySensorEntity): 74 | _attr_should_poll = False 75 | 76 | def __init__(self, hub, name, port, unique_id, active_low, bias, debounce): 77 | _LOGGER.debug(f"GPIODBinarySensor init: {port} - {name} - {unique_id}") 78 | self._hub = hub 79 | self._attr_name = name 80 | self._attr_unique_id = unique_id 81 | self._port = port 82 | self._active_low = active_low 83 | self._bias = bias 84 | self._debounce = debounce 85 | self._line, current_is_on = self._hub.add_sensor(self._port, self._active_low, self._bias, self._debounce) 86 | self._attr_is_on = current_is_on 87 | 88 | async def async_added_to_hass(self) -> None: 89 | await super().async_added_to_hass() 90 | _LOGGER.debug(f"GPIODBinarySensor async_added_to_hass: Adding fd:{self._line.fd}") 91 | self._hub._hass.loop.add_reader(self._line.fd, self.handle_event) 92 | 93 | async def async_will_remove_from_hass(self) -> None: 94 | await super().async_will_remove_from_hass() 95 | _LOGGER.debug(f"GPIODBinarySensor async_will_remove_from_hass: Removing fd:{self._line.fd}") 96 | self._hub._hass.loop.remove_reader(self._line.fd) 97 | self._line.release() 98 | 99 | def handle_event(self): 100 | for event in self._line.read_edge_events(): 101 | self._attr_is_on = True if event.event_type is event.Type.RISING_EDGE else False 102 | _LOGGER.debug(f"Event: {event}. New line value: {self._attr_is_on}") 103 | self.schedule_update_ha_state(False) 104 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/const.py: -------------------------------------------------------------------------------- 1 | 2 | DOMAIN = "rpi_gpio" 3 | 4 | 5 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/cover.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | from functools import cached_property 3 | 4 | from . import DOMAIN 5 | 6 | from time import sleep 7 | 8 | import logging 9 | _LOGGER = logging.getLogger(__name__) 10 | 11 | from homeassistant.core import HomeAssistant 12 | from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType 13 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 14 | from homeassistant.helpers.config_validation import PLATFORM_SCHEMA 15 | from homeassistant.components.cover import CoverEntity 16 | from homeassistant.const import CONF_COVERS, CONF_NAME, CONF_UNIQUE_ID 17 | from .hub import BIAS, DRIVE 18 | import homeassistant.helpers.config_validation as cv 19 | import voluptuous as vol 20 | import asyncio 21 | 22 | CONF_RELAY_PIN = "relay_pin" 23 | CONF_RELAY_TIME = "relay_time" 24 | CONF_STATE_PIN = "state_pin" 25 | CONF_STATE_PULL_MODE = "state_pull_mode" 26 | CONF_INVERT_STATE = "invert_state" 27 | CONF_INVERT_RELAY = "invert_relay" 28 | DEFAULT_RELAY_TIME = 0.2 29 | DEFAULT_STATE_PULL_MODE = "UP" 30 | DEFAULT_INVERT_STATE = False 31 | DEFAULT_INVERT_RELAY = False 32 | 33 | _COVERS_SCHEMA = vol.All( 34 | cv.ensure_list, 35 | [ 36 | vol.Schema( 37 | { 38 | CONF_NAME: cv.string, 39 | CONF_RELAY_PIN: cv.positive_int, 40 | CONF_STATE_PIN: cv.positive_int, 41 | vol.Optional(CONF_UNIQUE_ID): cv.string, 42 | } 43 | ) 44 | ], 45 | ) 46 | 47 | PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( 48 | { 49 | vol.Required(CONF_COVERS): _COVERS_SCHEMA, 50 | vol.Optional(CONF_STATE_PULL_MODE, default=DEFAULT_STATE_PULL_MODE): cv.string, 51 | vol.Optional(CONF_RELAY_TIME, default=DEFAULT_RELAY_TIME): cv.positive_int, 52 | vol.Optional(CONF_INVERT_STATE, default=DEFAULT_INVERT_STATE): cv.boolean, 53 | vol.Optional(CONF_INVERT_RELAY, default=DEFAULT_INVERT_RELAY): cv.boolean, 54 | } 55 | ) 56 | 57 | async def async_setup_platform( 58 | hass: HomeAssistant, 59 | config: ConfigType, 60 | async_add_entities: AddEntitiesCallback, 61 | discovery_info: DiscoveryInfoType | None = None) -> None: 62 | 63 | _LOGGER.debug(f"setup_platform: {config}") 64 | hub = hass.data[DOMAIN] 65 | if not hub._online: 66 | _LOGGER.error("hub not online, bailing out") 67 | 68 | relay_time = config[CONF_RELAY_TIME] 69 | state_pull_mode = config[CONF_STATE_PULL_MODE] 70 | invert_state = config[CONF_INVERT_STATE] 71 | invert_relay = config[CONF_INVERT_RELAY] 72 | covers = [] 73 | for cover in config.get(CONF_COVERS): 74 | try: 75 | covers.append( 76 | GPIODCover( 77 | hub, 78 | cover[CONF_NAME], 79 | cover.get(CONF_RELAY_PIN), 80 | relay_time, 81 | invert_relay, 82 | "AS_IS", 83 | "PUSH_PULL", 84 | cover.get(CONF_STATE_PIN), 85 | state_pull_mode, 86 | invert_state, 87 | cover.get(CONF_UNIQUE_ID) or f"{DOMAIN}_{cover.get(CONF_RELAY_PIN)}_{cover[CONF_NAME].lower().replace(' ', '_')}", 88 | ) 89 | ) 90 | except Exception as e: 91 | _LOGGER.error(f"Failed to add cover {cover[CONF_NAME]} for port {cover.get(CONF_RELAY_PIN)}:{cover.get(CONF_STATE_PIN)}: {e}") 92 | 93 | async_add_entities(covers) 94 | 95 | class GPIODCover(CoverEntity): 96 | _attr_should_poll = False 97 | 98 | def __init__(self, hub, name, relay_port, relay_time, relay_active_low, relay_bias, relay_drive, 99 | state_port, state_bias, state_active_low, unique_id): 100 | _LOGGER.debug(f"GPIODCover init: {relay_port}:{state_port} - {name} - {unique_id} - {relay_time}") 101 | self._hub = hub 102 | self._attr_name = name 103 | self._attr_unique_id = unique_id 104 | self._relay_port = relay_port 105 | self._relay_time = relay_time 106 | self._relay_active_low = relay_active_low 107 | self._relay_bias = relay_bias 108 | self._relay_drive = relay_drive 109 | self._state_port = state_port 110 | self._state_bias = state_bias 111 | self._state_active_low = state_active_low 112 | self._relay_line, self._state_line, current_is_on = self._hub.add_cover( 113 | self._relay_port, self._relay_active_low, self._relay_bias, self._relay_drive, 114 | self._state_port, self._state_bias, self._state_active_low) 115 | self._attr_is_closed = current_is_on 116 | self.is_on = current_is_on 117 | 118 | async def async_added_to_hass(self) -> None: 119 | await super().async_added_to_hass() 120 | _LOGGER.debug(f"GPIODCover async_added_to_hass: Adding fd:{self._state_line.fd}") 121 | self._hub._hass.loop.add_reader(self._state_line.fd, self.handle_event) 122 | 123 | async def async_will_remove_from_hass(self) -> None: 124 | await super().async_will_remove_from_hass() 125 | _LOGGER.debug(f"GPIODCover async_will_remove_from_hass: Removing fd:{self._state_line.fd}") 126 | self._hub._hass.loop.remove_reader(self._state_line.fd) 127 | self._relay_line.release() 128 | self._state_line.release() 129 | 130 | def handle_event(self): 131 | for event in self._state_line.read_edge_events(): 132 | self._attr_is_closed = True if event.event_type is event.Type.RISING_EDGE else False 133 | _LOGGER.debug(f"Event: {event}. New _attr_is_closed value: {self._attr_is_closed}") 134 | self.schedule_update_ha_state(False) 135 | 136 | async def async_close_cover(self, **kwargs): 137 | _LOGGER.debug(f"GPIODCover async_close_cover: is_closed: {self.is_closed}. is_closing: {self.is_closing}, is_opening: {self.is_opening}") 138 | if self.is_closed: 139 | return 140 | self._hub.turn_on(self._relay_line, self._relay_port) 141 | self._attr_is_closing = True 142 | self.async_write_ha_state() 143 | await asyncio.sleep(self._relay_time) 144 | if not self.is_closing: 145 | # closing stopped 146 | return 147 | self._hub.turn_off(self._relay_line, self._relay_port) 148 | self._attr_is_closing = False 149 | self.async_write_ha_state() 150 | 151 | async def async_open_cover(self, **kwargs): 152 | _LOGGER.debug(f"GPIODCover async_open_cover: is_closed: {self.is_closed}. is_closing: {self.is_closing}, is_opening: {self.is_opening}") 153 | if not self.is_closed: 154 | return 155 | self._hub.turn_on(self._relay_line, self._relay_port) 156 | self._attr_is_opening = True 157 | self.async_write_ha_state() 158 | await asyncio.sleep(self._relay_time) 159 | if not self.is_opening: 160 | # opening stopped 161 | return 162 | self._hub.turn_off(self._relay_line, self._relay_port) 163 | self._attr_is_opening = False 164 | self.async_write_ha_state() 165 | 166 | async def async_stop_cover(self, **kwargs): 167 | _LOGGER.debug(f"GPIODCover async_stop_cover: is_closed: {self.is_closed}. is_closing: {self.is_closing}, is_opening: {self.is_opening}") 168 | if not (self.is_closing or self.is_opening): 169 | return 170 | self._hub.turn_off(self._relay_line, self._relay_port) 171 | self._attr_is_opening = False 172 | self._attr_is_closing = False 173 | self.async_write_ha_state() 174 | 175 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/hub.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from . import DOMAIN 4 | 5 | import logging 6 | _LOGGER = logging.getLogger(__name__) 7 | 8 | from homeassistant.core import HomeAssistant 9 | from homeassistant.const import EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_START 10 | from homeassistant.exceptions import HomeAssistantError,ServiceValidationError 11 | 12 | from typing import Dict 13 | from datetime import timedelta 14 | import gpiod 15 | 16 | from gpiod.line import Direction, Value, Bias, Drive, Edge, Clock 17 | EventType = gpiod.EdgeEvent.Type 18 | 19 | BIAS = { 20 | "UP": Bias.PULL_UP, 21 | "DOWN": Bias.PULL_DOWN, 22 | "DISABLED": Bias.DISABLED, 23 | "AS_IS": Bias.AS_IS, 24 | } 25 | DRIVE = { 26 | "OPEN_DRAIN": Drive.OPEN_DRAIN, 27 | "OPEN_SOURCE": Drive.OPEN_SOURCE, 28 | "PUSH_PULL": Drive.PUSH_PULL, 29 | } 30 | 31 | class Hub: 32 | 33 | def __init__(self, hass: HomeAssistant, path: str) -> None: 34 | """GPIOD Hub""" 35 | 36 | self._path = path 37 | self._chip : gpiod.Chip 38 | self._name = path 39 | self._id = path 40 | self._hass = hass 41 | self._online = False 42 | 43 | if path: 44 | # use config 45 | _LOGGER.debug(f"trying to use configured device: {path}") 46 | if self.verify_gpiochip(path): 47 | self._online = True 48 | self._path = path 49 | else: 50 | # discover 51 | _LOGGER.debug(f"auto discovering gpio device") 52 | for d in [0,4,1,2,3,5]: 53 | # rpi3,4 using 0. rpi5 using 4 54 | path = f"/dev/gpiochip{d}" 55 | if self.verify_gpiochip(path): 56 | self._online = True 57 | self._path = path 58 | break 59 | 60 | self.verify_online() 61 | _LOGGER.debug(f"using gpio_device: {self._path}") 62 | 63 | def verify_online(self): 64 | if not self._online: 65 | _LOGGER.error("No gpio device detected, bailing out") 66 | raise HomeAssistantError("No gpio device detected") 67 | 68 | def verify_gpiochip(self, path): 69 | if not gpiod.is_gpiochip_device(path): 70 | _LOGGER.debug(f"verify_gpiochip: {path} not a gpiochip_device") 71 | return False 72 | 73 | _LOGGER.debug(f"verify_gpiochip: {path} is a gpiochip_device") 74 | self._chip = gpiod.Chip(path) 75 | info = self._chip.get_info() 76 | _LOGGER.debug(f"verify_gpiochip: {path} info is: {info}") 77 | if not "pinctrl" in info.label: 78 | _LOGGER.debug(f"verify_gpiochip: {path} no pinctrl {info.label}") 79 | return False 80 | 81 | _LOGGER.debug(f"verify_gpiochip gpiodevice: {path} has pinctrl") 82 | return True 83 | 84 | def verify_port_ready(self, port: int): 85 | info = self._chip.get_line_info(port) 86 | _LOGGER.debug(f"original port {port} info: {info}") 87 | if info.used: 88 | if info.consumer != DOMAIN: 89 | raise HomeAssistantError(f"Port {port} already in use by {info.consumer}") 90 | else: 91 | raise HomeAssistantError(f"Port {port} already in use by another entity, check your config for duplicates port usage") 92 | 93 | @property 94 | def hub_id(self) -> str: 95 | """ID for hub""" 96 | return self._id 97 | 98 | def add_switch(self, port, active_low, bias, drive_mode, init_state) -> gpiod.LineRequest: 99 | _LOGGER.debug(f"add_switch - port: {port}, active_low: {active_low}, bias: {bias}, drive_mode: {drive_mode}, init_state: {init_state}") 100 | self.verify_online() 101 | self.verify_port_ready(port) 102 | 103 | line_request = self._chip.request_lines( 104 | consumer=DOMAIN, 105 | config={port: gpiod.LineSettings( 106 | direction = Direction.OUTPUT, 107 | bias = BIAS[bias], 108 | drive = DRIVE[drive_mode], 109 | active_low = active_low, 110 | output_value = Value.ACTIVE if init_state is not None and init_state else Value.INACTIVE)}) 111 | _LOGGER.debug(f"add_switch line_request: {line_request}") 112 | return line_request 113 | 114 | def turn_on(self, line, port) -> None: 115 | _LOGGER.debug(f"in turn_on {port}") 116 | self.verify_online() 117 | line.set_value(port, Value.ACTIVE) 118 | 119 | def turn_off(self, line, port) -> None: 120 | _LOGGER.debug(f"in turn_off {port}") 121 | self.verify_online() 122 | line.set_value(port, Value.INACTIVE) 123 | 124 | def add_sensor(self, port, active_low, bias, debounce) -> gpiod.LineRequest: 125 | _LOGGER.debug(f"add_sensor - port: {port}, active_low: {active_low}, bias: {bias}, debounce: {debounce}") 126 | self.verify_online() 127 | self.verify_port_ready(port) 128 | 129 | line_request = self._chip.request_lines( 130 | consumer=DOMAIN, 131 | config={port: gpiod.LineSettings( 132 | direction = Direction.INPUT, 133 | edge_detection = Edge.BOTH, 134 | bias = BIAS[bias], 135 | active_low = active_low, 136 | debounce_period = timedelta(milliseconds=debounce), 137 | event_clock = Clock.REALTIME)}) 138 | _LOGGER.debug(f"add_sensor line_request: {line_request}") 139 | current_is_on = True if line_request.get_value(port) == Value.ACTIVE else False 140 | _LOGGER.debug(f"add_sensor current state: {current_is_on}") 141 | return line_request, current_is_on 142 | 143 | def add_cover(self, relay_port, relay_active_low, relay_bias, relay_drive, 144 | state_port, state_bias, state_active_low): 145 | _LOGGER.debug(f"add_cover - relay_port: {relay_port}, state_port: {state_port}") 146 | relay_line = self.add_switch(relay_port, relay_active_low, relay_bias, relay_drive, False) 147 | state_line, current_is_on = self.add_sensor(state_port, state_active_low, state_bias, 50) 148 | return relay_line, state_line, current_is_on 149 | 150 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "rpi_gpio", 3 | "name": "Raspberry Pi GPIO", 4 | "codeowners": [ "@thecode", "@tomer-w" ], 5 | "documentation": "https://github.com/thecode/ha-rpi_gpio", 6 | "integration_type": "hub", 7 | "iot_class": "local_push", 8 | "issue_tracker": "https://github.com/thecode/ha-rpi_gpio/issues", 9 | "requirements": [ "gpiod>=2.2.1" ], 10 | "version": "2025.2.1" 11 | } 12 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/services.yaml: -------------------------------------------------------------------------------- 1 | reload: 2 | name: Reload 3 | description: Reload all rpi_gpio entities. 4 | -------------------------------------------------------------------------------- /custom_components/rpi_gpio/switch.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | from typing import Any 3 | 4 | from . import DOMAIN 5 | 6 | import logging 7 | _LOGGER = logging.getLogger(__name__) 8 | 9 | from homeassistant.core import HomeAssistant 10 | from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType 11 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 12 | from homeassistant.helpers.config_validation import PLATFORM_SCHEMA 13 | from homeassistant.components.switch import SwitchEntity 14 | from homeassistant.const import CONF_SWITCHES, CONF_NAME, CONF_PORT, CONF_UNIQUE_ID, STATE_ON 15 | from homeassistant.helpers.restore_state import RestoreEntity 16 | from .hub import BIAS, DRIVE 17 | CONF_INVERT_LOGIC = "invert_logic" 18 | DEFAULT_INVERT_LOGIC = False 19 | CONF_PULL_MODE="pull_mode" 20 | DEFAULT_PULL_MODE = "AS_IS" 21 | CONF_DRIVE ="drive" 22 | DEFAULT_DRIVE = "PUSH_PULL" 23 | CONF_PERSISTENT = "persistent" 24 | DEFAULT_PERSISTENT = False 25 | 26 | import homeassistant.helpers.config_validation as cv 27 | import voluptuous as vol 28 | 29 | PLATFORM_SCHEMA = vol.All( 30 | PLATFORM_SCHEMA.extend({ 31 | vol.Exclusive(CONF_SWITCHES, CONF_SWITCHES): vol.All( 32 | cv.ensure_list, [{ 33 | vol.Required(CONF_NAME): cv.string, 34 | vol.Required(CONF_PORT): cv.positive_int, 35 | vol.Optional(CONF_UNIQUE_ID): cv.string, 36 | vol.Optional(CONF_INVERT_LOGIC, default=DEFAULT_INVERT_LOGIC): cv.boolean, 37 | vol.Optional(CONF_PULL_MODE, default=DEFAULT_PULL_MODE): vol.In(BIAS.keys()), 38 | vol.Optional(CONF_DRIVE, default=DEFAULT_DRIVE): vol.In(DRIVE.keys()), 39 | vol.Optional(CONF_PERSISTENT, default=DEFAULT_PERSISTENT): cv.boolean, 40 | }] 41 | ) 42 | }) 43 | ) 44 | 45 | 46 | async def async_setup_platform( 47 | hass: HomeAssistant, 48 | config: ConfigType, 49 | async_add_entities: AddEntitiesCallback, 50 | discovery_info: DiscoveryInfoType | None = None) -> None: 51 | 52 | _LOGGER.debug(f"setup_platform: {config}") 53 | hub = hass.data[DOMAIN] 54 | if not hub._online: 55 | _LOGGER.error("hub not online, bailing out") 56 | 57 | switches = [] 58 | for switch in config.get(CONF_SWITCHES): 59 | try: 60 | switches.append( 61 | GPIODSwitch( 62 | hub, 63 | switch[CONF_NAME], 64 | switch[CONF_PORT], 65 | switch.get(CONF_UNIQUE_ID) or f"{DOMAIN}_{switch[CONF_PORT]}_{switch[CONF_NAME].lower().replace(' ', '_')}", 66 | switch.get(CONF_INVERT_LOGIC), 67 | switch.get(CONF_PULL_MODE), 68 | switch.get(CONF_DRIVE), 69 | switch[CONF_PERSISTENT] 70 | ) 71 | ) 72 | except Exception as e: 73 | _LOGGER.error(f"Failed to add switch {switch[CONF_NAME]} for port {switch[CONF_PORT]}: {e}") 74 | 75 | async_add_entities(switches) 76 | 77 | 78 | class GPIODSwitch(SwitchEntity, RestoreEntity): 79 | _attr_should_poll = False 80 | 81 | def __init__(self, hub, name, port, unique_id, active_low, bias, drive, persistent): 82 | _LOGGER.debug(f"GPIODSwitch init: {port} - {name} - {unique_id} - active_low: {active_low} - bias: {bias} - drive: {drive} - persistent: {persistent}") 83 | self._hub = hub 84 | self._attr_name = name 85 | self._attr_unique_id = unique_id 86 | self._port = port 87 | self._active_low = active_low 88 | self._bias = bias 89 | self._drive_mode = drive 90 | self._persistent = persistent 91 | self._line = None 92 | self._hub.verify_port_ready(self._port) 93 | 94 | async def async_added_to_hass(self) -> None: 95 | """Call when the switch is added to hass.""" 96 | await super().async_added_to_hass() 97 | state = await self.async_get_last_state() 98 | if not state or not self._persistent: 99 | self._attr_is_on = False 100 | else: 101 | _LOGGER.debug(f"setting initial persistent state for: {self._port}. state: {state.state}") 102 | self._attr_is_on = True if state.state == STATE_ON else False 103 | self.async_write_ha_state() 104 | self._line = self._hub.add_switch(self._port, self._active_low, self._bias, self._drive_mode, self._attr_is_on) 105 | 106 | async def async_will_remove_from_hass(self) -> None: 107 | await super().async_will_remove_from_hass() 108 | _LOGGER.debug(f"GPIODSwitch async_will_remove_from_hass") 109 | if self._line: 110 | self._line.release() 111 | 112 | async def async_turn_on(self, **kwargs: Any) -> None: 113 | self._hub.turn_on(self._line, self._port) 114 | self._attr_is_on = True 115 | self.async_write_ha_state() 116 | 117 | async def async_turn_off(self, **kwargs: Any) -> None: 118 | self._hub.turn_off(self._line, self._port) 119 | self._attr_is_on = False 120 | self.async_write_ha_state() 121 | -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Raspberry Pi GPIO", 3 | "homeassistant": "2024.9.0" 4 | } -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | ignore=tests 3 | # Use a conservative default here; 2 should speed up most setups and not hurt 4 | # any too bad. Override on command line as appropriate. 5 | jobs=2 6 | persistent=no 7 | 8 | [BASIC] 9 | good-names=id,i,j,k,ex,Run,_,fp 10 | max-attributes=15 11 | 12 | [MESSAGES CONTROL] 13 | # Reasons disabled: 14 | # too-many-* - are not enforced for the sake of readability 15 | # too-few-* - same as too-many-* 16 | disable= 17 | too-few-public-methods, 18 | too-many-arguments, 19 | too-many-public-methods, 20 | too-many-instance-attributes, 21 | too-many-branches 22 | 23 | [REPORTS] 24 | score=no 25 | 26 | [FORMAT] 27 | expected-line-ending-format=LF 28 | -------------------------------------------------------------------------------- /requirements_lint.txt: -------------------------------------------------------------------------------- 1 | black==25.1.0 2 | flake8==7.2.0 3 | isort==6.0.1 4 | mypy==1.16.0 5 | pre-commit==4.2.0 6 | pydocstyle==6.3.0 7 | pylint==3.3.7 8 | --------------------------------------------------------------------------------