Files
ha-solaredge-optimizers/scripts/convert_portal_layout.py
T
jensandClaude Opus 5.5 ce03c05d84 Add 3D roof view card for optimizer power
The integration now serves solaredge-roof-card and loads it in every
frontend session. The card shows the building in 3D with the current
power in W and the Panel-Position on every panel; the colour runs from
dark (0 W) to bright (Skalenmaximum, default 460 W). Failed panels are
grey and hatched, a tap opens the more-info dialog.

scripts/convert_portal_layout.py turns the SolarEdge portal's physical
layout and site model into the card's layout once, so nothing depends
on the portal at runtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:25:47 +01:00

393 lines
14 KiB
Python

"""Convert the SolarEdge portal's site model into a solaredge-roof-card layout.
The SolarEdge Monitoring portal renders its 3D site view from two documents:
* ``GET /services/layout/physical/site/{siteId}`` (the *physical layout*), which
lists the strings with their optimizers in display order and links to
* the *site model* (``awsJsonModelDownloadLink``), which holds roof polygons,
vertex heights and module groups in metres (x = east, y = north, z = up).
This script reads both files once and prints the ``layout`` block for the card
configuration. Nothing in Home Assistant depends on the portal afterwards.
Usage::
python scripts/convert_portal_layout.py physical.json model.json \
[--areas areas.json] > layout.yaml
``areas.json`` uses the same format as the integration's area mapping
(``{"west1": ["1.1.1", ...]}``) and names the roofs after the areas of the
panels on them.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from collections import Counter
from dataclasses import dataclass
from typing import Any
MODULE_OFFSET_M = 0.05
"""Height of a panel above its roof surface, so the two never z-fight."""
FLAT_ROOF_SLOPE = 0.02
"""Roofs with a smaller slope (rise per metre) count as flat."""
type Point2 = tuple[float, float]
type Point3 = tuple[float, float, float]
@dataclass(frozen=True)
class Plane:
"""Roof plane z = a*x + b*y + c."""
a: float
b: float
c: float
def z(self, x: float, y: float) -> float:
"""Return the plane height at (x, y)."""
return self.a * x + self.b * y + self.c
@dataclass(frozen=True)
class Panel:
"""One panel with its corners in the card's coordinate system."""
panel_id: str
roof_id: str
corners: tuple[Point3, Point3, Point3, Point3]
"""Lower left, lower right, upper right, upper left (upper = up-slope)."""
def decode_module_handle(handle: int) -> tuple[int, int]:
"""Return (row, column) of a module handle id.
The low 32 bits are the module group id, followed by an 11-bit signed row
and an 11-bit signed column.
"""
upper = handle >> 32
row = upper & 0x7FF
column = (upper >> 11) & 0x7FF
if row >= 1024:
row -= 2048
if column >= 1024:
column -= 2048
return row, column
def polygon_outline(model: dict[str, Any], polygon_id: str) -> list[Point3]:
"""Return the polygon's vertices in edge order."""
vertices = model["vertices"]
edges = model["edges"]
pairs = [
(edges[edge_id]["vertexAId"], edges[edge_id]["vertexBId"])
for edge_id in model["polygons"][polygon_id]["edgeIds"]
]
loop = [pairs[0][0], pairs[0][1]]
remaining = pairs[1:]
while remaining:
edge = next((pair for pair in remaining if loop[-1] in pair), None)
if edge is None:
msg = f"Polygon {polygon_id} is not a closed loop"
raise ValueError(msg)
remaining.remove(edge)
loop.append(edge[1] if edge[0] == loop[-1] else edge[0])
if loop[0] == loop[-1]:
loop.pop()
return [
(
vertices[vertex_id]["position"]["x"],
vertices[vertex_id]["position"]["y"],
vertices[vertex_id]["heightWithoutPolygonGroups"],
)
for vertex_id in loop
]
def fit_plane(points: list[Point3]) -> Plane:
"""Least-squares plane through the points."""
n = len(points)
sx = sum(p[0] for p in points)
sy = sum(p[1] for p in points)
sz = sum(p[2] for p in points)
sxx = sum(p[0] * p[0] for p in points)
syy = sum(p[1] * p[1] for p in points)
sxy = sum(p[0] * p[1] for p in points)
sxz = sum(p[0] * p[2] for p in points)
syz = sum(p[1] * p[2] for p in points)
a, b, c = _solve3(
[[sxx, sxy, sx], [sxy, syy, sy], [sx, sy, float(n)]], [sxz, syz, sz]
)
return Plane(a, b, c)
def _solve3(matrix: list[list[float]], rhs: list[float]) -> list[float]:
rows = [row[:] + [value] for row, value in zip(matrix, rhs, strict=True)]
for col in range(3):
pivot = max(range(col, 3), key=lambda r: abs(rows[r][col]))
rows[col], rows[pivot] = rows[pivot], rows[col]
for r in range(3):
if r != col:
factor = rows[r][col] / rows[col][col]
rows[r] = [
x - factor * y for x, y in zip(rows[r], rows[col], strict=True)
]
return [rows[i][3] / rows[i][i] for i in range(3)]
def point_in_polygon(point: Point2, outline: list[Point3], tolerance: float) -> bool:
"""Return whether the point lies inside or within tolerance of the outline."""
x, y = point
inside = False
edges = list(zip(outline, outline[1:] + outline[:1], strict=True))
for (x1, y1, _), (x2, y2, _) in edges:
if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:
inside = not inside
if inside:
return True
for (x1, y1, _), (x2, y2, _) in edges:
dx, dy = x2 - x1, y2 - y1
t = max(0.0, min(1.0, ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy)))
if math.hypot(x - x1 - t * dx, y - y1 - t * dy) <= tolerance:
return True
return False
def module_group_panels(
group: dict[str, Any],
details: dict[str, Any],
module_size: tuple[float, float],
row_sign: int,
rotation: float,
) -> list[tuple[int, list[Point2], Point2]]:
"""Place the modules of one group on the ground plan.
Returns (handle, plan corners, up-slope unit vector) per module. Columns run
along the eave, rows up the slope; the group position is the outer corner of
module (0, 0). The up-slope vector is the direction in which the module
rises, taken from its azimuth.
"""
azimuth = details["azimuth"]
tilt = details["tilt"]
up = (-math.sin(azimuth), -math.cos(azimuth))
along = (-math.cos(azimuth), math.sin(azimuth))
length, width = module_size
if group["orientation"] == "PORTRAIT":
cell_w, cell_h = width, length
else:
cell_w, cell_h = length, width
# The portal measures columns along -along, so its rotation runs the other way.
cos_r, sin_r = math.cos(rotation), -math.sin(rotation)
cos_t = math.cos(tilt)
origin = (group["position"]["x"], group["position"]["y"])
def to_plan(u: float, v: float) -> Point2:
u, v = u * cos_r - v * sin_r, u * sin_r + v * cos_r
v *= cos_t
return (
origin[0] + u * along[0] + v * up[0],
origin[1] + u * along[1] + v * up[1],
)
result = []
for handle in details["moduleHandleIds"]:
row, column = decode_module_handle(handle)
u0 = column * (cell_w + group["columnSpacing"])
v0 = row_sign * row * (cell_h + group["rowSpacing"])
v_low = v0 if row_sign > 0 else v0 - cell_h
corners = [
to_plan(u0, v_low),
to_plan(u0 + cell_w, v_low),
to_plan(u0 + cell_w, v_low + cell_h),
to_plan(u0, v_low + cell_h),
]
result.append((handle, corners, up))
return result
def _order_corners(corners: list[Point2], up: Point2) -> list[Point2]:
"""Order corners lower-left, lower-right, upper-right, upper-left.
Seen from above with up-slope pointing up, "right" is up rotated clockwise.
"""
right = (up[1], -up[0])
cx = sum(p[0] for p in corners) / 4
cy = sum(p[1] for p in corners) / 4
def key(p: Point2) -> tuple[bool, bool]:
dx, dy = p[0] - cx, p[1] - cy
return (dx * up[0] + dy * up[1] > 0, dx * right[0] + dy * right[1] > 0)
by_key = {key(p): p for p in corners}
return [
by_key[(False, False)],
by_key[(False, True)],
by_key[(True, True)],
by_key[(True, False)],
]
def convert(
physical: dict[str, Any],
site_model: dict[str, Any],
areas: dict[str, list[str]] | None = None,
) -> dict[str, Any]:
"""Build the card layout from the portal documents."""
model = site_model["modelData"]
group_details = site_model["moduleGroupDetails"]
module_model = next(iter(model["moduleModels"].values()))
module_size = (module_model["length"] / 1000, module_model["width"] / 1000)
devices = physical["physicalDevicesMap"]
serial_to_panel_id: dict[str, str] = {}
strings = devices["strings"].values()
inverters = devices["inverters"]
for string in strings:
inverter_seq = inverters[string["inverterId"]]["sequenceNumber"]
for position, optimizer_key in enumerate(string["optimizerIds"], start=1):
serial = devices["optimizers"][str(optimizer_key)]["serialNumber"]
serial_to_panel_id[serial] = (
f"{inverter_seq}.{string['sequenceNumber']}.{position}"
)
handle_to_panel_id = {
int(optimizer["moduleIds"][0]): serial_to_panel_id[optimizer["serialNumber"]]
for optimizer in model["optimizers"].values()
if optimizer["moduleIds"] and optimizer["serialNumber"] in serial_to_panel_id
}
outlines = {pid: polygon_outline(model, pid) for pid in model["polygons"]}
planes = {pid: fit_plane(points) for pid, points in outlines.items()}
panels: list[Panel] = []
for group_id, details in group_details.items():
group = model["moduleGroups"][group_id]
polygon_id = group["polygonId"]
outline = outlines[polygon_id]
# The portal flips the row direction for some groups (seen on a rotated
# group on a flat roof). Pick the direction that keeps the modules on
# their roof.
plane = planes[polygon_id]
# On a flat roof the module azimuth already fixes the grid direction and
# facetRotation is an absolute angle that would rotate it a second time.
flat = math.hypot(plane.a, plane.b) < FLAT_ROOF_SLOPE
rotation = 0.0 if flat else group["facetRotation"]
candidates = [
module_group_panels(group, details, module_size, sign, rotation)
for sign in (1, -1)
]
placed = max(
candidates,
key=lambda modules: sum(
point_in_polygon(corner, outline, 0.05)
for _, corners, _ in modules
for corner in corners
),
)
module_tilt = math.tan(details["tilt"])
for handle, corners, up in placed:
panel_id = handle_to_panel_id.get(handle)
if panel_id is None:
continue
ordered = _order_corners(corners, up)
cx = sum(p[0] for p in ordered) / 4
cy = sum(p[1] for p in ordered) / 4
base = plane.z(cx, cy) + MODULE_OFFSET_M
corners3 = tuple(
(
p[0],
p[1],
base + ((p[0] - cx) * up[0] + (p[1] - cy) * up[1]) * module_tilt,
)
for p in ordered
)
panels.append(Panel(panel_id, polygon_id, corners3))
roof_names = _roof_names(outlines, panels, areas or {})
panels.sort(
key=lambda panel: tuple(int(part) for part in panel.panel_id.split("."))
)
return {
"module_power": module_model["stcPower"],
"roofs": [
{"name": roof_names[pid], "outline": [_round3(p) for p in outline]}
for pid, outline in outlines.items()
],
"panels": [
{
"id": panel.panel_id,
"roof": roof_names[panel.roof_id],
"corners": [_round3(p) for p in panel.corners],
}
for panel in panels
],
}
def _roof_names(
outlines: dict[str, list[Point3]],
panels: list[Panel],
areas: dict[str, list[str]],
) -> dict[str, str]:
panel_area = {
panel_id: area for area, panel_ids in areas.items() for panel_id in panel_ids
}
names: dict[str, str] = {}
for index, polygon_id in enumerate(outlines, start=1):
votes = Counter(
panel_area[panel.panel_id]
for panel in panels
if panel.roof_id == polygon_id and panel.panel_id in panel_area
)
names[polygon_id] = votes.most_common(1)[0][0] if votes else f"dach{index}"
return names
def _round3(point: Point3) -> list[float]:
return [round(value, 3) for value in point]
def to_yaml(layout: dict[str, Any]) -> str:
"""Render the layout as a compact YAML block for the card configuration."""
lines = [
"type: custom:solaredge-roof-card",
f"max_power: {layout['module_power']:g}",
"layout:",
" roofs:",
]
for roof in layout["roofs"]:
lines.append(f" - name: {json.dumps(roof['name'], ensure_ascii=False)}")
lines.append(f" outline: {json.dumps(roof['outline'])}")
lines.append(" panels:")
for panel in layout["panels"]:
lines.append(f' - id: "{panel["id"]}"')
lines.append(f" roof: {json.dumps(panel['roof'], ensure_ascii=False)}")
lines.append(f" corners: {json.dumps(panel['corners'])}")
return "\n".join(lines) + "\n"
def main(argv: list[str] | None = None) -> int:
"""Run the converter."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("physical", help="physical layout response (JSON)")
parser.add_argument("model", help="site model from awsJsonModelDownloadLink")
parser.add_argument("--areas", help="area mapping JSON used to name roofs")
args = parser.parse_args(argv)
with open(args.physical, encoding="utf-8") as file:
physical = json.load(file)
with open(args.model, encoding="utf-8") as file:
site_model = json.load(file)
areas = None
if args.areas:
with open(args.areas, encoding="utf-8") as file:
areas = json.load(file)
sys.stdout.write(to_yaml(convert(physical, site_model, areas)))
return 0
if __name__ == "__main__":
raise SystemExit(main())