Switch PV curve to HA History API for full day data

This commit is contained in:
Joan
2026-03-20 13:30:38 +01:00
parent 0df6d57483
commit be3d23bb79
2 changed files with 56 additions and 11 deletions

View File

@@ -2,6 +2,7 @@
Home Assistant API client for Matrix64 LED display.
"""
import requests
import datetime
from config import (
HA_TOKEN, HASS_URL,
BRIGHTNESS_ENTITY_ID, WEATHER_ENTITY_ID,
@@ -114,3 +115,47 @@ def get_solar_status():
"today_energy": safe_float(today_energy),
"tesla_power": tesla_power_w,
}
def get_solar_history():
"""Get today's solar production history from HA History API.
Returns list of (hour_float, watts) tuples."""
headers = {
"Authorization": f"Bearer {HA_TOKEN}",
"Content-Type": "application/json",
}
now = datetime.datetime.now()
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
start_str = start.strftime("%Y-%m-%dT%H:%M:%S")
url = (f"{HASS_URL}/api/history/period/{start_str}"
f"?filter_entity_id={SOLAR_PRODUCTION_ENTITY}"
f"&minimal_response&no_attributes")
try:
response = requests.get(url, headers=headers, timeout=15)
if response.status_code != 200:
return []
data = response.json()
if not data or not data[0]:
return []
points = []
for entry in data[0]:
try:
state = float(entry.get("state", 0))
ts = entry.get("last_changed", "")
# Parse ISO timestamp
if "+" in ts:
ts = ts.split("+")[0]
elif ts.endswith("Z"):
ts = ts[:-1]
dt = datetime.datetime.fromisoformat(ts)
# Convert UTC to local time
utc_offset = now - datetime.datetime.utcnow()
dt_local = dt + utc_offset
hour_f = dt_local.hour + dt_local.minute / 60.0
points.append((hour_f, state))
except (ValueError, TypeError):
continue
return points
except Exception as e:
print(f"Error fetching solar history: {e}")
return []