Skip to content

Commit

Permalink
Only modify charging state when car state is 'charging'
Browse files Browse the repository at this point in the history
The previous code would always update the charging state when receiving a new car state. This could sometimes cause the charging state to be set to "Disconnected" even when the car was physically connected. Avoid this by only changing the charging state if the new received car state is "charging". Otherwise don't modify the charging state of the car. Hopefully this should lead to consistent behavior.
  • Loading branch information
dagstuan authored Nov 6, 2023
1 parent 35b2ff4 commit c23a608
Showing 1 changed file with 11 additions and 22 deletions.
33 changes: 11 additions & 22 deletions custom_components/tesla_custom/teslamate.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
logger = logging.getLogger(__name__)


CHARGING_STATE_CHARGING = "Charging"

def is_car_state_charging(car_state: str) -> bool:
return car_state == "charging"

def cast_km_to_miles(km_to_convert: float) -> float:
"""Convert KM to Miles.
Expand Down Expand Up @@ -68,7 +73,6 @@ def cast_speed(speed: int) -> int:

return int(speed_miles)


def cast_plugged_in(val: str, car: TeslaCar) -> str:
"""Casts new car plugged_in.
Expand All @@ -85,29 +89,11 @@ def cast_plugged_in(val: str, car: TeslaCar) -> str:
)

if plugged_in:
return "Charging" if car.state == "charging" else "Stopped"
return CHARGING_STATE_CHARGING if is_car_state_charging(car.state) else "Stopped"

return "Disconnected"


def cast_car_state(state: str, car: TeslaCar) -> (str, str):
"""Casts new car state to both state and charging_state.
Since Teslamate doesn't have a direct 'charging_state' we need both
'state' and 'plugged_in' to determine the charging state. This
method uses both to determine the new state and charging_state.
"""
logger.debug(
"Casting car state. Current charging_state '%s', new state: '%s'",
car.charging_state,
state,
)

if state == "charging":
return (state, "Charging")
return (state, "Stopped" if car.charging_state == "Stopped" else "Disconnected")


MAP_DRIVE_STATE = {
"latitude": ("latitude", float),
"longitude": ("longitude", float),
Expand Down Expand Up @@ -369,8 +355,11 @@ async def async_handle_new_data(self, msg: ReceiveMessage):
self.update_charging_state(car, cast_plugged_in(msg.payload, car))

elif mqtt_attr == "state":
(state, charging_state) = cast_car_state(msg.payload, car)
self.update_charging_state(car, charging_state)
state = msg.payload

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

self.update_car_state(car, None, "state", state)

else:
Expand Down

0 comments on commit c23a608

Please sign in to comment.