mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
- energydata.js: Abruf SMARD (Last, Day-Ahead-Preis, Erzeugung nach Energietraegern), BNetzA-CSV Gasverbrauch und Gasspeicher, optional AGSI+ per GIE_API_KEY; Zeitlimits, Groessengrenze, je Quelle abgesichert, letzter guter Stand und Vorjahresdaten in SQLite - Normal aus denselben Kalendertagen/-wochen der Vorjahre; Energieindex aus gedeckelten Abweichungen mit Alterung und kleiner Spielschwankung - energy.js: Wirkung ueber die Bewertung (Ursache "Energielage (Strom & Gas)"), je Aktie und Erdgas begrenzt, hoechstens 2 % je Handelstag, nur im fortlaufenden Handel; Energiekosten der Bevoelkerung, gedrosselte Meldungen der Netzagentur Wiborien - Nachrichten -> Energie: Karte mit Index, Strommix, Preis, Verbrauch, Gas, Speicher, Verlaeufen und Branchenwirkung; Hilfe, Glossar, Handbuch mit Datenquellen - Admin: Einstellungsgruppe Energiedaten mit Status und "Jetzt abrufen"; GET /api/energy, GET /api/admin/energy, POST /api/admin/energy/fetch - Tests mit Beispielantworten der echten Quellen (ohne Netz) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
545 lines
29 KiB
JavaScript
545 lines
29 KiB
JavaScript
// Echte Energiedaten (Strom und Gas in Deutschland) für die Energielage im Spiel (energy.js).
|
||
//
|
||
// Quellen (öffentlich, ohne Schlüssel):
|
||
// – Strom: SMARD-Datenportal der Bundesnetzagentur, JSON-Chart-Schnittstelle
|
||
// {base}/{filter}/DE/index_{auflösung}.json → Zeitstempel der verfügbaren Dateien
|
||
// {base}/{filter}/DE/{filter}_DE_{auflösung}_{ts}.json → { series: [[ts, wert|null], …] }
|
||
// Stundenwerte der letzten zwei Wochen (aktueller Stand) und Tageswerte früherer Jahre (saisonales Normal).
|
||
// Lizenz: CC BY 4.0 (Namensnennung „Bundesnetzagentur | SMARD.de“).
|
||
// – Gas: Bundesnetzagentur „Aktuelle Lage der Gasversorgung“, CSV-Exporte (Daten von Trading Hub Europe):
|
||
// wöchentlicher Gasverbrauch (GWh/Tag) je Kalenderwoche und Jahr, Speicherfüllstand je Tag (Gasjahr).
|
||
// Lizenz: Datenlizenz Deutschland – Namensnennung – Version 2.0.
|
||
// – optional Gasspeicher über AGSI+ (Gas Infrastructure Europe) – nur mit Schlüssel in GIE_API_KEY (nie im Repo).
|
||
//
|
||
// Robustheit: jede Quelle einzeln mit Zeitlimit, Größenlimit und Plausibilitätsprüfung. Fällt eine Quelle aus oder
|
||
// ändert sich ihr Format, bleibt ihr letzter guter Stand erhalten (auch über Neustarts, Tabelle energy_cache) und der
|
||
// Fehler steht im Admin-Menü. Der Spielserver wird nie blockiert: Abrufe laufen asynchron und nacheinander.
|
||
// Im Spiel erscheinen nur fiktive Institutionen – die Quellenangabe steht in Hilfe und Handbuch.
|
||
import { settings } from './settings.js';
|
||
import { clamp } from './util.js';
|
||
|
||
const H = 3_600_000, DAY = 24 * H;
|
||
export const SMARD_BASE = process.env.SMARD_BASE || 'https://www.smard.de/app/chart_data';
|
||
export const BNETZA_BASE = process.env.BNETZA_BASE || 'https://www.bundesnetzagentur.de';
|
||
export const AGSI_BASE = process.env.AGSI_BASE || 'https://agsi.gie.eu';
|
||
export const USER_AGENT = 'WiBoSim-Energiedaten/1.0 (Browserspiel; liest öffentliche Energiedaten)';
|
||
const MAX_BYTES = 1_000_000;
|
||
const TZ = 'Europe/Berlin';
|
||
|
||
/** SMARD-Filter: Stromverbrauch, Großhandelspreis und Erzeugung nach Energieträger (ren: erneuerbar) */
|
||
export const SMARD_LOAD = 410; // Stromverbrauch: Netzlast (MWh je Stunde bzw. Tag)
|
||
export const SMARD_PRICE = 4169; // Großhandelspreis Day-Ahead, Marktgebiet DE/LU (€/MWh)
|
||
export const GEN = [
|
||
{ key: 'windOn', id: 4067, name: 'Wind an Land', group: 'wind', ren: true },
|
||
{ key: 'windOff', id: 1225, name: 'Wind auf See', group: 'wind', ren: true },
|
||
{ key: 'solar', id: 4068, name: 'Photovoltaik', group: 'solar', ren: true },
|
||
{ key: 'bio', id: 4066, name: 'Biomasse', group: 'bio', ren: true },
|
||
{ key: 'hydro', id: 1226, name: 'Wasserkraft', group: 'bio', ren: true },
|
||
{ key: 'otherRen', id: 1228, name: 'Sonstige Erneuerbare', group: 'bio', ren: true },
|
||
{ key: 'gas', id: 4071, name: 'Erdgas', group: 'gas', ren: false },
|
||
{ key: 'lignite', id: 1223, name: 'Braunkohle', group: 'coal', ren: false },
|
||
{ key: 'hardcoal', id: 4069, name: 'Steinkohle', group: 'coal', ren: false },
|
||
{ key: 'otherConv', id: 1227, name: 'Sonstige Konventionelle', group: 'other', ren: false },
|
||
{ key: 'pumped', id: 4070, name: 'Pumpspeicher', group: 'other', ren: false },
|
||
];
|
||
export const MIX_GROUPS = { wind: 'Wind', solar: 'Sonne', bio: 'Biomasse & Wasser', gas: 'Erdgas', coal: 'Kohle', other: 'Sonstige' };
|
||
/** CSV-Exporte der Bundesnetzagentur (Kennung der Grafik) */
|
||
export const BNETZA_GAS_ID = 870330; // Gasverbrauch gesamt, wöchentlicher Mittelwert in GWh/Tag
|
||
export const BNETZA_STORAGE_ID = 870304; // Speicherfüllstände in Prozent (je Gasjahr)
|
||
|
||
const WINDOW_H = 168; // aktueller Stand: Mittel der letzten 7 Tage
|
||
const RANGE = { // Plausibilitätsgrenzen
|
||
load: [20_000, 120_000], price: [-1000, 5000], gen: [0, 90_000], gas: [200, 10_000], storage: [0, 100.5],
|
||
};
|
||
|
||
export class EnergyError extends Error {
|
||
constructor(kind, message) { super(message); this.kind = kind; }
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Datum (Europe/Berlin)
|
||
const dtf = new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' });
|
||
/** Kalendertag in Berlin als 'JJJJ-MM-TT' */
|
||
export const berlinDate = (ts) => dtf.format(new Date(ts));
|
||
const shiftDate = (iso, days) => { const d = new Date(`${iso}T12:00:00Z`); d.setUTCDate(d.getUTCDate() + days); return d.toISOString().slice(0, 10); };
|
||
/** Montag der ISO-Kalenderwoche (UTC-Mitternacht) */
|
||
export function isoWeekStart(year, week) {
|
||
const jan4 = new Date(Date.UTC(year, 0, 4));
|
||
const mon = new Date(jan4); mon.setUTCDate(jan4.getUTCDate() - ((jan4.getUTCDay() + 6) % 7) + (week - 1) * 7);
|
||
return mon.getTime();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Parser
|
||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
||
|
||
/** SMARD index_*.json → aufsteigende Zeitstempel */
|
||
export function parseSmardIndex(j) {
|
||
const ts = j?.timestamps;
|
||
if (!Array.isArray(ts) || !ts.length || !ts.every((t) => Number.isInteger(t) && t > 1e12)) throw new EnergyError('format', 'SMARD: Zeitstempelliste fehlt oder ist ungültig');
|
||
return [...ts].sort((a, b) => a - b);
|
||
}
|
||
|
||
/** SMARD-Datendatei → [[ts, wert|null], …] (ungültige Einträge verworfen) */
|
||
export function parseSmardSeries(j) {
|
||
const s = j?.series;
|
||
if (!Array.isArray(s)) throw new EnergyError('format', 'SMARD: Datenreihe fehlt');
|
||
const out = [];
|
||
for (const e of s) {
|
||
if (!Array.isArray(e) || !Number.isInteger(e[0]) || e[0] < 1e12) continue;
|
||
out.push([e[0], num(e[1])]);
|
||
}
|
||
if (s.length && !out.length) throw new EnergyError('format', 'SMARD: Datenreihe ohne gültige Einträge');
|
||
return out;
|
||
}
|
||
|
||
/** Deutsche Zahl aus CSV („3.733“, „66,74“, leer = null) */
|
||
export function deNum(x) {
|
||
const t = String(x ?? '').trim();
|
||
if (!t) return null;
|
||
const n = Number(t.replace(/\.(?=\d{3}(\D|$))/g, '').replace(',', '.'));
|
||
return Number.isFinite(n) ? n : null;
|
||
}
|
||
const csvRows = (text) => String(text ?? '').replace(/^/, '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean).map((l) => l.split(';').map((c) => c.trim()));
|
||
|
||
/**
|
||
* Gasverbrauch (Bundesnetzagentur, wöchentlich): Kopf „.;2025;2026;2024;Durchschnittlicher Gasverbrauch 2018-2021;…“,
|
||
* dann je Kalenderwoche eine Zeile. → { years: {Jahr: {KW: Wert}}, ref: {KW: Wert} }
|
||
*/
|
||
export function parseGasCsv(text) {
|
||
const rows = csvRows(text);
|
||
if (rows.length < 5) throw new EnergyError('format', 'Gasverbrauch: zu wenige Zeilen');
|
||
const head = rows[0];
|
||
const yearCols = head.map((h, i) => (/^\d{4}$/.test(h) ? [i, Number(h)] : null)).filter(Boolean);
|
||
const refCol = head.findIndex((h) => /durchschnitt/i.test(h));
|
||
if (!yearCols.length) throw new EnergyError('format', 'Gasverbrauch: keine Jahresspalten gefunden');
|
||
const years = Object.fromEntries(yearCols.map(([, y]) => [y, {}]));
|
||
const ref = {};
|
||
for (const r of rows.slice(1)) {
|
||
const kw = Number(r[0]);
|
||
if (!Number.isInteger(kw) || kw < 1 || kw > 53) continue;
|
||
for (const [i, y] of yearCols) { const v = deNum(r[i]); if (v !== null) years[y][kw] = v; }
|
||
if (refCol >= 0) { const v = deNum(r[refCol]); if (v !== null) ref[kw] = v; }
|
||
}
|
||
if (!Object.values(years).some((m) => Object.keys(m).length)) throw new EnergyError('format', 'Gasverbrauch: keine Werte');
|
||
return { years, ref };
|
||
}
|
||
|
||
/**
|
||
* Speicherfüllstand (Bundesnetzagentur): Kopf „.;04/2025-03/2026;04/2026-03/2027“, Zeilen „TT.MM.;Wert;Wert“.
|
||
* → { cols: [{label, startYear}], rows: [{day, month, values: [..]}] }
|
||
*/
|
||
export function parseStorageCsv(text) {
|
||
const rows = csvRows(text);
|
||
if (rows.length < 5) throw new EnergyError('format', 'Speicher: zu wenige Zeilen');
|
||
const cols = rows[0].slice(1).map((h) => { const m = /^(\d{2})\/(\d{4})\s*-\s*(\d{2})\/(\d{4})$/.exec(h); return m ? { label: h, startYear: Number(m[2]) } : null; });
|
||
if (!cols.length || cols.some((c) => !c)) throw new EnergyError('format', 'Speicher: unbekannter Spaltenkopf');
|
||
const out = [];
|
||
for (const r of rows.slice(1)) {
|
||
const m = /^(\d{2})\.(\d{2})\.?$/.exec(r[0]);
|
||
if (!m) continue;
|
||
out.push({ day: Number(m[1]), month: Number(m[2]), values: cols.map((_, i) => deNum(r[i + 1])) });
|
||
}
|
||
if (!out.length) throw new EnergyError('format', 'Speicher: keine Werte');
|
||
return { cols, rows: out };
|
||
}
|
||
|
||
/** AGSI+ (Gas Infrastructure Europe): { data: [{ gasDayStart: 'JJJJ-MM-TT', full: '50.92' }, …] } → [{date, full}] */
|
||
export function parseAgsi(j) {
|
||
if (!j || !Array.isArray(j.data)) throw new EnergyError('format', `AGSI: ${j?.message ? String(j.message).slice(0, 80) : 'Datenliste fehlt'}`);
|
||
return j.data.map((d) => ({ date: String(d?.gasDayStart ?? ''), full: deNum(String(d?.full ?? '').replace('.', ',')) }))
|
||
.filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d.date) && d.full !== null);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Kennzahlen
|
||
const mean = (xs) => (xs.length ? xs.reduce((a, x) => a + x, 0) / xs.length : null);
|
||
export function median(xs) {
|
||
const s = xs.filter((x) => Number.isFinite(x)).sort((a, b) => a - b);
|
||
if (!s.length) return null;
|
||
const m = Math.floor(s.length / 2);
|
||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||
}
|
||
const r1 = (x) => (x === null || !Number.isFinite(x) ? null : Math.round(x * 10) / 10);
|
||
const r3 = (x) => (x === null || !Number.isFinite(x) ? null : Math.round(x * 1000) / 1000);
|
||
const inRange = (v, [lo, hi]) => v === null || (v >= lo && v <= hi);
|
||
|
||
/** Stundenreihen zusammenführen (mehrere Wochendateien) → Map ts → wert */
|
||
export function mergeSeries(list) {
|
||
const m = new Map();
|
||
for (const s of list) for (const [t, v] of s) if (v !== null || !m.has(t)) m.set(t, v);
|
||
return m;
|
||
}
|
||
/** Mittel der Werte im Fenster (end − hours, end] */
|
||
export function windowMean(map, end, hours) {
|
||
const xs = [];
|
||
for (const [t, v] of map) if (v !== null && t > end - hours * H && t <= end) xs.push(v);
|
||
return xs.length ? { mean: mean(xs), n: xs.length } : { mean: null, n: 0 };
|
||
}
|
||
/** Tageswerte (Map 'JJJJ-MM-TT' → Wert) aus SMARD-Tagesreihen */
|
||
export function dailyMap(seriesList) {
|
||
const m = new Map();
|
||
for (const s of seriesList) for (const [t, v] of s) if (v !== null) m.set(berlinDate(t + 2 * H), v);
|
||
return m;
|
||
}
|
||
/** Dieselben Kalendertage (dates: 'JJJJ-MM-TT') in einem früheren Jahr */
|
||
const sameDays = (dates, year) => dates.map((d) => `${year}${d.slice(4)}`);
|
||
|
||
/**
|
||
* Saisonales Normal: Mittel derselben Kalendertage in früheren Jahren, Median über die Jahre.
|
||
* daily: Map Datum → Tageswert; fn: Tageswert → Kennzahl (z. B. MWh/Tag → MW). Ein Jahr zählt nur mit fast vollständigem Fenster.
|
||
*/
|
||
export function seasonalNormal(daily, dates, years, fn = (x) => x) {
|
||
const per = [];
|
||
for (const y of years) {
|
||
const xs = sameDays(dates, y).map((d) => daily.get(d)).filter((v) => v !== undefined && v !== null);
|
||
if (xs.length >= Math.max(1, dates.length - 1)) per.push(fn(mean(xs)));
|
||
}
|
||
return { value: median(per), years: per.length };
|
||
}
|
||
|
||
/**
|
||
* Strom: Kennzahlen aus Stundenwerten (aktuell) und Tageswerten früherer Jahre (Normal).
|
||
* hourly: {filter: Map ts → wert}, daily: {filter: Map Datum → Tageswert}
|
||
*/
|
||
export function computePower({ hourly, daily, now, years }) {
|
||
const load = hourly[SMARD_LOAD];
|
||
if (!load?.size) throw new EnergyError('format', 'SMARD: keine Stundenwerte zum Stromverbrauch');
|
||
// Datenstand: letzte Stunde mit Stromverbrauch (nicht in der Zukunft)
|
||
let until = 0;
|
||
for (const [t, v] of load) if (v !== null && t <= now && t > until) until = t;
|
||
if (!until) throw new EnergyError('format', 'SMARD: keine aktuellen Werte zum Stromverbrauch');
|
||
const end = until;
|
||
const dates = Array.from({ length: 7 }, (_, i) => shiftDate(berlinDate(end), i - 6));
|
||
const w = (f, hours = WINDOW_H, e = end) => windowMean(hourly[f] ?? new Map(), e, hours);
|
||
const recent = (f) => w(f, 48).mean, before = (f) => w(f, 120, end - 48 * H).mean;
|
||
|
||
const loadNow = w(SMARD_LOAD);
|
||
if (loadNow.n < 96) throw new EnergyError('format', 'SMARD: zu wenige Stundenwerte zum Stromverbrauch');
|
||
const loadNorm = seasonalNormal(daily[SMARD_LOAD] ?? new Map(), dates, years, (x) => x / 24);
|
||
const priceNow = w(SMARD_PRICE);
|
||
const priceNorm = seasonalNormal(daily[SMARD_PRICE] ?? new Map(), dates, years);
|
||
// Erzeugung nach Energieträgern
|
||
const gen = {};
|
||
for (const g of GEN) gen[g.key] = w(g.id).mean;
|
||
const genKnown = GEN.filter((g) => gen[g.key] !== null);
|
||
const total = genKnown.reduce((a, g) => a + gen[g.key], 0);
|
||
const renNow = total > 0 && genKnown.length >= GEN.length - 2 ? GEN.filter((g) => g.ren).reduce((a, g) => a + (gen[g.key] ?? 0), 0) / total : null;
|
||
// Normal des Anteils: je früherem Jahr Summe erneuerbar / Summe gesamt, dann Median
|
||
const renPer = [];
|
||
for (const y of years) {
|
||
let ren = 0, all = 0, ok = 0;
|
||
for (const g of GEN) {
|
||
const xs = sameDays(dates, y).map((d) => daily[g.id]?.get(d)).filter((v) => v !== undefined && v !== null);
|
||
if (xs.length < dates.length - 1) continue;
|
||
ok++;
|
||
const m = mean(xs);
|
||
all += m; if (g.ren) ren += m;
|
||
}
|
||
if (ok >= GEN.length - 2 && all > 0) renPer.push(ren / all);
|
||
}
|
||
const renNorm = median(renPer);
|
||
const mix = Object.entries(MIX_GROUPS).map(([k, name]) => ({ key: k, name, share: total > 0 ? r3(GEN.filter((g) => g.group === k).reduce((a, g) => a + (gen[g.key] ?? 0), 0) / total) : null }));
|
||
|
||
// Tagesverlauf (für die Karte): vollständige Tage aus den Stundenwerten
|
||
const byDay = new Map();
|
||
for (const [t, v] of load) {
|
||
if (v === null || t > end) continue;
|
||
const d = berlinDate(t);
|
||
const b = byDay.get(d) ?? { n: 0, load: 0, price: [], ren: 0, all: 0, genN: 0 };
|
||
b.n++; b.load += v;
|
||
const p = hourly[SMARD_PRICE]?.get(t); if (p !== undefined && p !== null) b.price.push(p);
|
||
let all = 0, ren = 0, known = 0;
|
||
for (const g of GEN) { const x = hourly[g.id]?.get(t); if (x !== undefined && x !== null) { known++; all += x; if (g.ren) ren += x; } }
|
||
if (known >= GEN.length - 2 && all > 0) { b.ren += ren; b.all += all; b.genN++; }
|
||
byDay.set(d, b);
|
||
}
|
||
const days = [...byDay.entries()].filter(([, b]) => b.n >= 20).sort((a, b) => (a[0] < b[0] ? -1 : 1)).slice(-14)
|
||
.map(([d, b]) => ({ date: d, load: Math.round(b.load / b.n), price: r1(mean(b.price)), ren: b.genN >= 20 && b.all > 0 ? r3(b.ren / b.all) : null }));
|
||
|
||
const dev = (a, b) => (a !== null && b ? r3(a / b - 1) : null);
|
||
const out = {
|
||
until, dates: [dates[0], dates[6]], years: loadNorm.years,
|
||
load: { now: Math.round(loadNow.mean), normal: loadNorm.value === null ? null : Math.round(loadNorm.value), dev: dev(loadNow.mean, loadNorm.value), trend: dev(recent(SMARD_LOAD), before(SMARD_LOAD)) },
|
||
price: { now: r1(priceNow.mean), normal: r1(priceNorm.value), dev: priceNow.mean !== null && priceNorm.value ? r3(priceNow.mean / priceNorm.value - 1) : null, last48: r1(recent(SMARD_PRICE)), trend: priceNow.mean !== null && recent(SMARD_PRICE) !== null && before(SMARD_PRICE) !== null ? r1(recent(SMARD_PRICE) - before(SMARD_PRICE)) : null },
|
||
ren: { now: r3(renNow), normal: r3(renNorm), dev: renNow !== null && renNorm !== null ? r1((renNow - renNorm) * 100) : null },
|
||
mix, days,
|
||
};
|
||
// Plausibilität: unsinnige Werte deuten auf eine Formatänderung → nicht übernehmen
|
||
if (!inRange(out.load.now, RANGE.load) || !inRange(out.load.normal, RANGE.load)) throw new EnergyError('format', `SMARD: unplausibler Stromverbrauch (${out.load.now} MW)`);
|
||
if (!inRange(out.price.now, RANGE.price)) throw new EnergyError('format', `SMARD: unplausibler Strompreis (${out.price.now} €/MWh)`);
|
||
if (Object.values(gen).some((v) => !inRange(v, RANGE.gen))) throw new EnergyError('format', 'SMARD: unplausible Erzeugungswerte');
|
||
// Trend des Anteils Erneuerbarer: letzte 48 h gegen die 120 h davor (Prozentpunkte)
|
||
const share = (e, hours) => {
|
||
let ren = 0, all = 0;
|
||
for (const g of GEN) { const m = windowMean(hourly[g.id] ?? new Map(), e, hours).mean; if (m !== null) { all += m; if (g.ren) ren += m; } }
|
||
return all > 0 ? ren / all : null;
|
||
};
|
||
const s1 = share(end, 48), s0 = share(end - 48 * H, 120);
|
||
out.ren.trend = s1 !== null && s0 !== null ? r1((s1 - s0) * 100) : null;
|
||
return out;
|
||
}
|
||
|
||
/** Gas: aktuelle Woche gegen dieselbe Kalenderwoche der Vorjahre (ersatzweise Mittel 2018–2021) */
|
||
export function computeGas(parsed, { years: nYears = 3 } = {}) {
|
||
const ys = Object.keys(parsed.years).map(Number).filter((y) => Object.keys(parsed.years[y]).length).sort((a, b) => a - b);
|
||
const year = ys.at(-1);
|
||
const weeks = Object.keys(parsed.years[year]).map(Number).sort((a, b) => a - b);
|
||
const kw = weeks.at(-1);
|
||
const now = parsed.years[year][kw];
|
||
const normalOf = (k) => {
|
||
const prior = ys.filter((y) => y < year && y >= year - nYears).map((y) => parsed.years[y][k]).filter((v) => v !== undefined);
|
||
return prior.length ? { v: mean(prior), by: 'vorjahre', n: prior.length } : parsed.ref[k] !== undefined ? { v: parsed.ref[k], by: 'referenz', n: 0 } : { v: null, by: null, n: 0 };
|
||
};
|
||
const nrm = normalOf(kw);
|
||
if (!inRange(now, RANGE.gas) || !inRange(nrm.v, RANGE.gas)) throw new EnergyError('format', `Gasverbrauch: unplausibler Wert (${now} GWh/Tag)`);
|
||
const prev = parsed.years[year - 1]?.[kw] ?? null;
|
||
const hist = weeks.slice(-8).map((k) => ({ kw: k, now: parsed.years[year][k], normal: r1(normalOf(k).v) }));
|
||
return {
|
||
year, kw, now: r1(now), normal: r1(nrm.v), normalBy: nrm.by, normalYears: nrm.n, prev: r1(prev),
|
||
dev: nrm.v ? r3(now / nrm.v - 1) : null,
|
||
until: isoWeekStart(year, kw) + 7 * DAY,
|
||
weeks: hist,
|
||
};
|
||
}
|
||
|
||
/** Speicher (Bundesnetzagentur): neuester Füllstand gegen denselben Tag des Vorjahres */
|
||
export function computeStorage(parsed) {
|
||
const ci = parsed.cols.length - 1;
|
||
let last = null;
|
||
for (const r of parsed.rows) if (r.values[ci] !== null) last = r;
|
||
if (!last) throw new EnergyError('format', 'Speicher: kein aktueller Füllstand');
|
||
const now = last.values[ci], ref = ci > 0 ? last.values[ci - 1] : null;
|
||
if (!inRange(now, RANGE.storage) || !inRange(ref, RANGE.storage)) throw new EnergyError('format', `Speicher: unplausibler Füllstand (${now} %)`);
|
||
const y = parsed.cols[ci].startYear + (last.month < 4 ? 1 : 0);
|
||
const date = `${y}-${String(last.month).padStart(2, '0')}-${String(last.day).padStart(2, '0')}`;
|
||
return { now: r1(now), ref: r1(ref), refLabel: 'Vorjahr', dev: ref === null ? null : r1(now - ref), date, until: Date.parse(`${date}T00:00:00Z`) + DAY, source: 'bnetza' };
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Abruf
|
||
const NET_ERRORS = { ENOTFOUND: 'Adresse nicht gefunden', EAI_AGAIN: 'Namensauflösung gescheitert', ECONNREFUSED: 'Verbindung abgelehnt', ECONNRESET: 'Verbindung abgebrochen', ETIMEDOUT: 'Zeitüberschreitung' };
|
||
|
||
/** Text abrufen (Zeitlimit, Größenlimit, eigene Kennung ohne persönliche Daten) */
|
||
export async function fetchText(url, { timeoutMs = 15_000, headers = {}, fetchImpl = fetch } = {}) {
|
||
let res;
|
||
try {
|
||
res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), headers: { 'user-agent': USER_AGENT, accept: 'application/json, text/csv;q=0.9, */*;q=0.5', ...headers } });
|
||
} catch (e) {
|
||
if (e?.name === 'TimeoutError' || e?.name === 'AbortError') throw new EnergyError('timeout', `keine Antwort nach ${Math.round(timeoutMs / 1000)} s`);
|
||
const code = String(e?.cause?.code ?? '');
|
||
throw new EnergyError('net', (NET_ERRORS[code] ? `${NET_ERRORS[code]} (${code})` : String(e?.cause?.message ?? e?.message ?? e)).slice(0, 120));
|
||
}
|
||
if (!res.ok) throw new EnergyError('http', `HTTP ${res.status}`);
|
||
const reader = res.body.getReader();
|
||
const dec = new TextDecoder();
|
||
let body = '', n = 0;
|
||
try {
|
||
for (;;) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
n += value.length;
|
||
if (n > MAX_BYTES) { await reader.cancel(); throw new EnergyError('format', 'Antwort zu groß'); }
|
||
body += dec.decode(value, { stream: true });
|
||
}
|
||
} catch (e) {
|
||
if (e instanceof EnergyError) throw e;
|
||
if (e?.name === 'TimeoutError' || e?.name === 'AbortError') throw new EnergyError('timeout', `Abruf nach ${Math.round(timeoutMs / 1000)} s abgebrochen`);
|
||
throw new EnergyError('net', String(e?.message ?? e).slice(0, 120));
|
||
}
|
||
return body;
|
||
}
|
||
const parseJson = (t, what) => { try { return JSON.parse(t); } catch { throw new EnergyError('format', `${what}: kein gültiges JSON`); } };
|
||
|
||
/** Zwischenspeicher: SQLite (Store) oder – ohne Store – im Speicher */
|
||
class Cache {
|
||
constructor(store) { this.store = store; this.mem = new Map(); }
|
||
get(k) {
|
||
if (this.store?.energyGet) { try { const r = this.store.energyGet(k); return r ? JSON.parse(r) : null; } catch { return null; } }
|
||
return this.mem.get(k) ?? null;
|
||
}
|
||
set(k, v) {
|
||
if (this.store?.energySet) { try { this.store.energySet(k, JSON.stringify(v)); } catch (e) { console.warn('[energie] Zwischenspeicher', e.message); } return; }
|
||
this.mem.set(k, v);
|
||
}
|
||
}
|
||
|
||
const SOURCES = { smard: 'Strom (SMARD)', gas: 'Gasverbrauch', storage: 'Gasspeicher' };
|
||
|
||
export class EnergyFeed {
|
||
/**
|
||
* @param {{store?: any, cfg?: () => any, fetchImpl?: Function, now?: () => number, gieKey?: string, bases?: {smard?: string, bnetza?: string, agsi?: string}, pauseMs?: number, timeoutMs?: number}} o
|
||
*/
|
||
constructor({ store = null, cfg = () => settings.energy, fetchImpl = fetch, now = Date.now, gieKey = process.env.GIE_API_KEY ?? '', bases = {}, pauseMs = 150, timeoutMs = 15_000 } = {}) {
|
||
this.cache = new Cache(store);
|
||
this.cfg = cfg;
|
||
this.fetchImpl = fetchImpl;
|
||
this.now = now;
|
||
this.gieKey = String(gieKey || '').trim();
|
||
this.base = { smard: bases.smard ?? SMARD_BASE, bnetza: bases.bnetza ?? BNETZA_BASE, agsi: bases.agsi ?? AGSI_BASE };
|
||
this.pauseMs = pauseMs;
|
||
this.timeoutMs = timeoutMs;
|
||
/** letzter guter Stand je Quelle: { power, gas, storage, fetchedAt } */
|
||
this.data = null;
|
||
this.status = { running: false, lastRun: 0, lastOk: 0, nextAt: 0, requests: 0, error: null, fromCache: false, sources: Object.fromEntries(Object.keys(SOURCES).map((k) => [k, { ok: null, at: 0, okAt: 0, error: null }])) };
|
||
this.onData = null;
|
||
this.timer = null;
|
||
this.pending = null;
|
||
}
|
||
|
||
/** gespeicherten letzten guten Stand laden (Start, auch ohne Netz) */
|
||
loadCached() {
|
||
const st = this.cache.get('state');
|
||
if (st && typeof st === 'object') { this.data = st; this.status.fromCache = true; }
|
||
return this.data;
|
||
}
|
||
|
||
start() {
|
||
this.loadCached();
|
||
this.stop();
|
||
// erster Abruf kurz nach dem Start, danach im Abrufintervall (Prüfung jede Minute)
|
||
this.status.nextAt = this.now() + 20_000;
|
||
this.timer = setInterval(() => {
|
||
if (!this.cfg().enabled || this.now() < this.status.nextAt) return;
|
||
this.poll().catch(() => {});
|
||
}, 60_000);
|
||
this.timer.unref?.();
|
||
this.first = setTimeout(() => { if (this.cfg().enabled) this.poll().catch(() => {}); }, 20_000);
|
||
this.first.unref?.();
|
||
}
|
||
stop() { clearInterval(this.timer); clearTimeout(this.first); this.timer = null; }
|
||
/** nach geänderten Einstellungen: nächsten Abruf neu planen */
|
||
restart() { if (this.timer) this.status.nextAt = Math.min(this.status.nextAt, this.now() + 5_000); }
|
||
|
||
async #get(url, opt) {
|
||
this.status.requests++;
|
||
if (this.pauseMs) await new Promise((r) => setTimeout(r, this.pauseMs));
|
||
return fetchText(url, { fetchImpl: this.fetchImpl, timeoutMs: this.timeoutMs, ...opt });
|
||
}
|
||
async #json(url, what, opt) { return parseJson(await this.#get(url, opt), what); }
|
||
|
||
/** Ein Abruf aller eingeschalteten Quellen. Läuft schon einer, wird auf ihn gewartet. */
|
||
poll() {
|
||
if (this.pending) return this.pending;
|
||
this.pending = this.#run().finally(() => { this.pending = null; });
|
||
return this.pending;
|
||
}
|
||
|
||
async #run() {
|
||
const cfg = this.cfg();
|
||
const t0 = this.now();
|
||
this.status.running = true;
|
||
this.status.lastRun = t0;
|
||
this.status.nextAt = t0 + Math.max(5, cfg.intervalMin ?? 60) * 60_000;
|
||
const next = { ...(this.data ?? {}) };
|
||
let okAny = false;
|
||
const run = async (key, on, fn) => {
|
||
const st = this.status.sources[key];
|
||
if (!on) { st.ok = null; st.error = 'abgeschaltet'; return; }
|
||
st.at = this.now();
|
||
try {
|
||
next[key === 'smard' ? 'power' : key] = await fn();
|
||
st.ok = true; st.error = null; st.okAt = this.now(); okAny = true;
|
||
} catch (e) {
|
||
st.ok = false;
|
||
st.error = `${e instanceof EnergyError ? '' : 'Fehler: '}${String(e?.message ?? e).slice(0, 160)}`;
|
||
console.warn(`[energie] ${SOURCES[key]}: ${st.error}`);
|
||
}
|
||
};
|
||
try {
|
||
await run('smard', cfg.power !== false, () => this.#power(cfg));
|
||
await run('gas', cfg.gas !== false, () => this.#gas(cfg));
|
||
await run('storage', cfg.storage !== false, () => this.#storage());
|
||
if (cfg.power === false) delete next.power;
|
||
if (cfg.gas === false) delete next.gas;
|
||
if (cfg.storage === false) delete next.storage;
|
||
next.fetchedAt = this.now();
|
||
this.data = next;
|
||
this.status.fromCache = false;
|
||
if (okAny) { this.status.lastOk = this.now(); this.cache.set('state', next); }
|
||
this.status.error = okAny ? null : 'Keine Quelle erreichbar – letzter guter Stand bleibt';
|
||
try { this.onData?.(this.data); } catch (e) { console.warn('[energie]', e.message); }
|
||
} finally {
|
||
this.status.running = false;
|
||
}
|
||
return this.statusView();
|
||
}
|
||
|
||
async #power(cfg) {
|
||
const B = this.base.smard;
|
||
const idxHour = parseSmardIndex(await this.#json(`${B}/${SMARD_LOAD}/DE/index_hour.json`, 'SMARD-Index'));
|
||
const weeks = idxHour.slice(-2);
|
||
const idxDay = this.cache.get(`smard:index_day:${berlinDate(this.now()).slice(0, 7)}`) ?? parseSmardIndex(await this.#json(`${B}/${SMARD_LOAD}/DE/index_day.json`, 'SMARD-Index'));
|
||
this.cache.set(`smard:index_day:${berlinDate(this.now()).slice(0, 7)}`, idxDay);
|
||
// Jahresdateien früherer Jahre (für das Normal) – einmal geladen, danach aus dem Zwischenspeicher
|
||
const yearNow = Number(berlinDate(this.now()).slice(0, 4));
|
||
const nYears = clamp(Math.round(cfg.historyYears ?? 3), 1, 8);
|
||
const years = Array.from({ length: nYears }, (_, i) => yearNow - nYears + i);
|
||
const yearTs = new Map(idxDay.map((t) => [Number(berlinDate(t + 2 * H).slice(0, 4)), t]));
|
||
const filters = [SMARD_LOAD, SMARD_PRICE, ...GEN.map((g) => g.id)];
|
||
const hourly = {}, daily = {};
|
||
let missing = 0;
|
||
for (const f of filters) {
|
||
const parts = [];
|
||
for (const w of weeks) {
|
||
try { parts.push(parseSmardSeries(await this.#json(`${B}/${f}/DE/${f}_DE_hour_${w}.json`, 'SMARD'))); }
|
||
catch (e) { if (f === SMARD_LOAD) throw e; missing++; }
|
||
}
|
||
hourly[f] = mergeSeries(parts);
|
||
const dparts = [];
|
||
// Fenster um den Jahreswechsel: zusätzlich das Jahr davor
|
||
for (const y of [...(berlinDate(this.now()).slice(5) < '01-08' ? [years[0] - 1] : []), ...years]) {
|
||
const ts = yearTs.get(y);
|
||
if (!ts) continue;
|
||
const key = `smard:day:${f}:${ts}`;
|
||
let s = this.cache.get(key);
|
||
if (!s) {
|
||
try { s = parseSmardSeries(await this.#json(`${B}/${f}/DE/${f}_DE_day_${ts}.json`, 'SMARD')); this.cache.set(key, s); }
|
||
catch { missing++; continue; }
|
||
}
|
||
dparts.push(s);
|
||
}
|
||
daily[f] = dailyMap(dparts);
|
||
}
|
||
const out = computePower({ hourly, daily, now: this.now(), years });
|
||
out.missing = missing;
|
||
return out;
|
||
}
|
||
|
||
async #gas(cfg) {
|
||
const text = await this.#get(`${this.base.bnetza}/SiteGlobals/Functions/SVG/_functions/csv_export.html?view=renderCSV&id=${BNETZA_GAS_ID}`);
|
||
return computeGas(parseGasCsv(text), { years: clamp(Math.round(cfg.historyYears ?? 3), 1, 8) });
|
||
}
|
||
|
||
async #storage() {
|
||
if (this.gieKey) {
|
||
// AGSI+: aktueller Füllstand und Mittel desselben Tages der Vorjahre (Vorjahre einmal geladen)
|
||
const head = { 'x-key': this.gieKey };
|
||
const cur = parseAgsi(await this.#json(`${this.base.agsi}/api?country=de&size=3`, 'AGSI', { headers: head }));
|
||
if (!cur.length) throw new EnergyError('format', 'AGSI: kein aktueller Füllstand');
|
||
const last = cur.sort((a, b) => (a.date < b.date ? 1 : -1))[0];
|
||
const refs = [];
|
||
for (let k = 1; k <= 5; k++) {
|
||
const d = `${Number(last.date.slice(0, 4)) - k}${last.date.slice(4)}`;
|
||
let v = this.cache.get(`agsi:${d}`);
|
||
if (v === null) {
|
||
try { const r = parseAgsi(await this.#json(`${this.base.agsi}/api?country=de&date=${d}`, 'AGSI', { headers: head })); v = r[0]?.full ?? null; if (v !== null) this.cache.set(`agsi:${d}`, v); } catch { v = null; }
|
||
}
|
||
if (v !== null) refs.push(v);
|
||
}
|
||
const ref = mean(refs);
|
||
if (!inRange(last.full, RANGE.storage)) throw new EnergyError('format', 'AGSI: unplausibler Füllstand');
|
||
return { now: r1(last.full), ref: r1(ref), refLabel: refs.length ? `Mittel ${refs.length} Vorjahre` : null, dev: ref === null ? null : r1(last.full - ref), date: last.date, until: Date.parse(`${last.date}T00:00:00Z`) + DAY, source: 'agsi' };
|
||
}
|
||
const text = await this.#get(`${this.base.bnetza}/SiteGlobals/Functions/SVG/_functions/csv_export.html?view=renderCSV&id=${BNETZA_STORAGE_ID}`);
|
||
return computeStorage(parseStorageCsv(text));
|
||
}
|
||
|
||
/** Für das Admin-Menü: Zustand je Quelle (ohne Schlüssel) */
|
||
statusView() {
|
||
const s = this.status;
|
||
return {
|
||
running: s.running, lastRun: s.lastRun || null, lastOk: s.lastOk || null, nextAt: this.timer ? s.nextAt : null, requests: s.requests,
|
||
error: s.error, fromCache: s.fromCache, agsi: !!this.gieKey,
|
||
sources: Object.fromEntries(Object.entries(s.sources).map(([k, v]) => [k, { name: SOURCES[k], ...v, at: v.at || null, okAt: v.okAt || null }])),
|
||
fetchedAt: this.data?.fetchedAt ?? null,
|
||
};
|
||
}
|
||
}
|