Add switch platform to nrgkick integration for enabling or pausing car charging (#162563)

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
Andreas Jakl
2026-02-11 19:36:36 +01:00
committed by GitHub
parent 3cbe1295f9
commit 25a6b6fa65
13 changed files with 337 additions and 31 deletions

View File

@@ -12,6 +12,7 @@ from .coordinator import NRGkickConfigEntry, NRGkickDataUpdateCoordinator
PLATFORMS: list[Platform] = [
Platform.SENSOR,
Platform.SWITCH,
]

View File

@@ -1,7 +1,18 @@
"""Home Assistant exceptions for the NRGkick integration."""
"""API helpers and Home Assistant exceptions for the NRGkick integration."""
from __future__ import annotations
from collections.abc import Awaitable
import aiohttp
from nrgkick_api import (
NRGkickAPIDisabledError,
NRGkickAuthenticationError,
NRGkickCommandRejectedError,
NRGkickConnectionError,
NRGkickInvalidResponseError,
)
from homeassistant.exceptions import HomeAssistantError
from .const import DOMAIN
@@ -37,3 +48,38 @@ class NRGkickApiClientApiDisabledError(NRGkickApiClientError):
class NRGkickApiClientInvalidResponseError(NRGkickApiClientError):
"""Exception for invalid responses from the device."""
translation_domain = DOMAIN
translation_key = "invalid_response"
async def async_api_call[_T](awaitable: Awaitable[_T]) -> _T:
"""Call the NRGkick API and map common library errors.
This helper is intended for one-off API calls outside the coordinator,
such as command-style calls (switch/number/etc.) and config flow
validation, where errors should surface as user-facing `HomeAssistantError`
exceptions. Regular polling is handled by the coordinator.
"""
try:
return await awaitable
except NRGkickCommandRejectedError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="command_rejected",
translation_placeholders={"reason": err.reason},
) from err
except NRGkickAuthenticationError as err:
raise NRGkickApiClientAuthenticationError from err
except NRGkickAPIDisabledError as err:
raise NRGkickApiClientApiDisabledError from err
except NRGkickInvalidResponseError as err:
raise NRGkickApiClientInvalidResponseError from err
except NRGkickConnectionError as err:
raise NRGkickApiClientCommunicationError(
translation_placeholders={"error": str(err)}
) from err
except (TimeoutError, aiohttp.ClientError, OSError) as err:
raise NRGkickApiClientCommunicationError(
translation_placeholders={"error": str(err)}
) from err

View File

@@ -5,13 +5,7 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
import aiohttp
from nrgkick_api import (
NRGkickAPI,
NRGkickAPIDisabledError,
NRGkickAuthenticationError,
NRGkickConnectionError,
)
from nrgkick_api import NRGkickAPI
import voluptuous as vol
import yarl
@@ -33,6 +27,7 @@ from .api import (
NRGkickApiClientCommunicationError,
NRGkickApiClientError,
NRGkickApiClientInvalidResponseError,
async_api_call,
)
from .const import DOMAIN
@@ -96,15 +91,8 @@ async def validate_input(
session=session,
)
try:
await api.test_connection()
info = await api.get_info(["general"], raw=True)
except NRGkickAuthenticationError as err:
raise NRGkickApiClientAuthenticationError from err
except NRGkickAPIDisabledError as err:
raise NRGkickApiClientApiDisabledError from err
except (NRGkickConnectionError, TimeoutError, aiohttp.ClientError, OSError) as err:
raise NRGkickApiClientCommunicationError from err
await async_api_call(api.test_connection())
info = await async_api_call(api.get_info(["general"], raw=True))
device_name = info.get("general", {}).get("device_name")
if not device_name:

View File

