// app.js — the interactive, beginner-friendly form. Renders controls from the // schema, keeps a single `state` object, persists it (localStorage + share // link + downloadable project file) and shows a live preview generated by // generate.js. import { POWERMETERS, getPowermeter, PHASE_CAPABLE, DEVICE_TYPES, PER_METER_TUNING, CT_BASIC, CT_ACTIVE, CT_BALANCER, CT_DC_KEEPALIVE, CT_POWER_LIMITS, CT_EFFICIENCY, CT_SATURATION, CT_CLOUD, MARSTEK_FIELDS, MQTT_INSIGHTS_FIELDS, ESP_BOARDS, HARDWARE, type Field, type Powermeter, } from "./schema.js"; import { generate } from "./generate.js"; import { ghDoc } from "./links.js"; import { changedLines } from "./preview-diff.js"; import { STORAGE_KEY, newMeter, defaultState, safeParse, migrate, type State, type Meter } from "./state.js"; let state: State = loadState() || defaultState(); // ── tiny DOM helper ───────────────────────────────────────────────────────── type ElProps = Record; type ElChild = Node | string | null | undefined; function el( tag: K, props?: ElProps, children?: ElChild | ElChild[], ): HTMLElementTagNameMap[K]; function el(tag: string, props: ElProps = {}, children: ElChild | ElChild[] = []): HTMLElement { const node = document.createElement(tag); for (const [k, v] of Object.entries(props)) { if (k === "class") node.className = v; else if (k === "html") node.innerHTML = v; else if (k === "text") node.textContent = v; else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v as EventListener); else if (v === true) node.setAttribute(k, ""); else if (v !== false && v != null) node.setAttribute(k, String(v)); } const kids = Array.isArray(children) ? children : [children]; for (const c of kids) { if (c == null) continue; node.appendChild(typeof c === "string" ? document.createTextNode(c) : c); } return node; } // Cloud registration's default: on for a CT002/CT003, except on an ESP32 with // Bluetooth, where the Marstek app adds the board itself and the cloud login // stays off unless asked for. Applied only when one of its inputs changes, so // a box the user set by hand stays as they left it. function registrationByDefault(): boolean { // An ESPHome build always emulates a CT; the device types are the Python target's. const hasCt = state.target === "esphome" || hasCtType(state.general.deviceTypes); return hasCt && !(state.target === "esphome" && state.general.esphomeBluetooth); } // Whether the box was set by hand, kept in the project so it survives a reload. // A project saved before the mark existed counts as hand-set where its box // differs from the default. function settleRegistrationMark(): void { if (state.marstek.setByHand === undefined) { state.marstek.setByHand = state.marstek.enabled !== registrationByDefault(); } } settleRegistrationMark(); // For the target and Bluetooth switches, which only change whether the cloud // login is the way to add the CT: a choice the user made stands. function followRegistrationDefault(): void { if (!state.marstek.setByHand) state.marstek.enabled = registrationByDefault(); } // ── generic field renderer ─────────────────────────────────────────────────── // Renders one schema field bound to obj[field.key]. `phases` controls phase // expansion. Calls refreshPreview() on change; if field.structural, also calls // rerenderAll() so dependent sections appear/disappear. function fieldControl( field: Field, obj: Record, { phases = 1, structural = false, onChange, }: { phases?: number; structural?: boolean; onChange?: () => void } = {}, ): HTMLElement { const help = field.help ? el("p", { class: "help", text: field.help }) : null; const labelText = field.label + (field.required ? " *" : ""); // phase-aware text fields → three L1/L2/L3 boxes joined with ", " if (field.phase && phases === 3 && (field.type === "text" || field.type === "number")) { const parts = String(obj[field.key] || "").split(",").map((s) => s.trim()); while (parts.length < 3) parts.push(""); const boxes = ["L1", "L2", "L3"].map((ph, i) => { const inp = el("input", { type: field.type, value: parts[i] || "", placeholder: ph, "aria-label": `${field.label} ${ph}`, }); inp.addEventListener("input", () => { parts[i] = inp.value.trim(); obj[field.key] = joinPhases(parts); refreshPreview(); }); return inp; }); return el("div", { class: "field" }, [ el("label", { text: labelText, class: "field-label" }), el("div", { class: "phase-row" }, boxes), help, ]); } let control: HTMLInputElement | HTMLSelectElement; if (field.type === "select") { control = el( "select", {}, (field.options ?? []).map((o) => el("option", { value: o.value, ...(String(obj[field.key] ?? field.default ?? "") === o.value ? { selected: true } : {}) }, o.label), ), ); if (obj[field.key] === undefined && field.default !== undefined) obj[field.key] = field.default; control.addEventListener("change", () => { obj[field.key] = control.value; onChange?.(); if (structural) rerenderAll(); else refreshPreview(); }); } else if (field.type === "checkbox") { if (obj[field.key] === undefined) obj[field.key] = !!field.default; const cb = el("input", { type: "checkbox", ...(obj[field.key] ? { checked: true } : {}) }); cb.addEventListener("change", () => { obj[field.key] = cb.checked; onChange?.(); if (structural) rerenderAll(); else refreshPreview(); }); return el("div", { class: "field field-check" }, [ el("label", { class: "check-label" }, [cb, el("span", { text: labelText })]), help, ]); } else { control = el("input", { type: field.type, value: obj[field.key] ?? "", placeholder: field.placeholder || "", }); if (field.type === "password") control.classList.add("secret"); control.addEventListener("input", () => { obj[field.key] = control.value; refreshPreview(); }); } return el("div", { class: "field" }, [el("label", { text: labelText, class: "field-label" }), control, help]); } // HTML-escape a (possibly untrusted, restored) value before it goes into an // innerHTML string. Used for state values interpolated into `html:` props. function escapeHtml(v: unknown): string { return String(v ?? "") .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } function linkOut(href: string, text: string): HTMLElement { return el("a", { href, target: "_blank", rel: "noopener", class: "btn-link" }, text + " ↗"); } function joinPhases(parts: string[]): string { // keep up to the last non-empty entry so "a,,c" round-trips let last = -1; parts.forEach((p, i) => { if (p !== "") last = i; }); if (last < 0) return ""; return parts.slice(0, last + 1).join(", "); } // group a list of fields, splitting advanced ones into a
function fieldGroup(fields: Field[], obj: Record, ctx: { phases?: number; structural?: boolean } = {}): HTMLElement[] { const basic = fields.filter((f) => !f.advanced); const advanced = fields.filter((f) => f.advanced); const nodes = basic.map((f) => fieldControl(f, obj, ctx)); if (advanced.length) { nodes.push( el("details", { class: "adv" }, [ el("summary", { text: "Advanced options" }), el("div", { class: "field-grid" }, advanced.map((f) => fieldControl(f, obj, ctx))), ]), ); } return nodes; } // ── card builders ──────────────────────────────────────────────────────────── function card(n: number | null, title: string, subtitle: string | null, body: ElChild[]): HTMLElement { return el("section", { class: "card" }, [ el("div", { class: "card-head" }, [ n ? el("span", { class: "step", text: String(n) }) : null, el("div", {}, [el("h2", { text: title }), subtitle ? el("p", { class: "subtitle", text: subtitle }) : null]), ]), el("div", { class: "card-body" }, body), ]); } // Fields of the `homeassistant` meter that the add-on does NOT configure for // you (the host/port/token/API-path are set automatically by the add-on). Only // these grid-power entity fields are surfaced for the Home Assistant target. const HA_ADDON_METER_FIELDS = new Set([ "CURRENT_POWER_ENTITY", "POWER_CALCULATE", "POWER_INPUT_ALIAS", "POWER_OUTPUT_ALIAS", ]); // CT / Marstek fields the add-on actually accepts as options. Everything else // (active control, balancer, saturation, Marstek base URL / timezone, …) is set // automatically or only reachable via a custom config.ini, so it's hidden for // the Home Assistant target. const HA_ADDON_CT_FIELDS = new Set([ "CT_MAC", "PEAKSHAVING_THRESHOLD", "MIN_EFFICIENT_POWER", "MIN_EFFICIENT_CHARGE_POWER", "MIN_EFFICIENT_DISCHARGE_POWER", "EFFICIENCY_ROTATION_INTERVAL", "MIN_DISCHARGE_POWER", "MIN_CHARGE_POWER", "MIN_POWER_HYSTERESIS", "MAX_DISCHARGE_POWER", "MAX_CHARGE_POWER", "CLOUD_REPORTING", "CLOUD_REPORTING_HOST", "CLOUD_REPORTING_INTERVAL", ]); function hasCtType(types: string[]): boolean { return types.includes("ct002") || types.includes("ct003"); } const HA_ADDON_MARSTEK_FIELDS = new Set(["MAILBOX", "PASSWORD"]); const HA_ADDON_INSIGHTS_FIELDS = new Set(["BROKER", "PORT", "USERNAME", "PASSWORD", "TLS"]); // The Home Assistant add-on only reads grid power from a Home Assistant sensor // and runs a single meter, so collapse to one homeassistant meter when that // target is chosen (keeping the existing one if it already matches). function coerceHaMeter(): void { const first = state.meters[0]; state.meters = first && first.type === "homeassistant" ? [first] : [newMeter("homeassistant")]; } function targetCard(): HTMLElement { function choice(value: State["target"], title: string, desc: string): HTMLElement { const active = state.target === value; return el( "button", { class: "choice" + (active ? " active" : ""), type: "button", onclick: () => { // Both targets ship dashboard writes on, so the box carries over as // the user left it. (The ESP32's own controls are a separate flag — // it has no login to sit behind.) // Re-migrate rather than just assigning: a meter the new target // can't run (an esphomeOnly source leaving the ESPHome target) // has to be replaced here, or the generator emits a section the // Python loader silently skips. const wasEsphome = state.target === "esphome"; state = migrate({ ...state, target: value }); if (value === "homeassistant") coerceHaMeter(); // Entering or leaving the ESP32 target changes whether the app can // add the CT itself, so re-derive the registration default (edge- // triggered like the device-type pills below). if (wasEsphome !== (value === "esphome")) followRegistrationDefault(); rerenderAll(); }, }, [el("strong", { text: title }), el("span", { text: desc })], ); } return card(1, "How will you run AstraMeter?", "Pick where the emulator runs. Not sure? Choose the Home Assistant add-on option — it's the most common.", [ el("div", { class: "choice-row" }, [ choice("homeassistant", "Home Assistant add-on (UI options)", "Generates the add-on Configuration options (YAML) you paste into the add-on's Configuration tab. Reads grid power from a Home Assistant sensor."), choice("python", "config.ini (Docker, a PC, or advanced add-on)", "Generates a config.ini file. AstraMeter runs as software and talks to your power meter over the network."), choice("esphome", "On an ESP32 chip (ESPHome)", "Generates an ESPHome YAML file. The emulator runs on a tiny ESP32 board that reads a grid-power sensor."), ]), ]); } function deviceCard(): HTMLElement { if (state.target === "esphome") { const e = state.esphome; return card(2, "Your ESP32 device", "AstraMeter will run on a small ESP32 board you buy and plug in. Tell us which board you have so the file matches it.", [ el("details", { class: "intro-box", open: true }, [ el("summary", { text: "First time with ESPHome? Read this" }), el("p", { html: "ESPHome is free software that turns a tiny, cheap WiFi chip (an ESP32) into a smart device by flashing a config file onto it. Here, the ESP32 becomes the power meter your Marstek battery talks to — no PC, Docker, or Home Assistant add-on left running." }), el("p", { html: "You'll need to buy an ESP32 board (see below), install ESPHome once, paste the file this tool generates, and flash it over USB. Step-by-step instructions appear at the bottom of the page." }), ]), el("div", { class: "hw" }, [ el("h3", { text: "Recommended hardware" }), el("p", { class: "help", html: "We recommend the ESP32-S3 DevKitC-1 — it's cheap, widely available, and is the board this tool defaults to. One board is enough no matter how many batteries you have." }), el("ul", { class: "hw-links" }, [ el("li", {}, [linkOut(HARDWARE.single.url, "Buy 1× " + "ESP32-S3 DevKitC-1"), el("span", { class: "help", text: " — for a single setup" })]), el("li", {}, [linkOut(HARDWARE.pack3.url, "Buy 3× ESP32-S3 DevKitC-1"), el("span", { class: "help", text: " — cheaper per board; handy for spares or multiple homes" })]), ]), el("p", { class: "help affiliate", text: "These are affiliate links — they cost you nothing extra and help support AstraMeter." }), ]), el("div", { class: "field-grid" }, [ fieldControl({ key: "name", label: "Device name", help: "Lowercase name used by ESPHome (letters, numbers, hyphens). You can leave the default.", type: "text" }, e, {}), fieldControl({ key: "friendlyName", label: "Friendly name", help: "Display name shown in Home Assistant. Optional.", type: "text" }, e, {}), fieldControl({ key: "board", label: "ESP32 board", help: "⚠ This MUST match the board you actually bought, or flashing will fail. If you bought the recommended one, leave it as ESP32-S3 DevKitC-1.", type: "select", options: ESP_BOARDS }, e, { structural: true }), fieldControl({ key: "ctType", label: "Emulated CT type", help: "HME-4 emulates a CT002; HME-3 emulates a CT003. Match what your Marstek battery expects (CT002 is the common choice).", type: "select", options: [{ value: "HME-4", label: "CT002 (HME-4)" }, { value: "HME-3", label: "CT003 (HME-3)" }] }, e, {}), ]), el("p", { class: "note", html: "WiFi credentials aren't stored in the file — ESPHome reads them from a separate secrets.yaml. The flashing steps at the bottom show exactly what to put there." }), ]); } // Python: device-type multiselect const g = state.general; const typeButtons = DEVICE_TYPES.map((d) => { const active = g.deviceTypes.includes(d.value); return el( "button", { type: "button", class: "pill" + (active ? " active" : ""), title: d.help, onclick: () => { const hadCt = hasCtType(g.deviceTypes); if (active) g.deviceTypes = g.deviceTypes.filter((t) => t !== d.value); else g.deviceTypes = [...g.deviceTypes, d.value]; if (g.deviceTypes.length === 0) g.deviceTypes = [d.value]; // Marstek registration + MQTT Insights are CT002/CT003 features, so // flip their defaults when CT emulation is switched on or off. This is // edge-triggered (only on a CT-membership change), so a user can still // uncheck them afterwards without the next pill click snapping them back. const hasCt = hasCtType(g.deviceTypes); if (hasCt !== hadCt) { state.marstek.enabled = registrationByDefault(); state.marstek.setByHand = false; state.mqttInsights.enabled = hasCt; } rerenderAll(); }, }, d.label, ); }); // NOTE: `html:` renders as innerHTML. Only interpolate trusted static schema // constants here (d.label/d.help) — never user/restored state. g.deviceTypes // (user-controlled) is used only as a membership filter, not rendered. const selectedHelp = DEVICE_TYPES.filter((d) => g.deviceTypes.includes(d.value)).map((d) => el("li", { html: `${d.label}: ${d.help}` })); return card(2, "Which meter should AstraMeter pretend to be?", "Your battery talks to a power meter it trusts. AstraMeter impersonates one. Keep CT002.", [ el("div", { class: "pill-row" }, typeButtons), el("ul", { class: "pill-help" }, selectedHelp), el("details", { class: "adv" }, [ el("summary", { text: "Advanced general options" }), el("div", { class: "field-grid" }, [ // Device IDs, skip-test and the built-in web editor aren't add-on options. state.target === "homeassistant" ? null : fieldControl({ key: "deviceIds", label: "Device IDs", help: "Optional fixed IDs (comma-separated, same order as the meters above). Leave blank to auto-generate.", type: "text", placeholder: "shellypro3em-c59b15461a21" }, g, {}), state.target === "homeassistant" ? null : fieldControl({ key: "skipPowermeterTest", label: "Skip power meter test on startup", help: "Skip the connection check when AstraMeter starts.", type: "checkbox" }, g, {}), // These three are config.ini settings. The add-on always serves the // dashboard — it is the sidebar panel — so there is nothing to enable // there, only the write flag to relax; an ESP32 serves its dashboard // from a `ct002:` sub-block, so that target has its own toggle down in // the ESPHome card. state.target === "python" ? fieldControl({ key: "webConfigEnabled", label: "Built-in web config editor", help: "The editor at http://:/config, which is also the dashboard's Configuration tab. Left on default it comes with the dashboard below; \"Off\" keeps it out of the page while the battery controls stay.", type: "select", options: [{ value: "", label: "Default (with the dashboard)" }, { value: "true", label: "On" }, { value: "false", label: "Off" }] }, g, { structural: true }) : null, state.target === "python" ? fieldControl({ key: "dashboardEnabled", label: "Serve the live status dashboard", help: "Live status page at http://:/. On by default; uncheck to leave only the health check (and the config editor above, if you turned it on).", type: "checkbox" }, g, { structural: true }) : null, state.target === "homeassistant" || (state.target === "python" && g.dashboardEnabled) ? fieldControl({ key: "dashboardAllowWrite", label: "Allow changes from the dashboard", help: "Lets the dashboard edit your configuration and control batteries. Leave off for a read-only dashboard.", type: "checkbox" }, g, {}) : null, // Only the add-on has an ingress to sit behind, so this opt-out of it // is an add-on option — a config.ini reads it only when the add-on // runs from one, which the editor cannot tell from here. state.target === "homeassistant" ? fieldControl({ key: "dashboardDirectAccess", label: "Allow dashboard access outside Home Assistant", help: "Also serves the page on http://:52500 with NO login. Leave off unless you need it.", type: "checkbox" }, g, {}) : null, // Both targets here serve the port, so both can be reached under a // name. On the add-on that only matters once direct access is on — but // the field is cheap, and hiding it behind another toggle buries the // fix for the refusal someone is looking at. ESPHome takes the same // setting as a ct002: sub-block, so it appears in that card instead. state.target === "homeassistant" || (state.target === "python" && g.dashboardEnabled) ? fieldControl({ key: "dashboardAllowedHosts", label: "Extra dashboard host names", help: "Comma-separated. IP addresses, localhost, .local and .home.arpa names always work — add a name if you reach the dashboard through a reverse proxy, a private DNS entry, or a router-assigned name such as astrameter.fritz.box.", type: "text", placeholder: "astrameter.example.lan" }, g, {}) : null, state.target === "python" ? fieldControl({ key: "webServerPort", label: "Web server port", help: "Serves the health check, and the dashboard and editor when they are on. Default 52500.", type: "number", placeholder: "52500" }, g, {}) : null, fieldControl({ key: "throttleInterval", label: "Global throttle interval (s)", help: "Minimum seconds between readings for every meter. 0 = off. You can override per meter below.", type: "number", placeholder: "0" }, g, {}), fieldControl({ key: "waitForNextMessage", label: "Wait for fresh push (global)", help: "Wait up to 2s for the newest reading from push-based meters.", type: "select", options: [{ value: "", label: "Default (on)" }, { value: "true", label: "On" }, { value: "false", label: "Off" }] }, g, {}), fieldControl({ key: "dedupeTimeWindow", label: "Dedupe window (s)", help: "Ignore repeated requests from the same client within this window. 0 = off.", type: "number", placeholder: "0" }, g, {}), ]), ]), ]); } function meterEditor(meter: Meter, index: number): HTMLElement { const pm = getPowermeter(meter.type) || POWERMETERS[0]; const canPhase = PHASE_CAPABLE.has(meter.type); // The HA add-on fills in the connection details automatically (host, port, // token, API path), so for that target only the grid-power entity fields are // shown — the rest would be ignored. const fields = state.target === "homeassistant" ? pm.fields.filter((f) => HA_ADDON_METER_FIELDS.has(f.key)) : pm.fields; // Throttle / wait-for-push are set once in the General section for the HA // target, so drop them from this per-meter list to avoid duplication. const tuningFields = state.target === "homeassistant" ? PER_METER_TUNING.filter((f) => f.key !== "THROTTLE_INTERVAL" && f.key !== "WAIT_FOR_NEXT_MESSAGE") : PER_METER_TUNING; const sourceSelect = el( "select", { onchange: (e: Event) => { meter.type = (e.target as HTMLInputElement).value; meter.fields = {}; meter.phases = 1; rerenderAll(); }, }, POWERMETERS.filter((p) => !p.esphomeOnly || state.target === "esphome").map((p) => el("option", { value: p.id, ...(p.id === meter.type ? { selected: true } : {}) }, p.label), ), ); const badge = state.target === "esphome" ? esphomeBadge(pm) : null; // The HA add-on target is locked to a single Home Assistant sensor, so show a // static label instead of the power-meter type picker. const typeField = state.target === "homeassistant" ? el("div", { class: "field grow" }, [ el("label", { class: "field-label", text: "Power source" }), el("p", { class: "blurb", text: "Home Assistant sensor — the add-on reads grid power from an HA entity." }), ]) : el("div", { class: "field grow" }, [el("label", { class: "field-label", text: "Power meter type" }), sourceSelect]); const phaseToggle = canPhase ? el("div", { class: "field" }, [ el("label", { class: "field-label", text: "How many phases?" }), el( "select", { onchange: (e: Event) => { meter.phases = Number((e.target as HTMLInputElement).value); rerenderAll(); }, }, [ el("option", { value: "1", ...(meter.phases !== 3 ? { selected: true } : {}) }, "Single-phase (one value)"), el("option", { value: "3", ...(meter.phases === 3 ? { selected: true } : {}) }, "Three-phase (L1 / L2 / L3)"), ], ), el("p", { class: "help", text: "Most homes are single-phase. Pick three-phase only if your meter reports L1/L2/L3 separately." }), ]) : null; const removeBtn = state.meters.length > 1 ? el("button", { type: "button", class: "link-danger", onclick: () => { state.meters.splice(index, 1); rerenderAll(); } }, "Remove this meter") : null; const suffixField = state.meters.length > 1 ? fieldControl({ key: "suffix", label: "Section suffix", help: "Unique label so each meter has its own section, e.g. 1, garage.", type: "text", placeholder: String(index + 1) }, meter, {}) : null; const netmaskField = state.meters.length > 1 ? fieldControl({ key: "netmask", label: "NETMASK (which batteries use this meter)", help: "CIDR of battery IPs that should use this meter, e.g. 192.168.1.0/24.", type: "text", placeholder: "192.168.1.0/24" }, meter, {}) : null; // The reference for the platform being configured, falling back to the other one. const doc = state.target === "esphome" ? pm.docEsphome ?? pm.docPython : pm.docPython ?? pm.docEsphome; const docLink = doc ? el("a", { class: "doclink", href: ghDoc(doc), target: "_blank", rel: "noopener" }, "Reference for this meter ↗") : null; return el("div", { class: "meter" }, [ el("div", { class: "meter-head" }, [ typeField, badge, ]), el("p", { class: "blurb", text: pm.blurb }), docLink, suffixField, phaseToggle, el("div", { class: "field-grid" }, fieldGroup(fields, meter.fields, { phases: meter.phases })), el("details", { class: "adv" }, [ el("summary", { text: "Fine-tuning (smoothing, calibration, throttling, PID)" }), el("p", { class: "help", text: "All optional. These shape the reading before it reaches your battery." }), el("div", { class: "field-grid" }, fieldGroup(tuningFields, meter.tuning, { phases: meter.phases })), ]), netmaskField, removeBtn, ]); } function esphomeBadge(pm: Powermeter): HTMLElement { const tier = (pm.esphome && pm.esphome.tier) || "unsupported"; const map = { native: ["Native on ESP32", "ok"], generic: ["Works via HTTP poll", "ok"], alternate: ["Alternate path needed", "warn"], unsupported: ["No ESP32 support yet", "bad"], }; const [text, cls] = map[tier] || map.unsupported; const note = pm.esphome && pm.esphome.note ? pm.esphome.note : ""; return el("span", { class: "badge badge-" + cls, title: note, text }); } function meterCard(): HTMLElement { const meters = state.meters.map((m, i) => meterEditor(m, i)); const addBtn = state.target === "python" ? el("button", { type: "button", class: "secondary", onclick: () => { state.meters.push(newMeter("shelly")); rerenderAll(); } }, "+ Add another power meter") : null; const intro = state.target === "esphome" ? "On an ESP32 the emulator reads one grid-power sensor. Pick the source below — the badge shows how well each works on ESP32." : state.target === "homeassistant" ? "The add-on reads your grid power from one Home Assistant sensor. Enter the entity below." : "Tell us where AstraMeter should read your real grid power. Add more than one only for advanced multi-network setups."; const customConfigNote = state.target === "homeassistant" ? el("p", { class: "note", html: "The add-on supports a single Home Assistant power source. For other meter types, multiple meters, or options the add-on UI doesn't expose, switch to the config.ini target above, save the file to /addon_configs/a0ef98c5_b2500_meter/, and set the add-on's Custom Config option to its filename. See the custom configuration docs ↗." }) : null; return card(3, "Your power meter", intro, [...meters, addBtn, customConfigNote]); } function ctCard(): HTMLElement | null { const isHa = state.target === "homeassistant"; const showFlat = (state.target === "python" || isHa) && (state.general.deviceTypes.includes("ct002") || state.general.deviceTypes.includes("ct003")); const show = state.target === "esphome" || showFlat; if (!show) return null; const f = state.ct.fields; // The add-on only exposes a handful of CT options; show just those for the HA // target (the rest need a custom config.ini). if (isHa) { const haFields = [...CT_BASIC, ...CT_POWER_LIMITS, ...CT_EFFICIENCY, ...CT_CLOUD].filter((fl) => HA_ADDON_CT_FIELDS.has(fl.key)); return card(4, "Battery steering (CT002 / CT003)", "Optional CT options exposed by the add-on. Leave them blank to use the defaults.", [ el("div", { class: "field-grid" }, haFields.map((fl) => fieldControl(fl, f, {}))), ]); } const group = (title: string, fields: Field[], openByDefault = false): HTMLElement => el("details", { class: "adv", ...(openByDefault ? { open: true } : {}) }, [ el("summary", { text: title }), el("div", { class: "field-grid" }, fields.map((fl) => fieldControl(fl, f, {}))), ]); return card(4, "Battery steering (CT002 / CT003)", "How AstraMeter steers your battery (or balances several). The defaults work well — open a section only if you want to tune it.", [ el("div", { class: "field-grid" }, CT_BASIC.map((fl) => fieldControl(fl, f, {}))), group("Active control", CT_ACTIVE, true), group("Multi-battery balancing", CT_BALANCER), group("DC battery keep-alive", CT_DC_KEEPALIVE), group("Battery power limits", CT_POWER_LIMITS), group("Efficiency optimization (AC batteries only)", CT_EFFICIENCY), group("Saturation handling", CT_SATURATION), group("Cloud reporting (experimental)", CT_CLOUD), ]); } function extrasCard(): HTMLElement { const m = state.marstek; const mi = state.mqttInsights; const isHa = state.target === "homeassistant"; // For the HA target the add-on hardcodes the Marstek base URL/timezone and uses // HA's built-in broker, so only the credential / custom-broker fields apply. const marstekFields = isHa ? MARSTEK_FIELDS.filter((fl) => HA_ADDON_MARSTEK_FIELDS.has(fl.key)) : MARSTEK_FIELDS; const insightsFields = isHa ? MQTT_INSIGHTS_FIELDS.filter((fl) => HA_ADDON_INSIGHTS_FIELDS.has(fl.key)) : MQTT_INSIGHTS_FIELDS; // On an ESP32 with Bluetooth the app adds the board itself, so the cloud // login is only for boards without it. const marstekHelp = state.target === "esphome" && state.general.esphomeBluetooth ? "Not needed with Bluetooth on: the Marstek app adds the board itself. Use this on a board without Bluetooth (ESP32-S2, ESP32-P4) to create the CT in your Marstek account instead. Credentials are only needed once." : "Optional. Creates a fake CT in your Marstek account so the app can select it. Credentials are only needed once."; const marstekBody = [ fieldControl({ key: "enabled", label: "Auto-register a managed CT device in the Marstek cloud", help: marstekHelp, type: "checkbox" }, m, { structural: true, onChange: () => (state.marstek.setByHand = true), }), ]; if (m.enabled) marstekBody.push(el("div", { class: "field-grid" }, marstekFields.map((fl) => fieldControl(fl, m.fields, {})))); const insightsLabel = isHa ? "Use a custom MQTT broker" : "Publish internal state to MQTT (Home Assistant discovery)"; const insightsHelp = isHa ? "Optional. The add-on uses Home Assistant's built-in MQTT broker automatically. Turn this on only to point MQTT Insights at a different broker." : "Optional. Exposes grid power, targets and per-battery state to Home Assistant via MQTT."; const insightsBody = [ fieldControl({ key: "enabled", label: insightsLabel, help: insightsHelp, type: "checkbox" }, mi, { structural: true }), ]; if (mi.enabled) insightsBody.push(el("div", { class: "field-grid" }, fieldGroup(insightsFields, mi.fields, {}))); // The board's own status page. The other targets offer this in the general // options (it is a config.ini / add-on setting there); on an ESP32 it is a // ct002: sub-block, so it belongs with the other two. const dashboardBody = state.target === "esphome" ? [ el("hr", {}), el("h3", { text: "Live status dashboard" }), fieldControl( { key: "esphomeDashboard", label: "Serve the live status dashboard from the board", help: "On by default. A status page at http:/// showing grid power, every battery and the balancer's state. Configuration is not editable there — an ESP32's settings live in this file.", type: "checkbox", }, state.general, { structural: true }, ), // The page has no login of its own, so writes stay opt-in. state.general.esphomeDashboard ? fieldControl( { key: "esphomeControls", label: "Allow battery changes from the dashboard", help: "Lets anyone who can reach the device steer your batteries from the page. Leave off for a read-only dashboard.", type: "checkbox", }, state.general, {}, ) : null, // The board is reached by IP or by its .local mDNS name, both of // which the firmware allows outright — so this stays empty unless a // reverse proxy sits in front of it. state.general.esphomeDashboard ? fieldControl( { key: "dashboardAllowedHosts", label: "Extra dashboard host names", help: "Comma-separated. The board's IP address, localhost and its .local name always work — add a name only if you reach the page through a reverse proxy. Other names are refused, because a name is the one part of the address another website can aim at this device.", type: "text", placeholder: "astrameter.example.lan", }, state.general, {}, ) : null, ] : []; // A real meter's Bluetooth interface: on an ESP32 the Marstek app can add // the board the way it adds a real CT, which is the alternative to the // cloud registration below. const bluetoothBody = state.target === "esphome" ? [ el("h3", { text: "Add with the Marstek app" }), fieldControl( { key: "esphomeBluetooth", label: "Act as a real CT over Bluetooth", help: "On by default. The Marstek app finds the board in its regular Add device scan and can show live grid power over Bluetooth, with no Marstek login in this file. Turn off to leave Bluetooth out of the firmware (saves memory; also off on boards without Bluetooth, such as the ESP32-S2).", type: "checkbox", }, state.general, // Structural: the two switches below and the cloud registration // help depend on it. Turning Bluetooth off makes registration the // way to add the CT again, so its default follows. { structural: true, onChange: followRegistrationDefault }, ), ...(state.general.esphomeBluetooth ? [ fieldControl( { key: "esphomeBluetoothAllowWifiChange", label: "Allow the app to change the Wi-Fi", help: "Off by default: the board stays on the Wi-Fi in this file, and the app's Wi-Fi step still completes. Turn on to let the network you pick in the Marstek app replace it once the board connects. Any phone in Bluetooth range could then move the board to another network.", type: "checkbox", }, state.general, {}, ), fieldControl( { key: "esphomeBluetoothAllowDirectionChange", label: "Allow the app to reverse a phase", help: "Off by default. Turn on to let the Marstek app's Reverse Measurement Direction flip the sign of a phase's power (CT002). A wrong setting makes the batteries work against the grid, and any phone in Bluetooth range could change it. A sign that is wrong from the start is better fixed on the sensor.", type: "checkbox", }, state.general, {}, ), ] : []), el("hr", {}), ] : []; return card(5, "Optional extras", "Skip this unless you want Marstek-app integration or a custom MQTT broker.", [ ...bluetoothBody, el("h3", { text: "Marstek cloud registration" }), ...marstekBody, el("hr", {}), el("h3", { text: isHa ? "Custom MQTT broker" : "MQTT Insights / Home Assistant" }), ...insightsBody, ...dashboardBody, ]); } // Shown only for the ESPHome target: a no-prior-knowledge guide to actually // getting the generated YAML onto the chip. function esphomeStepsCard(): HTMLElement | null { if (state.target !== "esphome") return null; const e = state.esphome; const li = (html: string) => el("li", { html }); return card(6, "How to flash this onto your ESP32", "Follow these once. After that, the board runs on its own — you can unplug it from your PC and power it from any USB charger near your battery.", [ el("ol", { class: "steps" }, [ li("Get the board. Buy an ESP32-S3 DevKitC-1 (links in step 2 above) and plug it into your computer with a USB cable that supports data."), li("Install ESPHome. Easiest: in Home Assistant, go to Settings → Add-ons → Add-on Store and install ESPHome Device Builder. No Home Assistant? Use the web installer at web.esphome.io (Chrome/Edge), or install the CLI with pip install esphome."), li("Create the device. In ESPHome click + New Device, give it a name, and when it generates a starter file, replace the entire contents with the file from the preview on this page (use the Download file or Copy button)."), li( "Add your WiFi. ESPHome keeps secrets separately. Open Secrets (or secrets.yaml) and add:
wifi_ssid: \"YourWiFiName\"
wifi_password: \"YourWiFiPassword\"" + (state.marstek && state.marstek.enabled ? "
marstek_password: \"YourMarstekPassword\" (because you enabled Marstek cloud registration)" : ""), ), li("Check the board matches. The file uses board: " + escapeHtml(e.board || "esp32-s3-devkitc-1") + ". This must be the board you actually bought — change it in step 2 above if not."), li("Install / flash. Click Install → Plug into this computer for the first flash (USB). After that you can update it wirelessly over WiFi. Flashing takes a few minutes."), li("Point your battery at it. In the Marstek app, set the battery to use a CT002/CT003 meter (matching the CT type you chose). The ESP32 answers on your network automatically — power it from any USB charger near the battery."), ]), el("p", { class: "note", html: "Full reference: ESPHome external component docs ↗. Stuck? The board, WiFi, and CT-type are the three things to double-check." }), ]); } // ── preview + actions ───────────────────────────────────────────────────────── function outputFilename(): string { if (state.target === "esphome") return "astrameter.yaml"; if (state.target === "homeassistant") return "astrameter-options.yaml"; return "config.ini"; } function refreshPreview(): void { const pre = document.getElementById("preview-code"); if (!pre) return; let text = ""; try { text = generate(state); } catch (err) { text = "# Error generating config: " + (err as Error).message; } showPreview(pre, text); const fn = document.getElementById("preview-filename"); if (fn) fn.textContent = outputFilename(); saveState(); } // Render the config one line per , and after the first render mark the // lines the last change touched so the user can see what their answer did. // The first changed line is scrolled into view inside the preview if needed. let previewText: string | null = null; function showPreview(code: HTMLElement, text: string): void { if (text === previewText) return; const lines = text.split("\n"); let changed = previewText === null ? new Set() : changedLines(previewText.split("\n"), lines); // Switching the target rewrites the whole file; lighting all of it up says nothing. if (changed.size > lines.length / 2) changed = new Set(); previewText = text; const spans = lines.map((line, i) => el("span", changed.has(i) ? { class: "changed" } : {}, line + "\n")); code.replaceChildren(...spans); const first = spans.find((span) => span.classList.contains("changed")); const scroller = code.closest("pre"); if (!first || !scroller) return; const top = first.offsetTop - scroller.offsetTop; if (top < scroller.scrollTop || top > scroller.scrollTop + scroller.clientHeight - 40) { const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches; scroller.scrollTo({ top: Math.max(0, top - 40), behavior: reduce ? "auto" : "smooth" }); } } function previewPanel(): HTMLElement { const filename = outputFilename(); return el("aside", { class: "preview", id: "preview" }, [ el("div", { class: "preview-head" }, [ el("span", { text: "Live preview — " }), el("code", { id: "preview-filename", text: filename }), ]), el("pre", {}, [el("code", { id: "preview-code" })]), el("div", { class: "preview-actions" }, [ el("button", { type: "button", class: "secondary", onclick: copyConfig }, "Copy"), el("button", { type: "button", class: "primary", onclick: downloadConfig }, "Download file"), ]), ]); } function safeGenerate(): string | null { try { return generate(state); } catch { toast("Couldn't generate the config — check the preview for details", true); return null; } } function copyConfig(): void { const text = safeGenerate(); if (text == null) return; navigator.clipboard.writeText(text).then( () => toast("Copied to clipboard"), () => toast("Copy failed — select the text manually", true), ); } function downloadConfig(): void { const text = safeGenerate(); if (text == null) return; downloadText(outputFilename(), text); } function downloadText(filename: string, text: string): void { const blob = new Blob([text], { type: "text/plain" }); const url = URL.createObjectURL(blob); const a = el("a", { href: url, download: filename }); document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 0); } // ── project save / load ───────────────────────────────────────────────────── function saveState(): void { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch { /* storage may be unavailable (private mode) */ } } function loadState(): State | null { // 1) shared link wins try { const hash = location.hash.replace(/^#state=/, ""); if (hash) { const decoded = safeParse(decodeURIComponent(escape(atob(hash)))); history.replaceState(null, "", location.pathname + location.search); return migrate(decoded); } } catch { /* ignore bad hash */ } // 2) localStorage try { const raw = localStorage.getItem(STORAGE_KEY); if (raw) return migrate(safeParse(raw)); } catch { /* ignore */ } return null; } function saveProject(): void { downloadText("astrameter-project.json", JSON.stringify(state, null, 2)); } function loadProject(file: File): void { const reader = new FileReader(); reader.onload = () => { try { state = migrate(safeParse(reader.result as string)); settleRegistrationMark(); rerenderAll(); toast("Project loaded"); } catch { toast("Could not read that file", true); } }; reader.readAsText(file); } function shareLink(): void { try { const encoded = btoa(unescape(encodeURIComponent(JSON.stringify(state)))); const url = location.origin + location.pathname + "#state=" + encoded; navigator.clipboard.writeText(url).then( () => toast("Share link copied to clipboard"), () => prompt("Copy this link:", url), ); } catch { toast("Could not build share link", true); } } function resetProject(): void { if (!confirm("Start over? This clears everything you've entered.")) return; state = defaultState(); settleRegistrationMark(); rerenderAll(); } function toast(msg: string, isError = false): void { const t = el("div", { class: "toast" + (isError ? " toast-error" : ""), text: msg }); document.body.appendChild(t); requestAnimationFrame(() => t.classList.add("show")); setTimeout(() => { t.classList.remove("show"); setTimeout(() => t.remove(), 300); }, 2200); } // ── render ─────────────────────────────────────────────────────────────────── function rerenderAll(): void { const form = document.getElementById("form-col")!; form.innerHTML = ""; form.append(targetCard(), deviceCard(), meterCard()); const ct = ctCard(); if (ct) form.append(ct); form.append(extrasCard()); const steps = esphomeStepsCard(); if (steps) form.append(steps); form.append(projectCard()); refreshPreview(); } function projectCard(): HTMLElement { const fileInput = el("input", { type: "file", accept: "application/json", class: "hidden", onchange: (e: Event) => { const f = (e.target as HTMLInputElement).files?.[0]; if (f) loadProject(f); } }); return card(null, "Save your work", "Your answers are saved in this browser automatically. You can also export a project file to back up or continue on another device.", [ el("div", { class: "btn-row" }, [ el("button", { type: "button", class: "secondary", onclick: saveProject }, "Save project file"), el("button", { type: "button", class: "secondary", onclick: () => fileInput.click() }, "Load project file"), el("button", { type: "button", class: "secondary", onclick: shareLink }, "Copy share link"), el("button", { type: "button", class: "link-danger", onclick: resetProject }, "Start over"), fileInput, ]), ]); } function boot(): void { const root = document.getElementById("app")!; root.append(el("div", { class: "layout" }, [el("div", { id: "form-col", class: "form-col" }), previewPanel()])); rerenderAll(); } document.addEventListener("DOMContentLoaded", boot);