Skip to content

Skip processing MeterValues when HA reports unavailable sensor values#1806

Open
nlindn wants to merge 2 commits intolbbrhzn:mainfrom
nlindn:fix-skip-unavailable-ha-metervalues
Open

Skip processing MeterValues when HA reports unavailable sensor values#1806
nlindn wants to merge 2 commits intolbbrhzn:mainfrom
nlindn:fix-skip-unavailable-ha-metervalues

Conversation

@nlindn
Copy link
Copy Markdown
Contributor

@nlindn nlindn commented Nov 15, 2025

This change stops the MeterValues handler from processing readings when Home Assistant reports an entity as STATE_UNAVAILABLE. This can happen during or right after an HA restart. Before this fix, the handler could receive Unavailable from HA during the restore phase and mistakenly treat it as the value is not available at all. That caused incorrect restoration of energy_meter_start and transaction_id, which in turn produced wrong energy_session and energy_active_import values.

Changes

  • Adds a check: if get_ha_metric(...) returns STATE_UNAVAILABLE, the incoming MeterValues message is skipped.
  • Processing resumes automatically once HA finishes reloading and valid OCPP values can be restored again.

Example

After an HA reboot, all evcharger entities may temporarily show unavailable while the charger keeps sending OCPP MeterValues. Previously, this led to energy_meter_start being possibly restored as None, which produced incorrect energy calculations (energy_session, energy_active_import). With this change, the handler returns early and waits for HA to provide real values again, avoiding using responses before data is available in HA to be restored.

Summary by CodeRabbit

  • Bug Fixes
    • Better handling of unavailable metrics across charge point flows: the system now immediately treats unavailable sensor values as unavailable, logs the condition, schedules a refresh, and skips further processing for those meter/transaction updates to avoid incorrect state propagation.

@nlindn nlindn temporarily deployed to continuous-integration November 15, 2025 17:04 — with GitHub Actions Inactive
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 15, 2025

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 651fba14-9293-4293-8714-5841c0fa634b

📥 Commits

Reviewing files that changed from the base of the PR and between 59b325d and c74865c.

📒 Files selected for processing (2)
  • custom_components/ocpp/chargepoint.py
  • custom_components/ocpp/ocppv16.py
✅ Files skipped from review due to trivial changes (1)
  • custom_components/ocpp/ocppv16.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/ocpp/chargepoint.py

📝 Walkthrough

Walkthrough

Adds explicit short-circuit handling for Home Assistant STATE_UNAVAILABLE when restoring metrics and meter values: metric retrieval returns unavailable immediately, and meter value handlers abort processing, log, schedule an update, and return empty results.

Changes

Cohort / File(s) Summary
Metric retrieval unavailable handling
custom_components/ocpp/chargepoint.py
get_ha_metric now immediately returns STATE_UNAVAILABLE when a candidate HA sensor state equals STATE_UNAVAILABLE, short-circuiting further candidate checks.
Meter values unavailable handling
custom_components/ocpp/ocppv16.py
Imported STATE_UNAVAILABLE and added checks in on_meter_values (both connector_id and transaction_id paths): when restored meter_start/transaction_id equals STATE_UNAVAILABLE, the handler logs debug, schedules self.update(...), and returns an empty call_result.MeterValues() early.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • drc38

Poem

🐰 I found a grey state hiding in the stack,
I nipped it quick — no further checks to track,
A log, a ping, an update on the way,
Empty response and on we hop away! 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately describes the main change: skipping MeterValues processing when HA reports unavailable sensor values, which is the core objective of this PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can use Trivy to scan for security misconfigurations and secrets in Infrastructure as Code files.

Add a .trivyignore file to your project to customize which findings Trivy reports.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
custom_components/ocpp/ocppv16.py (1)

900-906: Duplicate logic (see comment on lines 875-881).

This block duplicates the unavailability handling logic from lines 875-881. See the previous comment for refactoring suggestions.

🧹 Nitpick comments (1)
custom_components/ocpp/ocppv16.py (1)

875-881: Consider refactoring duplicate code and improving log message specificity.

This block and the similar one at lines 900-906 contain nearly identical logic. Additionally, the log message states "Charger %s is unavailable" when it's more accurate to say the HA entity state is unavailable (the charger itself may still be operational).

Consider extracting the common logic into a helper function:

+def _handle_unavailable_metric(self, metric_name: str) -> bool:
+    """Return True if should skip MeterValues processing due to unavailable metric."""
+    _LOGGER.debug(
+        "HA entity for %s on charger %s is unavailable — skipping MeterValues processing.",
+        metric_name,
+        self.settings.cpid,
+    )
+    self.hass.async_create_task(self.update(self.settings.cpid))
+    return True

Then use it in both locations:

 if value and value == STATE_UNAVAILABLE:
-    _LOGGER.debug(
-        "Charger %s is unavailable — skipping received MeterValues processing.",
-        self.settings.cpid,
-    )
-    self.hass.async_create_task(self.update(self.settings.cpid))
-    return call_result.MeterValues()
+    if self._handle_unavailable_metric("meter_start"):
+        return call_result.MeterValues()
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e3c3c4 and 59b325d.

📒 Files selected for processing (2)
  • custom_components/ocpp/chargepoint.py (1 hunks)
  • custom_components/ocpp/ocppv16.py (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
custom_components/ocpp/ocppv16.py (1)
custom_components/ocpp/chargepoint.py (3)
  • value (84-86)
  • value (89-91)
  • update (605-637)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Run tests
🔇 Additional comments (2)
custom_components/ocpp/chargepoint.py (1)

1028-1029: Behavior change: early return prevents fallback to other candidates.

The early return when STATE_UNAVAILABLE is encountered prevents checking remaining candidate entity IDs (e.g., falling back from connector-specific to generic sensor). During an HA restart (the primary use case), all entities are unavailable simultaneously, so this is appropriate. However, in edge cases where only the connector-specific sensor is unavailable, the generic sensor won't be used as a fallback.

This trade-off is acceptable for the stated objective.

custom_components/ocpp/ocppv16.py (1)

10-10: LGTM!

Import correctly added for the new unavailability checks.

@codecov
Copy link
Copy Markdown

codecov bot commented Nov 15, 2025

Codecov Report

❌ Patch coverage is 72.72727% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.90%. Comparing base (7ceb78f) to head (c74865c).

Files with missing lines Patch % Lines
custom_components/ocpp/ocppv16.py 66.66% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1806      +/-   ##
==========================================
- Coverage   94.99%   94.90%   -0.09%     
==========================================
  Files          12       12              
  Lines        2975     2985      +10     
==========================================
+ Hits         2826     2833       +7     
- Misses        149      152       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions
Copy link
Copy Markdown

Stale pull request message

@github-actions
Copy link
Copy Markdown

Stale pull request message

@nlindn
Copy link
Copy Markdown
Contributor Author

nlindn commented Mar 18, 2026

Bump, ready for review.

@drc38
Copy link
Copy Markdown
Collaborator

drc38 commented Mar 19, 2026

Bump, ready for review.

Review comments above

@nlindn nlindn temporarily deployed to continuous-integration March 19, 2026 18:41 — with GitHub Actions Inactive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants