Skip to content

Commit

Permalink
v0.1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Bre77 committed Mar 2, 2024
1 parent 5fed04e commit 8759471
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setuptools.setup(
name="teslemetry_stream",
version="0.1.0",
version="0.1.1",
author="Brett Adams",
author_email="[email protected]",
description="Teslemetry Streaming API library for Python",
Expand Down
25 changes: 20 additions & 5 deletions teslemetry_stream/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from collections.abc import Callable, Awaitable
from collections.abc import Callable
import aiohttp
import asyncio
import json
import logging
from datetime import datetime
from .const import TelemetryFields, TelemetryAlerts


Expand Down Expand Up @@ -45,6 +46,7 @@ def __init__(
access_token: str,
server: str | None = None,
vin: str | None = None,
parse_timestamp: bool = False,
):
if not server and not vin:
raise ValueError("Either server or VIN is required")
Expand All @@ -56,12 +58,19 @@ def __init__(
self.server = server
self._session = session
self._headers = {"Authorization": f"Bearer {access_token}"}
self.parse_timestamp = parse_timestamp

async def get_config(self) -> None:
async def get_config(self, vin: str | None = None) -> None:
"""Get the current stream config."""

vin = vin or self.vin

if not vin:
raise ValueError("VIN is required")

LOGGER.debug("Getting fleet telemetry config from %s", vin)
req = await self._session.get(
f"https://api.teslemetry.com/api/1/vehicles/{self.vin}/fleet_telemetry_config",
f"https://api.teslemetry.com/api/1/vehicles/{vin}/fleet_telemetry_config",
headers=self._headers,
raise_for_status=True,
)
Expand Down Expand Up @@ -133,7 +142,6 @@ async def update(self, wait: int = 1) -> None:
async def connect(self) -> None:
"""Connect to the telemetry stream."""
if not self.server:
LOGGER.debug("No server, getting config")
await self.get_config()

LOGGER.debug("Connecting to %s", self.server)
Expand All @@ -150,6 +158,7 @@ async def connect(self) -> None:
def close(self) -> None:
"""Close connection."""
if self._response is not None:
LOGGER.debug("Disconnecting from %s", self.server)
self._response.close()
self._response = None

Expand All @@ -174,7 +183,13 @@ async def __anext__(self) -> dict:
async for line_in_bytes in self._response.content:
line = line_in_bytes.decode("utf8")
if line.startswith("data:"):
LOGGER.debug("Received: %s", line[5:])
data = json.loads(line[5:])
if self.parse_timestamp:
main, _, ns = data["createdAt"].partition(".")
data["timestamp"] = int(
datetime.strptime(main, "%Y-%m-%dT%H:%M:%S").timestamp()
) * 1000 + int(ns[:3])
LOGGER.debug("event %s", json.dumps(data))
return json.loads(line[5:])
continue
except aiohttp.ClientConnectionError as error:
Expand Down

0 comments on commit 8759471

Please sign in to comment.