├── .eslintignore ├── .eslintrc ├── .github ├── ISSUE_TEMPLATE │ ├── bug-report.md │ ├── config.yml │ ├── feature-request.md │ └── support-request.md ├── dependabot.yml └── workflows │ ├── build.yml │ ├── codeql-analysis.yml │ └── dependabot.yml ├── .gitignore ├── .husky └── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc.json ├── .vscode ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── config.schema.json ├── nodemon.json ├── package-lock.json ├── package.json ├── src ├── accessory.ts ├── characteristics │ ├── air-purifier │ │ ├── active.ts │ │ ├── current-air-purifier-state.ts │ │ ├── filter-change-indication.ts │ │ ├── filter-life-level.ts │ │ ├── lock-physical-controls.ts │ │ ├── rotation-speed.ts │ │ └── target-air-purifier-state.ts │ ├── air-quality.ts │ ├── current-relative-humidity.ts │ ├── current-temperature.ts │ └── pm2_5-density.ts ├── index.ts ├── miio-consts.ts ├── settings.ts └── utils.ts └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | /dist/** 2 | test.js 3 | !.eslintrc.js 4 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "extends": [ 4 | "eslint:recommended", 5 | "plugin:@typescript-eslint/eslint-recommended", 6 | // uses the recommended rules from the @typescript-eslint/eslint-plugin 7 | "plugin:@typescript-eslint/recommended", 8 | "prettier" 9 | ], 10 | "parserOptions": { 11 | "ecmaVersion": 2018, 12 | "sourceType": "module" 13 | }, 14 | "ignorePatterns": ["dist"], 15 | "rules": { 16 | "quotes": ["warn", "single"], 17 | "semi": ["off"], 18 | "comma-dangle": ["warn", "always-multiline"], 19 | "dot-notation": "off", 20 | "eqeqeq": "warn", 21 | "curly": ["warn", "all"], 22 | "brace-style": ["warn"], 23 | "prefer-arrow-callback": ["warn"], 24 | "max-len": ["warn", 140], 25 | "no-console": ["warn"], // use the provided Homebridge log method instead 26 | "no-non-null-assertion": ["off"], 27 | "comma-spacing": ["error"], 28 | "no-multi-spaces": ["warn", { "ignoreEOLComments": true }], 29 | "lines-between-class-members": [ 30 | "warn", 31 | "always", 32 | { "exceptAfterSingleLine": true } 33 | ], 34 | "@typescript-eslint/explicit-function-return-type": "off", 35 | "@typescript-eslint/no-non-null-assertion": "off", 36 | "@typescript-eslint/explicit-module-boundary-types": "off", 37 | "@typescript-eslint/no-explicit-any": "off", 38 | "@typescript-eslint/semi": ["warn"], 39 | "@typescript-eslint/member-delimiter-style": ["warn"] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | --- 8 | 9 | 10 | 11 | **Describe The Bug:** 12 | 13 | 14 | 15 | **To Reproduce:** 16 | 17 | 18 | 19 | **Expected behavior:** 20 | 21 | 22 | 23 | **Logs:** 24 | 25 | ``` 26 | Show the Homebridge logs here, remove any sensitive information. 27 | ``` 28 | 29 | **Plugin Config:** 30 | 31 | ```json 32 | Show your Homebridge config.json here, remove any sensitive information. 33 | ``` 34 | 35 | **Screenshots:** 36 | 37 | 38 | 39 | **Environment:** 40 | 41 | - **Plugin Version**: 42 | - **Homebridge Version**: 43 | - **Node.js Version**: 44 | - **NPM Version**: 45 | - **Device**: 46 | - **Operating System**: 47 | 48 | 49 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | # blank_issues_enabled: false 2 | # contact_links: 3 | # - name: Homebridge Discord Community 4 | # url: https://discord.gg/kqNCe2D 5 | # about: Ask your questions in the #YOUR_CHANNEL_HERE channel 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe:** 10 | 11 | 12 | 13 | **Describe the solution you'd like:** 14 | 15 | 16 | 17 | **Describe alternatives you've considered:** 18 | 19 | 20 | 21 | **Additional context:** 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/support-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Support Request 3 | about: Need help? 4 | title: '' 5 | labels: question 6 | assignees: '' 7 | --- 8 | 9 | 10 | 11 | **Describe Your Problem:** 12 | 13 | 14 | 15 | **Logs:** 16 | 17 | ``` 18 | Show the Homebridge logs here, remove any sensitive information. 19 | ``` 20 | 21 | **Plugin Config:** 22 | 23 | ```json 24 | Show your Homebridge config.json here, remove any sensitive information. 25 | ``` 26 | 27 | **Screenshots:** 28 | 29 | 30 | 31 | **Environment:** 32 | 33 | - **Plugin Version**: 34 | - **Homebridge Version**: 35 | - **Node.js Version**: 36 | - **NPM Version**: 37 | - **Operating System**: 38 | 39 | 40 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Please see the documentation for all configuration options: 2 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 3 | 4 | version: 2 5 | updates: 6 | # Enable version updates for npm 7 | - package-ecosystem: "npm" 8 | # Look for `package.json` and `lock` files in the `root` directory 9 | directory: "/" 10 | # Check the npm registry for updates every day (weekdays) 11 | schedule: 12 | interval: "daily" 13 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and Lint 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | strategy: 10 | matrix: 11 | # the Node.js versions to build on 12 | node-version: [12.x, 16.x] 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | 17 | - name: Use Node.js ${{ matrix.node-version }} 18 | uses: actions/setup-node@v1 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | 22 | - name: Install dependencies 23 | run: npm install 24 | 25 | - name: Lint the project 26 | run: npm run lint 27 | 28 | - name: Build the project 29 | run: npm run build 30 | env: 31 | CI: true 32 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [ main ] 9 | schedule: 10 | - cron: '45 2 * * 0' 11 | 12 | jobs: 13 | analyze: 14 | name: Analyze 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | language: [ 'javascript' ] 21 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 22 | # Learn more: 23 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 24 | 25 | steps: 26 | - name: Checkout repository 27 | uses: actions/checkout@v2 28 | 29 | # Initializes the CodeQL tools for scanning. 30 | - name: Initialize CodeQL 31 | uses: github/codeql-action/init@v1 32 | with: 33 | languages: ${{ matrix.language }} 34 | # If you wish to specify custom queries, you can do so here or in a config file. 35 | # By default, queries listed here will override any specified in a config file. 36 | # Prefix the list here with "+" to use these queries and those in the config file. 37 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 38 | 39 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 40 | # If this step fails, then you should remove it and run the build manually (see below) 41 | - name: Autobuild 42 | uses: github/codeql-action/autobuild@v1 43 | 44 | # ℹ️ Command-line programs to run using the OS shell. 45 | # 📚 https://git.io/JvXDl 46 | 47 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 48 | # and modify them (or add more) to build your code if your project 49 | # uses a compiled language 50 | 51 | #- run: | 52 | # make bootstrap 53 | # make release 54 | 55 | - name: Perform CodeQL Analysis 56 | uses: github/codeql-action/analyze@v1 57 | -------------------------------------------------------------------------------- /.github/workflows/dependabot.yml: -------------------------------------------------------------------------------- 1 | name: Dependabot Automerge 2 | on: pull_request 3 | jobs: 4 | worker: 5 | runs-on: ubuntu-latest 6 | if: github.actor == 'dependabot[bot]' 7 | steps: 8 | - uses: actions/github-script@v3 9 | with: 10 | script: |- 11 | github.pulls.createReview({ 12 | owner: context.payload.repository.owner.login, 13 | repo: context.payload.repository.name, 14 | pull_number: context.payload.pull_request.number, 15 | event: 'APPROVE' 16 | }) 17 | github.pulls.merge({ 18 | owner: context.payload.repository.owner.login, 19 | repo: context.payload.repository.name, 20 | pull_number: context.payload.pull_request.number, 21 | merge_method: 'squash' 22 | }) 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | test.js 2 | 3 | # Ignore compiled code 4 | dist 5 | 6 | # ------------- Defaults ------------- # 7 | 8 | # Logs 9 | logs 10 | *.log 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | lerna-debug.log* 15 | 16 | # Diagnostic reports (https://nodejs.org/api/report.html) 17 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 18 | 19 | # Runtime data 20 | pids 21 | *.pid 22 | *.seed 23 | *.pid.lock 24 | 25 | # Directory for instrumented libs generated by jscoverage/JSCover 26 | lib-cov 27 | 28 | # Coverage directory used by tools like istanbul 29 | coverage 30 | *.lcov 31 | 32 | # nyc test coverage 33 | .nyc_output 34 | 35 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 36 | .grunt 37 | 38 | # Bower dependency directory (https://bower.io/) 39 | bower_components 40 | 41 | # node-waf configuration 42 | .lock-wscript 43 | 44 | # Compiled binary addons (https://nodejs.org/api/addons.html) 45 | build/Release 46 | 47 | # Dependency directories 48 | node_modules/ 49 | jspm_packages/ 50 | 51 | # Snowpack dependency directory (https://snowpack.dev/) 52 | web_modules/ 53 | 54 | # TypeScript cache 55 | *.tsbuildinfo 56 | 57 | # Optional npm cache directory 58 | .npm 59 | 60 | # Optional eslint cache 61 | .eslintcache 62 | 63 | # Microbundle cache 64 | .rpt2_cache/ 65 | .rts2_cache_cjs/ 66 | .rts2_cache_es/ 67 | .rts2_cache_umd/ 68 | 69 | # Optional REPL history 70 | .node_repl_history 71 | 72 | # Output of 'npm pack' 73 | *.tgz 74 | 75 | # Yarn Integrity file 76 | .yarn-integrity 77 | 78 | # dotenv environment variables file 79 | .env 80 | .env.test 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | 89 | # Nuxt.js build / generate output 90 | .nuxt 91 | dist 92 | 93 | # Gatsby files 94 | .cache/ 95 | # Comment in the public line in if your project uses Gatsby and not Next.js 96 | # https://nextjs.org/blog/next-9-1#public-directory-support 97 | # public 98 | 99 | # vuepress build output 100 | .vuepress/dist 101 | 102 | # Serverless directories 103 | .serverless/ 104 | 105 | # FuseBox cache 106 | .fusebox/ 107 | 108 | # DynamoDB Local files 109 | .dynamodb/ 110 | 111 | # TernJS port file 112 | .tern-port 113 | 114 | # Stores VSCode versions used for testing VSCode extensions 115 | .vscode-test 116 | 117 | # yarn v2 118 | 119 | .yarn/cache 120 | .yarn/unplugged 121 | .yarn/build-state.yml 122 | .pnp.* 123 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Ignore source code 2 | src 3 | test.js 4 | 5 | # ------------- Defaults ------------- # 6 | 7 | # gitHub actions 8 | .github 9 | 10 | # eslint 11 | .eslintrc 12 | .eslintignore 13 | 14 | # prettier 15 | .prettierignore 16 | .prettierrc.json 17 | 18 | # typescript 19 | tsconfig.json 20 | 21 | # vscode 22 | .vscode 23 | 24 | # nodemon 25 | nodemon.json 26 | 27 | # Logs 28 | logs 29 | *.log 30 | npm-debug.log* 31 | yarn-debug.log* 32 | yarn-error.log* 33 | lerna-debug.log* 34 | 35 | # Diagnostic reports (https://nodejs.org/api/report.html) 36 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 37 | 38 | # Runtime data 39 | pids 40 | *.pid 41 | *.seed 42 | *.pid.lock 43 | 44 | # Directory for instrumented libs generated by jscoverage/JSCover 45 | lib-cov 46 | 47 | # Coverage directory used by tools like istanbul 48 | coverage 49 | *.lcov 50 | 51 | # nyc test coverage 52 | .nyc_output 53 | 54 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 55 | .grunt 56 | 57 | # Bower dependency directory (https://bower.io/) 58 | bower_components 59 | 60 | # node-waf configuration 61 | .lock-wscript 62 | 63 | # Compiled binary addons (https://nodejs.org/api/addons.html) 64 | build/Release 65 | 66 | # Dependency directories 67 | node_modules/ 68 | jspm_packages/ 69 | 70 | # Snowpack dependency directory (https://snowpack.dev/) 71 | web_modules/ 72 | 73 | # TypeScript cache 74 | *.tsbuildinfo 75 | 76 | # Optional npm cache directory 77 | .npm 78 | 79 | # Optional eslint cache 80 | .eslintcache 81 | 82 | # Microbundle cache 83 | .rpt2_cache/ 84 | .rts2_cache_cjs/ 85 | .rts2_cache_es/ 86 | .rts2_cache_umd/ 87 | 88 | # Optional REPL history 89 | .node_repl_history 90 | 91 | # Output of 'npm pack' 92 | *.tgz 93 | 94 | # Yarn Integrity file 95 | .yarn-integrity 96 | 97 | # dotenv environment variables file 98 | .env 99 | .env.test 100 | 101 | # parcel-bundler cache (https://parceljs.org/) 102 | .cache 103 | .parcel-cache 104 | 105 | # Next.js build output 106 | .next 107 | 108 | # Nuxt.js build / generate output 109 | .nuxt 110 | dist 111 | 112 | # Gatsby files 113 | .cache/ 114 | # Comment in the public line in if your project uses Gatsby and not Next.js 115 | # https://nextjs.org/blog/next-9-1#public-directory-support 116 | # public 117 | 118 | # vuepress build output 119 | .vuepress/dist 120 | 121 | # Serverless directories 122 | .serverless/ 123 | 124 | # FuseBox cache 125 | .fusebox/ 126 | 127 | # DynamoDB Local files 128 | .dynamodb/ 129 | 130 | # TernJS port file 131 | .tern-port 132 | 133 | # Stores VSCode versions used for testing VSCode extensions 134 | .vscode-test 135 | 136 | # yarn v2 137 | 138 | .yarn/cache 139 | .yarn/unplugged 140 | .yarn/build-state.yml 141 | .pnp.* 142 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Ignore artifacts: 2 | dist 3 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["dbaeumer.vscode-eslint"] 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.eol": "\n", 3 | "editor.codeActionsOnSave": { 4 | "source.fixAll.eslint": true 5 | }, 6 | "editor.rulers": [140] 7 | } 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![verified-by-homebridge](https://badgen.net/badge/homebridge/verified/purple)](https://github.com/homebridge/homebridge/wiki/Verified-Plugins) 2 | 3 | Control and monitor your **Xiaomi Mi Air Purifier** purifier with HomeKit. 4 | 5 |

6 | 7 |

8 | 9 | ## Features 10 | 11 | - Air Purifier Accessory 12 | - Turn on/off 13 | - Control Fan Speed 14 | - Toggle Child Lock 15 | - Change Mode (Auto/Manual) 16 | - Filter Live Level 17 | - Filter Change Warning 18 | - Air Quality Sensor 19 | - Air Quality 20 | - PM2.5 Density 21 | - Temperature Sensor 22 | - Relative Humidity Sensor 23 | 24 | ## Prerequisites 25 | 26 | - Installation of [Homebridge](https://homebridge.io/) 27 | 28 | ## Installation 29 | 30 | Install using `npm`: 31 | 32 | ```bash 33 | npm install -g homebridge-xiaomi-mi-air-purifier 34 | ``` 35 | 36 | Or, search for `homebridge-xiaomi-mi-air-purifier ` in Plugins. 37 | 38 | Note that it might be neccessary to enter the search string inside double quotes i.e. `"homebridge-xiaomi-mi-air-purifier"` in some Homebridge UI variants (such as [Hoobs](https://hoobs.com/)) in order to find it among the plethora of similarly named plugins. 39 | 40 | ## Configuration 41 | 42 | Configure the plugin in the GUI / [Homebridge Config UI X](https://github.com/oznu/homebridge-config-ui-x) (highly recommended), otherwise head over to [Manual Config](#manual-config) 43 | 44 | 45 | 46 | ### Getting a Token 47 | 48 | Use [Xiaomi Cloud Tokens Extractor](https://github.com/PiotrMachowski/Xiaomi-cloud-tokens-extractor) to get a token for your device. 49 | 50 | ### Manual Config 51 | 52 | Add this to your homebridge config.json file. 53 | 54 | ```json 55 | { 56 | "accessories": [ 57 | { 58 | "name": "Air Purifier", 59 | "address": "", 60 | "token": "", 61 | "enableAirQuality": true, 62 | "enableTemperature": true, 63 | "enableHumidity": true, 64 | "filterChangeThreshold": 5, 65 | "enableFanSpeedControl": true, 66 | "enableChildLockControl": true, 67 | "accessory": "XiaomiMiAirPurifier" 68 | } 69 | ] 70 | } 71 | ``` 72 | 73 | ## HomeKit pairing 74 | 75 | 1. Open the Home app on your device. 76 | 2. Tap the Home tab, then tap . 77 | 3. Tap _Add Accessory_, and select _I Don't Have a Code or Cannot Scan_. 78 | -------------------------------------------------------------------------------- /config.schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "pluginAlias": "XiaomiMiAirPurifier", 3 | "pluginType": "accessory", 4 | "singular": false, 5 | "schema": { 6 | "type": "object", 7 | "properties": { 8 | "name": { 9 | "title": "Name", 10 | "type": "string", 11 | "required": true, 12 | "default": "Air Purifier", 13 | "placeholder": "Air Purifier" 14 | }, 15 | "address": { 16 | "title": "IP Address", 17 | "type": "string", 18 | "required": true, 19 | "format": "ipv4" 20 | }, 21 | "token": { 22 | "title": "Token", 23 | "type": "string", 24 | "required": true, 25 | "pattern": "^\\w{32}$" 26 | }, 27 | "enableAirQuality": { 28 | "title": "Air Quality", 29 | "type": "boolean", 30 | "default": true 31 | }, 32 | "enableTemperature": { 33 | "title": "Temperature", 34 | "type": "boolean", 35 | "default": true 36 | }, 37 | "enableHumidity": { 38 | "title": "Humidity", 39 | "type": "boolean", 40 | "default": true 41 | }, 42 | "filterChangeThreshold": { 43 | "title": "Filter Change Warning Threshold", 44 | "type": "integer", 45 | "default": 5, 46 | "minimum": 0, 47 | "maximum": 100, 48 | "description": "Show Change Filter warning once Filter Life reaches this value." 49 | }, 50 | "enableFanSpeedControl": { 51 | "title": "Fan Speed", 52 | "type": "boolean", 53 | "default": false, 54 | "description": "Allows you to see control the fan speed." 55 | }, 56 | "enableChildLockControl": { 57 | "title": "Child Lock", 58 | "type": "boolean", 59 | "default": false, 60 | "description": "Allows you to lock/unlock the physical control." 61 | } 62 | } 63 | }, 64 | "layout": [ 65 | { "key": "name" }, 66 | { 67 | "type": "flex", 68 | "flex-flow": "row wrap", 69 | "items": ["address", "token"] 70 | }, 71 | { 72 | "type": "help", 73 | "helpvalue": "Please check the README for instruction about how to get a token." 74 | }, 75 | { 76 | "type": "section", 77 | "title": "Sensors", 78 | "expandable": true, 79 | "expanded": true, 80 | "items": [ 81 | { "key": "enableAirQuality" }, 82 | { "key": "enableTemperature" }, 83 | { "key": "enableHumidity" } 84 | ] 85 | }, 86 | { 87 | "type": "section", 88 | "title": "Advanced options", 89 | "expandable": true, 90 | "expanded": false, 91 | "items": [ 92 | { "key": "filterChangeThreshold" }, 93 | { "key": "enableFanSpeedControl" }, 94 | { "key": "enableChildLockControl" } 95 | ] 96 | } 97 | ] 98 | } 99 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "ts", 4 | "ignore": [], 5 | "exec": "tsc && homebridge -I -D -P .", 6 | "signal": "SIGTERM", 7 | "env": { 8 | "NODE_OPTIONS": "--trace-warnings" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "displayName": "Xiaomi Mi Air Purifier", 3 | "name": "homebridge-xiaomi-mi-air-purifier", 4 | "version": "2.0.2", 5 | "description": "A short description about what your plugin does.", 6 | "license": "Apache-2.0", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/torifat/xiaomi-mi-air-purifier" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/torifat/xiaomi-mi-air-purifier/issues" 13 | }, 14 | "funding": { 15 | "type": "paypal", 16 | "url": "https://paypal.me/RifatNabi" 17 | }, 18 | "engines": { 19 | "node": ">=10.17.0", 20 | "homebridge": ">=1.3.0" 21 | }, 22 | "main": "dist/index.js", 23 | "scripts": { 24 | "lint": "eslint src/**/**.ts --max-warnings=0", 25 | "watch": "npm run build && npm link && nodemon", 26 | "build": "rimraf ./dist && tsc", 27 | "prepublishOnly": "npm run lint && npm run build && pinst --disable", 28 | "postinstall": "husky install", 29 | "postpublish": "pinst --enable" 30 | }, 31 | "keywords": [ 32 | "homebridge-plugin" 33 | ], 34 | "dependencies": { 35 | "@rifat/miio": "^2.0.1" 36 | }, 37 | "devDependencies": { 38 | "@types/node": "^16.11.11", 39 | "@typescript-eslint/eslint-plugin": "^5.5.0", 40 | "@typescript-eslint/parser": "^5.5.0", 41 | "eslint": "^8.2.0", 42 | "eslint-config-prettier": "^8.3.0", 43 | "homebridge": "^1.3.8", 44 | "husky": "^7.0.4", 45 | "lint-staged": "^12.1.2", 46 | "nodemon": "^2.0.15", 47 | "pinst": "^2.1.6", 48 | "prettier": "^2.5.0", 49 | "rimraf": "^3.0.2", 50 | "ts-node": "^10.4.0", 51 | "typescript": "^4.4.4" 52 | }, 53 | "husky": { 54 | "hooks": { 55 | "pre-commit": "lint-staged" 56 | } 57 | }, 58 | "lint-staged": { 59 | "*.ts": "eslint --cache --fix", 60 | "*.{ts,css,md}": "prettier --write" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/accessory.ts: -------------------------------------------------------------------------------- 1 | import { 2 | API, 3 | Logger, 4 | Service, 5 | AccessoryConfig, 6 | AccessoryPlugin, 7 | } from 'homebridge'; 8 | import miio from '@rifat/miio'; 9 | import { retry, isDefined } from './utils'; 10 | import { add as addActive } from './characteristics/air-purifier/active'; 11 | import { add as addCurrentAirPurifierState } from './characteristics/air-purifier/current-air-purifier-state'; 12 | import { add as addTargetAirPurifierState } from './characteristics/air-purifier/target-air-purifier-state'; 13 | import { add as addFilterLifeLevel } from './characteristics/air-purifier/filter-life-level'; 14 | import { 15 | add as addFilterChangeIndication, 16 | DEFAULT_FILTER_CHANGE_THRESHOLD, 17 | } from './characteristics/air-purifier/filter-change-indication'; 18 | import { add as addRotationSpeed } from './characteristics/air-purifier/rotation-speed'; 19 | import { add as addLockPhysicalControls } from './characteristics/air-purifier/lock-physical-controls'; 20 | import { add as addAirQuality } from './characteristics/air-quality'; 21 | import { add as addPm2_5Density } from './characteristics/pm2_5-density'; 22 | import { add as addCurrentTemperature } from './characteristics/current-temperature'; 23 | import { add as addCurrentRelativeHumidity } from './characteristics/current-relative-humidity'; 24 | 25 | // TODO: Add this under "Advanced Settings" 26 | // Try to connect to the device after RETRY_DELAY ms delay in case of failure 27 | const RETRY_DELAY = 5000; 28 | 29 | export interface XiaomiMiAirPurifierAccessoryConfig extends AccessoryConfig { 30 | token: string; 31 | address: string; 32 | enableAirQuality: boolean; 33 | enableTemperature: boolean; 34 | enableHumidity: boolean; 35 | enableFanSpeedControl: boolean; 36 | enableChildLockControl: boolean; 37 | filterChangeThreshold: number; 38 | } 39 | 40 | function isValidConfig( 41 | config: AccessoryConfig, 42 | ): config is XiaomiMiAirPurifierAccessoryConfig { 43 | return !!config.token && !!config.address; 44 | } 45 | 46 | export class XiaomiMiAirPurifierAccessory implements AccessoryPlugin { 47 | private readonly name?: string; 48 | protected readonly config?: XiaomiMiAirPurifierAccessoryConfig; 49 | 50 | private readonly airPurifierService?: Service; 51 | private readonly accessoryInformationService?: Service; 52 | private readonly filterMaintenanceService?: Service; 53 | private readonly airQualitySensorService?: Service; 54 | private readonly temperatureSensorService?: Service; 55 | private readonly humiditySensorService?: Service; 56 | 57 | private connection?: Promise; 58 | protected readonly maybeDevice?: Promise; 59 | 60 | constructor( 61 | protected readonly log: Logger, 62 | config: AccessoryConfig, 63 | protected readonly api: API, 64 | ) { 65 | if (isValidConfig(config)) { 66 | this.config = config; 67 | 68 | const { 69 | Service: { 70 | AirPurifier, 71 | HumiditySensor, 72 | AirQualitySensor, 73 | TemperatureSensor, 74 | AccessoryInformation, 75 | }, 76 | Characteristic, 77 | } = api.hap; 78 | 79 | this.name = config.name; 80 | this.maybeDevice = this.connect(config).then((device) => { 81 | log.info(`Connected to "${this.name}" @ ${config.address}!`); 82 | return device; 83 | }); 84 | 85 | // Air Purifier Service 86 | // Required characteristics 87 | this.airPurifierService = new AirPurifier(this.name); 88 | addActive( 89 | this.maybeDevice, 90 | this.airPurifierService, 91 | Characteristic.Active, 92 | ); 93 | addCurrentAirPurifierState( 94 | this.maybeDevice, 95 | this.airPurifierService, 96 | Characteristic.CurrentAirPurifierState, 97 | ); 98 | addTargetAirPurifierState( 99 | this.maybeDevice, 100 | this.airPurifierService, 101 | Characteristic.TargetAirPurifierState, 102 | ); 103 | 104 | // Optional characteristics 105 | if (config.enableFanSpeedControl) { 106 | addRotationSpeed( 107 | this.maybeDevice, 108 | this.airPurifierService, 109 | Characteristic.RotationSpeed, 110 | ); 111 | } 112 | 113 | if (config.enableChildLockControl) { 114 | addLockPhysicalControls( 115 | this.maybeDevice, 116 | this.airPurifierService, 117 | Characteristic.LockPhysicalControls, 118 | ); 119 | } 120 | 121 | // Air Quality Sensor Service 122 | if (config.enableAirQuality) { 123 | this.airQualitySensorService = new AirQualitySensor( 124 | `Air Quality on ${this.name}`, 125 | ); 126 | addAirQuality( 127 | this.maybeDevice, 128 | this.airQualitySensorService, 129 | Characteristic.AirQuality, 130 | ); 131 | addPm2_5Density( 132 | this.maybeDevice, 133 | this.airQualitySensorService, 134 | Characteristic.PM2_5Density, 135 | ); 136 | addFilterLifeLevel( 137 | this.maybeDevice, 138 | this.airQualitySensorService, 139 | Characteristic.FilterLifeLevel, 140 | ); 141 | addFilterChangeIndication( 142 | this.maybeDevice, 143 | this.airQualitySensorService, 144 | Characteristic.FilterChangeIndication, 145 | { 146 | filterChangeThreshold: 147 | config.filterChangeThreshold | DEFAULT_FILTER_CHANGE_THRESHOLD, 148 | }, 149 | ); 150 | } 151 | 152 | // Temperature Sensor Service 153 | if (config.enableTemperature) { 154 | this.temperatureSensorService = new TemperatureSensor( 155 | `Temperature on ${this.name}`, 156 | ); 157 | 158 | addCurrentTemperature( 159 | this.maybeDevice, 160 | this.temperatureSensorService, 161 | Characteristic.CurrentTemperature, 162 | ); 163 | } 164 | 165 | // Humidity Sensor Service 166 | if (config.enableHumidity) { 167 | this.humiditySensorService = new HumiditySensor( 168 | `Humidity on ${this.name}`, 169 | ); 170 | addCurrentRelativeHumidity( 171 | this.maybeDevice, 172 | this.humiditySensorService, 173 | Characteristic.CurrentRelativeHumidity, 174 | ); 175 | } 176 | 177 | // Device Info 178 | this.accessoryInformationService = new AccessoryInformation().setCharacteristic( 179 | Characteristic.Manufacturer, 180 | 'Xiaomi Corporation', 181 | ); 182 | 183 | log.info(`${this.name} finished initializing!`); 184 | } else { 185 | log.error('Your must provide IP address and token of the Air Purifier.'); 186 | } 187 | } 188 | 189 | connect(config) { 190 | if (!this.connection) { 191 | this.connection = new Promise((resolve) => { 192 | const { address, token } = config; 193 | // Now keeps retrying forever. 194 | // Maybe can add a max retries number as an option 195 | retry(() => miio.device({ address, token }), RETRY_DELAY) 196 | .then(resolve) 197 | .catch((e) => { 198 | this.log.error('Error occurred during retry:', e); 199 | }); 200 | }); 201 | } 202 | return this.connection; 203 | } 204 | 205 | /* 206 | * This method is optional to implement. It is called when HomeKit ask to identify the accessory. 207 | * Typical this only ever happens at the pairing process. 208 | */ 209 | identify() { 210 | this.log.info(`Identifying "${this.name}" @ ${this.config?.address}`); 211 | } 212 | 213 | /* 214 | * This method is called directly after creation of this instance. 215 | * It should return all services which should be added to the accessory. 216 | */ 217 | getServices(): Service[] { 218 | return [ 219 | this.airPurifierService, 220 | this.airQualitySensorService, 221 | this.temperatureSensorService, 222 | this.humiditySensorService, 223 | this.filterMaintenanceService, 224 | this.accessoryInformationService, 225 | ].filter(isDefined); 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/active.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/Active 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.Active, 8 | ) { 9 | const { ACTIVE, INACTIVE } = characteristic; 10 | 11 | maybeDevice.then((device) => { 12 | device.on('powerChanged', (isOn: boolean) => { 13 | service.updateCharacteristic(characteristic, isOn ? ACTIVE : INACTIVE); 14 | }); 15 | }); 16 | 17 | return service 18 | .getCharacteristic(characteristic) 19 | .onGet(async () => { 20 | const device = await maybeDevice; 21 | return (await device.power()) ? ACTIVE : INACTIVE; 22 | }) 23 | .onSet(async function (this: Characteristic, newStatus) { 24 | const device = await maybeDevice; 25 | const currentStatus = await device.power(); 26 | if (currentStatus !== newStatus) { 27 | await device.changePower(newStatus); 28 | } 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/current-air-purifier-state.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic, CharacteristicEventTypes } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/CurrentAirPurifierState 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.CurrentAirPurifierState, 8 | ) { 9 | const { 10 | INACTIVE, 11 | // IDLE - Shows "Turning off.." with a spinner, 12 | PURIFYING_AIR, 13 | } = characteristic; 14 | 15 | maybeDevice.then((device) => { 16 | device.on('powerChanged', (isOn: boolean) => { 17 | service.updateCharacteristic( 18 | characteristic, 19 | isOn ? PURIFYING_AIR : INACTIVE, 20 | ); 21 | }); 22 | }); 23 | 24 | return service.getCharacteristic(characteristic).onGet(async () => { 25 | const device = await maybeDevice; 26 | const isOn = await device.power(); 27 | return isOn ? PURIFYING_AIR : INACTIVE; 28 | }); 29 | } 30 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/filter-change-indication.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic, CharacteristicEventTypes } from 'homebridge'; 2 | 3 | export const DEFAULT_FILTER_CHANGE_THRESHOLD = 5; 4 | 5 | interface FilterChangeIndicationOptions { 6 | filterChangeThreshold: number; 7 | } 8 | 9 | // https://developers.homebridge.io/#/characteristic/FilterChangeIndication 10 | export function add( 11 | maybeDevice: Promise, 12 | service: Service, 13 | characteristic: typeof Characteristic.FilterChangeIndication, 14 | options: FilterChangeIndicationOptions, 15 | ) { 16 | const { FILTER_OK, CHANGE_FILTER } = characteristic; 17 | 18 | maybeDevice.then((device) => { 19 | device.on('filterLifeChanged', (value: number) => { 20 | if (value <= options.filterChangeThreshold) { 21 | service.updateCharacteristic(characteristic, CHANGE_FILTER); 22 | } 23 | }); 24 | }); 25 | 26 | return service.getCharacteristic(characteristic).onGet(async () => { 27 | const device = await maybeDevice; 28 | return (await device.filterLifeLevel()) <= options.filterChangeThreshold 29 | ? CHANGE_FILTER 30 | : FILTER_OK; 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/filter-life-level.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic, CharacteristicEventTypes } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/FilterLifeLevel 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.FilterLifeLevel, 8 | ) { 9 | maybeDevice.then((device) => { 10 | device.on('filterLifeChanged', (value: number) => { 11 | service.updateCharacteristic(characteristic, value); 12 | }); 13 | }); 14 | 15 | return service.getCharacteristic(characteristic).onGet(async () => { 16 | const device = await maybeDevice; 17 | return await device.filterLifeLevel(); 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/lock-physical-controls.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic, CharacteristicEventTypes } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/LockPhysicalControls 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.LockPhysicalControls, 8 | ) { 9 | const { CONTROL_LOCK_ENABLED, CONTROL_LOCK_DISABLED } = characteristic; 10 | 11 | maybeDevice.then((device) => { 12 | device.on('childLockChanged', (isLocked: boolean) => { 13 | service.updateCharacteristic( 14 | characteristic, 15 | isLocked ? CONTROL_LOCK_ENABLED : CONTROL_LOCK_DISABLED, 16 | ); 17 | }); 18 | }); 19 | 20 | return service 21 | .getCharacteristic(characteristic) 22 | .onGet(async () => { 23 | const device = await maybeDevice; 24 | return (await device.childLock()) 25 | ? CONTROL_LOCK_ENABLED 26 | : CONTROL_LOCK_DISABLED; 27 | }) 28 | .onSet(async (newStatus) => { 29 | const device = await maybeDevice; 30 | await device.changeChildLock(newStatus); 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/rotation-speed.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic, CharacteristicEventTypes } from 'homebridge'; 2 | import { MODE } from '../../miio-consts'; 3 | 4 | // http://miot-spec.org/miot-spec-v2/instance?type=urn:miot-spec-v2:device:air-purifier:0000A007:zhimi-ma4:1 5 | // Range 0 - 3000 6 | const RATIO = 30; 7 | // NOTE: `.toFixed` returns `string` 8 | const toPercentage = (speed: number) => Math.round((speed / RATIO) * 100) / 100; 9 | 10 | // https://developers.homebridge.io/#/characteristic/Active 11 | export function add( 12 | maybeDevice: Promise, 13 | service: Service, 14 | characteristic: typeof Characteristic.RotationSpeed, 15 | ) { 16 | maybeDevice.then((device) => { 17 | device.on('fanSpeedChanged', (speed) => { 18 | service.updateCharacteristic(characteristic, toPercentage(speed)); 19 | }); 20 | }); 21 | 22 | return service 23 | .getCharacteristic(characteristic) 24 | .onGet(async () => { 25 | const device = await maybeDevice; 26 | return toPercentage(await device.fanSpeed()); 27 | }) 28 | .onSet(async (speed) => { 29 | const device = await maybeDevice; 30 | console.log(device); 31 | // If the device isn't in manual mode change it first 32 | if ((await device.mode()) !== MODE.NONE) { 33 | await device.changeMode(MODE.NONE); 34 | } 35 | await device.changeFanSpeed(+speed * RATIO); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /src/characteristics/air-purifier/target-air-purifier-state.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic, CharacteristicEventTypes } from 'homebridge'; 2 | import { MODE } from '../../miio-consts'; 3 | 4 | // https://developers.homebridge.io/#/characteristic/TargetAirPurifierState 5 | export function add( 6 | maybeDevice: Promise, 7 | service: Service, 8 | characteristic: typeof Characteristic.TargetAirPurifierState, 9 | ) { 10 | const { AUTO, MANUAL } = characteristic; 11 | 12 | maybeDevice.then((device) => { 13 | device.on('modeChanged', (mode) => { 14 | service.updateCharacteristic(characteristic, mode ? MANUAL : AUTO); 15 | }); 16 | }); 17 | 18 | return service 19 | .getCharacteristic(characteristic) 20 | .onGet(async () => { 21 | const device = await maybeDevice; 22 | return (await device.mode()) ? MANUAL : AUTO; 23 | }) 24 | .onSet(async (mode) => { 25 | const device = await maybeDevice; 26 | const newMode = mode === AUTO ? MODE.AUTO : MODE.NONE; 27 | const currentMode = await device.mode(); 28 | if (newMode !== currentMode) { 29 | await device.changeMode(newMode); 30 | } 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /src/characteristics/air-quality.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic } from 'homebridge'; 2 | 3 | function pm2_5ToAqi(aqi: number) { 4 | if (!aqi) { 5 | return 0; // Error or unknown response 6 | } else if (aqi <= 25) { 7 | return 1; // Return EXCELLENT 8 | } else if (aqi > 25 && aqi <= 50) { 9 | return 2; // Return GOOD 10 | } else if (aqi > 50 && aqi <= 75) { 11 | return 3; // Return FAIR 12 | } else if (aqi > 75 && aqi <= 100) { 13 | return 4; // Return INFERIOR 14 | } else if (aqi > 100) { 15 | return 5; // Return POOR (Homekit only goes to cat 5, so the last two AQI cats of Very Unhealty and Hazardous. 16 | } else { 17 | return 0; // Error or unknown response. 18 | } 19 | } 20 | 21 | // https://developers.homebridge.io/#/characteristic/AirQuality 22 | export function add( 23 | maybeDevice: Promise, 24 | service: Service, 25 | characteristic: typeof Characteristic.AirQuality, 26 | ) { 27 | maybeDevice.then((device) => { 28 | device.on('pm2.5Changed', (value: number) => { 29 | service.updateCharacteristic(characteristic, pm2_5ToAqi(value)); 30 | }); 31 | }); 32 | 33 | return service.getCharacteristic(characteristic).onGet(async () => { 34 | const device = await maybeDevice; 35 | return pm2_5ToAqi(await device.pm2_5()); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /src/characteristics/current-relative-humidity.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/CurrentRelativeHumidity 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.CurrentRelativeHumidity, 8 | ) { 9 | maybeDevice.then((device) => { 10 | device.on('relativeHumidityChanged', (value: number) => { 11 | service.updateCharacteristic(characteristic, value); 12 | }); 13 | }); 14 | 15 | return service.getCharacteristic(characteristic).onGet(async () => { 16 | const device = await maybeDevice; 17 | return await device.rh(); 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /src/characteristics/current-temperature.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/CurrentTemperature 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.CurrentTemperature, 8 | ) { 9 | maybeDevice.then((device) => { 10 | device.on('temperatureChanged', ({ value }) => { 11 | service.updateCharacteristic(characteristic, value); 12 | }); 13 | }); 14 | 15 | return service.getCharacteristic(characteristic).onGet( 16 | // Temperature { value: 23.4, unit: 'C' } 17 | async () => { 18 | const device = await maybeDevice; 19 | return (await device.temperature()).value; 20 | }, 21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /src/characteristics/pm2_5-density.ts: -------------------------------------------------------------------------------- 1 | import { Service, Characteristic } from 'homebridge'; 2 | 3 | // https://developers.homebridge.io/#/characteristic/PM2_5Density 4 | export function add( 5 | maybeDevice: Promise, 6 | service: Service, 7 | characteristic: typeof Characteristic.PM2_5Density, 8 | ) { 9 | maybeDevice.then((device) => { 10 | device.on('pm2.5Changed', (value) => { 11 | service.updateCharacteristic(characteristic, value); 12 | }); 13 | }); 14 | 15 | return service.getCharacteristic(characteristic).onGet(async () => { 16 | const device = await maybeDevice; 17 | return await device.pm2_5(); 18 | }); 19 | } 20 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import type { API } from 'homebridge'; 2 | 3 | import { ACCESSORY_NAME } from './settings'; 4 | import { XiaomiMiAirPurifierAccessory } from './accessory'; 5 | 6 | /** 7 | * This method registers the platform with Homebridge 8 | */ 9 | export = (api: API) => { 10 | api.registerAccessory(ACCESSORY_NAME, XiaomiMiAirPurifierAccessory); 11 | }; 12 | -------------------------------------------------------------------------------- /src/miio-consts.ts: -------------------------------------------------------------------------------- 1 | export enum MODE { 2 | AUTO = 'auto', // 0 3 | SLEEP = 'sleep', // 1 4 | FAVORITE = 'favorite', //2 5 | NONE = 'none', // 3 6 | } 7 | -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the name of the platform that users will use to register the plugin in the Homebridge config.json 3 | */ 4 | export const ACCESSORY_NAME = 'XiaomiMiAirPurifier'; 5 | 6 | /** 7 | * This must match the name of your plugin as defined the package.json 8 | */ 9 | export const PLUGIN_NAME = 'homebridge-xiaomi-mi-air-purifier'; 10 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Wait for {delay} ms 3 | * @param delay in milliseconds 4 | */ 5 | export const wait = (delay: number) => 6 | new Promise((resolve) => setTimeout(resolve, delay)); 7 | 8 | export const retry = ( 9 | task: () => Promise, 10 | delay: number, 11 | retries = Number.POSITIVE_INFINITY, 12 | ) => 13 | new Promise((resolve, reject) => 14 | task() 15 | .then(resolve) 16 | .catch((reason) => 17 | retries > 0 18 | ? wait(delay) 19 | .then(retry.bind(null, task, delay, retries - 1)) 20 | .then(resolve) 21 | .catch(reject) 22 | : reject(reason), 23 | ), 24 | ); 25 | 26 | export const isDefined = (value: T): value is NonNullable => 27 | value != null; 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2018", // ~node10 4 | "module": "commonjs", 5 | "lib": ["es2015", "es2016", "es2017", "es2018"], 6 | "declaration": true, 7 | "declarationMap": true, 8 | "sourceMap": true, 9 | "outDir": "./dist", 10 | "rootDir": "./src", 11 | "strict": true, 12 | "esModuleInterop": true, 13 | "noImplicitAny": false 14 | }, 15 | "include": ["src/"], 16 | "exclude": ["**/*.spec.ts"] 17 | } 18 | --------------------------------------------------------------------------------