Skip to content
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

add odometer event / topic #351

Merged
merged 6 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ def on_event(event: Event):
print(f"Battery is {event.event.data.soc}% charged.")
```

There is three types of events:
There is four types of events:
WebSpider marked this conversation as resolved.
Show resolved Hide resolved

* `EventType.SERVICE_EVENT`: Sent proactively by the vehicle, when something changed.
* `EventType.OPERATION`: Sent by Skoda's server as response to an operation executed on the vehicle. It will track the operation's status.
* `EventType.ACCOUNT_EVENT`
* `EventType.ACCOUNT_EVENT`
* `EventType.VEHICLE_EVENT`: Sent proactively by the vehicle, when something changed.
6 changes: 6 additions & 0 deletions myskoda/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@
"departure",
"vehicle-status/access",
"vehicle-status/lights",
"vehicle-status/odometer",
]

MQTT_VEHICLE_EVENT_TOPICS = [
"vehicle-connection-status-update",
"vehicle-ignition-status",
]

MQTT_ACCOUNT_EVENT_TOPICS = [
Expand Down
36 changes: 36 additions & 0 deletions myskoda/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from .models.operation_request import OperationRequest
from .models.service_event import ServiceEvent
from .models.vehicle_event import VehicleEvent


class ServiceEventTopic(StrEnum):
Expand All @@ -18,6 +19,12 @@ class ServiceEventTopic(StrEnum):
CHARGING = "CHARGING"
LIGHTS = "LIGHTS"
DEPARTURE = "DEPARTURE"
ODOMETER = "ODOMETER"


class VehicleEventTopic(StrEnum):
VEHICLE_CONNECTION_STATUS_UPDATE = "VEHICLE_CONNECTION_STATUS_UPDATE"
VEHICLE_IGNITION_STATUS = "VEHICLE_IGNITION_STATUS"


class AccountEventTopic(StrEnum):
Expand All @@ -28,6 +35,7 @@ class EventType(StrEnum):
ACCOUNT_EVENT = "account-event"
OPERATION = "operation-request"
SERVICE_EVENT = "service-event"
VEHICLE_EVENT = "vehicle-event"


@dataclass
Expand Down Expand Up @@ -78,6 +86,13 @@ class EventLights(BaseEvent):
topic: Literal[ServiceEventTopic.LIGHTS] = ServiceEventTopic.LIGHTS


@dataclass
class EventOdometer(BaseEvent):
event: ServiceEvent
type: Literal[EventType.SERVICE_EVENT] = EventType.SERVICE_EVENT
topic: Literal[ServiceEventTopic.ODOMETER] = ServiceEventTopic.ODOMETER


@dataclass
class EventDeparture(BaseEvent):
event: ServiceEvent
Expand All @@ -91,6 +106,24 @@ class EventAccountPrivacy(BaseEvent):
topic: Literal[AccountEventTopic.ACCOUNT_PRIVACY] = AccountEventTopic.ACCOUNT_PRIVACY


@dataclass
class EventVehicleIgnitionStatus(BaseEvent):
event: VehicleEvent
type: Literal[EventType.VEHICLE_EVENT] = EventType.VEHICLE_EVENT
topic: Literal[VehicleEventTopic.VEHICLE_IGNITION_STATUS] = (
VehicleEventTopic.VEHICLE_IGNITION_STATUS
)


@dataclass
class EventVehicleConnectionStatusUpdate(BaseEvent):
event: VehicleEvent
type: Literal[EventType.VEHICLE_EVENT] = EventType.VEHICLE_EVENT
topic: Literal[VehicleEventTopic.VEHICLE_CONNECTION_STATUS_UPDATE] = (
VehicleEventTopic.VEHICLE_CONNECTION_STATUS_UPDATE
)


Event = (
EventAccountPrivacy
| EventOperation
Expand All @@ -99,5 +132,8 @@ class EventAccountPrivacy(BaseEvent):
| EventAuxiliaryHeating
| EventCharging
| EventLights
| EventOdometer
| EventDeparture
| EventVehicleIgnitionStatus
| EventVehicleConnectionStatusUpdate
)
1 change: 1 addition & 0 deletions myskoda/models/service_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class ServiceEventName(StrEnum):
CHANGE_ACCESS = "change-access"
CHANGE_CHARGE_MODE = "change-charge-mode"
CHANGE_LIGHTS = "change-lights"
CHANGE_ODOMETER = "change-odometer"
CHANGE_REMAINING_TIME = "change-remaining-time"
CHANGE_SOC = "change-soc"
CHARGING_COMPLETED = "charging-completed"
Expand Down
71 changes: 71 additions & 0 deletions myskoda/models/vehicle_event.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Models related to vehicle events from the MQTT broker."""

from dataclasses import dataclass, field
from datetime import datetime
from enum import StrEnum
from typing import Generic, TypeVar

from mashumaro import field_options
from mashumaro.mixins.orjson import DataClassORJSONMixin

from myskoda.models.vehicle_ignition_status import IgnitionStatus, UnexpectedIgnitionStatusError


class VehicleEventName(StrEnum):
"""List of known vehicle EventNames."""

VEHICLE_AWAKE = "vehicle-awake"
VEHICLE_CONNECTION_ONLINE = "vehicle-connection-online"
VEHICLE_WARNING_BATTEYLEVEL = "vehicle-warning-batterylevel"
VEHICLE_IGNITION_STATUS_CHANGED = "vehicle-ignition-status-changed"


@dataclass
class VehicleEventData(DataClassORJSONMixin):
"""Base class for data in vehicle events."""

user_id: str = field(metadata=field_options(alias="userId"))
vin: str


T = TypeVar("T", bound=VehicleEventData)


@dataclass
class VehicleEvent(Generic[T], DataClassORJSONMixin):
"""Main model for Vehicle Events.

Vehicle Events are unsolicited events emitted by the MQTT bus towards the client.
"""

version: int
producer: str
name: VehicleEventName
data: T
trace_id: str = field(metadata=field_options(alias="traceId"))
timestamp: datetime | None = field(default=None)


def _deserialize_ignition_status(value: str) -> IgnitionStatus:
match value:
case "ON":
return IgnitionStatus.ON
case "OFF":
return IgnitionStatus.OFF
case _:
raise UnexpectedIgnitionStatusError


@dataclass
class VehicleEventVehicleIgnitionStatusData(VehicleEventData):
"""Ignition data inside vehicle service event vehicle-ignition-status."""

ignition_status: IgnitionStatus | None = field(
default=None,
metadata=field_options(alias="ignitionStatus", deserialize=_deserialize_ignition_status),
)


@dataclass
class VehicleEventWithVehicleIgnitionStatusData(VehicleEvent):
data: VehicleEventVehicleIgnitionStatusData
10 changes: 10 additions & 0 deletions myskoda/models/vehicle_ignition_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from enum import StrEnum


class IgnitionStatus(StrEnum):
ON = "ON"
OFF = "OFF"


class UnexpectedIgnitionStatusError(Exception):
pass
46 changes: 46 additions & 0 deletions myskoda/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from myskoda.auth.authorization import Authorization
from myskoda.models.service_event import ServiceEvent, ServiceEventWithChargingData
from myskoda.models.vehicle_event import VehicleEvent, VehicleEventWithVehicleIgnitionStatusData

from .const import (
MQTT_ACCOUNT_EVENT_TOPICS,
Expand All @@ -28,6 +29,7 @@
MQTT_OPERATION_TOPICS,
MQTT_RECONNECT_DELAY,
MQTT_SERVICE_EVENT_TOPICS,
MQTT_VEHICLE_EVENT_TOPICS,
)
from .event import (
Event,
Expand All @@ -38,8 +40,11 @@
EventCharging,
EventDeparture,
EventLights,
EventOdometer,
EventOperation,
EventType,
EventVehicleConnectionStatusUpdate,
EventVehicleIgnitionStatus,
)
from .models.operation_request import OperationName, OperationRequest, OperationStatus

Expand Down Expand Up @@ -167,6 +172,7 @@ async def _connect_and_listen(self) -> None:
_LOGGER.info("Connected to MQTT")
_LOGGER.debug("using MQTT client %s", client)
for vin in self.vehicle_vins:
# await client.subscribe(f"{self.user_id}/{vin}/#")
Copy link
Contributor

Choose a reason for hiding this comment

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

Why add this remark?

Copy link
Contributor Author

@ExploracuriousAlex ExploracuriousAlex Feb 10, 2025

Choose a reason for hiding this comment

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

It was an mistake that I left this in the commit. I'll toggle the comment to subscribe to all topics.

for topic in MQTT_OPERATION_TOPICS:
await client.subscribe(
f"{self.user_id}/{vin}/operation-request/{topic}"
Expand All @@ -175,6 +181,8 @@ async def _connect_and_listen(self) -> None:
await client.subscribe(f"{self.user_id}/{vin}/service-event/{topic}")
for topic in MQTT_ACCOUNT_EVENT_TOPICS:
await client.subscribe(f"{self.user_id}/{vin}/account-event/{topic}")
for topic in MQTT_VEHICLE_EVENT_TOPICS:
await client.subscribe(f"{self.user_id}/{vin}/vehicle-event/{topic}")

self._subscribed.set()
self._reconnect_delay = MQTT_RECONNECT_DELAY
Expand Down Expand Up @@ -221,6 +229,14 @@ def _get_charging_event(data: str) -> ServiceEvent:
event = ServiceEvent.from_json(data)
return event

@staticmethod
def _get_vehicle_ignition_status_changed_event(data: str) -> VehicleEvent:
try:
event = VehicleEventWithVehicleIgnitionStatusData.from_json(data)
except ValueError:
event = VehicleEvent.from_json(data)
return event

def _parse_topic(self, topic_match: re.Match[str], data: str) -> None:
"""Parse the topic and extract relevant parts."""
[user_id, vin, event_type, topic] = topic_match.groups()
Expand Down Expand Up @@ -301,6 +317,36 @@ def _parse_topic(self, topic_match: re.Match[str], data: str) -> None:
event=ServiceEvent.from_json(data),
)
)
elif event_type == EventType.SERVICE_EVENT and topic == "vehicle-status/odometer":
self._emit(
EventOdometer(
vin=vin,
user_id=user_id,
timestamp=datetime.now(tz=UTC),
event=ServiceEvent.from_json(data),
)
)
elif event_type == EventType.VEHICLE_EVENT and topic == "vehicle-ignition-status":
self._emit(
EventVehicleIgnitionStatus(
vin=vin,
user_id=user_id,
timestamp=datetime.now(tz=UTC),
event=self._get_vehicle_ignition_status_changed_event(data),
)
)
elif (
event_type == EventType.VEHICLE_EVENT
and topic == "vehicle-connection-status-update"
):
self._emit(
EventVehicleConnectionStatusUpdate(
vin=vin,
user_id=user_id,
timestamp=datetime.now(tz=UTC),
event=VehicleEvent.from_json(data),
)
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning("Exception parsing MQTT event: %s", exc)

Expand Down
Loading