Constat d'origine, rejoué et daté au banc : 90 s d'écoute, arbitre actif, ~2 kW exportés
→ ZÉRO notification NymeaEnergy.*. L'état runtime de l'arbitre (allocation, budget, verrous,
paliers, disponibilité, motifs) ne franchissait aucune frontière RPC : il vivait exclusivement
dans qCInfo(dcNymeaEnergy). Expliquer les décisions au client n'avait donc aucun transport.
Après déploiement, même geste : 13 notifications en 480 s.
Aucune phrase composée par la box. La locale nymea est PAR CONNEXION (JSONRPC.Hello o:locale),
et NymeaEnergyJsonHandler est un JsonHandler sans pluginId — donc hors du catalogue de
traduction : rien ne rattraperait une phrase française émise là. La box transporte un CODE et
des PARAMÈTRES ; la phrase est fabriquée par le client.
LoadAction::reason devient DecisionReason{code, params}. La ligne française du journal est
RENDUE depuis ce couple par renderFr(), source unique — jamais maintenue en parallèle. Les 19
codes sont EXTRAITS des sites existants, pas inventés ; les motifs d'ECS-309 et ECS-309-b sont
repris mot pour mot. Prouvé par comparaison de traces (1726 lignes de journal identiques en
simulation), par une table d'or qui échoue au premier code sans phrase attendue, et au banc sur
7 motifs distincts. Le libellé de la charge n'entre pas dans la charge utile : il est substitué
au RENDU, par l'appelant qui le connaît.
Les verrous sortent en SECONDES RESTANTES, pas en watts. Ceci n'enfreint pas ECS-306 : cette
exigence interdit qu'un index de PALIER franchisse la frontière d'ALLOCATION ; une valeur
d'AFFICHAGE sortante est un autre chemin. Le mécanisme sort en union discriminée
(relay|variable|sgReady), toutes clés internes optionnelles au schéma (LM-302).
ILoadAdapter::runtimeView() est PURE VIRTUELLE à dessein — mais la pure virtuelle force à
RÉPONDRE, pas à répondre quelque chose. testRuntimeViewIsSubstantial() est le second verrou :
les quatre adaptateurs, amenés dans un état non trivial, doivent rendre les valeurs runtime
réelles, les verrous en secondes ET leur expiration, et les codes de défaut. Deux mutants
« vue vide » introduits puis retirés : le test échoue sur chacun.
budget publié : surplusW, evReservedW, recreditedW, allocatedW, remainingW, avec l'identité
surplus + recrédit − alloué == restant. recreditedW n'est pas décoratif : sans lui l'identité
serait fausse DÈS QU'UNE CHARGE CONSOMME, et le client chercherait un écart inexplicable. Le
banc l'a montré aussitôt — surplusW −250 W avec recreditedW 3000 W — rendant lisible l'artefact
de banc documenté dans AGENTS.md (relais sans mesure + rootmeter aveugle).
Champs omis, jamais nuls : timestamp absent = aucun cycle depuis le démarrage ; budget absent =
mode dégradé, planification suspendue. Publier un zéro se lirait « exécuté, rien à allouer ».
Cadence : changement qualitatif ou variation d'allocation > 50 W, plus un battement de 60 s.
C'est le battement qui rend un arbitre FIGÉ détectable — les notifications continuent tandis que
le timestamp cesse d'avancer. Observé 3 fois au banc. Volume mesuré : ≈ 1,7 Mo/jour, un client.
GetChargingSchedules rend enfin degradedMode : il était POUSSÉ en notification seule, donc
illisible par un client connecté après la bascule (famille ECS-411). Règles absolues 11 et 12
ajoutées à AGENTS.md.
LoadConfig : champ optionnel domain (ecs·ev·heating·hvac·battery), PURE métadonnée d'intention
que l'arbitre ne lit pas. Absente ou vide = non classée. Forme exacte découverte au banc et
corrigée dans la doc ET le test : GetLoadConfig sérialise via le méta-objet, donc la propriété
sort TOUJOURS, à "" — comme sgReady:{} ou powerLevels:[]. C'est le corollaire LM-302.
Règle 7-c, deux silences fermés : les retours idempotents du RelayRouter et du SgReadyAdapter
étaient MUETS — « consigne reçue, palier déjà bon » ne se distinguait pas de « l'action n'est
jamais parvenue à l'adaptateur », et c'est le cas ordinaire qu'on vient vérifier.
⚠️ Porté au contrat : loads[] n'est PAS en correspondance 1:1 avec GetLoadConfig. « pac-terrain »
est la PAC SG-Ready CODÉE EN DUR d'energypluginnymea.cpp (K1/K2 = Relay4/Relay5, {3:1500,
4:3000}) — arbitrée et publiée, mais inconfigurable : ni rang, ni domain, ni enabled:false.
INTERFACE.md porte la règle de détection pour l'app. Son sort reste À TRANCHER (RELEVE_LOTB §8-bis b).
Déploiement : la recette de TEST_TERRAIN.md §b portait un glob « dpkg -i /tmp/…_*_arm64.deb »,
de la même famille que celui qui a rétrogradé .75 de +etm12 à +etm9. Remplacée par
etm-powersync-deploy/deploy.sh (archivage avant dépôt, installation par nom, refus de
rétrogradation, contrôle de version après coup).
Vérifié sur .75 (1.15.2+etm13 puis +etm14) : critères 1, 2, 4, 5, 6, 7, 8 du brief. Critère 3
(épisode dégradé) vérifié en simulation seulement — le déclencher demande de faire taire un
simulateur SunSpec partagé, hors périmètre. Relevé complet, critère par critère, avec ce qui n'a
PAS été vérifié sur la machine et pourquoi : docs/RELEVE_LOTB.md.
Suites : simulation 38/38, charging 46/46, spotmarket 32/32, y compris en build DEBUG où les
Q_ASSERT_X du validateur JSON-RPC sont actifs (le schéma déclaré correspond donc à la charge
utile émise, retours ET notifications). Cross-arm64 : 0 avertissement. Doxygen : 10, inchangé.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MfvSskkYrrFriYcj4683D
263 lines
9.8 KiB
C++
263 lines
9.8 KiB
C++
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
// Copyright (C) 2025 - 2026, Patrick Schurig / ETM PowerSync
|
|
|
|
#include "etmvariableloadadapter.h"
|
|
#include "plugininfo.h"
|
|
|
|
#include <QDateTime>
|
|
#include <algorithm>
|
|
#include <integrations/thingmanager.h>
|
|
#include <integrations/thing.h>
|
|
#include <types/action.h>
|
|
#include <types/param.h>
|
|
#include <integrations/thingactioninfo.h>
|
|
|
|
EtmVariableLoadAdapter::EtmVariableLoadAdapter(ThingManager *thingManager,
|
|
const QString &id,
|
|
const QString &label,
|
|
const QList<int> &powerLevels,
|
|
int maxPowerW,
|
|
int priority,
|
|
const LoadNeeds &needs,
|
|
QObject *parent)
|
|
: QObject(parent)
|
|
, m_thingManager(thingManager)
|
|
, m_id(id)
|
|
, m_label(label)
|
|
, m_powerLevels(powerLevels)
|
|
, m_maxPowerW(maxPowerW)
|
|
, m_priority(priority)
|
|
, m_needs(needs)
|
|
{
|
|
// Re-tri par sécurité : l'UI émet trié, l'energymanager re-trie (contrat §6 cas limites).
|
|
std::sort(m_powerLevels.begin(), m_powerLevels.end());
|
|
// Contrat §2 : les paliers incluent 0. En *fixed* (liste non vide), 0 doit être présent.
|
|
Q_ASSERT(m_powerLevels.isEmpty() || m_powerLevels.first() == 0);
|
|
}
|
|
|
|
LoadDescriptor EtmVariableLoadAdapter::descriptor() const
|
|
{
|
|
LoadDescriptor d;
|
|
d.id = m_id;
|
|
d.label = m_label;
|
|
d.adapter = QStringLiteral("etmvariableload");
|
|
d.priority = m_priority;
|
|
|
|
d.declared.powerLevels = m_powerLevels;
|
|
d.declared.maxPowerW = m_maxPowerW;
|
|
d.needs = m_needs;
|
|
|
|
d.supportedKinds = { LoadAction::Setpoint };
|
|
return d;
|
|
}
|
|
|
|
LoadTelemetry EtmVariableLoadAdapter::telemetry() const
|
|
{
|
|
LoadTelemetry t;
|
|
Thing *thing = m_thingManager->findConfiguredThing(ThingId(m_id));
|
|
t.available = (thing != nullptr) && !m_faulted;
|
|
t.currentPowerW = readCurrentPowerW(); // juge runtime (contrat §4)
|
|
// ECS-414 — INDÉTERMINATION : écriture en vol, on annonce la plus HAUTE des deux
|
|
// consignes possibles si le thing ne mesure pas. Jamais moins que ce qui peut couler.
|
|
if (m_pending > 0 && t.currentPowerW <= 0)
|
|
t.currentPowerW = qMax(m_setpointPrev, m_setpointTarget);
|
|
t.lastActionAt = m_lastActionAt;
|
|
return t;
|
|
}
|
|
|
|
LoadContext EtmVariableLoadAdapter::toLoadContext(const QDateTime &now) const
|
|
{
|
|
Q_UNUSED(now) // aucune fenêtre de verrou côté moteur : l'anti-rebond vit dans le thing.
|
|
|
|
LoadContext ctx;
|
|
ctx.id = m_id;
|
|
ctx.adapter = QStringLiteral("etmvariableload");
|
|
ctx.label = m_label;
|
|
ctx.priority = m_priority;
|
|
ctx.declared = descriptor().declared;
|
|
|
|
ctx.telemetry.currentPowerW = telemetry().currentPowerW;
|
|
ctx.telemetry.available = telemetry().available;
|
|
if (m_faulted) {
|
|
// Charge FIGÉE : plancher == plafond == puissance crue engagée.
|
|
ctx.telemetry.lockMinPowerW = ctx.telemetry.currentPowerW;
|
|
ctx.telemetry.lockMaxPowerW = ctx.telemetry.currentPowerW;
|
|
}
|
|
return ctx;
|
|
}
|
|
|
|
LoadAction EtmVariableLoadAdapter::applyAction(const LoadAction &action, const QDateTime &now)
|
|
{
|
|
if (action.kind != LoadAction::Setpoint)
|
|
return action;
|
|
|
|
if (action.reason.isEmpty()) {
|
|
qCWarning(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— LoadAction sans reason rejetée.";
|
|
return action;
|
|
}
|
|
|
|
// ECS-414 — en défaut, plus aucune consigne écrite, y compris forcée.
|
|
if (m_faulted) {
|
|
LoadAction refused = action;
|
|
refused.powerW = refused.estimatedPowerW = m_currentSetpointW;
|
|
return refused;
|
|
}
|
|
|
|
// Second filet (invariant ILoadAdapter) : borner la consigne au plafond physique.
|
|
// L'arrondi au powerLevels (mode *fixed*) est fait par le scheduler (contrat §4, T3).
|
|
const double setpointW = qBound(0.0, action.powerW, static_cast<double>(m_maxPowerW));
|
|
|
|
qCInfo(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "→ setpoint" << qRound(setpointW) << "W"
|
|
<< (action.force ? "(force)" : "")
|
|
<< "|" << renderFr(action.reason, m_label);
|
|
|
|
m_setpointPrev = m_currentSetpointW;
|
|
m_setpointTarget = setpointW;
|
|
m_writeFailed = false;
|
|
writeSetpoint(setpointW);
|
|
|
|
m_currentSetpointW = setpointW;
|
|
m_lastActionAt = now;
|
|
|
|
LoadAction applied = action;
|
|
applied.powerW = setpointW;
|
|
applied.estimatedPowerW = setpointW;
|
|
return applied;
|
|
}
|
|
|
|
LoadRuntimeView EtmVariableLoadAdapter::runtimeView(const QDateTime &now) const
|
|
{
|
|
Q_UNUSED(now) // aucun verrou côté moteur : l'anti-rebond vit dans le thing (cf. toLoadContext).
|
|
|
|
LoadRuntimeView v;
|
|
v.mechanismKind = QStringLiteral("variable");
|
|
v.mechanism.insert(QStringLiteral("setpointW"), m_currentSetpointW);
|
|
// Le pourcentage est la lecture NATURELLE d'une modulation continue — c'est ce qu'un
|
|
// utilisateur reconnaît d'un routeur PV. Il reste dérivé de la consigne, jamais l'inverse :
|
|
// les watts sont la grandeur commandée, le pourcentage n'est qu'une vue.
|
|
if (m_maxPowerW > 0)
|
|
v.mechanism.insert(QStringLiteral("percent"),
|
|
qRound(1000.0 * m_currentSetpointW / m_maxPowerW) / 10.0);
|
|
v.mechanism.insert(QStringLiteral("maxPowerW"), static_cast<double>(m_maxPowerW));
|
|
|
|
// ECS-414 — deux causes DISTINCTES d'indisponibilité, deux codes. Les confondre enverrait
|
|
// diagnostiquer un matériel muet là où c'est un Thing absent de la configuration.
|
|
if (m_faulted)
|
|
v.faultCode = QStringLiteral("WRITE_FAILED");
|
|
else if (!m_thingManager || !m_thingManager->findConfiguredThing(ThingId(m_id)))
|
|
v.faultCode = QStringLiteral("THING_MISSING");
|
|
return v;
|
|
}
|
|
|
|
void EtmVariableLoadAdapter::applySafeState(const QDateTime &now)
|
|
{
|
|
LoadAction sur;
|
|
sur.loadId = m_id;
|
|
sur.kind = LoadAction::Setpoint;
|
|
sur.powerW = 0;
|
|
sur.force = true;
|
|
sur.reason = { DecisionCode::SafeStateSetpoint };
|
|
applyAction(sur, now);
|
|
}
|
|
|
|
// ---- privé ---------------------------------------------------------------
|
|
|
|
double EtmVariableLoadAdapter::readCurrentPowerW() const
|
|
{
|
|
Thing *thing = m_thingManager->findConfiguredThing(ThingId(m_id));
|
|
if (!thing)
|
|
return 0.0;
|
|
if (thing->thingClass().stateTypes().findByName("currentPowerW").id().isNull())
|
|
return 0.0;
|
|
return thing->stateValue("currentPowerW").toDouble();
|
|
}
|
|
|
|
void EtmVariableLoadAdapter::writeSetpoint(double powerW)
|
|
{
|
|
Thing *thing = m_thingManager ? m_thingManager->findConfiguredThing(ThingId(m_id)) : nullptr;
|
|
if (!thing) {
|
|
qCWarning(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— thing non trouvé:" << m_id;
|
|
m_writeFailed = true;
|
|
settleTransition();
|
|
return;
|
|
}
|
|
|
|
StateType setpointStateType = thing->thingClass().stateTypes().findByName("powerSetpoint");
|
|
if (setpointStateType.id().isNull()) {
|
|
thing->setStateValue("powerSetpoint", powerW); // repli mock : synchrone
|
|
return;
|
|
}
|
|
|
|
Action setpointAction(setpointStateType.id(), thing->id(), Action::TriggeredByRule);
|
|
setpointAction.setParams(ParamList() << Param(setpointStateType.id(), powerW));
|
|
ThingActionInfo *info = m_thingManager->executeAction(setpointAction);
|
|
if (!info) {
|
|
m_writeFailed = true;
|
|
settleTransition();
|
|
return;
|
|
}
|
|
// ECS-414 — même modèle qu'ECS-410 : aucune attente, verdict par signal, `this` en contexte.
|
|
++m_pending;
|
|
connect(info, &ThingActionInfo::finished, this, [this, info]() {
|
|
if (info->status() != Thing::ThingErrorNoError) {
|
|
m_writeFailed = true;
|
|
qCWarning(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— écriture consigne en échec, status" << info->status();
|
|
}
|
|
if (--m_pending == 0)
|
|
settleTransition();
|
|
});
|
|
}
|
|
|
|
void EtmVariableLoadAdapter::settleTransition()
|
|
{
|
|
if (!m_writeFailed) {
|
|
m_setpointPrev = m_setpointTarget = m_currentSetpointW;
|
|
return;
|
|
}
|
|
m_writeFailed = false;
|
|
|
|
switch (m_phase) {
|
|
case PhaseNominale:
|
|
qCWarning(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— échec d'écriture : retour à" << m_setpointPrev << "W.";
|
|
m_phase = PhaseRepli;
|
|
m_currentSetpointW = m_setpointPrev;
|
|
writeSetpoint(m_setpointPrev);
|
|
break;
|
|
case PhaseRepli:
|
|
qCWarning(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— retour arrière en échec : consigne 0 W.";
|
|
m_phase = PhasePlancher;
|
|
m_currentSetpointW = 0;
|
|
m_setpointTarget = 0;
|
|
writeSetpoint(0);
|
|
break;
|
|
case PhasePlancher:
|
|
case PhaseDefaut:
|
|
qCCritical(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— consigne 0 W en échec : charge EN DÉFAUT, plus aucune"
|
|
<< "commande. Levée par NymeaEnergy.ClearLoadFault.";
|
|
m_phase = PhaseDefaut;
|
|
m_faulted = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
bool EtmVariableLoadAdapter::clearFault()
|
|
{
|
|
if (!m_faulted)
|
|
return false; // rien à lever — l'arbitre le dira (règle 7-c)
|
|
qCInfo(dcNymeaEnergy()) << "[EtmVariableLoadAdapter]" << m_label
|
|
<< "— défaut levé par l'opérateur (ClearLoadFault).";
|
|
m_faulted = false;
|
|
m_phase = PhaseNominale;
|
|
m_writeFailed = false;
|
|
m_currentSetpointW = readCurrentPowerW(); // relu, pas supposé
|
|
m_setpointPrev = m_setpointTarget = m_currentSetpointW;
|
|
return true;
|
|
}
|