Files
EVCS/tools/ponctuel/20261004-import-sud-ouest.js

42 lines
3.0 KiB
JavaScript

// Calcule (et importe si IMPORT=1) l'historique Sud/Ouest depuis les stats horaires des trackers.
const ws = new WebSocket(process.env.HA_URL.replace(/^http/, 'ws') + '/api/websocket');
let id = 1; const pend = {};
const call = (m) => new Promise(r => { const i = id++; pend[i] = r; ws.send(JSON.stringify({ id: i, ...m })); });
const T = (i) => `sensor.mppt_450_200_hq2449yr9pt_tracker_solar_${i}_yield_today`;
ws.onmessage = async (e) => {
const m = JSON.parse(e.data);
if (m.type === 'auth_required') return ws.send(JSON.stringify({ type: 'auth', access_token: process.env.HA_TOKEN }));
if (m.type !== 'auth_ok') { if (pend[m.id]) { pend[m.id](m); delete pend[m.id]; } return; }
const fin = new Date(); fin.setMinutes(0, 0, 0);
const r = await call({ type: 'recorder/statistics_during_period', start_time: '2025-01-01T00:00:00Z',
end_time: fin.toISOString(), period: 'hour', types: ['state'], statistic_ids: [1, 2, 3, 4].map(T) });
const st = r.result;
const par = {}; // start -> {1:..,4:..}
for (const i of [1, 2, 3, 4]) for (const x of (st[T(i)] || [])) { (par[x.start] ||= {})[i] = x.state; }
const heures = Object.keys(par).map(Number).sort((a, b) => a - b);
console.log('heures', heures.length, new Date(heures[0]).toISOString(), '->', new Date(heures.at(-1)).toISOString());
const serie = (ids) => { const out = []; let prev = null, sum = 0, last = {};
for (const h of heures) {
for (const i of ids) if (par[h][i] !== undefined && par[h][i] !== null) last[i] = par[h][i];
if (!ids.every(i => last[i] !== undefined)) continue;
const v = Math.round(ids.reduce((a, i) => a + last[i], 0) * 100) / 100;
if (prev !== null) sum += v >= prev ? v - prev : v;
prev = v; out.push({ start: new Date(h).toISOString(), state: v, sum: Math.round(sum * 1000) / 1000 });
} return out; };
const sud = serie([1, 2, 3]), ouest = serie([4]);
console.log('sud', sud.length, 'total', sud.at(-1).sum, '| ouest', ouest.length, 'total', ouest.at(-1).sum);
// controle : derniere journee complete
const jour = (s, d0, d1) => { const a = s.filter(x => x.start >= d0 && x.start < d1); return a.length ? (a.at(-1).sum - (s[s.indexOf(a[0]) - 1]?.sum ?? 0)).toFixed(2) : null; };
console.log('03/10 sud', jour(sud, '2026-10-02T22', '2026-10-03T22'), 'ouest', jour(ouest, '2026-10-02T22', '2026-10-03T22'));
console.log('02/10 sud', jour(sud, '2026-10-01T22', '2026-10-02T22'), 'ouest', jour(ouest, '2026-10-01T22', '2026-10-02T22'));
if (process.env.IMPORT === '1') {
for (const [sid, nom, s] of [['sensor.pv_rs_450_sud_production_du_jour', 'PV RS 450 Sud - production du jour', sud],
['sensor.pv_rs_450_ouest_production_du_jour', 'PV RS 450 Ouest - production du jour', ouest]]) {
const res = await call({ type: 'recorder/import_statistics', metadata: { has_mean: false, has_sum: true, name: nom,
source: 'recorder', statistic_id: sid, unit_of_measurement: 'kWh' }, stats: s });
console.log('import', sid, res.success, JSON.stringify(res.error || ''));
}
}
ws.close();
};