Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
706580fab2
|
||
|
|
d6e935e8d7 | ||
|
|
3929546ea5
|
||
|
|
41a05a1a69 | ||
|
|
b01e200fb3
|
@@ -0,0 +1,49 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
# This repo used to run Home Assistant's hassfest and the HACS validation
|
||||
# action. Both are GitHub-hosted actions that only work against a github.com
|
||||
# repository, and the integration is no longer distributed through HACS, so the
|
||||
# checks here are self-contained: ruff for the Python, and a manifest/strings
|
||||
# consistency check that covers the parts of hassfest that actually matter for
|
||||
# a manually installed custom component.
|
||||
|
||||
env:
|
||||
# Pinned: ruff's default rule set and formatter output change between
|
||||
# releases, so an unpinned version turns an unrelated push red.
|
||||
RUFF_VERSION: "0.16.8"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install ruff
|
||||
run: |
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install --quiet "ruff==${RUFF_VERSION}"
|
||||
|
||||
- name: Ruff check
|
||||
run: .venv/bin/ruff check --output-format=github .
|
||||
|
||||
- name: Ruff format
|
||||
run: .venv/bin/ruff format --check --diff .
|
||||
|
||||
validate:
|
||||
name: Validate integration
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Byte-compile
|
||||
run: python3 -m compileall -q custom_components smoke-test
|
||||
|
||||
- name: Validate manifest and translations
|
||||
run: python3 scripts/validate_integration.py
|
||||
@@ -1,33 +0,0 @@
|
||||
name: Validate
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
hassfest:
|
||||
name: Hassfest validation
|
||||
runs-on: ubuntu-latest
|
||||
if: github.server_url == 'https://github.com'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: home-assistant/actions/hassfest@master
|
||||
|
||||
hacs:
|
||||
name: HACS validation
|
||||
runs-on: ubuntu-latest
|
||||
if: github.server_url == 'https://github.com'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: hacs/action@main
|
||||
with:
|
||||
category: integration
|
||||
ignore: brands
|
||||
@@ -1 +1,5 @@
|
||||
/.env
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
/.venv/
|
||||
/smoke-test/.venv/
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,13 @@
|
||||
homeassistant-dkncloudna
|
||||
Copyright (c) 2026 Sebastien Lavoie
|
||||
Copyright (c) 2026 James Griffin-Allwood
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (see LICENSE).
|
||||
|
||||
This repository is a fork of homeassistant-dkncloudna by Sebastien
|
||||
Lavoie (https://github.com/lavoiesl/homeassistant-dkncloudna), which
|
||||
is itself a port of the homebridge-dkncloudna plugin by @plecong
|
||||
(https://github.com/plecong/homebridge-dkncloudna), licensed under
|
||||
the Apache License, Version 2.0. Portions of this project (API
|
||||
protocol details, device mode mappings, and overall behavior) are
|
||||
derived from those works.
|
||||
@@ -1,11 +1,8 @@
|
||||
# DKN Cloud NA — Home Assistant Integration
|
||||
|
||||
[![HACS][hacs-badge]][hacs-url]
|
||||
[![Validate][validate-badge]][validate-url]
|
||||
|
||||
Control your Daikin mini-split air conditioners through Home Assistant using the DKN Cloud NA cloud service.
|
||||
|
||||
This integration is a port of the [homebridge-dkncloudna](https://github.com/plecong/homebridge-dkncloudna) plugin by [@plecong](https://github.com/plecong), adapted for Home Assistant and distributed via HACS.
|
||||
This integration is a port of the [homebridge-dkncloudna](https://github.com/plecong/homebridge-dkncloudna) plugin by [@plecong](https://github.com/plecong), adapted for Home Assistant.
|
||||
|
||||
---
|
||||
|
||||
@@ -20,24 +17,18 @@ Any Daikin mini-split system connected to the **DKN Cloud NA** WiFi adapter (Nor
|
||||
- A working [DKN Cloud NA](https://dkncloudna.com) account
|
||||
- Your Daikin unit(s) already set up and visible in the DKN Cloud NA app
|
||||
- Home Assistant 2024.1 or later
|
||||
- HACS 2.0 or later
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
### Via HACS (recommended)
|
||||
This integration is installed manually — it is not published to HACS.
|
||||
|
||||
1. Open HACS in your Home Assistant instance
|
||||
2. Go to **Integrations**
|
||||
3. Click the **⋮** menu → **Custom repositories**
|
||||
4. Add `https://github.com/lavoiesl/homeassistant-dkncloudna` as an **Integration**
|
||||
5. Search for **DKN Cloud NA** and install it
|
||||
6. Restart Home Assistant
|
||||
1. Download or clone this repository
|
||||
2. Copy the `custom_components/dkncloudna/` directory into your Home Assistant `config/custom_components/` directory, so that you end up with `config/custom_components/dkncloudna/manifest.json`
|
||||
3. Restart Home Assistant
|
||||
|
||||
### Manual
|
||||
|
||||
Copy the `custom_components/dkncloudna/` directory into your Home Assistant `config/custom_components/` directory and restart.
|
||||
To upgrade, replace the `dkncloudna` directory with the newer copy and restart again.
|
||||
|
||||
---
|
||||
|
||||
@@ -84,12 +75,29 @@ Each device exposes the following entities:
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
CI runs on Gitea Actions (`.gitea/workflows/ci.yml`). To reproduce it locally:
|
||||
|
||||
```sh
|
||||
pip install ruff==0.16.8 # version is pinned in CI
|
||||
ruff check .
|
||||
ruff format --check .
|
||||
python3 scripts/validate_integration.py
|
||||
```
|
||||
|
||||
`scripts/validate_integration.py` checks that every JSON file parses, that
|
||||
`manifest.json` has the keys Home Assistant requires of a custom integration,
|
||||
and that each file in `translations/` has the same key structure as
|
||||
`strings.json`.
|
||||
|
||||
`smoke-test/run.sh` exercises the client against a real DKN Cloud NA account.
|
||||
It needs a `.env` with `DKN_CLOUD_NA_EMAIL` and `DKN_CLOUD_NA_PASSWORD` (see
|
||||
`.env.example`) and is run by hand, not in CI.
|
||||
|
||||
---
|
||||
|
||||
## Credits
|
||||
|
||||
- Original Homebridge plugin: [homebridge-dkncloudna](https://github.com/plecong/homebridge-dkncloudna) by [@plecong](https://github.com/plecong)
|
||||
- EU counterpart inspiration: [DKNCloud-HASS](https://github.com/eXPerience83/DKNCloud-HASS) by [@eXPerience83](https://github.com/eXPerience83)
|
||||
|
||||
[hacs-badge]: https://img.shields.io/badge/HACS-Custom-orange.svg
|
||||
[hacs-url]: https://github.com/hacs/integration
|
||||
[validate-badge]: https://github.com/lavoiesl/homeassistant-dkncloudna/actions/workflows/validate.yml/badge.svg
|
||||
[validate-url]: https://github.com/lavoiesl/homeassistant-dkncloudna/actions/workflows/validate.yml
|
||||
|
||||
@@ -49,6 +49,11 @@ class DknCloudNaClient:
|
||||
token: str | None = None,
|
||||
refresh_token: str | None = None,
|
||||
) -> None:
|
||||
"""Initialise the client.
|
||||
|
||||
Either ``password`` (for a fresh login) or ``token`` /
|
||||
``refresh_token`` (to resume an existing session) should be supplied.
|
||||
"""
|
||||
self._username = username
|
||||
self._session = session
|
||||
self._password = password
|
||||
@@ -65,6 +70,10 @@ class DknCloudNaClient:
|
||||
self._socket_refresh_callback: Callable[[], Awaitable[None]] | None = None
|
||||
self._last_command_ack: dict[str, Any] | None = None
|
||||
self._recent_socket_events: deque[dict[str, Any]] = deque(maxlen=20)
|
||||
# Incremented on every successful Socket.IO connection so consumers can
|
||||
# tell that live state accumulated from the previous session is no
|
||||
# longer trustworthy and must be re-synced from REST.
|
||||
self.socket_session = 0
|
||||
|
||||
def clear_password(self) -> None:
|
||||
"""Discard password from memory after token exchange."""
|
||||
@@ -186,7 +195,11 @@ class DknCloudNaClient:
|
||||
socketio_path=API_SOCKET_PATH.strip("/"),
|
||||
namespaces=namespaces,
|
||||
)
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err: # noqa: BLE001 - socket is best-effort
|
||||
# The Socket.IO connection is an optimisation on top of polling.
|
||||
# python-socketio surfaces transport failures as a grab-bag of
|
||||
# exception types, and none of them should take the integration
|
||||
# down: returning False just means we fall back to the poll cycle.
|
||||
LOGGER.debug("DKN socket connect failed: %s", err)
|
||||
await sio.disconnect()
|
||||
return False
|
||||
@@ -194,6 +207,7 @@ class DknCloudNaClient:
|
||||
self._socket = sio
|
||||
self._socket_installations = installation_ids
|
||||
self._socket_token = self.token
|
||||
self.socket_session += 1
|
||||
return True
|
||||
|
||||
async def _ensure_socket_ready_for_write_locked(self, installation_id: str) -> None:
|
||||
@@ -215,6 +229,15 @@ class DknCloudNaClient:
|
||||
async with self._socket_lock:
|
||||
await self._disconnect_socket_locked()
|
||||
|
||||
@property
|
||||
def socket_connected(self) -> bool:
|
||||
"""Return whether the Socket.IO connection is currently up.
|
||||
|
||||
Live updates arrive over this connection; when it is down the
|
||||
integration still works, but only refreshes on the poll interval.
|
||||
"""
|
||||
return self._socket is not None and self._socket.connected
|
||||
|
||||
async def async_send_machine_event(
|
||||
self,
|
||||
installation_id: str,
|
||||
@@ -246,7 +269,7 @@ class DknCloudNaClient:
|
||||
"ack": ack,
|
||||
}
|
||||
LOGGER.debug("DKN socket ack %s %s", namespace, ack)
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err:
|
||||
raise DknConnectionError(str(err) or type(err).__name__) from err
|
||||
|
||||
def pop_last_command_debug(self) -> dict[str, Any] | None:
|
||||
@@ -270,8 +293,11 @@ class DknCloudNaClient:
|
||||
if socket is not None:
|
||||
try:
|
||||
await socket.disconnect()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
except Exception as err: # noqa: BLE001 - teardown must never raise
|
||||
# The socket reference is already dropped, so a failed
|
||||
# disconnect leaves nothing to act on. Log it rather than
|
||||
# swallowing it silently, so a recurring failure is visible.
|
||||
LOGGER.debug("DKN socket disconnect failed: %s", err)
|
||||
|
||||
def _store_tokens(self, data: Any) -> None:
|
||||
"""Persist access and refresh tokens from an API response."""
|
||||
@@ -392,7 +418,7 @@ class DknCloudNaClient:
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
) as response:
|
||||
data = await self._read_response(response)
|
||||
except asyncio.TimeoutError as err:
|
||||
except TimeoutError as err:
|
||||
raise DknConnectionError("Request timed out") from err
|
||||
except ClientError as err:
|
||||
raise DknConnectionError(str(err) or type(err).__name__) from err
|
||||
@@ -446,6 +472,7 @@ class DknCloudNaClient:
|
||||
return f"HTTP {response.status}: {response.reason}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Return a debug representation with the username and token redacted."""
|
||||
first = self._username[0] if self._username else "?"
|
||||
token_state = "set" if self.token else "none"
|
||||
return f"DknCloudNaClient(u={first}***, token={token_state})"
|
||||
|
||||
@@ -22,6 +22,7 @@ from .entity import DknEntity
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class DknBinarySensorEntityDescription(BinarySensorEntityDescription):
|
||||
"""Extend BinarySensorEntityDescription with a device_data key."""
|
||||
|
||||
data_key: str = ""
|
||||
|
||||
|
||||
@@ -67,12 +68,14 @@ class DknBinarySensorEntity(DknEntity, BinarySensorEntity):
|
||||
mac: str,
|
||||
description: DknBinarySensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialise the binary sensor from its description."""
|
||||
super().__init__(coordinator, mac)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{DOMAIN}_{mac}_{description.key}"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return the described device flag, or None if absent."""
|
||||
value = self._device_data.get(self.entity_description.data_key)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from homeassistant.components.climate import (
|
||||
HVACAction,
|
||||
ClimateEntity,
|
||||
ClimateEntityFeature,
|
||||
HVACAction,
|
||||
HVACMode,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
@@ -30,6 +30,8 @@ from .const import (
|
||||
SPEED_100,
|
||||
SPEED_AUTO,
|
||||
)
|
||||
from .coordinator import DknCoordinator
|
||||
from .entity import DknEntity
|
||||
from .model import (
|
||||
available_fan_speeds,
|
||||
current_temperature as model_current_temperature,
|
||||
@@ -39,11 +41,9 @@ from .model import (
|
||||
supports_swing,
|
||||
target_temperature as model_target_temperature,
|
||||
target_temperature_key,
|
||||
writable_target_temperature_key,
|
||||
to_device_temperature,
|
||||
writable_target_temperature_key,
|
||||
)
|
||||
from .coordinator import DknCoordinator
|
||||
from .entity import DknEntity
|
||||
|
||||
_MODE_TO_HVAC: dict[int, HVACMode] = {
|
||||
DEVICE_MODE_AUTO: HVACMode.AUTO,
|
||||
@@ -85,7 +85,7 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
_attr_name = None
|
||||
_attr_temperature_unit = UnitOfTemperature.CELSIUS
|
||||
_attr_precision = PRECISION_WHOLE
|
||||
_attr_hvac_modes = [
|
||||
_attr_hvac_modes: ClassVar[list[HVACMode]] = [
|
||||
HVACMode.OFF,
|
||||
HVACMode.AUTO,
|
||||
HVACMode.COOL,
|
||||
@@ -93,12 +93,13 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
HVACMode.DRY,
|
||||
HVACMode.FAN_ONLY,
|
||||
]
|
||||
_attr_swing_modes = ["off", "swing"]
|
||||
_attr_swing_modes: ClassVar[list[str]] = ["off", "swing"]
|
||||
_attr_min_temp = 16
|
||||
_attr_max_temp = 32
|
||||
_attr_target_temperature_step = 1
|
||||
|
||||
def __init__(self, coordinator: DknCoordinator, mac: str) -> None:
|
||||
"""Initialise the climate entity for a single indoor unit."""
|
||||
super().__init__(coordinator, mac)
|
||||
self._attr_unique_id = f"{DOMAIN}_{mac}"
|
||||
|
||||
@@ -116,11 +117,13 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
|
||||
@property
|
||||
def fan_modes(self) -> list[str] | None:
|
||||
"""Return the fan speeds this unit reports as available."""
|
||||
labels = fan_mode_labels(self._device_data)
|
||||
return labels or None
|
||||
|
||||
@property
|
||||
def hvac_mode(self) -> HVACMode:
|
||||
"""Return the current mode, preferring an unexpired optimistic write."""
|
||||
data = self._device_data
|
||||
power = self._optimistic_get("power", data.get("power", False))
|
||||
if not power:
|
||||
@@ -133,10 +136,21 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
|
||||
@property
|
||||
def hvac_action(self) -> HVACAction | None:
|
||||
if self.hvac_mode == HVACMode.OFF:
|
||||
"""Return what the unit is inferred to be doing right now.
|
||||
|
||||
The cloud API reports no explicit action, so this is derived from the
|
||||
mode and the gap between room and target temperature.
|
||||
"""
|
||||
mode = self.hvac_mode
|
||||
if mode == HVACMode.OFF:
|
||||
return HVACAction.OFF
|
||||
|
||||
action = inferred_hvac_action(self._device_data)
|
||||
action = inferred_hvac_action(
|
||||
self._device_data,
|
||||
mode=_HVAC_TO_MODE.get(mode),
|
||||
target=self.target_temperature,
|
||||
power=True,
|
||||
)
|
||||
if action == "heating":
|
||||
return HVACAction.HEATING
|
||||
if action == "cooling":
|
||||
@@ -151,37 +165,59 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
|
||||
@property
|
||||
def current_temperature(self) -> float | None:
|
||||
"""Return the room temperature in Celsius."""
|
||||
return model_current_temperature(self._device_data)
|
||||
|
||||
@property
|
||||
def target_temperature(self) -> float | None:
|
||||
"""Return the setpoint for the effective mode, in Celsius."""
|
||||
mode = self.hvac_mode
|
||||
if mode in _NO_TARGET_TEMP_MODES:
|
||||
return None
|
||||
fallback = model_target_temperature(self._device_data)
|
||||
# Read the setpoint for the effective mode so the value shown matches
|
||||
# the key a write would target, even while a mode change is still
|
||||
# propagating through the cloud.
|
||||
fallback = model_target_temperature(self._device_data, _HVAC_TO_MODE.get(mode))
|
||||
if fallback is None:
|
||||
fallback = model_target_temperature(self._device_data)
|
||||
if fallback is None:
|
||||
return None
|
||||
return self._optimistic_get("target_temp", fallback)
|
||||
|
||||
@property
|
||||
def target_temperature_high(self) -> float | None:
|
||||
"""Return None: the unit has a single setpoint, not a range."""
|
||||
return None
|
||||
|
||||
@property
|
||||
def target_temperature_low(self) -> float | None:
|
||||
"""Return None: the unit has a single setpoint, not a range."""
|
||||
return None
|
||||
|
||||
@property
|
||||
def fan_mode(self) -> str | None:
|
||||
"""Return the current fan speed label."""
|
||||
speed = self._device_data.get("speed_state", SPEED_AUTO)
|
||||
return self._optimistic_get("fan_mode", _SPEED_TO_FAN.get(int(speed), "auto"))
|
||||
|
||||
@property
|
||||
def swing_mode(self) -> str | None:
|
||||
"""Return whether the vertical slats are swinging."""
|
||||
slat = self._device_data.get("slats_vertical_1", 0)
|
||||
return self._optimistic_get("swing_mode", "swing" if int(slat) == 9 else "off")
|
||||
|
||||
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
|
||||
"""Turn the unit off, or switch it on into the requested mode."""
|
||||
# Resolved before the try block below. An unsupported mode is a caller
|
||||
# error, not a cloud failure, and raising it inside the try would let
|
||||
# the blanket handler re-wrap it as "Failed to set HVAC mode:
|
||||
# Unsupported HVAC mode: ...".
|
||||
mode: int | None = None
|
||||
if hvac_mode != HVACMode.OFF:
|
||||
mode = _HVAC_TO_MODE.get(hvac_mode)
|
||||
if mode is None:
|
||||
raise HomeAssistantError(f"Unsupported HVAC mode: {hvac_mode}")
|
||||
|
||||
installation_id = self._installation_id
|
||||
async with self._get_device_lock():
|
||||
try:
|
||||
@@ -199,9 +235,6 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
device_value=False,
|
||||
)
|
||||
else:
|
||||
mode = _HVAC_TO_MODE.get(hvac_mode)
|
||||
if mode is None:
|
||||
raise HomeAssistantError(f"Unsupported HVAC mode: {hvac_mode}")
|
||||
await self.coordinator.client.async_send_machine_event(
|
||||
installation_id, self._command_mac, "power", True
|
||||
)
|
||||
@@ -217,13 +250,14 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
device_key="mode",
|
||||
device_value=mode,
|
||||
)
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err:
|
||||
raise HomeAssistantError(f"Failed to set HVAC mode: {err}") from err
|
||||
|
||||
self._schedule_refresh()
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_set_temperature(self, **kwargs: Any) -> None:
|
||||
"""Set the target temperature, optionally changing mode first."""
|
||||
hvac_mode = kwargs.get("hvac_mode")
|
||||
if hvac_mode is not None:
|
||||
await self.async_set_hvac_mode(hvac_mode)
|
||||
@@ -239,35 +273,26 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
)
|
||||
|
||||
installation_id = self._installation_id
|
||||
property_name = self._writable_temperature_property_for_mode(target_mode)
|
||||
device_temp = self._to_device_temperature(float(temperature))
|
||||
requested_mode_code = _HVAC_TO_MODE.get(target_mode)
|
||||
|
||||
async with self._get_device_lock():
|
||||
# A mode change made moments ago (either above, or by a separate
|
||||
# set_hvac_mode call from the UI) may not have landed in the cloud
|
||||
# yet. Give it a bounded window to be echoed back before writing the
|
||||
# setpoint, so the setpoint is not applied against the old mode.
|
||||
if (
|
||||
requested_mode_code is not None
|
||||
and self._device_data.get("mode") != requested_mode_code
|
||||
):
|
||||
await self._async_wait_for_device_value("mode", requested_mode_code)
|
||||
|
||||
property_name = self._writable_temperature_property_for_mode(target_mode)
|
||||
device_temp = self._to_device_temperature(float(temperature))
|
||||
try:
|
||||
requested_mode_code = _HVAC_TO_MODE.get(target_mode)
|
||||
if (
|
||||
requested_mode_code is not None
|
||||
and self._device_data.get("mode") != requested_mode_code
|
||||
):
|
||||
await self.coordinator.client.async_send_machine_event(
|
||||
installation_id, self._command_mac, "power", True
|
||||
)
|
||||
await self.coordinator.client.async_send_machine_event(
|
||||
installation_id, self._command_mac, "mode", requested_mode_code
|
||||
)
|
||||
self._optimistic_set(
|
||||
"power", True, device_key="power", device_value=True
|
||||
)
|
||||
self._optimistic_set(
|
||||
"hvac_mode",
|
||||
target_mode,
|
||||
device_key="mode",
|
||||
device_value=requested_mode_code,
|
||||
)
|
||||
await self.coordinator.client.async_send_machine_event(
|
||||
installation_id, self._command_mac, property_name, device_temp
|
||||
)
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err:
|
||||
raise HomeAssistantError(f"Failed to set temperature: {err}") from err
|
||||
|
||||
self._optimistic_set(
|
||||
@@ -280,6 +305,7 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_set_fan_mode(self, fan_mode: str) -> None:
|
||||
"""Set the fan speed."""
|
||||
speed = _FAN_TO_SPEED.get(fan_mode)
|
||||
if speed is None:
|
||||
raise HomeAssistantError(f"Unsupported fan mode: {fan_mode}")
|
||||
@@ -292,7 +318,7 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
await self.coordinator.client.async_send_machine_event(
|
||||
installation_id, self._command_mac, "speed_state", speed
|
||||
)
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err:
|
||||
raise HomeAssistantError(f"Failed to set fan mode: {err}") from err
|
||||
|
||||
self._optimistic_set(
|
||||
@@ -302,6 +328,7 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_set_swing_mode(self, swing_mode: str) -> None:
|
||||
"""Start or stop the vertical slat swing."""
|
||||
if swing_mode not in {"off", "swing"}:
|
||||
raise HomeAssistantError(f"Unsupported swing mode: {swing_mode}")
|
||||
if not supports_swing(self._device_data):
|
||||
@@ -314,7 +341,7 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
await self.coordinator.client.async_send_machine_event(
|
||||
installation_id, self._command_mac, "slats_vertical_1", slat
|
||||
)
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err:
|
||||
raise HomeAssistantError(f"Failed to set swing mode: {err}") from err
|
||||
|
||||
self._optimistic_set(
|
||||
@@ -324,9 +351,11 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_turn_on(self) -> None:
|
||||
"""Turn the unit on into auto mode."""
|
||||
await self.async_set_hvac_mode(HVACMode.AUTO)
|
||||
|
||||
async def async_turn_off(self) -> None:
|
||||
"""Turn the unit off."""
|
||||
await self.async_set_hvac_mode(HVACMode.OFF)
|
||||
|
||||
@property
|
||||
@@ -354,10 +383,14 @@ class DknClimateEntity(DknEntity, ClimateEntity):
|
||||
return key
|
||||
|
||||
def _writable_temperature_property_for_mode(self, hvac_mode: HVACMode) -> str:
|
||||
preferred = writable_target_temperature_key(self._device_data)
|
||||
if preferred is not None:
|
||||
return preferred
|
||||
return self._temperature_property_for_mode(hvac_mode)
|
||||
# The key must follow the mode being requested, not whatever mode the
|
||||
# cached device payload still reports; that payload lags behind a mode
|
||||
# change and would send e.g. a heat setpoint to setpoint_air_cool.
|
||||
requested = self._temperature_property_for_mode(hvac_mode)
|
||||
preferred = writable_target_temperature_key(
|
||||
self._device_data, _HVAC_TO_MODE.get(hvac_mode)
|
||||
)
|
||||
return preferred or requested
|
||||
|
||||
def _to_device_temperature(self, temperature_c: float) -> float | int:
|
||||
return to_device_temperature(temperature_c, self._device_data.get("units"))
|
||||
|
||||
@@ -6,11 +6,11 @@ import asyncio
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import voluptuous as vol
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import voluptuous as vol
|
||||
|
||||
from .api import DknAuthError, DknCloudNaClient, DknConnectionError
|
||||
from .const import (
|
||||
@@ -49,6 +49,7 @@ class DknConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
VERSION = 1
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialise the flow's accumulated state."""
|
||||
self._email: str = ""
|
||||
self._scan_interval: int = DEFAULT_SCAN_INTERVAL
|
||||
self._expose_pii: bool = False
|
||||
@@ -59,6 +60,7 @@ class DknConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
def async_get_options_flow(
|
||||
entry: config_entries.ConfigEntry,
|
||||
) -> config_entries.OptionsFlow:
|
||||
"""Return the options flow for an existing entry."""
|
||||
return DknOptionsFlow(entry)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -68,6 +70,7 @@ class DknConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> config_entries.FlowResult:
|
||||
"""Collect credentials and verify them against the cloud."""
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
@@ -91,7 +94,7 @@ class DknConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
errors["base"] = "invalid_auth"
|
||||
except DknConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected error during login")
|
||||
errors["base"] = "unknown"
|
||||
finally:
|
||||
@@ -158,14 +161,17 @@ class DknConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def async_step_reauth(
|
||||
self, entry_data: dict[str, Any]
|
||||
self,
|
||||
entry_data: dict[str, Any], # noqa: ARG002 - required by the HA flow API
|
||||
) -> config_entries.FlowResult:
|
||||
"""Handle re-authentication after the refresh token stops working."""
|
||||
self._reauth_entry_id = (self.context or {}).get("entry_id")
|
||||
return await self.async_step_reauth_confirm()
|
||||
|
||||
async def async_step_reauth_confirm(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> config_entries.FlowResult:
|
||||
"""Prompt for the password again and store a fresh token."""
|
||||
entry = None
|
||||
if getattr(self, "_reauth_entry_id", None):
|
||||
entry = self.hass.config_entries.async_get_entry(self._reauth_entry_id)
|
||||
@@ -192,7 +198,8 @@ class DknConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
errors["base"] = "invalid_auth"
|
||||
except DknConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected error during reauthentication")
|
||||
errors["base"] = "unknown"
|
||||
finally:
|
||||
client.clear_password()
|
||||
@@ -216,11 +223,13 @@ class DknOptionsFlow(config_entries.OptionsFlow):
|
||||
"""Options flow: scan interval + PII toggle."""
|
||||
|
||||
def __init__(self, entry: config_entries.ConfigEntry) -> None:
|
||||
"""Initialise the options flow for an existing entry."""
|
||||
self._entry = entry
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> config_entries.FlowResult:
|
||||
"""Show and persist the scan interval and PII toggle."""
|
||||
opts = self._entry.options
|
||||
defaults = {
|
||||
CONF_SCAN_INTERVAL: int(
|
||||
|
||||
@@ -31,8 +31,9 @@ SOCKET_RECONNECT_ATTEMPTS = 5
|
||||
# Config/options keys
|
||||
CONF_SCAN_INTERVAL = "scan_interval"
|
||||
CONF_EXPOSE_PII = "expose_pii"
|
||||
CONF_USER_TOKEN = "user_token"
|
||||
CONF_REFRESH_TOKEN = "refresh_token"
|
||||
# These two are config-entry key names, not credentials.
|
||||
CONF_USER_TOKEN = "user_token" # noqa: S105
|
||||
CONF_REFRESH_TOKEN = "refresh_token" # noqa: S105
|
||||
|
||||
# Defaults
|
||||
DEFAULT_SCAN_INTERVAL = 60 # seconds
|
||||
@@ -48,6 +49,12 @@ OPTIMISTIC_TTL_SEC: float = 30.0
|
||||
# Post-write coordinator refresh: coalesced delay after a device command.
|
||||
POST_WRITE_REFRESH_DELAY_SEC: float = 1.0
|
||||
|
||||
# Bounded wait for the cloud to echo a dependent write (e.g. confirming a mode
|
||||
# change before the matching setpoint is sent) and the poll step used while
|
||||
# waiting.
|
||||
DEVICE_ECHO_TIMEOUT_SEC: float = 8.0
|
||||
DEVICE_ECHO_POLL_SEC: float = 0.25
|
||||
|
||||
# Device modes (from homebridge plugin src/types.ts)
|
||||
# DeviceMode: 1=Auto, 2=Cool, 3=Heat, 4=Fan, 5=Dry
|
||||
DEVICE_MODE_AUTO = 1
|
||||
|
||||
@@ -12,7 +12,13 @@ from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .api import DknAuthError, DknCloudNaClient, DknConnectionError
|
||||
from .const import CONF_REFRESH_TOKEN, CONF_USER_TOKEN, DEFAULT_SCAN_INTERVAL, DOMAIN, LOGGER
|
||||
from .const import (
|
||||
CONF_REFRESH_TOKEN,
|
||||
CONF_USER_TOKEN,
|
||||
DEFAULT_SCAN_INTERVAL,
|
||||
DOMAIN,
|
||||
LOGGER,
|
||||
)
|
||||
|
||||
|
||||
class DknCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
|
||||
@@ -34,6 +40,7 @@ class DknCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
|
||||
entry: ConfigEntry,
|
||||
client: DknCloudNaClient,
|
||||
) -> None:
|
||||
"""Initialise the coordinator with the entry's scan interval."""
|
||||
scan_interval = int(entry.options.get("scan_interval", DEFAULT_SCAN_INTERVAL))
|
||||
super().__init__(
|
||||
hass,
|
||||
@@ -44,6 +51,11 @@ class DknCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
|
||||
self.client = client
|
||||
self._entry = entry
|
||||
self.entry_id = entry.entry_id
|
||||
# Values pushed over Socket.IO during the current socket session, keyed
|
||||
# by mac. The REST /installations snapshot can lag behind reality, so
|
||||
# these take precedence over it until the socket reconnects.
|
||||
self._live_state: dict[str, dict[str, Any]] = {}
|
||||
self._live_state_session: int = 0
|
||||
|
||||
async def _async_update_data(self) -> dict[str, dict[str, Any]]:
|
||||
"""Fetch all installations and flatten into {mac: device_dict}."""
|
||||
@@ -61,10 +73,11 @@ class DknCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
|
||||
raise UpdateFailed(f"Cannot reach DKN Cloud NA: {err}") from err
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as err: # noqa: BLE001
|
||||
except Exception as err:
|
||||
raise UpdateFailed(f"Unexpected error: {type(err).__name__}") from err
|
||||
|
||||
self._persist_tokens_if_changed()
|
||||
self._discard_stale_live_state()
|
||||
|
||||
devices: dict[str, dict[str, Any]] = {}
|
||||
existing = self.data or {}
|
||||
@@ -77,11 +90,27 @@ class DknCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
|
||||
devices[mac] = {
|
||||
**existing.get(mac, {}),
|
||||
**device,
|
||||
# Socket.IO pushes are the live source of truth; the REST
|
||||
# snapshot is frequently a few minutes behind and would
|
||||
# otherwise revert state the socket already reported.
|
||||
**self._live_state.get(mac, {}),
|
||||
"_installation_id": inst_id,
|
||||
}
|
||||
|
||||
return devices
|
||||
|
||||
def _discard_stale_live_state(self) -> None:
|
||||
"""Drop accumulated live state when the socket session has changed.
|
||||
|
||||
A new socket session means updates may have been missed while it was
|
||||
down, so the REST snapshot becomes authoritative again until fresh
|
||||
pushes arrive.
|
||||
"""
|
||||
session = self.client.socket_session
|
||||
if session != self._live_state_session:
|
||||
self._live_state_session = session
|
||||
self._live_state = {}
|
||||
|
||||
def _persist_tokens_if_changed(self) -> None:
|
||||
"""Save refreshed tokens back to the config entry so they survive restarts."""
|
||||
opts = self._entry.options
|
||||
@@ -105,6 +134,8 @@ class DknCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
|
||||
self, mac: str, data: dict[str, Any]
|
||||
) -> None:
|
||||
"""Merge live device-data from Socket.IO into coordinator state."""
|
||||
self._discard_stale_live_state()
|
||||
self._live_state[mac] = {**self._live_state.get(mac, {}), **data}
|
||||
current = dict(self.data or {})
|
||||
current[mac] = {**current.get(mac, {}), **data}
|
||||
self.async_set_updated_data(current)
|
||||
|
||||
@@ -10,6 +10,8 @@ from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, Device
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from .const import (
|
||||
DEVICE_ECHO_POLL_SEC,
|
||||
DEVICE_ECHO_TIMEOUT_SEC,
|
||||
DOMAIN,
|
||||
MANUFACTURER,
|
||||
OPTIMISTIC_TTL_SEC,
|
||||
@@ -32,6 +34,7 @@ class DknEntity(CoordinatorEntity[DknCoordinator]):
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(self, coordinator: DknCoordinator, mac: str) -> None:
|
||||
"""Initialise the entity for the device with this MAC."""
|
||||
super().__init__(coordinator)
|
||||
self._mac = mac
|
||||
|
||||
@@ -50,6 +53,7 @@ class DknEntity(CoordinatorEntity[DknCoordinator]):
|
||||
|
||||
@property
|
||||
def device_info(self) -> DeviceInfo:
|
||||
"""Return the device registry entry for this indoor unit."""
|
||||
data = self._device_data
|
||||
return DeviceInfo(
|
||||
identifiers={(DOMAIN, self._mac)},
|
||||
@@ -137,6 +141,37 @@ class DknEntity(CoordinatorEntity[DknCoordinator]):
|
||||
self._reconcile_optimistic()
|
||||
super()._handle_coordinator_update()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Waiting for the cloud to echo a write
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _async_wait_for_device_value(
|
||||
self,
|
||||
device_key: str,
|
||||
expected: Any,
|
||||
timeout: float = DEVICE_ECHO_TIMEOUT_SEC,
|
||||
) -> bool:
|
||||
"""Wait until the device reports ``expected`` for ``device_key``.
|
||||
|
||||
Socket.IO pushes land in coordinator data, so polling it is enough. A
|
||||
single mid-window refresh covers the case where no push arrives.
|
||||
Returns whether the value was observed before the timeout.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout
|
||||
refreshed = False
|
||||
while True:
|
||||
if self._device_data.get(device_key) == expected:
|
||||
return True
|
||||
remaining = deadline - loop.time()
|
||||
if remaining <= 0:
|
||||
return False
|
||||
if not refreshed and remaining < timeout / 2:
|
||||
refreshed = True
|
||||
await self.coordinator.async_request_refresh()
|
||||
continue
|
||||
await asyncio.sleep(min(DEVICE_ECHO_POLL_SEC, remaining))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Post-write coordinator refresh (coalesced)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"domain": "dkncloudna",
|
||||
"name": "DKN Cloud NA",
|
||||
"codeowners": ["@lavoiesl"],
|
||||
"codeowners": ["@thatguygriff"],
|
||||
"config_flow": true,
|
||||
"documentation": "https://github.com/lavoiesl/homeassistant-dkncloudna",
|
||||
"documentation": "https://git.unsupervised.ca/GitHub/homeassistant-dkncloudna",
|
||||
"integration_type": "hub",
|
||||
"iot_class": "cloud_polling",
|
||||
"issue_tracker": "https://github.com/lavoiesl/homeassistant-dkncloudna/issues",
|
||||
"issue_tracker": "https://git.unsupervised.ca/GitHub/homeassistant-dkncloudna/issues",
|
||||
"requirements": ["python-socketio>=4.6.1,<5"],
|
||||
"version": "0.2.0"
|
||||
"version": "0.2.1"
|
||||
}
|
||||
|
||||
@@ -84,19 +84,35 @@ def target_temperature_key(mode: int | None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def target_temperature(data: dict[str, Any]) -> float | None:
|
||||
"""Return the requested target temperature in Celsius."""
|
||||
key = target_temperature_key(requested_mode(data))
|
||||
def target_temperature(data: dict[str, Any], mode: int | None = None) -> float | None:
|
||||
"""Return the target temperature in Celsius for ``mode``.
|
||||
|
||||
``mode`` defaults to the device's requested mode. Callers that already know
|
||||
the effective mode (for example while an optimistic mode change is still
|
||||
propagating) should pass it so the read uses the same setpoint key the
|
||||
write used.
|
||||
"""
|
||||
key = target_temperature_key(mode if mode is not None else requested_mode(data))
|
||||
if key is None:
|
||||
return None
|
||||
return to_celsius(data.get(key), data.get("units"))
|
||||
|
||||
|
||||
def writable_target_temperature_key(data: dict[str, Any]) -> str | None:
|
||||
"""Return the setpoint key most likely to be writable for the current state."""
|
||||
def writable_target_temperature_key(
|
||||
data: dict[str, Any], mode: int | None = None
|
||||
) -> str | None:
|
||||
"""Return the setpoint key to write for ``mode``.
|
||||
|
||||
``mode`` is the mode the write is intended for and takes priority over
|
||||
anything in ``data``, which may still describe the pre-change state while a
|
||||
mode change propagates through the cloud. The device-reported modes are
|
||||
only consulted as a fallback for payloads that do not expose the requested
|
||||
mode's setpoint at all.
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
for mode in (live_mode(data), requested_mode(data), DEVICE_MODE_AUTO):
|
||||
key = target_temperature_key(mode)
|
||||
preference = (mode, live_mode(data), requested_mode(data), DEVICE_MODE_AUTO)
|
||||
for candidate_mode in preference:
|
||||
key = target_temperature_key(candidate_mode)
|
||||
if key is not None and key not in candidates:
|
||||
candidates.append(key)
|
||||
|
||||
@@ -107,15 +123,28 @@ def writable_target_temperature_key(data: dict[str, Any]) -> str | None:
|
||||
return candidates[0] if candidates else None
|
||||
|
||||
|
||||
def inferred_hvac_action(data: dict[str, Any]) -> str:
|
||||
"""Infer the active HVAC action from requested mode and temperatures."""
|
||||
power = as_bool(data.get("power"))
|
||||
def inferred_hvac_action(
|
||||
data: dict[str, Any],
|
||||
mode: int | None = None,
|
||||
target: float | None = None,
|
||||
power: bool | None = None,
|
||||
) -> str:
|
||||
"""Infer the active HVAC action from the effective mode and temperatures.
|
||||
|
||||
``mode``, ``target`` and ``power`` let callers supply the effective
|
||||
(possibly still optimistic) values so the reported action matches the
|
||||
reported mode.
|
||||
"""
|
||||
if power is None:
|
||||
power = as_bool(data.get("power"))
|
||||
if not power:
|
||||
return "off"
|
||||
|
||||
mode = requested_mode(data)
|
||||
if mode is None:
|
||||
mode = requested_mode(data)
|
||||
current = current_temperature(data)
|
||||
target = target_temperature(data)
|
||||
if target is None:
|
||||
target = target_temperature(data, mode)
|
||||
|
||||
if mode == DEVICE_MODE_HEAT:
|
||||
if current is not None and target is not None and current < target:
|
||||
|
||||
@@ -91,12 +91,14 @@ class DknSensorEntity(DknEntity, SensorEntity):
|
||||
mac: str,
|
||||
description: DknSensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialise the sensor from its description."""
|
||||
super().__init__(coordinator, mac)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{DOMAIN}_{mac}_{description.key}"
|
||||
|
||||
@property
|
||||
def native_value(self) -> Any:
|
||||
"""Return the described device value, converted where needed."""
|
||||
if self.entity_description.data_key == "work_temp":
|
||||
return current_temperature(self._device_data)
|
||||
if self.entity_description.data_key == "ext_temp":
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "DKN Cloud NA",
|
||||
"homeassistant": "2024.1.0",
|
||||
"hacs": "2.0.0"
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
# Lint config for CI.
|
||||
#
|
||||
# The rule set is broad on purpose and tracks Home Assistant core's conventions
|
||||
# reasonably closely, so that this integration would not need a rewrite to be
|
||||
# read by anyone used to HA code.
|
||||
#
|
||||
# CI pins the ruff version (see .gitea/workflows/ci.yml) because ruff's default
|
||||
# rule set and formatter output change between releases.
|
||||
|
||||
target-version = "py312"
|
||||
line-length = 88
|
||||
|
||||
# Dated design records. They contain illustrative, intentionally incomplete
|
||||
# code blocks and are not maintained source.
|
||||
exclude = ["docs"]
|
||||
|
||||
[lint]
|
||||
select = [
|
||||
"A", # flake8-builtins
|
||||
"ARG", # flake8-unused-arguments
|
||||
"ASYNC", # flake8-async
|
||||
"B", # flake8-bugbear
|
||||
"BLE", # flake8-blind-except
|
||||
"C4", # flake8-comprehensions
|
||||
"D", # pydocstyle
|
||||
"E", # pycodestyle errors
|
||||
"F", # pyflakes
|
||||
"FLY", # flynt
|
||||
"G", # flake8-logging-format
|
||||
"I", # isort
|
||||
"ICN", # flake8-import-conventions
|
||||
"INP", # flake8-no-pep420
|
||||
"ISC", # flake8-implicit-str-concat
|
||||
"LOG", # flake8-logging
|
||||
"N", # pep8-naming
|
||||
"PERF", # perflint
|
||||
"PIE", # flake8-pie
|
||||
"PT", # flake8-pytest-style
|
||||
"PTH", # flake8-use-pathlib
|
||||
"Q", # flake8-quotes
|
||||
"RET", # flake8-return
|
||||
"RSE", # flake8-raise
|
||||
"RUF", # ruff-specific
|
||||
"S", # flake8-bandit
|
||||
"SIM", # flake8-simplify
|
||||
"SLF", # flake8-self
|
||||
"TID", # flake8-tidy-imports
|
||||
"TRY", # tryceratops
|
||||
"UP", # pyupgrade
|
||||
"W", # pycodestyle warnings
|
||||
]
|
||||
|
||||
ignore = [
|
||||
# Wants every raise to use a purpose-built exception class whose message is
|
||||
# baked in, rather than `raise DknConnectionError("Request timed out")`.
|
||||
# That trades readable, situation-specific messages for a pile of
|
||||
# single-use classes. Home Assistant core disables this rule too.
|
||||
"TRY003",
|
||||
# Wants `async with asyncio.timeout(...)` at the call site instead of a
|
||||
# `timeout` parameter. The wait helpers here use the timeout value for
|
||||
# scheduling decisions (e.g. refreshing at the halfway point), not just for
|
||||
# cancellation, so the value has to be passed in.
|
||||
"ASYNC109",
|
||||
]
|
||||
|
||||
[lint.per-file-ignores]
|
||||
# Standalone scripts, deliberately not packages, and printing to stdout is
|
||||
# their entire job.
|
||||
"scripts/*" = ["INP001", "T201"]
|
||||
"smoke-test/*" = ["INP001", "T201"]
|
||||
|
||||
[lint.isort]
|
||||
# Home Assistant core style.
|
||||
force-sort-within-sections = true
|
||||
combine-as-imports = true
|
||||
|
||||
[lint.flake8-tidy-imports]
|
||||
ban-relative-imports = "parents"
|
||||
|
||||
[lint.pydocstyle]
|
||||
convention = "pep257"
|
||||
Executable
+190
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the integration's static metadata.
|
||||
|
||||
This replaces the parts of Home Assistant's `hassfest` action that matter for a
|
||||
manually installed custom component. hassfest itself is a GitHub-hosted action
|
||||
and cannot run on the Gitea runner, and it also enforces rules that only apply
|
||||
to integrations vendored into HA core.
|
||||
|
||||
Checks performed:
|
||||
* every JSON file in the component parses
|
||||
* manifest.json has the keys HA requires of a custom integration, with sane
|
||||
values (domain matches the directory, version is present, etc.)
|
||||
* every translation file has exactly the same key structure as strings.json,
|
||||
so a missing translation shows up here rather than as a blank label in the
|
||||
UI
|
||||
|
||||
Exits non-zero with one line per problem.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
COMPONENTS_DIR = REPO_ROOT / "custom_components"
|
||||
|
||||
# Keys HA reads from a custom integration's manifest. `version` is required for
|
||||
# custom components specifically (core integrations must omit it).
|
||||
REQUIRED_MANIFEST_KEYS = (
|
||||
"domain",
|
||||
"name",
|
||||
"codeowners",
|
||||
"documentation",
|
||||
"iot_class",
|
||||
"version",
|
||||
)
|
||||
|
||||
VALID_IOT_CLASSES = {
|
||||
"assumed_state",
|
||||
"cloud_polling",
|
||||
"cloud_push",
|
||||
"local_polling",
|
||||
"local_push",
|
||||
"calculated",
|
||||
}
|
||||
|
||||
VALID_INTEGRATION_TYPES = {
|
||||
"device",
|
||||
"entity",
|
||||
"hardware",
|
||||
"helper",
|
||||
"hub",
|
||||
"service",
|
||||
"system",
|
||||
"virtual",
|
||||
}
|
||||
|
||||
|
||||
def key_structure(value: object, prefix: str = "") -> set[str]:
|
||||
"""Flatten a nested dict into dotted key paths, ignoring leaf values."""
|
||||
if not isinstance(value, dict):
|
||||
return {prefix}
|
||||
paths: set[str] = set()
|
||||
for key, child in value.items():
|
||||
paths |= key_structure(child, f"{prefix}.{key}" if prefix else key)
|
||||
return paths
|
||||
|
||||
|
||||
def check_json_parses(errors: list[str]) -> dict[Path, object]:
|
||||
"""Parse every JSON file under custom_components/, recording failures."""
|
||||
parsed: dict[Path, object] = {}
|
||||
for path in sorted(COMPONENTS_DIR.rglob("*.json")):
|
||||
try:
|
||||
parsed[path] = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as err:
|
||||
errors.append(f"{path.relative_to(REPO_ROOT)}: invalid JSON: {err}")
|
||||
return parsed
|
||||
|
||||
|
||||
def check_manifest(component: Path, manifest: object, errors: list[str]) -> None:
|
||||
"""Validate a single manifest.json payload."""
|
||||
rel = (component / "manifest.json").relative_to(REPO_ROOT)
|
||||
|
||||
if not isinstance(manifest, dict):
|
||||
errors.append(f"{rel}: expected a JSON object")
|
||||
return
|
||||
|
||||
errors.extend(
|
||||
f"{rel}: missing required key '{key}'"
|
||||
for key in REQUIRED_MANIFEST_KEYS
|
||||
if key not in manifest
|
||||
)
|
||||
|
||||
if manifest.get("domain") != component.name:
|
||||
errors.append(
|
||||
f"{rel}: domain '{manifest.get('domain')}' does not match "
|
||||
f"directory name '{component.name}'"
|
||||
)
|
||||
|
||||
iot_class = manifest.get("iot_class")
|
||||
if iot_class is not None and iot_class not in VALID_IOT_CLASSES:
|
||||
errors.append(f"{rel}: unknown iot_class '{iot_class}'")
|
||||
|
||||
integration_type = manifest.get("integration_type")
|
||||
if integration_type is not None and integration_type not in VALID_INTEGRATION_TYPES:
|
||||
errors.append(f"{rel}: unknown integration_type '{integration_type}'")
|
||||
|
||||
codeowners = manifest.get("codeowners")
|
||||
if not isinstance(codeowners, list):
|
||||
errors.append(f"{rel}: codeowners must be a list")
|
||||
else:
|
||||
errors.extend(
|
||||
f"{rel}: codeowner '{owner}' must start with '@'"
|
||||
for owner in codeowners
|
||||
if not isinstance(owner, str) or not owner.startswith("@")
|
||||
)
|
||||
|
||||
# config_flow: true requires strings.json to describe the flow, otherwise
|
||||
# the user sees untranslated keys.
|
||||
if manifest.get("config_flow") and not (component / "strings.json").is_file():
|
||||
errors.append(f"{rel}: config_flow is true but strings.json is missing")
|
||||
|
||||
|
||||
def check_translations(
|
||||
component: Path, parsed: dict[Path, object], errors: list[str]
|
||||
) -> None:
|
||||
"""Ensure each translation file mirrors strings.json exactly."""
|
||||
strings_path = component / "strings.json"
|
||||
if strings_path not in parsed:
|
||||
return
|
||||
|
||||
expected = key_structure(parsed[strings_path])
|
||||
translations_dir = component / "translations"
|
||||
if not translations_dir.is_dir():
|
||||
errors.append(
|
||||
f"{component.relative_to(REPO_ROOT)}: strings.json exists but "
|
||||
"translations/ is missing"
|
||||
)
|
||||
return
|
||||
|
||||
for path in sorted(translations_dir.glob("*.json")):
|
||||
if path not in parsed:
|
||||
continue
|
||||
rel = path.relative_to(REPO_ROOT)
|
||||
actual = key_structure(parsed[path])
|
||||
errors.extend(
|
||||
f"{rel}: missing key '{key}'" for key in sorted(expected - actual)
|
||||
)
|
||||
errors.extend(
|
||||
f"{rel}: key '{key}' not present in strings.json"
|
||||
for key in sorted(actual - expected)
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Run every check and report the problems found."""
|
||||
errors: list[str] = []
|
||||
parsed = check_json_parses(errors)
|
||||
|
||||
components = sorted(p for p in COMPONENTS_DIR.iterdir() if p.is_dir())
|
||||
if not components:
|
||||
errors.append("custom_components/ contains no integration directory")
|
||||
|
||||
for component in components:
|
||||
manifest_path = component / "manifest.json"
|
||||
if manifest_path not in parsed:
|
||||
if not manifest_path.is_file():
|
||||
errors.append(
|
||||
f"{component.relative_to(REPO_ROOT)}: manifest.json is missing"
|
||||
)
|
||||
continue
|
||||
check_manifest(component, parsed[manifest_path], errors)
|
||||
check_translations(component, parsed, errors)
|
||||
|
||||
if errors:
|
||||
for error in errors:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
print(f"\n{len(errors)} problem(s) found.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(
|
||||
f"OK: validated {len(components)} integration(s), {len(parsed)} JSON file(s)."
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -3,12 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from aiohttp import ClientSession
|
||||
@@ -311,8 +311,7 @@ async def _main() -> None:
|
||||
current_device["_installation_id"] = installation_id
|
||||
|
||||
await client.ensure_socket_connection(installations, on_data, on_refresh)
|
||||
socket = client._socket # noqa: SLF001
|
||||
results["socket_connect"] = bool(socket and socket.connected)
|
||||
results["socket_connect"] = client.socket_connected
|
||||
if not results["socket_connect"]:
|
||||
raise RuntimeError("Socket.IO connection did not come up")
|
||||
|
||||
@@ -323,10 +322,8 @@ async def _main() -> None:
|
||||
if _has_live_state(current_device):
|
||||
return True
|
||||
remaining = max(0.1, deadline - loop.time())
|
||||
try:
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(queue.get(), timeout=min(2.0, remaining))
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
if _has_live_state(current_device):
|
||||
return True
|
||||
await fetch_current_device()
|
||||
@@ -349,10 +346,8 @@ async def _main() -> None:
|
||||
deadline = loop.time() + timeout
|
||||
while loop.time() < deadline:
|
||||
remaining = max(0.1, deadline - loop.time())
|
||||
try:
|
||||
with suppress(TimeoutError):
|
||||
await asyncio.wait_for(queue.get(), timeout=min(2.0, remaining))
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
if current_device.get(property_name) == expected:
|
||||
return True
|
||||
await fetch_current_device()
|
||||
@@ -370,7 +365,7 @@ async def _main() -> None:
|
||||
payload = await asyncio.wait_for(
|
||||
queue.get(), timeout=min(0.5, remaining)
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
except TimeoutError:
|
||||
continue
|
||||
deltas.append(payload)
|
||||
return deltas
|
||||
|
||||
Reference in New Issue
Block a user