-
-
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.
Open
Add OpenEVSE diagnostics #171762
Changes from 13 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
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,156 @@ | ||
| """Provide diagnostics for OpenEVSE.""" | ||
|
|
||
| import asyncio | ||
| from datetime import date, datetime | ||
| from enum import Enum | ||
| from typing import Any | ||
|
|
||
| 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} | ||
|
|
||
| MAX_JSON_DEPTH = 20 | ||
|
|
||
| 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, seen: set[int] | None = None, depth: int = 0) -> 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 depth > MAX_JSON_DEPTH: | ||
| return f"<Depth limit exceeded: {type(val).__name__}>" | ||
|
|
||
| if seen is None: | ||
| seen = set() | ||
|
|
||
| val_id = id(val) | ||
| if val_id in seen: | ||
| return f"<Circular reference detected: {type(val).__name__}>" | ||
|
|
||
| if isinstance(val, (datetime, date)): | ||
| return val.isoformat() | ||
| if isinstance(val, Enum): | ||
| return _to_json_safe(val.value, seen, depth + 1) | ||
| if isinstance(val, (set, frozenset)): | ||
| seen.add(val_id) | ||
| try: | ||
| return [_to_json_safe(v, seen, depth + 1) for v in sorted(val, key=str)] | ||
| finally: | ||
| seen.remove(val_id) | ||
| if isinstance(val, (list, tuple)): | ||
| seen.add(val_id) | ||
| try: | ||
| return [_to_json_safe(v, seen, depth + 1) for v in val] | ||
| finally: | ||
| seen.remove(val_id) | ||
| if isinstance(val, dict): | ||
| seen.add(val_id) | ||
| try: | ||
| res = {} | ||
| for k in sorted(val, key=str): | ||
| if isinstance(k, str): | ||
| key_str = k | ||
| elif isinstance(k, (int, float, bool)) or k is None: | ||
| key_str = f"<{type(k).__name__}: {k}>" | ||
| elif isinstance(k, Enum): | ||
| key_str = f"{type(k).__name__}.{k.name}" | ||
| else: | ||
| key_str = f"<{type(k).__name__}>" | ||
| res[key_str] = _to_json_safe(val[k], seen, depth + 1) | ||
|
firstof9 marked this conversation as resolved.
Outdated
|
||
| return res | ||
|
firstof9 marked this conversation as resolved.
|
||
| finally: | ||
| seen.remove(val_id) | ||
| 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: | ||
| try: | ||
| val = getattr(charger, prop) | ||
| except AttributeError: | ||
| continue | ||
|
firstof9 marked this conversation as resolved.
|
||
| except asyncio.CancelledError: | ||
| raise | ||
| 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, | ||
| } | ||
Oops, something went wrong.
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.