Source code for energy_data_retrieval.bess_oem_catalogue.bsb

"""Offline staging for independently reviewed BSB battery specification tables."""

from html.parser import HTMLParser
from math import isfinite


class _Table(HTMLParser):
    def __init__(self):
        super().__init__()
        self.rows = []
        self.row = []
        self.cell = None

    def handle_starttag(self, tag, attrs):
        if tag == "tr":
            self.row = []
        elif tag in {"td", "th"}:
            self.cell = ""

    def handle_data(self, data):
        if self.cell is not None:
            self.cell += data

    def handle_endtag(self, tag):
        if tag in {"td", "th"} and self.cell is not None:
            self.row.append(" ".join(self.cell.split()))
            self.cell = None
        elif tag == "tr" and self.row:
            self.rows.append(self.row)


def _stage(html: str, expected: list[str]) -> list[dict]:
    """Stage exact models; fail closed on identity, header, unit or shape drift.

    Ah rate/temperature/endpoint are unstated. Do not derive energy or power.
    Keep body height separate from overall height including terminals.
    """
    parser = _Table()
    parser.feed(html)
    rows = parser.rows
    if (
        len(rows) != len(expected) + 2
        or rows[0]
        != [
            "Code No.",
            "Voltage",
            "Capacity",
            "Length",
            "Width",
            "Height",
            "Total Height",
            "Terminal",
        ]
        or rows[1] != ["(V)", "(Ah)", "mm", "in", "mm", "in", "mm", "in", "mm", "in", "Type"]
    ):
        raise ValueError("Unreviewed table shape or units")
    if [r[0] for r in rows[2:]] != expected:
        raise ValueError("Missing, duplicate or unreviewed model")
    result = []
    for index, r in enumerate(rows[2:], 3):
        if len(r) != 12 or not r[1].endswith("V") or not r[2].endswith("Ah") or r[11] != "M8":
            raise ValueError("Unreviewed model row")
        voltage = float(r[1][:-1].strip())
        capacity = float(r[2][:-2].strip())
        dimensions = [float(r[i]) for i in (3, 5, 7, 9)]
        if (
            voltage != (12 if r[0].startswith(("TG12-", "FAC12-", "LCB12-")) else 2)
            or not all(isfinite(x) for x in [capacity, *dimensions])
            or capacity <= 0
            or min(dimensions) <= 0
            or dimensions[3] < dimensions[2]
        ):
            raise ValueError("Invalid physical rating")
        result.append(
            dict(
                model=r[0],
                voltage_v=voltage,
                capacity_ah=capacity,
                length_mm=dimensions[0],
                width_mm=dimensions[1],
                body_height_mm=dimensions[2],
                total_height_mm=dimensions[3],
                terminal="M8",
                table_row=index,
                capacity_rate=None,
                capacity_temperature_c=None,
                capacity_endpoint_v=None,
            )
        )
    return result


[docs] def stage_opzv(html: str) -> list[dict]: """Stage the reviewed gel battery table only.""" expected = [f"TG12-{x}" for x in (100, 150, 200)] + [ f"OPzV2-{x}" for x in (150, 200, 250, 300, 350, 420, 500, 600, 800, 1000, 1200, 1500, 2000, 2500, 3000) ] return _stage(html, expected)
[docs] def stage_opzs(html: str) -> list[dict]: """Stage the distinct flooded table; never transfer OPzV conditions.""" expected = [ f"OPzS2-{x}" for x in ( 150, 200, 250, 300, 350, 420, 500, 600, 700, 770, 800, 1000, 1200, 1500, 2000, 2500, 3000, ) ] return _stage(html, expected)
[docs] def stage_lcb(html: str) -> list[dict]: """Stage the 20 lead-carbon units, preserving distinct S-suffix identities. Common series claims are not extracted as exact-model test results. Ah remains battery-unit capacity with unknown discharge/test conditions. """ expected = [f"FAC12-{x}" for x in (100, 170, 200)] expected += [f"LCB12-{x}" for x in (100, 120, 150, 200, 250)] expected += [f"LCB2-{x}" for x in (200, 300)] expected += [f"LCB2-{x}{suffix}" for x in (400, 500, 600, 800, 1000) for suffix in ("S", "")] return _stage(html, expected)