@@ -13,6 +13,7 @@ from nrgkick_api import (
NRGkickAPIDisabledError,
NRGkickAuthenticationError,
NRGkickConnectionError,
NRGkickInvalidResponseError,
)
from homeassistant.config_entries import ConfigEntry
@@ -79,6 +80,11 @@ class NRGkickDataUpdateCoordinator(DataUpdateCoordinator[NRGkickData]):
translation_key="communication_error",
translation_placeholders={"error": str(error)},
) from error
except NRGkickInvalidResponseError as error:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="invalid_response",
) from error
except (TimeoutError, aiohttp.ClientError, OSError) as error:
raise UpdateFailed(
translation_domain=DOMAIN,

View File

@@ -2,12 +2,14 @@
from __future__ import annotations
from collections.abc import Awaitable
from typing import Any
from homeassistant.const import CONF_HOST
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .api import async_api_call
from .const import DOMAIN
from .coordinator import NRGkickDataUpdateCoordinator
@@ -55,3 +57,9 @@ class NRGkickEntity(CoordinatorEntity[NRGkickDataUpdateCoordinator]):
device_info_typed["connections"] = connections
self._attr_device_info = device_info_typed
async def _async_call_api[_T](self, awaitable: Awaitable[_T]) -> _T:
"""Call the API, map errors, and refresh coordinator data."""
result = await async_api_call(awaitable)
await self.coordinator.async_refresh()
return result

View File

@@ -286,6 +286,11 @@
"unsupported_charging_mode": "Unsupported charging mode"
}
}
},
"switch": {
"charging_enabled": {
"name": "Charging enabled"
}
}
},
"exceptions": {
@@ -295,6 +300,9 @@
"authentication_error": {
"message": "Authentication failed. Please check your credentials."
},
"command_rejected": {
"message": "The device rejected the request: {reason}"
},
"communication_error": {
"message": "Communication error with NRGkick device: {error}"
},

View File

@@ -0,0 +1,59 @@
"""Switch platform for NRGkick."""
from __future__ import annotations
from typing import Any
from nrgkick_api.const import CONTROL_KEY_CHARGE_PAUSE
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import NRGkickConfigEntry, NRGkickData, NRGkickDataUpdateCoordinator
from .entity import NRGkickEntity
PARALLEL_UPDATES = 0
CHARGING_ENABLED_KEY = "charging_enabled"
def _is_charging_enabled(data: NRGkickData) -> bool:
"""Return True if charging is enabled (not paused)."""
return bool(data.control.get(CONTROL_KEY_CHARGE_PAUSE) == 0)
async def async_setup_entry(
_hass: HomeAssistant,
entry: NRGkickConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up NRGkick switches based on a config entry."""
coordinator = entry.runtime_data
async_add_entities([NRGkickChargingEnabledSwitch(coordinator)])
class NRGkickChargingEnabledSwitch(NRGkickEntity, SwitchEntity):
"""Representation of the NRGkick charging enabled switch."""
_attr_translation_key = CHARGING_ENABLED_KEY
def __init__(self, coordinator: NRGkickDataUpdateCoordinator) -> None:
"""Initialize the switch."""
super().__init__(coordinator, CHARGING_ENABLED_KEY)
@property
def is_on(self) -> bool:
"""Return the state of the switch."""
data = self.coordinator.data
assert data is not None
return _is_charging_enabled(data)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on (enable charging)."""
await self._async_call_api(self.coordinator.api.set_charge_pause(False))
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off (pause charging)."""
await self._async_call_api(self.coordinator.api.set_charge_pause(True))

View File

@@ -2,14 +2,28 @@
from __future__ import annotations
from collections.abc import Iterable
from unittest.mock import patch
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None:
async def setup_integration(
hass: HomeAssistant,
config_entry: MockConfigEntry,
platforms: Iterable[Platform] | None = None,
) -> None:
"""Set up the component for tests."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
if platforms is None:
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return
with patch("homeassistant.components.nrgkick.PLATFORMS", list(platforms)):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()

View File

@@ -48,10 +48,10 @@ def mock_nrgkick_api(
api.get_control.return_value = mock_control_data
api.get_values.return_value = mock_values_data
api.set_current.return_value = {"current_set": 16.0}
api.set_charge_pause.return_value = {"charge_pause": 0}
api.set_energy_limit.return_value = {"energy_limit": 0}
api.set_phase_count.return_value = {"phase_count": 3}
api.set_current.return_value = 16.0
api.set_charge_pause.return_value = 0
api.set_energy_limit.return_value = 0
api.set_phase_count.return_value = 3
yield api

View File

@@ -0,0 +1,50 @@
# serializer version: 1
# name: test_switch_entities[switch.nrgkick_test_charging_enabled-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'switch',
'entity_category': None,
'entity_id': 'switch.nrgkick_test_charging_enabled',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Charging enabled',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Charging enabled',
'platform': 'nrgkick',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'charging_enabled',
'unique_id': 'TEST123456_charging_enabled',
'unit_of_measurement': None,
})
# ---
# name: test_switch_entities[switch.nrgkick_test_charging_enabled-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'NRGkick Test Charging enabled',
}),
'context': <ANY>,
'entity_id': 'switch.nrgkick_test_charging_enabled',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---

