├── custom_components └── xiaomi_miio_airconditioningcompanion │ ├── __init__.py │ ├── manifest.json │ ├── strings.json │ ├── services.yaml │ └── climate.py ├── .hound.yml ├── climate.png ├── .github ├── FUNDING.yml └── workflows │ └── ci.yaml ├── .gitignore ├── .flake8 ├── hacs.json ├── .pre-commit-config.yaml ├── README.md └── LICENSE /custom_components/xiaomi_miio_airconditioningcompanion/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.hound.yml: -------------------------------------------------------------------------------- 1 | python: 2 | enabled: true 3 | config_file: .flake8 4 | -------------------------------------------------------------------------------- /climate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syssi/xiaomi_airconditioningcompanion/HEAD/climate.png -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | buy_me_a_coffee: syssi 2 | ko_fi: syssi 3 | custom: ["https://paypal.me/syssi84"] 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | .idea/ 7 | venv/ 8 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = .git,.tox,__pycache__ 3 | max-line-length = 100 4 | select = C,E,F,W,B,B950 5 | ignore = E501,W503,E203 6 | -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Xiaomi Mi and Aqara Air Conditioning Companion Integration", 3 | "content_in_root": false, 4 | "render_readme": true 5 | } 6 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: "Hassfest and hacs validation" 2 | on: 3 | push: 4 | pull_request: 5 | schedule: 6 | - cron: '0 0 * * *' 7 | 8 | jobs: 9 | ci: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: home-assistant/actions/hassfest@master 14 | - uses: hacs/action@main 15 | with: 16 | category: integration 17 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/astral-sh/ruff-pre-commit 3 | rev: v0.4.5 4 | hooks: 5 | - id: ruff 6 | args: 7 | - --fix 8 | - id: ruff-format 9 | 10 | - repo: https://github.com/pycqa/flake8 11 | rev: 7.0.0 12 | hooks: 13 | - id: flake8 14 | additional_dependencies: [flake8-docstrings, flake8-bugbear, flake8-builtins, flake8-print, flake8-pytest-style, flake8-return, flake8-simplify, flake8-annotations] 15 | -------------------------------------------------------------------------------- /custom_components/xiaomi_miio_airconditioningcompanion/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "xiaomi_miio_airconditioningcompanion", 3 | "name": "Xiaomi Mi and Aqara Air Conditioning Companion", 4 | "codeowners": [ 5 | "@syssi" 6 | ], 7 | "config_flow": false, 8 | "dependencies": ["sensor"], 9 | "documentation": "https://github.com/syssi/xiaomi_airconditioningcompanion", 10 | "iot_class": "local_polling", 11 | "issue_tracker": "https://github.com/syssi/xiaomi_airconditioningcompanion/issues", 12 | "requirements": [ 13 | "construct==2.10.68", 14 | "python-miio>=0.5.12" 15 | ], 16 | "version": "2024.8.1.2" 17 | } 18 | -------------------------------------------------------------------------------- /custom_components/xiaomi_miio_airconditioningcompanion/strings.json: -------------------------------------------------------------------------------- 1 | { 2 | "services": { 3 | "climate_learn_command": { 4 | "name": "Learn command", 5 | "description": "Learn an IR command, press \"Call Service\", point the remote at the IR device, and the learned command will be shown as a notification in Overview.", 6 | "fields": { 7 | "entity_id": { 8 | "name": "Entity ID", 9 | "description": "Name of the xiaomi miio airconditioningcompanion entity." 10 | }, 11 | "slot": { 12 | "name": "Slot", 13 | "description": "Define the slot used to save the IR command. Defaults to slot ID 30." 14 | }, 15 | "timeout": { 16 | "name": "Timeout", 17 | "description": "Define the timeout in seconds, before which the command must be learned." 18 | } 19 | } 20 | }, 21 | "climate_send_command": { 22 | "name": "Send command", 23 | "description": "Send captured infrared command or device configuration.", 24 | "fields": { 25 | "entity_id": { 26 | "name": "Entity ID", 27 | "description": "Name of the xiaomi miio airconditioningcompanion entity." 28 | }, 29 | "command": { 30 | "name": "Command", 31 | "description": "Infrared command. Must start with FE or 01." 32 | }, 33 | "num_repeats": { 34 | "name": "Repeats", 35 | "description": "The number of times you want to repeat the command(s)." 36 | }, 37 | "delay_secs": { 38 | "name": "Delay Seconds", 39 | "description": "The time you want to wait in between repeated commands." 40 | } 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /custom_components/xiaomi_miio_airconditioningcompanion/services.yaml: -------------------------------------------------------------------------------- 1 | climate_learn_command: 2 | name: Learn command 3 | description: Learn an IR command, press "Call Service", point the remote at the IR device, and the learned command will be shown as a notification in Overview. 4 | fields: 5 | entity_id: 6 | name: Entity ID 7 | description: Name of the xiaomi miio airconditioningcompanion entity. 8 | selector: 9 | entity: 10 | integration: xiaomi_miio_airconditioningcompanion 11 | domain: climate 12 | slot: 13 | name: Slot 14 | description: Define the slot used to save the IR command. Defaults to slot ID 30. 15 | example: 30 16 | timeout: 17 | name: Timeout 18 | description: Define the timeout in seconds, before which the command must be learned. 19 | example: 30 20 | 21 | climate_send_command: 22 | name: Send command 23 | description: Send captured infrared command or device configuration. 24 | fields: 25 | entity_id: 26 | name: Entity ID 27 | description: Name of the xiaomi miio airconditioningcompanion entity. 28 | selector: 29 | entity: 30 | integration: xiaomi_miio_airconditioningcompanion 31 | domain: climate 32 | command: 33 | name: Command 34 | description: Infrared command. Must start with FE or 01. 35 | num_repeats: 36 | name: Repeats 37 | description: The number of times you want to repeat the command(s). 38 | default: 1 39 | selector: 40 | number: 41 | min: 0 42 | max: 255 43 | delay_secs: 44 | name: Delay Seconds 45 | description: The time you want to wait in between repeated commands. 46 | default: 0.4 47 | selector: 48 | number: 49 | min: 0 50 | max: 60 51 | step: 0.1 52 | unit_of_measurement: seconds 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Xiaomi Mi and Aqara Air Conditioning Companion 2 | 3 | ![GitHub actions](https://github.com/syssi/xiaomi_airconditioningcompanion/actions/workflows/ci.yaml/badge.svg) 4 | ![GitHub stars](https://img.shields.io/github/stars/syssi/xiaomi_airconditioningcompanion) 5 | ![GitHub forks](https://img.shields.io/github/forks/syssi/xiaomi_airconditioningcompanion) 6 | ![GitHub watchers](https://img.shields.io/github/watchers/syssi/xiaomi_airconditioningcompanion) 7 | [!["Buy Me A Coffee"](https://img.shields.io/badge/buy%20me%20a%20coffee-donate-yellow.svg)](https://www.buymeacoffee.com/syssi) 8 | 9 | This is a custom component for home assistant to integrate the Xiaomi Mi and Aqara Air Conditioning Companion: 10 | 11 | | Model ID | Model number | Product name | Shape | 12 | |-------------------|--------------|-----------------------------------------|----------| 13 | | `acpartner.v1` | KTBL01LM | Aqara Air Conditioning Companion | square | 14 | | `acaprtner.v2` | KTBL02LM | Xiaomi Mi Air Conditioner Companion | round | 15 | | `acpartner.v3` | KTBL11LM | Aqara Air Conditioning Companion | square | 16 | 17 | Unsupported devices: `lumi.acpartner.mcn02` 18 | 19 | Please follow the instructions on [Retrieving the Access Token](https://www.home-assistant.io/components/vacuum.xiaomi_miio/#retrieving-the-access-token) to get the API token to use in the configuration.yaml file. 20 | 21 | Credits: Thanks to [Rytilahti](https://github.com/rytilahti/python-miio) for all the work. 22 | 23 | ## Features 24 | * Power (on, off) 25 | * Operation Mode (Heat, Cool, Auto, Dehumidify, Ventilate) 26 | * Fan Speed (Low, Medium, High, Auto) 27 | * Swing Mode (On, Off) 28 | * Target Temperature 29 | * Capture and replay infrared commands 30 | * Attributes 31 | - ac_model 32 | - ac_power (on, off) 33 | - load_power (Wh) 34 | - operation_mode 35 | - fan_speed 36 | - swing_mode 37 | 38 | 39 | ## Install 40 | 41 | You can install this custom component by adding this repository ([https://github.com/syssi/xiaomi_airconditioningcompanion](https://github.com/syssi/xiaomi_airconditioningcompanion/)) to [HACS](https://hacs.xyz/) in the settings menu of HACS first. You will find the custom component in the integration menu afterwards, look for 'Xiaomi Mi and Aqara Air Conditioning Companion Integration'. Alternatively, you can install it manually by copying the custom_component folder to your Home Assistant configuration folder. 42 | 43 | 44 | ## Setup 45 | 46 | ```yaml 47 | # configuration.yaml 48 | 49 | climate: 50 | - platform: xiaomi_miio_airconditioningcompanion 51 | name: Aqara Air Conditioning Companion 52 | host: 192.168.130.71 53 | token: b7c4a758c251955d2c24b1d9e41ce47d 54 | target_sensor: sensor.temperature_158d0001f53706 55 | scan_interval: 60 56 | ``` 57 | 58 | ![climate entity](climate.png "climate entity") 59 | 60 | ## Debugging 61 | 62 | If the custom component doesn't work out of the box for your device please update your configuration to enable a higher log level: 63 | 64 | ```yaml 65 | # configuration.yaml 66 | 67 | logger: 68 | default: warn 69 | logs: 70 | custom_components.xiaomi_miio_airconditioningcompanion: debug 71 | miio: debug 72 | ``` 73 | 74 | ## Platform services 75 | 76 | #### Service `xiaomi_miio_airconditioningcompanion.climate_learn_command` 77 | 78 | Capture an infrared command. 79 | 80 | | Service data attribute | Optional | Description | 81 | |---------------------------|----------|----------------------------------------------------------------------| 82 | | `entity_id` | no | Only act on a specific Xiaomi miIO fan entity. | 83 | | `slot` | yes | Storage slot. Defaults to slot ID 30. | 84 | | `timeout` | yes | Capturing timeout. Defaults to 10 seconds. | 85 | 86 | #### Service `xiaomi_miio_airconditioningcompanion.climate_send_command` 87 | 88 | Send captured infrared command or device configuration. 89 | 90 | | Service data attribute | Optional | Description | 91 | |---------------------------|----------|----------------------------------------------------------------------| 92 | | `entity_id` | no | Only act on a specific Xiaomi miIO fan entity. | 93 | | `command` | no | Infrared command. Must start with `FE` or `01`. | 94 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /custom_components/xiaomi_miio_airconditioningcompanion/climate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Support for Xiaomi Mi Home Air Conditioner Companion (AC Partner) 3 | 4 | For more details about this platform, please refer to the documentation 5 | https://home-assistant.io/components/climate.xiaomi_miio 6 | """ 7 | 8 | import asyncio 9 | import enum 10 | import logging 11 | import time 12 | from datetime import timedelta 13 | from functools import partial 14 | 15 | import homeassistant.helpers.config_validation as cv 16 | import voluptuous as vol 17 | from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity 18 | from homeassistant.components.climate.const import ( 19 | ATTR_HVAC_MODE, 20 | ClimateEntityFeature, 21 | HVACMode, 22 | ) 23 | from homeassistant.components.remote import ( 24 | ATTR_DELAY_SECS, 25 | ATTR_NUM_REPEATS, 26 | DEFAULT_DELAY_SECS, 27 | DEFAULT_NUM_REPEATS, 28 | ) 29 | from homeassistant.const import ( 30 | ATTR_ENTITY_ID, 31 | ATTR_TEMPERATURE, 32 | ATTR_UNIT_OF_MEASUREMENT, 33 | CONF_HOST, 34 | CONF_NAME, 35 | CONF_TIMEOUT, 36 | CONF_TOKEN, 37 | STATE_ON, 38 | UnitOfTemperature, 39 | ) 40 | from homeassistant.core import callback 41 | from homeassistant.exceptions import PlatformNotReady 42 | from homeassistant.helpers.event import async_track_state_change_event 43 | from homeassistant.util.dt import utcnow 44 | 45 | _LOGGER = logging.getLogger(__name__) 46 | 47 | SUCCESS = ["ok"] 48 | 49 | DEFAULT_NAME = "Xiaomi AC Companion" 50 | DATA_KEY = "climate.xiaomi_miio_airconditioningcompanion" 51 | DOMAIN = "xiaomi_miio_airconditioningcompanion" 52 | TARGET_TEMPERATURE_STEP = 1 53 | 54 | DEFAULT_TIMEOUT = 10 55 | DEFAULT_SLOT = 30 56 | 57 | ATTR_AIR_CONDITION_MODEL = "ac_model" 58 | ATTR_SWING_MODE = "swing_mode" 59 | ATTR_FAN_MODE = "fan_mode" 60 | ATTR_LOAD_POWER = "load_power" 61 | ATTR_LED = "led" 62 | 63 | SUPPORT_FLAGS = ( 64 | ClimateEntityFeature.TARGET_TEMPERATURE 65 | | ClimateEntityFeature.FAN_MODE 66 | | ClimateEntityFeature.SWING_MODE 67 | | ClimateEntityFeature.TURN_OFF 68 | | ClimateEntityFeature.TURN_ON 69 | ) 70 | 71 | CONF_SENSOR = "target_sensor" 72 | CONF_MIN_TEMP = "min_temp" 73 | CONF_MAX_TEMP = "max_temp" 74 | CONF_SLOT = "slot" 75 | CONF_COMMAND = "command" 76 | CONF_POWER_SENSOR = "power_sensor" 77 | 78 | SCAN_INTERVAL = timedelta(seconds=15) 79 | 80 | PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( 81 | { 82 | vol.Required(CONF_HOST): cv.string, 83 | vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)), 84 | vol.Required(CONF_SENSOR): cv.entity_id, 85 | vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, 86 | vol.Optional(CONF_MIN_TEMP, default=16): vol.Coerce(int), 87 | vol.Optional(CONF_MAX_TEMP, default=30): vol.Coerce(int), 88 | vol.Optional(CONF_POWER_SENSOR): cv.entity_id, 89 | } 90 | ) 91 | 92 | SERVICE_LEARN_COMMAND = "climate_learn_command" 93 | SERVICE_SEND_COMMAND = "climate_send_command" 94 | 95 | SERVICE_SCHEMA = vol.Schema({vol.Optional(ATTR_ENTITY_ID): cv.entity_ids}) 96 | 97 | SERVICE_SCHEMA_LEARN_COMMAND = SERVICE_SCHEMA.extend( 98 | { 99 | vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.All( 100 | int, vol.Range(min=0) 101 | ), 102 | vol.Optional(CONF_SLOT, default=DEFAULT_SLOT): vol.All( 103 | int, vol.Range(min=2, max=1000000) 104 | ), 105 | } 106 | ) 107 | 108 | SERVICE_SCHEMA_SEND_COMMAND = SERVICE_SCHEMA.extend( 109 | { 110 | vol.Optional(CONF_COMMAND): cv.string, 111 | vol.Optional(ATTR_NUM_REPEATS, default=DEFAULT_NUM_REPEATS): cv.positive_int, 112 | vol.Optional(ATTR_DELAY_SECS, default=DEFAULT_DELAY_SECS): vol.Coerce(float), 113 | } 114 | ) 115 | 116 | SERVICE_TO_METHOD = { 117 | SERVICE_LEARN_COMMAND: { 118 | "method": "async_learn_command", 119 | "schema": SERVICE_SCHEMA_LEARN_COMMAND, 120 | }, 121 | SERVICE_SEND_COMMAND: { 122 | "method": "async_send_command", 123 | "schema": SERVICE_SCHEMA_SEND_COMMAND, 124 | }, 125 | } 126 | 127 | 128 | # pylint: disable=unused-argument 129 | async def async_setup_platform(hass, config, async_add_devices, discovery_info=None): 130 | """Set up the air conditioning companion from config.""" 131 | from miio import AirConditioningCompanion, DeviceException 132 | 133 | if DATA_KEY not in hass.data: 134 | hass.data[DATA_KEY] = {} 135 | 136 | host = config.get(CONF_HOST) 137 | name = config.get(CONF_NAME) 138 | token = config.get(CONF_TOKEN) 139 | min_temp = config.get(CONF_MIN_TEMP) 140 | max_temp = config.get(CONF_MAX_TEMP) 141 | sensor_entity_id = config.get(CONF_SENSOR) 142 | power_sensor_entity_id = config.get(CONF_POWER_SENSOR) 143 | 144 | _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) 145 | 146 | try: 147 | device = AirConditioningCompanion(host, token) 148 | device_info = device.info() 149 | model = device_info.model 150 | unique_id = "{}-{}".format(model, device_info.mac_address) 151 | _LOGGER.info( 152 | "%s %s %s detected", 153 | model, 154 | device_info.firmware_version, 155 | device_info.hardware_version, 156 | ) 157 | except DeviceException as ex: 158 | _LOGGER.error("Device unavailable or token incorrect: %s", ex) 159 | raise PlatformNotReady 160 | 161 | air_conditioning_companion = XiaomiAirConditioningCompanion( 162 | hass, 163 | name, 164 | device, 165 | unique_id, 166 | sensor_entity_id, 167 | power_sensor_entity_id, 168 | min_temp, 169 | max_temp, 170 | ) 171 | hass.data[DATA_KEY][host] = air_conditioning_companion 172 | async_add_devices([air_conditioning_companion], update_before_add=True) 173 | 174 | async def async_service_handler(service): 175 | """Map services to methods on XiaomiAirConditioningCompanion.""" 176 | method = SERVICE_TO_METHOD.get(service.service) 177 | params = { 178 | key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID 179 | } 180 | entity_ids = service.data.get(ATTR_ENTITY_ID) 181 | if entity_ids: 182 | devices = [ 183 | device 184 | for device in hass.data[DATA_KEY].values() 185 | if device.entity_id in entity_ids 186 | ] 187 | else: 188 | devices = hass.data[DATA_KEY].values() 189 | 190 | update_tasks = [] 191 | for device in devices: 192 | if not hasattr(device, method["method"]): 193 | continue 194 | await getattr(device, method["method"])(**params) 195 | update_tasks.append(asyncio.create_task(device.async_update_ha_state(True))) 196 | 197 | if update_tasks: 198 | await asyncio.wait(update_tasks) 199 | 200 | for service in SERVICE_TO_METHOD: 201 | schema = SERVICE_TO_METHOD[service].get("schema", SERVICE_SCHEMA) 202 | hass.services.async_register( 203 | DOMAIN, service, async_service_handler, schema=schema 204 | ) 205 | 206 | 207 | class OperationMode(enum.Enum): 208 | Heat = HVACMode.HEAT 209 | Cool = HVACMode.COOL 210 | Auto = HVACMode.AUTO 211 | Dehumidify = HVACMode.DRY 212 | Ventilate = HVACMode.FAN_ONLY 213 | Off = HVACMode.OFF 214 | 215 | 216 | class XiaomiAirConditioningCompanion(ClimateEntity): 217 | """Representation of a Xiaomi Air Conditioning Companion.""" 218 | 219 | def __init__( 220 | self, 221 | hass, 222 | name, 223 | device, 224 | unique_id, 225 | sensor_entity_id, 226 | power_sensor_entity_id, 227 | min_temp, 228 | max_temp, 229 | ): 230 | """Initialize the climate device.""" 231 | self.hass = hass 232 | self._name = name 233 | self._device = device 234 | self._unique_id = unique_id 235 | self._sensor_entity_id = sensor_entity_id 236 | self._power_sensor_entity_id = power_sensor_entity_id 237 | 238 | self._available = False 239 | self._state = None 240 | self._state_attrs = { 241 | ATTR_AIR_CONDITION_MODEL: None, 242 | ATTR_LOAD_POWER: None, 243 | ATTR_TEMPERATURE: None, 244 | ATTR_SWING_MODE: None, 245 | ATTR_HVAC_MODE: None, 246 | ATTR_LED: None, 247 | } 248 | 249 | self._max_temp = max_temp 250 | self._min_temp = min_temp 251 | self._current_temperature = None 252 | self._swing_mode = None 253 | self._last_on_operation = None 254 | self._hvac_mode = None 255 | self._fan_mode = None 256 | self._air_condition_model = None 257 | self._target_temperature = None 258 | 259 | if sensor_entity_id: 260 | async_track_state_change_event( 261 | hass, sensor_entity_id, self._async_sensor_changed 262 | ) 263 | sensor_state = hass.states.get(sensor_entity_id) 264 | if sensor_state: 265 | self._async_update_temp(sensor_state) 266 | 267 | if power_sensor_entity_id: 268 | async_track_state_change_event( 269 | hass, power_sensor_entity_id, self._async_power_sensor_changed 270 | ) 271 | sensor_state = hass.states.get(power_sensor_entity_id) 272 | if sensor_state: 273 | self._async_update_power_state(sensor_state) 274 | 275 | @callback 276 | def _async_update_temp(self, state): 277 | """Update thermostat with latest state from sensor.""" 278 | if state.state is None or state.state in ["unknown", "unavailable"]: 279 | return 280 | 281 | unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) 282 | 283 | try: 284 | self._current_temperature = self.hass.config.units.temperature( 285 | float(state.state), unit 286 | ) 287 | except ValueError as ex: 288 | _LOGGER.error("Unable to update from sensor: %s", ex) 289 | 290 | @callback 291 | async def _async_update_power_state(self, state): 292 | """Update thermostat with latest state from power sensor.""" 293 | if state.state is None: 294 | return 295 | if state.state == STATE_ON: 296 | await self.async_turn_on() 297 | else: 298 | await self.async_turn_off() 299 | 300 | async def _async_sensor_changed(self, event): 301 | """Handle temperature changes.""" 302 | new_state = event.data["new_state"] 303 | if new_state is None: 304 | return 305 | self._async_update_temp(new_state) 306 | 307 | async def _async_power_sensor_changed(self, entity_id, old_state, new_state): 308 | """Handle power sensor changes.""" 309 | if new_state is None: 310 | return 311 | 312 | await self._async_update_power_state(new_state) 313 | 314 | async def _try_command(self, mask_error, func, *args, **kwargs): 315 | """Call a AC companion command handling error messages.""" 316 | from miio import DeviceException 317 | 318 | try: 319 | result = await self.hass.async_add_executor_job(partial(func, *args, **kwargs)) 320 | 321 | _LOGGER.debug("Response received: %s", result) 322 | 323 | return result == SUCCESS 324 | except DeviceException as exc: 325 | _LOGGER.error(mask_error, exc) 326 | self._available = False 327 | return False 328 | 329 | async def async_turn_on(self, speed: str = None, **kwargs) -> None: 330 | """Turn the miio device on.""" 331 | result = await self._try_command( 332 | "Turning the miio device on failed.", self._device.on 333 | ) 334 | 335 | if result: 336 | self._state = True 337 | 338 | async def async_turn_off(self, **kwargs) -> None: 339 | """Turn the miio device off.""" 340 | result = await self._try_command( 341 | "Turning the miio device off failed.", self._device.off 342 | ) 343 | 344 | if result: 345 | self._state = False 346 | 347 | async def async_update(self): 348 | """Update the state of this climate device.""" 349 | from miio import DeviceException 350 | 351 | try: 352 | state = await self.hass.async_add_executor_job(self._device.status) 353 | _LOGGER.debug("Got new state: %s", state) 354 | 355 | self._available = True 356 | self._state_attrs.update( 357 | { 358 | ATTR_AIR_CONDITION_MODEL: state.air_condition_model.hex(), 359 | ATTR_LOAD_POWER: state.load_power, 360 | ATTR_TEMPERATURE: state.target_temperature, 361 | ATTR_SWING_MODE: state.swing_mode.name.lower(), 362 | ATTR_FAN_MODE: state.fan_speed.name.lower(), 363 | ATTR_HVAC_MODE: state.mode.name.lower() if self._state else "off", 364 | ATTR_LED: state.led, 365 | } 366 | ) 367 | self._last_on_operation = OperationMode[state.mode.name].value 368 | if state.power == "off": 369 | self._hvac_mode = HVACMode.OFF 370 | self._state = False 371 | else: 372 | self._hvac_mode = self._last_on_operation 373 | self._state = True 374 | self._target_temperature = state.target_temperature 375 | self._fan_mode = state.fan_speed 376 | self._swing_mode = state.swing_mode 377 | if self._air_condition_model is None: 378 | self._air_condition_model = state.air_condition_model.hex() 379 | 380 | except DeviceException as ex: 381 | self._available = False 382 | _LOGGER.error("Got exception while fetching the state: %s", ex) 383 | 384 | @property 385 | def supported_features(self): 386 | """Return the list of supported features.""" 387 | return SUPPORT_FLAGS 388 | 389 | @property 390 | def min_temp(self): 391 | """Return the minimum temperature.""" 392 | return self._min_temp 393 | 394 | @property 395 | def max_temp(self): 396 | """Return the maximum temperature.""" 397 | return self._max_temp 398 | 399 | @property 400 | def target_temperature_step(self): 401 | """Return the target temperature step.""" 402 | return TARGET_TEMPERATURE_STEP 403 | 404 | @property 405 | def should_poll(self): 406 | """Return the polling state.""" 407 | return True 408 | 409 | @property 410 | def unique_id(self): 411 | """Return an unique ID.""" 412 | return self._unique_id 413 | 414 | @property 415 | def name(self): 416 | """Return the name of the climate device.""" 417 | return self._name 418 | 419 | @property 420 | def available(self): 421 | """Return true when state is known.""" 422 | return self._available 423 | 424 | @property 425 | def extra_state_attributes(self): 426 | """Return the extra state attributes of the device.""" 427 | return self._state_attrs 428 | 429 | @property 430 | def temperature_unit(self): 431 | """Return the unit of measurement.""" 432 | return UnitOfTemperature.CELSIUS 433 | 434 | @property 435 | def current_temperature(self): 436 | """Return the current temperature.""" 437 | return self._current_temperature 438 | 439 | @property 440 | def target_temperature(self): 441 | """Return the temperature we try to reach.""" 442 | return self._target_temperature 443 | 444 | @property 445 | def hvac_mode(self): 446 | """Return new hvac mode ie. heat, cool, fan only.""" 447 | return self._hvac_mode 448 | 449 | @property 450 | def last_on_operation(self): 451 | """Return the last operation when the AC is on (ie heat, cool, fan only)""" 452 | return self._last_on_operation 453 | 454 | @property 455 | def hvac_modes(self): 456 | """Return the list of available hvac modes.""" 457 | return [mode.value for mode in OperationMode] 458 | 459 | @property 460 | def fan_mode(self): 461 | """Return the current fan mode.""" 462 | return self._fan_mode.name.lower() 463 | 464 | @property 465 | def fan_modes(self): 466 | """Return the list of available fan modes.""" 467 | from miio.airconditioningcompanion import FanSpeed 468 | 469 | return [speed.name.lower() for speed in FanSpeed] 470 | 471 | async def async_set_temperature(self, **kwargs): 472 | """Set target temperature.""" 473 | if kwargs.get(ATTR_TEMPERATURE) is not None: 474 | self._target_temperature = kwargs.get(ATTR_TEMPERATURE) 475 | if kwargs.get(ATTR_HVAC_MODE) is not None: 476 | self._hvac_mode = OperationMode(kwargs.get(ATTR_HVAC_MODE)) 477 | 478 | await self._send_configuration() 479 | 480 | async def async_set_swing_mode(self, swing_mode): 481 | """Set the swing mode.""" 482 | from miio.airconditioningcompanion import SwingMode 483 | 484 | self._swing_mode = SwingMode[swing_mode.title()] 485 | await self._send_configuration() 486 | 487 | async def async_set_fan_mode(self, fan_mode): 488 | """Set the fan mode.""" 489 | from miio.airconditioningcompanion import FanSpeed 490 | 491 | self._fan_mode = FanSpeed[fan_mode.title()] 492 | await self._send_configuration() 493 | 494 | async def async_set_hvac_mode(self, hvac_mode): 495 | """Set new target hvac mode.""" 496 | if hvac_mode == OperationMode.Off.value: 497 | result = await self._try_command( 498 | "Turning the miio device off failed.", self._device.off 499 | ) 500 | if result: 501 | self._state = False 502 | self._hvac_mode = HVACMode.OFF 503 | await self._send_configuration() 504 | else: 505 | self._hvac_mode = OperationMode(hvac_mode).value 506 | self._state = True 507 | await self._send_configuration() 508 | 509 | @property 510 | def swing_mode(self): 511 | """Return the current swing setting.""" 512 | return self._swing_mode.name.lower() 513 | 514 | @property 515 | def swing_modes(self): 516 | """List of available swing modes.""" 517 | from miio.airconditioningcompanion import SwingMode 518 | 519 | return [mode.name.lower() for mode in SwingMode] 520 | 521 | async def _send_configuration(self): 522 | from miio.airconditioningcompanion import Led 523 | from miio.airconditioningcompanion import OperationMode as MiioOperationMode 524 | from miio.airconditioningcompanion import Power 525 | 526 | if self._air_condition_model is not None: 527 | await self._try_command( 528 | "Sending new air conditioner configuration failed.", 529 | self._device.send_configuration, 530 | self._air_condition_model, 531 | Power(int(self._state)), 532 | ( 533 | MiioOperationMode[OperationMode(self._hvac_mode).name] 534 | if self._state 535 | else MiioOperationMode[OperationMode(self._last_on_operation).name] 536 | ), 537 | int(self._target_temperature), 538 | self._fan_mode, 539 | self._swing_mode, 540 | Led.Off, 541 | ) 542 | else: 543 | _LOGGER.error( 544 | "Model number of the air condition unknown. " 545 | "Configuration cannot be sent." 546 | ) 547 | 548 | async def async_learn_command(self, slot, timeout): 549 | """Learn a infrared command.""" 550 | await self.hass.async_add_executor_job(self._device.learn, slot) 551 | 552 | _LOGGER.info("Press the key you want Home Assistant to learn") 553 | start_time = utcnow() 554 | while (utcnow() - start_time) < timedelta(seconds=timeout): 555 | message = await self.hass.async_add_executor_job(self._device.learn_result) 556 | # FIXME: Improve python-miio here? 557 | message = message[0] 558 | _LOGGER.debug("Message received from device: '%s'", message) 559 | if message.startswith("FE"): 560 | log_msg = "Received command is: {}".format(message) 561 | _LOGGER.info(log_msg) 562 | self.hass.components.persistent_notification.async_create( 563 | log_msg, title="Xiaomi Miio Remote" 564 | ) 565 | await self.hass.async_add_executor_job(self._device.learn_stop, slot) 566 | return 567 | 568 | await asyncio.sleep(1) 569 | 570 | await self.hass.async_add_executor_job(self._device.learn_stop, slot) 571 | _LOGGER.error("Timeout. No infrared command captured") 572 | self.hass.components.persistent_notification.async_create( 573 | "Timeout. No infrared command captured", title="Xiaomi Miio Remote" 574 | ) 575 | 576 | async def async_send_command(self, command, **kwargs): 577 | """Send a infrared command.""" 578 | repeat = kwargs[ATTR_NUM_REPEATS] 579 | delay = kwargs[ATTR_DELAY_SECS] 580 | first_command = True 581 | for _ in range(repeat): 582 | if not first_command: 583 | time.sleep(delay) 584 | 585 | if command.startswith("01"): 586 | await self._try_command( 587 | "Sending new air conditioner configuration failed.", 588 | self._device.send_command, 589 | command, 590 | ) 591 | elif command.startswith("FE"): 592 | if self._air_condition_model is not None: 593 | # Learned infrared commands has the prefix 'FE' 594 | await self._try_command( 595 | "Sending custom infrared command failed.", 596 | self._device.send_ir_code, 597 | self._air_condition_model, 598 | command, 599 | ) 600 | else: 601 | _LOGGER.error( 602 | "Model number of the air condition unknown. " 603 | "IR command cannot be sent." 604 | ) 605 | else: 606 | _LOGGER.error("Invalid IR command.") 607 | 608 | first_command = False 609 | --------------------------------------------------------------------------------