-
-
Notifications
You must be signed in to change notification settings - Fork 37.5k
Add OpenEVSE diagnostics #171762
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
firstof9
wants to merge
14
commits into
home-assistant:dev
Choose a base branch
from
firstof9:openevse-diagnostics
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+441
−0
Open
Add OpenEVSE diagnostics #171762
Changes from 9 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
320af57
Add OpenEVSE diagnostics and tests with mock fix
firstof9 da73270
Address PR review comments on diagnostics
firstof9 56896db
Ensure diagnostics are JSON-serializable and fix test patching
firstof9 5a27c4d
Address additional PR review comments on diagnostics
firstof9 9782be2
Address additional PR comments: rename unused hass, isolate test mock…
firstof9 08184c3
Address PR review comments, hide raw exception messages, and achieve …
firstof9 c3cbc34
Handle callables and type fallbacks in JSON conversion, add static in…
firstof9 3259d38
Restrict static inspection check to Mock/MagicMock objects to support…
firstof9 ce74111
Address final PR comments: explicit mock checks, document callable ha…
firstof9 2a9677e
Refactor diagnostics to be mock-agnostic and sort dictionary keys det…
firstof9 a1e49b8
Test recursion, circular reference detection, and dictionary key seri…
firstof9 3b3e98a
Extract MAX_JSON_DEPTH constant, recursively coerce Enum.value, and u…
firstof9 976f4dc
Address remaining PR comments
firstof9 e20a562
Deterministic sorting and clear depth-limit boundaries in diagnostics
firstof9 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| """Provide diagnostics for OpenEVSE.""" | ||
|
|
||
| from datetime import date, datetime | ||
| from enum import Enum | ||
| import inspect | ||
| from typing import Any | ||
| from unittest.mock import Mock, NonCallableMock | ||
|
|
||
| from homeassistant.components.diagnostics import async_redact_data | ||
| from homeassistant.const import CONF_PASSWORD, CONF_USERNAME | ||
| from homeassistant.core import HomeAssistant | ||
|
|
||
| from .coordinator import OpenEVSEConfigEntry | ||
|
|
||
| REDACT_CONFIG_DATA = {CONF_PASSWORD, CONF_USERNAME} | ||
|
|
||
| CHARGER_PROPERTIES = ( | ||
| "status", | ||
| "vehicle", | ||
| "mode", | ||
| "charge_mode", | ||
| "divertmode", | ||
| "manual_override", | ||
| "ota_update", | ||
| "service_level", | ||
| "charge_time_elapsed", | ||
| "vehicle_eta", | ||
| "charging_current", | ||
| "charging_voltage", | ||
| "charging_power", | ||
| "current_power", | ||
| "current_capacity", | ||
| "max_current", | ||
| "min_amps", | ||
| "max_amps", | ||
| "max_current_soft", | ||
| "available_current", | ||
| "smoothed_available_current", | ||
| "charge_rate", | ||
| "ambient_temperature", | ||
| "ir_temperature", | ||
| "rtc_temperature", | ||
| "esp_temperature", | ||
| "usage_session", | ||
| "usage_total", | ||
| "total_day", | ||
| "total_week", | ||
| "total_month", | ||
| "total_year", | ||
| "vehicle_soc", | ||
| "vehicle_range", | ||
| "wifi_signal", | ||
| "shaper_live_power", | ||
| "shaper_available_current", | ||
| "shaper_max_power", | ||
| "gfi_trip_count", | ||
| "no_gnd_trip_count", | ||
| "stuck_relay_trip_count", | ||
| "uptime", | ||
| "freeram", | ||
| "wifi_firmware", | ||
| "openevse_firmware", | ||
| ) | ||
|
|
||
|
|
||
| def _to_json_safe(val: Any) -> Any: | ||
| """Coerce value to be JSON-serializable. | ||
|
|
||
| Top-level callables on the charger object are skipped entirely in the main | ||
| diagnostics loop. For nested structures (lists, dicts, tuples, sets), any | ||
| encountered callable elements are coerced to None here to preserve the | ||
| structure while remaining JSON-safe. | ||
| """ | ||
| if isinstance(val, (str, int, float, bool)) or val is None: | ||
| return val | ||
| if isinstance(val, (datetime, date)): | ||
| return val.isoformat() | ||
| if isinstance(val, Enum): | ||
| return val.value | ||
|
firstof9 marked this conversation as resolved.
Outdated
|
||
| if isinstance(val, (set, frozenset)): | ||
| return [_to_json_safe(v) for v in sorted(val, key=str)] | ||
| if isinstance(val, (list, tuple)): | ||
| return [_to_json_safe(v) for v in val] | ||
| if isinstance(val, dict): | ||
| return {str(k): _to_json_safe(v) for k, v in val.items()} | ||
|
firstof9 marked this conversation as resolved.
Outdated
|
||
| if callable(val): | ||
| return None | ||
| return f"<{type(val).__name__} object>" | ||
|
firstof9 marked this conversation as resolved.
|
||
|
|
||
|
|
||
| async def async_get_config_entry_diagnostics( | ||
| _hass: HomeAssistant, config_entry: OpenEVSEConfigEntry | ||
| ) -> dict[str, Any]: | ||
| """Return diagnostics for a config entry.""" | ||
| coordinator = config_entry.runtime_data | ||
| charger = coordinator.charger | ||
|
|
||
| charger_data: dict[str, Any] = {} | ||
|
|
||
| for prop in CHARGER_PROPERTIES: | ||
| # To prevent auto-creating mock attributes during tests when using MagicMock, | ||
| # we statically check for the attribute's existence on mock objects. | ||
| # This is restricted to mock objects to support dynamic runtime attributes in production. | ||
| if isinstance(charger, (Mock, NonCallableMock)): | ||
|
firstof9 marked this conversation as resolved.
Outdated
|
||
| try: | ||
| inspect.getattr_static(charger, prop) | ||
| except AttributeError: | ||
| continue | ||
|
|
||
| try: | ||
| val = getattr(charger, prop) | ||
| except AttributeError: | ||
| continue | ||
| except Exception as err: # noqa: BLE001 | ||
| charger_data[prop] = f"Error: {type(err).__name__}" | ||
| continue | ||
|
firstof9 marked this conversation as resolved.
firstof9 marked this conversation as resolved.
|
||
|
|
||
| # Top-level callables on the charger object are omitted from diagnostics. | ||
| # Any nested callables within collections are coerced to None by _to_json_safe. | ||
| if callable(val): | ||
| continue | ||
|
firstof9 marked this conversation as resolved.
|
||
|
|
||
| charger_data[prop] = _to_json_safe(val) | ||
|
firstof9 marked this conversation as resolved.
|
||
|
|
||
| return { | ||
| "config_entry": async_redact_data(config_entry.as_dict(), REDACT_CONFIG_DATA), | ||
| "charger": charger_data, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| """Test OpenEVSE diagnostics.""" | ||
|
|
||
| from datetime import datetime | ||
| from enum import Enum | ||
| from typing import Any | ||
| from unittest.mock import MagicMock | ||
|
|
||
| from homeassistant.core import HomeAssistant | ||
|
|
||
| from tests.common import MockConfigEntry | ||
| from tests.components.diagnostics import get_diagnostics_for_config_entry | ||
| from tests.typing import ClientSessionGenerator | ||
|
|
||
|
|
||
| async def test_entry_diagnostics( | ||
| hass: HomeAssistant, | ||
| hass_client: ClientSessionGenerator, | ||
| mock_config_entry: MockConfigEntry, | ||
| mock_charger: MagicMock, | ||
| ) -> None: | ||
| """Test OpenEVSE diagnostics.""" | ||
| mock_config_entry.add_to_hass(hass) | ||
| assert await hass.config_entries.async_setup(mock_config_entry.entry_id) | ||
| await hass.async_block_till_done() | ||
|
firstof9 marked this conversation as resolved.
|
||
|
|
||
| diagnostics = await get_diagnostics_for_config_entry( | ||
| hass, hass_client, mock_config_entry | ||
| ) | ||
|
|
||
| assert diagnostics["config_entry"]["data"] == { | ||
| "host": "192.168.1.100", | ||
| } | ||
| assert diagnostics["charger"]["status"] == "Charging" | ||
| assert diagnostics["charger"]["charging_voltage"] == 240 | ||
| assert diagnostics["charger"]["charging_current"] == 32000.0 | ||
|
|
||
|
|
||
| async def test_entry_diagnostics_redact( | ||
| hass: HomeAssistant, | ||
| hass_client: ClientSessionGenerator, | ||
| mock_charger: MagicMock, | ||
| ) -> None: | ||
| """Test OpenEVSE diagnostics with auth data redacted.""" | ||
| entry = MockConfigEntry( | ||
| title="openevse_mock_config", | ||
| domain="openevse", | ||
| data={ | ||
| "host": "192.168.1.100", | ||
| "username": "my_username", | ||
| "password": "my_password", | ||
| }, | ||
| entry_id="FAKE_AUTH", | ||
| unique_id="deadbeeffeed", | ||
| ) | ||
| entry.add_to_hass(hass) | ||
| assert await hass.config_entries.async_setup(entry.entry_id) | ||
| await hass.async_block_till_done() | ||
|
|
||
| diagnostics = await get_diagnostics_for_config_entry(hass, hass_client, entry) | ||
|
|
||
| assert diagnostics["config_entry"]["data"] == { | ||
| "host": "192.168.1.100", | ||
| "username": "**REDACTED**", | ||
| "password": "**REDACTED**", | ||
| } | ||
|
|
||
|
|
||
| async def test_entry_diagnostics_exceptions( | ||
| hass: HomeAssistant, | ||
| hass_client: ClientSessionGenerator, | ||
| mock_config_entry: MockConfigEntry, | ||
| mock_charger: MagicMock, | ||
| ) -> None: | ||
| """Test OpenEVSE diagnostics handles exceptions and JSON coercion correctly.""" | ||
|
|
||
| class MockEnum(Enum): | ||
| TEST = "test_value" | ||
|
|
||
| class FakeCharger: | ||
| """Fake charger to raise exceptions and return custom values for properties.""" | ||
|
|
||
| def __init__(self, original_charger: MagicMock) -> None: | ||
| self._original_charger = original_charger | ||
| # Copy other properties so that inspect.getattr_static finds them in __dict__ | ||
|
firstof9 marked this conversation as resolved.
Outdated
|
||
| excluded = { | ||
| "status", | ||
| "charging_voltage", | ||
| "vehicle_eta", | ||
| "mode", | ||
| "divertmode", | ||
| "manual_override", | ||
| "ota_update", | ||
| "service_level", | ||
| "uptime", | ||
| "wifi_firmware", | ||
| } | ||
| # Copy all mock attributes except the overridden ones | ||
| for key, val in original_charger.__dict__.items(): | ||
| if key not in excluded: | ||
| self.__dict__[key] = val | ||
|
|
||
|
firstof9 marked this conversation as resolved.
firstof9 marked this conversation as resolved.
|
||
| @property | ||
| def charging_voltage(self) -> int: | ||
| raise ValueError("Connection error") | ||
|
|
||
| @property | ||
| def vehicle_eta(self) -> datetime: | ||
| return datetime(2000, 1, 1, 12, 0, 0) | ||
|
|
||
| @property | ||
| def mode(self) -> MockEnum: | ||
| return MockEnum.TEST | ||
|
|
||
| @property | ||
| def divertmode(self) -> set[str]: | ||
| return {"solar", "eco"} | ||
|
|
||
| @property | ||
| def manual_override(self) -> frozenset[str]: | ||
| return frozenset({"override"}) | ||
|
|
||
| @property | ||
| def ota_update(self) -> tuple[Any, ...]: | ||
| return ("v1.0", lambda: "nested_callable") | ||
|
|
||
| @property | ||
| def service_level(self) -> dict[MockEnum, str]: | ||
| return {MockEnum.TEST: "level_2"} | ||
|
|
||
| @property | ||
| def uptime(self) -> object: | ||
| class CustomObj: | ||
| def __str__(self) -> str: | ||
| return "custom_str" | ||
|
|
||
| return CustomObj() | ||
|
|
||
| @property | ||
| def wifi_firmware(self) -> Any: | ||
| return lambda: "callable_value" | ||
|
|
||
| mock_config_entry.add_to_hass(hass) | ||
| assert await hass.config_entries.async_setup(mock_config_entry.entry_id) | ||
| await hass.async_block_till_done() | ||
|
|
||
| # Inject the FakeCharger into the coordinator to isolate side effects | ||
| coordinator = mock_config_entry.runtime_data | ||
| coordinator.charger = FakeCharger(mock_charger) | ||
|
|
||
| diagnostics = await get_diagnostics_for_config_entry( | ||
| hass, hass_client, mock_config_entry | ||
| ) | ||
|
|
||
| # status should be omitted because the attribute is not present | ||
| assert "status" not in diagnostics["charger"] | ||
|
|
||
| # charging_voltage should show the recorded error type only | ||
| assert diagnostics["charger"]["charging_voltage"] == "Error: ValueError" | ||
|
|
||
| # vehicle_eta should be coerced to ISO format string | ||
| assert diagnostics["charger"]["vehicle_eta"] == "2000-01-01T12:00:00" | ||
|
|
||
| # mode should be coerced to Enum raw value | ||
| assert diagnostics["charger"]["mode"] == "test_value" | ||
|
|
||
| # divertmode should be sorted and coerced to list | ||
| assert diagnostics["charger"]["divertmode"] == ["eco", "solar"] | ||
|
|
||
| # manual_override should be sorted and coerced to list | ||
| assert diagnostics["charger"]["manual_override"] == ["override"] | ||
|
|
||
| # ota_update should be coerced to list, with callable elements coerced to None | ||
| assert diagnostics["charger"]["ota_update"] == ["v1.0", None] | ||
|
|
||
| # service_level should have keys coerced to str | ||
| assert diagnostics["charger"]["service_level"] == {"MockEnum.TEST": "level_2"} | ||
|
|
||
| # uptime should fallback to type name representation | ||
| assert diagnostics["charger"]["uptime"] == "<CustomObj object>" | ||
|
|
||
| # wifi_firmware should be omitted because it is callable | ||
| assert "wifi_firmware" not in diagnostics["charger"] | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.