View File

@@ -23,7 +23,9 @@ from tests.common import MockConfigEntry
async def test_load_unload_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nrgkick_api: AsyncMock
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test successful load and unload of entry."""
await setup_integration(hass, mock_config_entry)

View File

@@ -1,12 +1,14 @@
"""Tests for the NRGkick sensor platform."""
from __future__ import annotations
from unittest.mock import AsyncMock
from nrgkick_api import ChargingStatus, ConnectorType
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_UNKNOWN
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@@ -26,7 +28,7 @@ async def test_sensor_entities(
snapshot: SnapshotAssertion,
) -> None:
"""Test sensor entities."""
await setup_integration(hass, mock_config_entry)
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@@ -43,10 +45,12 @@ async def test_mapped_unknown_values_become_state_unknown(
ChargingStatus.UNKNOWN
)
await setup_integration(hass, mock_config_entry)
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
assert hass.states.get("sensor.nrgkick_test_connector_type").state == STATE_UNKNOWN
assert hass.states.get("sensor.nrgkick_test_status").state == STATE_UNKNOWN
assert (state := hass.states.get("sensor.nrgkick_test_connector_type"))
assert state.state == STATE_UNKNOWN
assert (state := hass.states.get("sensor.nrgkick_test_status"))
assert state.state == STATE_UNKNOWN
async def test_cellular_and_gps_entities_are_gated_by_model_type(
@@ -58,7 +62,7 @@ async def test_cellular_and_gps_entities_are_gated_by_model_type(
mock_nrgkick_api.get_info.return_value["general"]["model_type"] = "NRGkick Gen2"
await setup_integration(hass, mock_config_entry)
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
assert hass.states.get("sensor.nrgkick_test_cellular_mode") is None
assert hass.states.get("sensor.nrgkick_test_cellular_signal_strength") is None

View File

@@ -0,0 +1,120 @@
"""Tests for the NRGkick switch platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, call
from nrgkick_api import NRGkickCommandRejectedError
from nrgkick_api.const import CONTROL_KEY_CHARGE_PAUSE
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
pytestmark = pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test switch entities."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.SWITCH])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_charge_switch_service_calls_update_state(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test the charge switch calls the API and updates state."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.SWITCH])
entity_id = "switch.nrgkick_test_charging_enabled"
assert (state := hass.states.get(entity_id))
assert state.state == "on"
# Pause charging
# Simulate the device reporting the new paused state after the command.
control_data = mock_nrgkick_api.get_control.return_value.copy()
control_data[CONTROL_KEY_CHARGE_PAUSE] = 1
mock_nrgkick_api.get_control.return_value = control_data
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert (state := hass.states.get(entity_id))
assert state.state == "off"
# Resume charging
# Simulate the device reporting the resumed state after the command.
control_data = mock_nrgkick_api.get_control.return_value.copy()
control_data[CONTROL_KEY_CHARGE_PAUSE] = 0
mock_nrgkick_api.get_control.return_value = control_data
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert (state := hass.states.get(entity_id))
assert state.state == "on"
assert mock_nrgkick_api.set_charge_pause.await_args_list == [
call(True),
call(False),
]
async def test_charge_switch_rejected_by_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test the switch surfaces device rejection messages and keeps state."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.SWITCH])
entity_id = "switch.nrgkick_test_charging_enabled"
# Device refuses the command and the library raises an exception.
mock_nrgkick_api.set_charge_pause.side_effect = NRGkickCommandRejectedError(
"Charging pause is blocked by solar-charging"
)
with pytest.raises(HomeAssistantError) as err:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert err.value.translation_key == "command_rejected"
assert err.value.translation_placeholders == {
"reason": "Charging pause is blocked by solar-charging"
}
# State should reflect actual device control data (still not paused).
assert (state := hass.states.get(entity_id))
assert state.state == "on"