Skip to content

Conversation

@cguedel
Copy link
Contributor

@cguedel cguedel commented Jun 1, 2025

Observe charging_state topic directly to update charging state of car when using Teslamate.

Fixes #1108

Summary by CodeRabbit

  • Bug Fixes
    • Charging status now updates directly from the charging state attribute for more reliable and timely information.

@coderabbitai
Copy link

coderabbitai bot commented Jun 1, 2025

Walkthrough

The constant CHARGING_STATE_CHARGING and the function cast_plugged_in were removed. Charging state updates no longer rely on "plugged_in" or "state" MQTT attributes but instead use direct updates from the "charging_state" MQTT attribute via the updated MAP_CHARGE_STATE dictionary.

Changes

File(s) Change Summary
custom_components/tesla_custom/teslamate.py Removed CHARGING_STATE_CHARGING constant and cast_plugged_in function; updated MAP_CHARGE_STATE to include "charging_state"; modified async_handle_new_data to rely on direct "charging_state" MQTT updates instead of "plugged_in" or "state".

Assessment against linked issues

Objective Addressed Explanation
Charging binary sensor returns to "Not charging" when car finishes charging but remains plugged in (#1108) Charging state updates no longer consider "plugged_in" or "state" attributes, but no explicit logic ensures the binary sensor updates to "Not charging" when charging ends without unplugging.

Poem

A rabbit watched the data flow,
Where charging states no longer grow.
Gone the plugs and states combined,
Now direct updates are aligned.
Though changes shift the sensor’s tune,
The code hops forward, changes soon!
🐇⚡📡


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d5784c9 and baaa17a.

📒 Files selected for processing (1)
  • custom_components/tesla_custom/teslamate.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/tesla_custom/teslamate.py
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@cguedel cguedel changed the title Fix car never reverting back from 'charging' re-plugged fix: car never reverting back from 'charging' re-plugged Jun 1, 2025
@cguedel cguedel changed the title fix: car never reverting back from 'charging' re-plugged fix: car never reverting back from 'charging' Jun 1, 2025
Copy link

@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 56bf2be and d5784c9.

📒 Files selected for processing (1)
  • custom_components/tesla_custom/teslamate.py (3 hunks)
🔇 Additional comments (2)
custom_components/tesla_custom/teslamate.py (2)

34-34: LGTM! Good practice using constants.

Adding the CHARGING_STATE_STOPPED constant follows good coding practices by replacing magic strings with named constants, improving maintainability and consistency with the existing CHARGING_STATE_CHARGING constant.


99-101: LGTM! Proper use of the new constant.

The update to use CHARGING_STATE_STOPPED instead of the hardcoded string "Stopped" is consistent with the constant addition and improves code maintainability.

Comment on lines 372 to 373
else:
self.update_charging_state(car, CHARGING_STATE_STOPPED)
Copy link

@coderabbitai coderabbitai bot Jun 1, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Core fix looks good, but verify interaction with plugged_in handler.

The addition of the else clause correctly addresses the issue where charging state wasn't being updated when the car stopped charging. However, there's a potential logical concern:

When a car is unplugged (not charging), this handler sets charging state to "Stopped", but the plugged_in handler in cast_plugged_in would set it to "Disconnected". Depending on the order of MQTT messages, the final charging state could be inconsistent.

Consider whether the logic should check if the car is plugged in before setting the state to "Stopped":


🏁 Script executed:

#!/bin/bash
# Description: Search for other references to charging states to understand the expected behavior
# Expected: Find usage patterns of Disconnected vs Stopped states

echo "=== Searching for charging state references ==="
rg -A 3 -B 3 "Disconnected|Stopped|charging_state" --type py

echo "=== Searching for plugged_in related logic ==="
rg -A 5 -B 5 "plugged_in" --type py

Length of output: 12264


🏁 Script executed:

#!/bin/bash
echo "=== Showing cast_plugged_in definition ==="
rg -n "def cast_plugged_in" -n custom_components/tesla_custom/teslamate.py -A10 -B5

echo
echo "=== Showing is_car_state_charging ==="
rg -n "def is_car_state_charging" -n custom_components/tesla_custom/teslamate.py -A5 -B5

echo
echo "=== Showing MAP_DRIVE_STATE mapping ==="
rg -n "MAP_DRIVE_STATE" -n custom_components/tesla_custom/teslamate.py -A5 -B5

Length of output: 2073


Gate “Stopped” updates on plugged-in status to avoid race

In async_handle_new_data (custom_components/tesla_custom/teslamate.py), the state branch currently does:

    if is_car_state_charging(state):
        self.update_charging_state(car, CHARGING_STATE_CHARGING)
    else:
        self.update_charging_state(car, CHARGING_STATE_STOPPED)

Because the plugged_in handler can later set “Disconnected,” an unplug event may be overwritten by the next state message.

• File: custom_components/tesla_custom/teslamate.py
– Around the elif mqtt_attr == "state" block, change to:

 else:
-    self.update_charging_state(car, CHARGING_STATE_STOPPED)
+    # Only mark “Stopped” if still plugged in; unplugged should remain “Disconnected”
+    if car.conn_charge_cable:
+        self.update_charging_state(car, CHARGING_STATE_STOPPED)

Please update this logic so that a “Disconnected” state from the plugged_in handler cannot be overridden by subsequent state messages.

🤖 Prompt for AI Agents
In custom_components/tesla_custom/teslamate.py around lines 372 to 373, the else
clause sets the charging state to "Stopped" without checking if the car is
plugged in, which can cause the "Disconnected" state set by the plugged_in
handler to be overwritten. Modify the else branch to first check if the car is
plugged in before setting the charging state to "Stopped," ensuring that if the
car is unplugged, the "Disconnected" state remains and is not overridden by
subsequent state messages.

Copy link
Owner

Choose a reason for hiding this comment

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

@cguedel Thanks again! Can you consider whether the ai is correct with it's suggestion please? I can merge it once you review and decide one way or the other.

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@alandtse Looks like the AI might be correct, the car could change from "charging" to "online" while being disconnected I think. I didn't realize the charging state was charging/stopped/disconnected. I'll need to think about a solution for this.

@cguedel cguedel changed the title fix: car never reverting back from 'charging' fix: car never reverting back from 'charging' when using Teslamate Jun 3, 2025
@cguedel
Copy link
Contributor Author

cguedel commented Jun 3, 2025

@alandtse After digging through this some more, I'm not actually sure why the code observes plugged_in in the first place, as Teslamate reports (at least on my end) a perfectly fine charging_state topic. According to the docs, the available states are: Charging, Disconnected, Stopped, NoPower, Complete, which seems to match what the Tesla API also provides.

Happy to change this further if you think that's the wrong way, but from my (very limited) testing, it looks like it works when plugging in, starting to charge, stopping the charge, disconnecting the charger.

@cguedel cguedel requested a review from alandtse June 3, 2025 16:21
@alandtse
Copy link
Owner

alandtse commented Jun 3, 2025

No worries. The AI can be wrong. If someone reports it as a reality, then we can fix it then.

@alandtse alandtse merged commit 19076b1 into alandtse:dev Jun 3, 2025
9 checks passed
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.

Charging binary sensor never returns to "Not charging" when using Teslamate/MQTT

2 participants