Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 44 additions & 10 deletions custom_components/checkwatt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import random
from typing import TypedDict

from pycheckwatt import CheckwattManager, CheckWattRankManager
from pycheckwatt import CheckWattRankManager
import voluptuous as vol

from homeassistant.config_entries import ConfigEntry
Expand Down Expand Up @@ -36,6 +36,11 @@
EVENT_SIGNAL_FCRD,
INTEGRATION_NAME,
)
from .api import (
PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH,
CheckwattRateLimitError,
create_checkwatt_manager,
)

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -138,7 +143,9 @@ async def update_history_items(call: ServiceCall) -> ServiceResponse:
status = None
stored_items = 0
total_items = 0
async with CheckwattManager(username, password, INTEGRATION_NAME) as cw:
async with create_checkwatt_manager(
hass, username, password, INTEGRATION_NAME
) as cw:
try:
# Login to EnergyInBalance
if await cw.login():
Expand Down Expand Up @@ -203,6 +210,9 @@ async def update_history_items(call: ServiceCall) -> ServiceResponse:
except CheckwattError as err:
status = f"Failed to update CheckWattRank: {err}"

except CheckwattRateLimitError as err:
status = f"CheckWatt rate limited requests for {err.retry_after}"

return {
"start_date": start_date_str,
"end_date": end_date_str,
Expand All @@ -217,7 +227,9 @@ async def push_cwr(call: ServiceCall) -> ServiceResponse:
password = entry.data.get(CONF_PASSWORD)
cwr_name = entry.options.get(CONF_CWR_NAME)
status = None
async with CheckwattManager(username, password, INTEGRATION_NAME) as cw:
async with create_checkwatt_manager(
hass, username, password, INTEGRATION_NAME
) as cw:
try:
# Login to EnergyInBalance
if await cw.login():
Expand Down Expand Up @@ -254,6 +266,9 @@ async def push_cwr(call: ServiceCall) -> ServiceResponse:
except CheckwattError as err:
status = f"Failed to update CheckWattRank: {err}"

except CheckwattRateLimitError as err:
status = f"CheckWatt rate limited requests for {err.retry_after}"

return {
"result": status,
}
Expand Down Expand Up @@ -320,10 +335,21 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=DOMAIN,
update_interval=timedelta(minutes=CONF_UPDATE_INTERVAL_ALL),
)
self._entry = entry
self.client = (
create_checkwatt_manager(
hass,
entry.data.get(CONF_USERNAME),
entry.data.get(CONF_PASSWORD),
INTEGRATION_NAME,
)
if PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH
else None
)
self.last_cw_rank_push = None
self.is_boot = True
self.energy_provider = None
Expand All @@ -350,16 +376,19 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901
"""Fetch the latest data from the source."""

try:
username = self._entry.data.get(CONF_USERNAME)
password = self._entry.data.get(CONF_PASSWORD)
use_power_sensors = self._entry.options.get(CONF_POWER_SENSORS)
push_to_cw_rank = self._entry.options.get(CONF_PUSH_CW_TO_RANK)
use_cm10_sensor = self._entry.options.get(CONF_CM10_SENSOR)
cwr_name = self._entry.options.get(CONF_CWR_NAME)

async with CheckwattManager(
username, password, INTEGRATION_NAME
) as cw_inst:
# Legacy managers accumulate revenue and must be fresh per poll.
client = self.client or create_checkwatt_manager(
self.hass,
self._entry.data.get(CONF_USERNAME),
self._entry.data.get(CONF_PASSWORD),
INTEGRATION_NAME,
)
async with client as cw_inst:
if not await cw_inst.login():
_LOGGER.error("Failed to login, abort update")
raise UpdateFailed("Failed to login")
Expand All @@ -379,7 +408,6 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901

# Only fetch some parameters every 15 min
if self.update_all == 0 and not self.is_boot:
self.update_all = CONF_UPDATE_INTERVAL_MONETARY
_LOGGER.debug("Fetching daily revenue")
if not await cw_inst.get_fcrd_today_net_revenue():
raise UpdateFailed("Unknown error get_fcrd_revenue")
Expand All @@ -405,19 +433,20 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901
self.fcrd_daily_net_average = cw_inst.fcrd_daily_net_average
self.fcrd_year_net_revenue = cw_inst.fcrd_year_net_revenue
self.monthly_grid_peak_power = cw_inst.month_peak_effect
self.update_all = CONF_UPDATE_INTERVAL_MONETARY

if not self.is_boot:
self.update_all -= 1

if self.is_boot:
self.is_boot = False
self.energy_provider = await cw_inst.get_energy_trading_company(
cw_inst.energy_provider_id
)

# Store fcrd_state at boot, used to spark event
self.fcrd_state = cw_inst.fcrd_state
self._id = cw_inst.customer_details["Id"]
self.is_boot = False

# Price Zone is used both as Detailed Sensor and by Push to CheckWattRank
if push_to_cw_rank or use_power_sensors:
Expand Down Expand Up @@ -555,6 +584,11 @@ async def _async_update_data(self) -> CheckwattResp: # noqa: C901

return resp

except CheckwattRateLimitError as err:
raise UpdateFailed(
"CheckWatt rate limited requests",
retry_after=err.retry_after.total_seconds(),
) from err
except InvalidAuth as err:
raise ConfigEntryAuthFailed from err
except CheckwattError as err:
Expand Down
46 changes: 46 additions & 0 deletions custom_components/checkwatt/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Compatibility helpers for the pyCheckwatt API."""

from importlib.metadata import PackageNotFoundError, version

from packaging.version import Version
from pycheckwatt import CheckwattManager

from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession

try:
from pycheckwatt import CheckwattRateLimitError
except ImportError:
PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = False

class CheckwattRateLimitError(Exception):
"""Placeholder that cannot be raised by legacy pyCheckwatt."""

else:
# Earlier development builds exposed the exception before retained revenue
# was safe. The stabilized release is the persistence boundary.
try:
PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = Version(
version("pycheckwatt")
) >= Version("0.3.0")
except PackageNotFoundError:
PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH = False


def create_checkwatt_manager(
hass: HomeAssistant,
username: str,
password: str,
application: str = "pyCheckwatt",
) -> CheckwattManager:
"""Create a manager using optional APIs only when they are available."""
if PYCHECKWATT_SUPPORTS_PERSISTENT_AUTH:
return CheckwattManager(
username,
password,
application,
session=async_get_clientsession(hass),
raise_on_rate_limit=True,
)

return CheckwattManager(username, password, application)
15 changes: 10 additions & 5 deletions custom_components/checkwatt/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import logging
from typing import Any

from pycheckwatt import CheckwattManager
import voluptuous as vol

from homeassistant import config_entries
Expand All @@ -14,6 +13,7 @@
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError

from .api import CheckwattRateLimitError, create_checkwatt_manager
from .const import (
CONF_CM10_SENSOR,
CONF_CWR_NAME,
Expand All @@ -36,11 +36,16 @@

async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate that the user input allows us to connect to CheckWatt."""
async with CheckwattManager(
data[CONF_USERNAME], data[CONF_PASSWORD]
async with create_checkwatt_manager(
hass,
data[CONF_USERNAME],
data[CONF_PASSWORD],
) as check_watt_instance:
if not await check_watt_instance.login():
raise InvalidAuth
try:
if not await check_watt_instance.login():
raise InvalidAuth
except CheckwattRateLimitError as err:
raise CannotConnect from err


class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
Expand Down
4 changes: 2 additions & 2 deletions custom_components/checkwatt/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
"homekit": {},
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/faanskit/ha-checkwatt/issues",
"requirements": ["pycheckwatt~=0.2.11", "aiohttp>=3.9.1"],
"requirements": ["pycheckwatt~=0.3.0", "aiohttp>=3.9.1"],
"ssdp": [],
"version": "0.2.7",
"version": "0.3.0",
"zeroconf": []
}

2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "CheckWatt",
"homeassistant": "2023.12.3",
"homeassistant": "2025.12.0",
"render_readme": true,
"country": ["ALL"]
}
6 changes: 6 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
testpaths = tests
pythonpath = .
addopts = --tb=short
12 changes: 12 additions & 0 deletions tests/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Build context is an isolated test directory containing artifacts/*.whl.
ARG HA_VERSION=2025.12.0
FROM ghcr.io/home-assistant/home-assistant:${HA_VERSION}
RUN uv pip install --system --index https://pypi.org/simple pytest==8.4.2 pytest-asyncio==1.1.1 pip==25.3
COPY artifacts/*.whl /wheels/
ARG LIBRARY_WHEEL
# For legacy runtime tests only; candidate installation must use the default.
ARG LEGACY_METADATA_WORKAROUND=""
RUN python -m pip install --no-deps ${LEGACY_METADATA_WORKAROUND} /wheels/${LIBRARY_WHEEL}
WORKDIR /workspace
ENTRYPOINT []
CMD ["python", "-m", "pytest", "-q", "-p", "no:cacheprovider"]
17 changes: 17 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Integration tests

Place `pycheckwatt-0.3.0-py3-none-any.whl` in `artifacts/` under a separate
build directory. From that directory, set `$repo` to your ha-checkwatt checkout:

```powershell
$repo = "C:/path/to/ha-checkwatt"
docker build -f "$repo/tests/Dockerfile" --build-arg HA_VERSION=2025.12.0 --build-arg LIBRARY_WHEEL=pycheckwatt-0.3.0-py3-none-any.whl -t ha-checkwatt-tests .
docker run --rm --network none --env CHECKWATT_EXPECT_PERSISTENT_AUTH=true --mount "type=bind,source=$repo,target=/workspace,readonly" ha-checkwatt-tests
```

Repeat with `HA_VERSION=2026.9.0`. Tests use local fake HTTP; platform loading
is stubbed. No live account or HA configuration is needed.

For legacy regression coverage, build with the 0.2.11 wheel and
`--build-arg LEGACY_METADATA_WORKAROUND=--ignore-requires-python`, then run with
`CHECKWATT_EXPECT_PERSISTENT_AUTH=false`. This override is for tests only.
Loading
Loading