From 0cdab58514d247e664dff27c528866e3e0c1d0da Mon Sep 17 00:00:00 2001 From: Carlo Costanzo Date: Mon, 5 Oct 2026 17:25:11 -0400 Subject: [PATCH] Cache Tesla visited map snapshots --- .../infrastructure/partials/car_sections.yaml | 11 ++++ config/packages/tesla_model_y.yaml | 17 +++++ .../teslamate_visited_snapshot.py | 65 +++++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 config/shell_scripts/teslamate_visited_snapshot.py diff --git a/config/dashboards/infrastructure/partials/car_sections.yaml b/config/dashboards/infrastructure/partials/car_sections.yaml index c50aebbb..78ad5045 100644 --- a/config/dashboards/infrastructure/partials/car_sections.yaml +++ b/config/dashboards/infrastructure/partials/car_sections.yaml @@ -9,6 +9,7 @@ # Related Issue: 1944 # Notes: No cards expose Tesla or JuiceBox controls. # Notes: TeslaMate retains detailed drive, charge, and mileage history. +# Notes: Tap either Odometer tile for the daily visited-map image; hold for details. # Notes: Useful tiles use restored last-valid values without timestamp churn. # Notes: Raw JuiceBox energy retains long-term history; power is session-only. # Notes: The Tesla's Home location charge-current setting is intentionally 16 A. @@ -65,6 +66,11 @@ entity: sensor.car_odometer_last_known name: Odometer icon: mdi:counter + tap_action: + action: more-info + entity: camera.tesla_visited_map + hold_action: + action: more-info state_display: > [[[ const value = Number(entity?.state); @@ -229,6 +235,11 @@ entity: sensor.car_odometer_last_known name: Odometer icon: mdi:counter + tap_action: + action: more-info + entity: camera.tesla_visited_map + hold_action: + action: more-info state_display: > [[[ const value = Number(entity?.state); diff --git a/config/packages/tesla_model_y.yaml b/config/packages/tesla_model_y.yaml index 5594f8f7..6b75aea2 100644 --- a/config/packages/tesla_model_y.yaml +++ b/config/packages/tesla_model_y.yaml @@ -46,12 +46,29 @@ # their own recovery checks. Older untagged alerts require dismissal on the phone. # Notes: Portainer state remains diagnostic and cannot by itself mark the # charger monitor offline. +# Notes: The visited-map camera uses a private daily Grafana PNG. An hourly +# command checks the cache; the first check after 06:00 refreshes it. +# Failed renders retain the previous image and retry at the next check. # Tire-pressure video: https://youtu.be/hDNyZfTfTtE # Tire-pressure post: https://www.vcloudinfo.com/2026/09/home-assistant-tesla-tire-pressure-alerts.html # Related garage video: https://youtu.be/wFO0H5zgnzk # Related garage post: https://www.vcloudinfo.com/2026/05/home-assistant-garage-automations-arrival-alerts-tesla.html ###################################################################### +command_line: + - sensor: + name: Tesla Visited Map Updated + unique_id: tesla_visited_map_updated + command: "python3 /config/shell_scripts/teslamate_visited_snapshot.py" + scan_interval: 3600 + command_timeout: 180 + device_class: timestamp + value_template: "{{ value_json.updated_at }}" + availability: "{{ value_json.updated_at is not none }}" + json_attributes: + - last_error + - stale + input_boolean: tesla_high_charge_rate_alert_active: name: Tesla Home Charging Incident Active diff --git a/config/shell_scripts/teslamate_visited_snapshot.py b/config/shell_scripts/teslamate_visited_snapshot.py new file mode 100644 index 00000000..104ef2fb --- /dev/null +++ b/config/shell_scripts/teslamate_visited_snapshot.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Cache one authenticated Grafana map render per day for a local-file camera.""" + +from datetime import datetime, timedelta +from io import BytesIO +import json +from pathlib import Path +import tempfile +from urllib.request import Request, urlopen +from zoneinfo import ZoneInfo + +from PIL import Image + +CONFIG = Path('/config/secrets/teslamate_snapshot.json') +OUTPUT = Path('/config/image/teslamate_visited.png') +TIMEZONE = ZoneInfo('America/New_York') +MAX_BYTES = 10 * 1024 * 1024 + + +def refresh(config_path=CONFIG, output=OUTPUT): + """Replace the cached image only after a complete, valid PNG arrives.""" + now = datetime.now(TIMEZONE) + due = now.replace(hour=6, minute=0, second=0, microsecond=0) + if now < due: + due -= timedelta(days=1) + updated = datetime.fromtimestamp(output.stat().st_mtime, TIMEZONE) if output.exists() else None + error = None + if updated is None or updated < due: + try: + config = json.loads(config_path.read_text()) + request = Request(config['render_url'], headers={ + 'Authorization': 'Bearer ' + config['token'], + 'Accept': 'image/png', + }) + with urlopen(request, timeout=150) as response: + if response.headers.get_content_type() != 'image/png': + raise ValueError('Expected a PNG response') + data = response.read(MAX_BYTES + 1) + if len(data) > MAX_BYTES: + raise ValueError('Image exceeds size limit') + with Image.open(BytesIO(data)) as img: + if img.format != 'PNG' or img.width < 800 or img.height < 400: + raise ValueError('Unexpected image format or dimensions') + img.verify() + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=output.parent, suffix='.png', delete=False) as file: + temporary = Path(file.name) + file.write(data) + try: + temporary.replace(output) + finally: + temporary.unlink(missing_ok=True) + updated = datetime.fromtimestamp(output.stat().st_mtime, TIMEZONE) + except Exception as exc: + # Keep URLs, credentials, and upstream error bodies out of HA state/logs. + error = type(exc).__name__ + return { + 'updated_at': updated.isoformat() if updated else None, + 'last_error': error, + 'stale': updated is None or updated < due, + } + + +if __name__ == '__main__': + print(json.dumps(refresh()))